1 ;;; org.el --- Outline-based notes management and organize
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (c) 2004, 2005, 2006 Free Software Foundation
5 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around a NOTES file that contains
34 ;; information about projects as plain text. Org-mode is implemented on top
35 ;; of outline-mode - ideal to keep the content of large files well structured.
36 ;; It supports ToDo items, deadlines and time stamps, which can be extracted
37 ;; to create a daily/weekly agenda that also integrates the diary of the Emacs
38 ;; calendar. Tables are easily created with a built-in table editor. Plain
39 ;; text URL-like links connect to websites, emails (VM, RMAIL, WANDERLUST),
40 ;; Usenet messages (Gnus), BBDB entries, and any files related to the
41 ;; projects. For printing and sharing of notes, an Org-mode file (or a part
42 ;; of it) can be exported as a structured ASCII file, or as HTML.
46 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
47 ;; only need to copy the following lines to your .emacs file. The last two
48 ;; lines define *global* keys for the commands `org-store-link' and
49 ;; `org-agenda' - please choose suitable keys yourself.
51 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
52 ;; (define-key global-map "\C-cl" 'org-store-link)
53 ;; (define-key global-map "\C-ca" 'org-agenda)
55 ;; If you have downloaded Org-mode from the Web, you must byte-compile
56 ;; org.el and put it on your load path. In addition to the Emacs Lisp
57 ;; lines above, you also need to add the following lines to .emacs:
59 ;; (autoload 'org-mode "org" "Org mode" t)
60 ;; (autoload 'org-diary "org" "Diary entries from Org mode")
61 ;; (autoload 'org-agenda "org" "Multi-file agenda from Org mode" t)
62 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
63 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
64 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
66 ;; This setup will put all files with extension ".org" into Org-mode. As
67 ;; an alternative, make the first line of a file look like this:
69 ;; MY PROJECTS -*- mode: org; -*-
71 ;; which will select Org-mode for this buffer no matter what the file's
76 ;; The documentation of Org-mode can be found in the TeXInfo file. The
77 ;; distribution also contains a PDF version of it. At the homepage of
78 ;; Org-mode, you can read the same text online as HTML. There is also an
79 ;; excellent reference card made by Philip Rooke. This card can be found
80 ;; in the etc/ directory of Emacs 22.
82 ;; Changes since version 4.00:
83 ;; ---------------------------
85 ;; - Cleanup tags display in agenda.
89 ;; - Table alignment fixed for use with wide characters.
90 ;; - `C-c -' leaves cursor in current table line.
91 ;; - The current TAG can be incorporated into the agenda prefix.
92 ;; See option `org-agenda-prefix-format' for details.
95 ;; - Minor bug fixes and improvements around tag searches.
96 ;; - XEmacs compatibility fixes.
99 ;; - Tags can also be set remotely from agenda buffer.
100 ;; - Boolean logic for tag searches.
101 ;; - Additional agenda commands can be configured through the variable
102 ;; `org-agenda-custom-commands'.
103 ;; - Minor bug fixes.
107 (eval-when-compile (require 'cl) (require 'calendar))
112 (defvar calc-embedded-close-formula)
113 (defvar calc-embedded-open-formula)
114 (defvar font-lock-unfontify-region-function)
116 ;;; Customization variables
118 (defvar org-version "4.04"
119 "The version number of the file org.el.")
120 (defun org-version ()
122 (message "Org-mode version %s" org-version))
124 ;; The following two constants are for compatibility with different Emacs
125 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
126 ;; The compatibility code in org.el is based on these two constants.
127 (defconst org-xemacs-p (featurep 'xemacs)
128 "Are we running xemacs?")
129 (defconst org-noutline-p (featurep 'noutline)
130 "Are we using the new outline mode?")
133 "Outline-based notes management and organizer "
139 (defgroup org-startup nil
140 "Options concerning startup of Org-mode."
144 (defcustom org-CUA-compatible nil
145 "Non-nil means use alternative key bindings for S-<cursor movement>.
146 Org-mode used S-<cursor movement> for changing timestamps and priorities.
147 S-<cursor movement> is also used for example by `CUA-mode' to select text.
148 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
149 alternative bindings. Setting this variable to t will replace the following
150 keys both in Org-mode and in the Org-agenda buffer.
158 If you do not like the alternative keys, take a look at the variable
161 This option is only relevant at load-time of Org-mode. Changing it requires
162 a restart of Emacs to become effective."
166 (defvar org-disputed-keys
167 '((S-up [(shift up)] [(meta ?p)])
168 (S-down [(shift down)] [(meta ?n)])
169 (S-left [(shift left)] [(meta ?-)])
170 (S-right [(shift right)] [(meta ?+)])
171 (S-return [(shift return)] [(control shift return)]))
172 "Keys for which Org-mode and other modes compete.
173 This is an alist, cars are symbols for lookup, 1st element is the default key,
174 second element will be used when `org-CUA-compatible' is t.")
177 "Select a key according to `org-CUA-compatible'."
178 (nth (if org-CUA-compatible 2 1)
179 (or (assq key org-disputed-keys)
180 (error "Invalid Key %s in `org-key'" key))))
182 (defcustom org-startup-folded t
183 "Non-nil means, entering Org-mode will switch to OVERVIEW.
184 This can also be configured on a per-file basis by adding one of
185 the following lines anywhere in the buffer:
192 (const :tag "nofold: show all" nil)
193 (const :tag "fold: overview" t)
194 (const :tag "content: all headlines" content)))
196 (defcustom org-startup-truncated t
197 "Non-nil means, entering Org-mode will set `truncate-lines'.
198 This is useful since some lines containing links can be very long and
199 uninteresting. Also tables look terrible when wrapped."
203 (defcustom org-startup-with-deadline-check nil
204 "Non-nil means, entering Org-mode will run the deadline check.
205 This means, if you start editing an org file, you will get an
206 immediate reminder of any due deadlines.
207 This can also be configured on a per-file basis by adding one of
208 the following lines anywhere in the buffer:
211 #+STARTUP: nodlcheck"
215 (defcustom org-insert-mode-line-in-empty-file nil
216 "Non-nil means insert the first line setting Org-mode in empty files.
217 When the function `org-mode' is called interactively in an empty file, this
218 normally means that the file name does not automatically trigger Org-mode.
219 To ensure that the file will always be in Org-mode in the future, a
220 line enforcing Org-mode will be inserted into the buffer, if this option
225 (defgroup org-keywords nil
226 "Options concerning TODO items in Org-mode."
230 (defcustom org-todo-keywords '("TODO" "DONE")
231 "List of TODO entry keywords.
232 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
233 considered to mean that the entry is \"done\". All the other mean that
234 action is required, and will make the entry show up in todo lists, diaries
236 The command \\[org-todo] cycles an entry through these states, and an
237 additional state where no keyword is present. For details about this
238 cycling, see also the variable `org-todo-interpretation'
239 Changes become only effective after restarting Emacs."
241 :type '(repeat (string :tag "Keyword")))
243 (defcustom org-todo-interpretation 'sequence
244 "Controls how TODO keywords are interpreted.
245 \\<org-mode-map>Possible values are `sequence' and `type'.
246 This variable is only relevant if `org-todo-keywords' contains more than two
247 states. There are two ways how these keywords can be used:
249 - As a sequence in the process of working on a TODO item, for example
250 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
251 org-todo-interpretation 'sequence)
253 - As different types of TODO items, for example
254 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
255 org-todo-interpretation 'type)
257 When the states are interpreted as a sequence, \\[org-todo] always cycles
258 to the next state, in order to walk through all different states. So with
259 \\[org-todo], you turn an empty entry into the state TODO. When you started
260 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
261 later to VERIFY and finally to DONE.
263 When the states are interpreted as types, \\[org-todo] still cycles through
264 when it is called several times in direct succession, in order to initially
265 select the type. However, if not called immediately after a previous
266 \\[org-todo], it switches from each type directly to DONE. So with the
267 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
268 RELAXED. If you later return to this entry and press \\[org-todo] again,
269 RELAXED will not be changed REMIND, but directly to DONE.
271 You can create a large number of types. To initially select a
272 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
273 type with completion. Of course, you can also type the keyword
274 directly into the buffer. M-TAB completes TODO keywords at the
275 beginning of a headline."
277 :type '(choice (const sequence)
280 (defcustom org-default-priority ?B
281 "The default priority of TODO items.
282 This is the priority an item get if no explicit priority is given."
286 (defcustom org-lowest-priority ?C
287 "The lowest priority of TODO items. A character like ?A, ?B etc."
291 (defcustom org-deadline-string "DEADLINE:"
292 "String to mark deadline entries.
293 A deadline is this string, followed by a time stamp. Should be a word,
294 terminated by a colon. You can insert a schedule keyword and
295 a timestamp with \\[org-deadline].
296 Changes become only effective after restarting Emacs."
300 (defcustom org-scheduled-string "SCHEDULED:"
301 "String to mark scheduled TODO entries.
302 A schedule is this string, followed by a time stamp. Should be a word,
303 terminated by a colon. You can insert a schedule keyword and
304 a timestamp with \\[org-schedule].
305 Changes become only effective after restarting Emacs."
309 (defcustom org-closed-string "CLOSED:"
310 "String ued as the prefix for timestamps logging closing a TODO entry."
314 (defcustom org-comment-string "COMMENT"
315 "Entries starting with this keyword will never be exported.
316 An entry can be toggled between COMMENT and normal with
317 \\[org-toggle-comment].
318 Changes become only effective after restarting Emacs."
322 (defcustom org-quote-string "QUOTE"
323 "Entries starting with this keyword will be exported in fixed-width font.
324 Quoting applies only to the text in the entry following the headline, and does
325 not extend beyond the next headline, even if that is lower level.
326 An entry can be toggled between QUOTE and normal with
327 \\[org-toggle-fixed-width-section]"
331 (defcustom org-after-todo-state-change-hook nil
332 "Hook which is run after the state of a TODO item was changed.
333 The new state (a string with a todo keyword, or nil) is available in the
334 Lisp variable `state'."
338 ;; Variables for pre-computed regular expressions, all buffer local
339 (defvar org-todo-kwd-priority-p nil
340 "Do TODO items have priorities?")
341 (make-variable-buffer-local 'org-todo-kwd-priority-p)
342 (defvar org-todo-kwd-max-priority nil
343 "Maximum priority of TODO items.")
344 (make-variable-buffer-local 'org-todo-kwd-max-priority)
345 (defvar org-ds-keyword-length 12
346 "Maximum length of the Deadline and SCHEDULED keywords.")
347 (make-variable-buffer-local 'org-ds-keyword-length)
348 (defvar org-done-string nil
349 "The last string in `org-todo-keywords', indicating an item is DONE.")
350 (make-variable-buffer-local 'org-done-string)
351 (defvar org-todo-regexp nil
352 "Matches any of the TODO state keywords.")
353 (make-variable-buffer-local 'org-todo-regexp)
354 (defvar org-not-done-regexp nil
355 "Matches any of the TODO state keywords except the last one.")
356 (make-variable-buffer-local 'org-not-done-regexp)
357 (defvar org-todo-line-regexp nil
358 "Matches a headline and puts TODO state into group 2 if present.")
359 (make-variable-buffer-local 'org-todo-line-regexp)
360 (defvar org-nl-done-regexp nil
361 "Matches newline followed by a headline with the DONE keyword.")
362 (make-variable-buffer-local 'org-nl-done-regexp)
363 (defvar org-looking-at-done-regexp nil
364 "Matches the DONE keyword a point.")
365 (make-variable-buffer-local 'org-looking-at-done-regexp)
366 (defvar org-deadline-regexp nil
367 "Matches the DEADLINE keyword.")
368 (make-variable-buffer-local 'org-deadline-regexp)
369 (defvar org-deadline-time-regexp nil
370 "Matches the DEADLINE keyword together with a time stamp.")
371 (make-variable-buffer-local 'org-deadline-time-regexp)
372 (defvar org-deadline-line-regexp nil
373 "Matches the DEADLINE keyword and the rest of the line.")
374 (make-variable-buffer-local 'org-deadline-line-regexp)
375 (defvar org-scheduled-regexp nil
376 "Matches the SCHEDULED keyword.")
377 (make-variable-buffer-local 'org-scheduled-regexp)
378 (defvar org-scheduled-time-regexp nil
379 "Matches the SCHEDULED keyword together with a time stamp.")
380 (make-variable-buffer-local 'org-scheduled-time-regexp)
382 (defvar org-category nil
383 "Variable used by org files to set a category for agenda display.
384 Such files should use a file variable to set it, for example
386 -*- mode: org; org-category: \"ELisp\"
388 or contain a special line
392 If the file does not specify a category, then file's base name
394 (make-variable-buffer-local 'org-category)
396 (defgroup org-time nil
397 "Options concerning time stamps and deadlines in Org-mode."
401 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
402 "Formats for `format-time-string' which are used for time stamps.
403 It is not recommended to change this constant.")
406 (defcustom org-deadline-warning-days 30
407 "No. of days before expiration during which a deadline becomes active.
408 This variable governs the display in the org file."
412 (defcustom org-popup-calendar-for-date-prompt t
413 "Non-nil means, pop up a calendar when prompting for a date.
414 In the calendar, the date can be selected with mouse-1. However, the
415 minibuffer will also be active, and you can simply enter the date as well.
416 When nil, only the minibuffer will be available."
420 (defcustom org-calendar-follow-timestamp-change t
421 "Non-nil means, make the calendar window follow timestamp changes.
422 When a timestamp is modified and the calendar window is visible, it will be
423 moved to the new date."
427 (defcustom org-log-done nil
428 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
429 When the state of an entry is changed from nothing to TODO, remove a previous
434 (defgroup org-agenda nil
435 "Options concerning agenda display Org-mode."
439 (defcustom org-agenda-files nil
440 "A list of org files for agenda/diary display.
441 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
442 \\[org-remove-file]. You can also use customize to edit the list."
444 :type '(repeat file))
446 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
447 "Custom commands for the agenda.
448 These commands will be offered on the splash screen displayed by the
449 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
451 key The key (a single char as a string) to be associated with the command.
452 type The command type, any of the following symbols:
453 todo Entries with a specific TODO keyword, in all agenda files.
454 tags Tags match in all agenda files.
455 todo-tree Sparse tree of specific TODO keyword in *current* file.
456 tags-tree Sparse tree with all tags matches in *current* file.
457 occur-tree Occur sparse tree for current file.
458 match What to search for:
459 - a single keyword for TODO keyword searches
460 - a tags match expression for tags searches
461 - a regular expression for occur searches"
464 (list (string :tag "Key")
466 (const :tag "Tags search in all agenda files" tags)
467 (const :tag "TODO keyword search in all agenda files" todo)
468 (const :tag "Tags sparse tree in current buffer" tags-tree)
469 (const :tag "TODO keyword tree in current buffer" todo-tree)
470 (const :tag "Occur tree in current buffer" occur-tree))
471 (string :tag "Match"))))
473 (defcustom org-select-timeline-window t
474 "Non-nil means, after creating a timeline, move cursor into Timeline window.
475 When nil, cursor will remain in the current window."
479 (defcustom org-select-agenda-window t
480 "Non-nil means, after creating an agenda, move cursor into Agenda window.
481 When nil, cursor will remain in the current window."
485 (defcustom org-fit-agenda-window t
486 "Non-nil means, change window size of agenda to fit content."
490 (defcustom org-agenda-show-all-dates t
491 "Non-nil means, `org-agenda' shows every day in the selected range.
492 When nil, only the days which actually have entries are shown."
496 ;; FIXME: First day of month works only for current month because it would
497 ;; require a variable ndays treatment.
498 (defcustom org-agenda-start-on-weekday 1
499 "Non-nil means, start the overview always on the specified weekday.
500 0 Denotes Sunday, 1 denotes Monday etc.
501 When nil, always start on the current day."
503 :type '(choice (const :tag "Today" nil)
504 (const :tag "First day of month" t)
505 (number :tag "Weekday No.")))
507 (defcustom org-agenda-ndays 7
508 "Number of days to include in overview display."
512 (defcustom org-agenda-include-all-todo t
513 "Non-nil means, the agenda will always contain all TODO entries.
514 When nil, date-less entries will only be shown if `org-agenda' is called
515 with a prefix argument.
516 When non-nil, the TODO entries will be listed at the top of the agenda, before
517 the entries for specific days."
521 (defcustom org-agenda-include-diary nil
522 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
526 (defcustom org-calendar-to-agenda-key [?c]
527 "The key to be installed in `calendar-mode-map' for switching to the agenda.
528 The command `org-calendar-goto-agenda' will be bound to this key. The
529 default is the character `c' because then`c' can be used to switch back and
530 force between agenda and calendar."
534 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
535 "Sorting structure for the agenda items of a single day.
536 This is a list of symbols which will be used in sequence to determine
537 if an entry should be listed before another entry. The following
538 symbols are recognized.
540 time-up Put entries with time-of-day indications first, early first
541 time-down Put entries with time-of-day indications first, late first
542 category-keep Keep the default order of categories, corresponding to the
543 sequence in `org-agenda-files'.
544 category-up Sort alphabetically by category, A-Z.
545 category-down Sort alphabetically by category, Z-A.
546 priority-up Sort numerically by priority, high priority last.
547 priority-down Sort numerically by priority, high priority first.
549 The different possibilities will be tried in sequence, and testing stops
550 if one comparison returns a \"not-equal\". For example, the default
551 '(time-up category-keep priority-down)
552 means: Pull out all entries having a specified time of day and sort them,
553 in order to make a time schedule for the current day the first thing in the
554 agenda listing for the day. Of the entries without a time indication, keep
555 the grouped in categories, don't sort the categories, but keep them in
556 the sequence given in `org-agenda-files'. Within each category sort by
559 Leaving out `category-keep' would mean that items will be sorted across
560 categories by priority."
566 (const category-keep)
568 (const category-down)
570 (const priority-down))))
572 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
573 "Format specification for the prefix of items in the agenda buffer.
574 This format works similar to a printf format, with the following meaning:
576 %c the category of the item, \"Diary\" for entries from the diary, or
577 as given by the CATEGORY keyword or derived from the file name.
578 %T the first tag of the item.
579 %t the time-of-day specification if one applies to the entry, in the
581 %s Scheduling/Deadline information, a short string
583 All specifiers work basically like the standard `%s' of printf, but may
584 contain two additional characters: A question mark just after the `%' and
585 a whitespace/punctuation character just before the final letter.
587 If the first character after `%' is a question mark, the entire field
588 will only be included if the corresponding value applies to the
589 current entry. This is useful for fields which should have fixed
590 width when present, but zero width when absent. For example,
591 \"%?-12t\" will result in a 12 character time field if a time of the
592 day is specified, but will completely disappear in entries which do
595 If there is punctuation or whitespace character just before the final
596 format letter, this character will be appended to the field value if
597 the value is not empty. For example, the format \"%-12:c\" leads to
598 \"Diary: \" if the category is \"Diary\". If the category were be
599 empty, no additional colon would be interted.
601 The default value of this option is \" %-12:c%?-12t% s\", meaning:
602 - Indent the line with two space characters
603 - Give the category in a 12 chars wide field, padded with whitespace on
604 the right (because of `-'). Append a colon if there is a category
606 - If there is a time-of-day, put it into a 12 chars wide field. If no
607 time, don't put in an empty field, just skip it (because of '?').
608 - Finally, put the scheduling information and append a whitespace.
610 As another example, if you don't want the time-of-day of entries in
611 the prefix, you could use:
613 (setq org-agenda-prefix-format \" %-11:c% s\")
615 See also the variables `org-agenda-remove-times-when-in-prefix' and
616 `org-agenda-remove-tags-when-in-prefix'."
620 (defcustom org-timeline-prefix-format " % s"
621 "Like `org-agenda-prefix-format', but for the timeline of a single file."
625 (defvar org-prefix-format-compiled nil
626 "The compiled version of the most recently used prefix format.
627 Depending on which command was used last, this may be the compiled version
628 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
630 (defcustom org-agenda-use-time-grid t
631 "Non-nil means, show a time grid in the agenda schedule.
632 A time grid is a set of lines for specific times (like every two hours between
633 8:00 and 20:00. The items scheduled for a day at specific times are
634 sorted in between these lines.
635 For deails about when the grid will be shown, and what it will look like, see
636 the variable `org-agenda-time-grid'."
640 (defcustom org-agenda-time-grid
641 '((daily today require-timed)
643 (800 1000 1200 1400 1600 1800 2000))
645 "The settings for time grid for agenda display.
646 This is a list of three items. The first item is again a list. It contains
647 symbols specifying conditions when the grid should be displayed:
649 daily if the agenda shows a single day
650 weekly if the agenda shows an entire week
651 today show grid on current date, independent of daily/weekly display
652 require-timed show grid only if at least on item has a time specification
654 The second item is a string which will be places behing the grid time.
656 The third item is a list of integers, indicating the times that should have
661 (set :greedy t :tag "Grid Display Options"
662 (const :tag "Show grid in single day agenda display" daily)
663 (const :tag "Show grid in weekly agenda display" weekly)
664 (const :tag "Always show grid for today" today)
665 (const :tag "Show grid only if any timed entries are present"
667 (const :tag "Skip grid times already present in an entry"
669 (string :tag "Grid String")
670 (repeat :tag "Grid Times" (integer :tag "Time"))))
672 (defcustom org-agenda-remove-times-when-in-prefix t
673 "Non-nil means, remove duplicate time specifications in agenda items.
674 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
675 time-of-day specification in a headline or diary entry is extracted and
676 placed into the prefix. If this option is non-nil, the original specification
677 \(a timestamp or -range, or just a plain time(range) specification like
678 11:30-4pm) will be removed for agenda display. This makes the agenda less
680 The option can be t or nil. It may also be the symbol `beg', indicating
681 that the time should only be removed what it is located at the beginning of
682 the headline/diary entry."
685 (const :tag "Always" t)
686 (const :tag "Never" nil)
687 (const :tag "When at beginning of entry" beg)))
689 (defcustom org-sort-agenda-notime-is-late t
690 "Non-nil means, items without time are considered late.
691 This is only relevant for sorting. When t, items which have no explicit
692 time like 15:30 will be considered as 24:01, i.e. later than any items which
693 do have a time. When nil, the default time is before 0:00. You can use this
694 option to decide if the schedule for today should come before or after timeless
699 (defcustom org-agenda-remove-tags-when-in-prefix nil
700 "Non-nil means, the tags from copy of headline in agenda.
701 When this is the symbol `prefix', only remove tags when
702 `org-agenda-prefix-format' contains a `%T' specifier."
705 (const :tag "Always" t)
706 (const :tag "Never" nil)
707 (const :tag "When prefix format contains %T" prefix)))
709 (defgroup org-structure nil
710 "Options concerning structure editing in Org-mode."
714 (defcustom org-cycle-include-plain-lists nil
715 "Non-nil means, include plain lists into visibility cycling.
716 This means that during cycling, plain list items will *temporarily* be
717 interpreted as outline headlines with a level given by 1000+i where i is the
718 indentation of the bullet. In all other operations, plain list items are
719 not seen as headlines. For example, you cannot assign a TODO keyword to
721 :group 'org-structure
724 (defcustom org-cycle-emulate-tab t
725 "Where should `org-cycle' emulate TAB.
727 white Only in completely white lines
728 t Everywhere except in headlines"
729 :group 'org-structure
730 :type '(choice (const :tag "Never" nil)
731 (const :tag "Only in completely white lines" white)
732 (const :tag "Everywhere except in headlines" t)
735 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
736 "Hook that is run after `org-cycle' has changed the buffer visibility.
737 The function(s) in this hook must accept a single argument which indicates
738 the new state that was set by the most recent `org-cycle' command. The
739 argument is a symbol. After a global state change, it can have the values
740 `overview', `content', or `all'. After a local state change, it can have
741 the values `folded', `children', or `subtree'."
742 :group 'org-structure
745 (defcustom org-highlight-sparse-tree-matches t
746 "Non-nil means, highlight all matches that define a sparse tree.
747 The highlights will automatically disappear the next time the buffer is
748 changed by an edit command."
749 :group 'org-structure
752 (defcustom org-show-hierarchy-above t
753 "Non-nil means, show full hierarchy when showing a spot in the tree.
754 Turning this off makes sparse trees more compact, but also less clear."
755 :group 'org-structure
758 (defcustom org-show-following-heading t
759 "Non-nil means, show heading following match in `org-occur'.
760 When doing an `org-occur' it is useful to show the headline which
761 follows the match, even if they do not match the regexp. This makes it
762 easier to edit directly inside the sparse tree. However, if you use
763 org-occur mainly as an overview, the following headlines are
764 unnecessary clutter."
765 :group 'org-structure
768 (defcustom org-occur-hook '(org-first-headline-recenter)
769 "Hook that is run after `org-occur' has constructed a sparse tree.
770 This can be used to recenter the window to show as much of the structure
772 :group 'org-structure
775 (defcustom org-level-color-stars-only nil
776 "Non-nil means fontify only the stars in each headline.
777 When nil, the entire headline is fontified.
778 After changin this, requires restart of Emacs to become effective."
779 :group 'org-structure
782 (defcustom org-adapt-indentation t
783 "Non-nil means, adapt indentation when promoting and demoting.
784 When this is set and the *entire* text in an entry is indented, the
785 indentation is increased by one space in a demotion command, and
786 decreased by one in a promotion command. If any line in the entry
787 body starts at column 0, indentation is not changed at all."
788 :group 'org-structure
791 (defcustom org-plain-list-ordered-item-terminator t
792 "The character that makes a line with leading number an ordered list item.
793 Valid values are ?. and ?\). To get both terminators, use t. While
794 ?. may look nicer, it creates the danger that a line with leading
795 number may be incorrectly interpreted as an item. ?\) therefore is
797 :group 'org-structure
798 :type '(choice (const :tag "dot like in \"2.\"" ?.)
799 (const :tag "paren like in \"2)\"" ?\))
800 (const :tab "both" t)))
802 (defcustom org-auto-renumber-ordered-lists t
803 "Non-nil means, automatically renumber ordered plain lists.
804 Renumbering happens when the sequence have been changed with
805 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
806 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
807 :group 'org-structure
810 (defcustom org-enable-fixed-width-editor t
811 "Non-nil means, lines starting with \":\" are treated as fixed-width.
812 This currently only means, they are never auto-wrapped.
813 When nil, such lines will be treated like ordinary lines.
814 See also the QUOTE keyword."
815 :group 'org-structure
818 (defcustom org-archive-location "%s_archive::"
819 "The location where subtrees should be archived.
820 This string consists of two parts, separated by a double-colon.
822 The first part is a file name - when omitted, archiving happens in the same
823 file. %s will be replaced by the current file name (without directory part).
824 Archiving to a different file is useful to keep archived entries from
825 contributing to the Org-mode Agenda.
827 The part after the double colon is a headline. The archived entries will be
828 filed under that headline. When omitted, the subtrees are simply filed away
829 at the end of the file, as top-level entries.
831 Here are a few examples:
833 If the current file is Projects.org, archive in file
834 Projects.org_archive, as top-level trees. This is the default.
836 \"::* Archived Tasks\"
837 Archive in the current file, under the top-level headline
838 \"* Archived Tasks\".
840 \"~/org/archive.org::\"
841 Archive in file ~/org/archive.org (absolute path), as top-level trees.
843 \"basement::** Finished Tasks\"
844 Archive in file ./basement (relative path), as level 3 trees
845 below the level 2 heading \"** Finished Tasks\".
847 You may set this option on a per-file basis by adding to the buffer a
850 #+ARCHIVE: basement::** Finished Tasks"
851 :group 'org-structure
854 (defcustom org-archive-mark-done t
855 "Non-nil means, mark archived entries as DONE."
856 :group 'org-structure
859 (defcustom org-archive-stamp-time t
860 "Non-nil means, add a time stamp to archived entries.
861 The time stamp will be added directly after the TODO state keyword in the
862 first line, so it is probably best to use this in combinations with
863 `org-archive-mark-done'."
864 :group 'org-structure
867 (defgroup org-tags nil
868 "Options concerning startup of Org-mode."
872 (defcustom org-tags-column 48
873 "The column to which tags should be indented in a headline.
874 If this number is positive, it specified the column. If it is negative,
875 it means that the tags should be flushright to that column. For example,
876 -79 works well for a normal 80 character screen."
880 (defcustom org-auto-align-tags t
881 "Non-nil means, realign tags after pro/demotion of TODO state change.
882 These operations change the length of a headline and therefore shift
883 the tags around. With this options turned on, after each such operation
884 the tags are again aligned to `org-tags-column'."
888 (defcustom org-use-tag-inheritance t
889 "Non-nil means, tags in levels apply also for sublevels.
890 When nil, only the tags directly give in a specific line apply there.
891 If you turn off this option, you very likely want to turn on the
892 companion option `org-tags-match-list-sublevels'."
896 (defcustom org-tags-match-list-sublevels nil
897 "Non-nil means list also sublevels of headlines matching tag search.
898 Because of tag inheritance (see variable `org-use-tag-inheritance'),
899 the sublevels of a headline matching a tag search often also match
900 the same search. Listing all of them can create very long lists.
901 Setting this variable to nil causes subtrees to be skipped.
902 This option is off by default, because inheritance in on. If you turn
903 inheritance off, you very likely want to turn this option on.
905 As a special case, if the tag search is restricted to TODO items, the
906 value of this variable is ignored and sublevels are always checked, to
907 make sure all corresponding TODO items find their way into the list."
911 (defvar org-tags-history nil
912 "History of minibuffer reads for tags.")
913 (defvar org-last-tags-completion-table nil
914 "The last used completion table for tags.")
916 (defgroup org-link nil
917 "Options concerning links in Org-mode."
921 (defcustom org-tab-follows-link nil
922 "Non-nil means, on links TAB will follow the link.
923 Needs to be set before org.el is loaded."
927 (defcustom org-return-follows-link nil
928 "Non-nil means, on links RET will follow the link.
929 Needs to be set before org.el is loaded."
933 (defcustom org-link-format "<%s>"
934 "Default format for linkes in the buffer.
935 This is a format string for printf, %s will be replaced by the link text.
936 If you want to make sure that your link is always properly terminated,
937 include angle brackets into this format, like \"<%s>\". Some people also
938 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
941 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
942 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
943 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
944 (string :tag "Other" :value "<%s>")))
946 (defcustom org-allow-space-in-links t
947 "Non-nil means, file names in links may contain space characters.
948 When nil, it becomes possible to put several links into a line.
949 Note that in tables, a link never extends accross fields, so in a table
950 it is always possible to put several links into a line.
951 Changing this varable requires a re-launch of Emacs of become effective."
955 (defcustom org-context-in-file-links t
956 "Non-nil means, file links from `org-store-link' contain context.
957 The line number will be added to the file name with :: as separator and
958 used to find the context when the link is activated by the command
960 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
961 negates this setting for the duration of the command."
965 (defcustom org-keep-stored-link-after-insertion nil
966 "Non-nil means, keep link in list for entire session.
968 The command `org-store-link' adds a link pointing to the current
969 location to an internal list. These links accumulate during a session.
970 The command `org-insert-link' can be used to insert links into any
971 Org-mode file (offering completion for all stored links). When this
972 option is nil, every link which has been inserted once using \\[org-insert-link]
973 will be removed from the list, to make completing the unused links
978 (defcustom org-link-frame-setup
979 '((vm . vm-visit-folder-other-frame)
980 (gnus . gnus-other-frame)
981 (file . find-file-other-window))
982 "Setup the frame configuration for following links.
983 When following a link with Emacs, it may often be useful to display
984 this link in another window or frame. This variable can be used to
985 set this up for the different types of links.
988 `vm-visit-folder-other-frame'
994 `find-file-other-window'
995 `find-file-other-frame'
996 For the calendar, use the variable `calendar-setup'.
997 For BBDB, it is currently only possible to display the matches in
1003 (const vm-visit-folder)
1004 (const vm-visit-folder-other-window)
1005 (const vm-visit-folder-other-frame)))
1009 (const gnus-other-frame)))
1013 (const find-file-other-window)
1014 (const find-file-other-frame)))))
1016 (defcustom org-usenet-links-prefer-google nil
1017 "Non-nil means, `org-store-link' will create web links to google groups.
1018 When nil, Gnus will be used for such links.
1019 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1020 negates this setting for the duration of the command."
1024 (defcustom org-open-non-existing-files nil
1025 "Non-nil means, `org-open-file' will open non-existing file.
1026 When nil, an error will be generated."
1030 (defcustom org-confirm-shell-links t
1031 "Non-nil means, ask for confirmation before executing shell links.
1032 The default is true, to keep new users from shooting into their own foot."
1036 (defconst org-file-apps-defaults-gnu
1038 "Default file applications on a UNIX/LINUX system.
1039 See `org-file-apps'.")
1041 (defconst org-file-apps-defaults-macosx
1046 ("eps.gz" . "gv %s")
1048 ("fig" . "xfig %s"))
1049 "Default file applications on a MacOS X system.
1050 The system \"open\" is known as a default, but we use X11 applications
1051 for some files for which the OS does not have a good default.
1052 See `org-file-apps'.")
1054 (defconst org-file-apps-defaults-windowsnt
1055 '((t . (w32-shell-execute "open" file)))
1056 "Default file applications on a Windows NT system.
1057 The system \"open\" is used for most files.
1058 See `org-file-apps'.")
1060 (defcustom org-file-apps
1068 "External applications for opening `file:path' items in a document.
1069 Org-mode uses system defaults for different file types, but
1070 you can use this variable to set the application for a given file
1071 extension. The entries in this list are cons cells with a file extension
1072 and the corresponding command. Possible values for the command are:
1073 `emacs' The file will be visited by the current Emacs process.
1074 `default' Use the default application for this file type.
1075 string A command to be executed by a shell; %s will be replaced
1076 by the path to the file.
1077 sexp A Lisp form which will be evaluated. The file path will
1078 be available in the Lisp variable `file'.
1079 For more examples, see the system specific constants
1080 `org-file-apps-defaults-macosx'
1081 `org-file-apps-defaults-windowsnt'
1082 `org-file-apps-defaults-gnu'."
1085 (cons (string :tag "Extension")
1087 (const :tag "Visit with Emacs" 'emacs)
1088 (const :tag "Use system default" 'default)
1089 (string :tag "Command")
1090 (sexp :tag "Lisp form")))))
1093 (defgroup org-remember nil
1094 "Options concerning interaction with remember.el."
1098 (defcustom org-directory "~/org"
1099 "Directory with org files.
1100 This directory will be used as default to prompt for org files.
1101 Used by the hooks for remember.el."
1102 :group 'org-remember
1105 (defcustom org-default-notes-file "~/.notes"
1106 "Default target for storing notes.
1107 Used by the hooks for remember.el. This can be a string, or nil to mean
1108 the value of `remember-data-file'."
1109 :group 'org-remember
1111 (const :tag "Default from remember-data-file" nil)
1114 (defcustom org-reverse-note-order nil
1115 "Non-nil means, store new notes at the beginning of a file or entry.
1116 When nil, new notes will be filed to the end of a file or entry."
1117 :group 'org-remember
1119 (const :tag "Reverse always" t)
1120 (const :tag "Reverse never" nil)
1121 (repeat :tag "By file name regexp"
1122 (cons regexp boolean))))
1124 (defgroup org-table nil
1125 "Options concerning tables in Org-mode."
1129 (defcustom org-enable-table-editor 'optimized
1130 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1131 When nil, such lines will be treated like ordinary lines.
1133 When equal to the symbol `optimized', the table editor will be optimized to
1135 - Use automatic overwrite mode in front of whitespace in table fields.
1136 This make the structure of the table stay in tact as long as the edited
1137 field does not exceed the column width.
1138 - Minimize the number of realigns. Normally, the table is aligned each time
1139 TAB or RET are pressed to move to another field. With optimization this
1140 happens only if changes to a field might have changed the column width.
1141 Optimization requires replacing the functions `self-insert-command',
1142 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1143 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1144 very good at guessing when a re-align will be necessary, but you can always
1145 force one with \\[org-ctrl-c-ctrl-c].
1147 If you would like to use the optimized version in Org-mode, but the
1148 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1150 This variable can be used to turn on and off the table editor during a session,
1151 but in order to toggle optimization, a restart is required.
1153 See also the variable `org-table-auto-blank-field'."
1156 (const :tag "off" nil)
1158 (const :tag "on, optimized" optimized)))
1160 ;; FIXME: We could have a third option which makes it jump only over the first
1161 ;; hline in a table.
1162 (defcustom org-table-tab-jumps-over-hlines t
1163 "Non-nil means, tab in the last column of a table with jump over a hline.
1164 If a horizontal separator line is following the current line,
1165 `org-table-next-field' can either create a new row before that line, or jump
1166 over the line. When this option is nil, a new line will be created before
1171 (defcustom org-table-auto-blank-field t
1172 "Non-nil means, automatically blank table field when starting to type into it.
1173 This only happens when typing immediately after a field motion
1174 command (TAB, S-TAB or RET).
1175 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1179 (defcustom org-table-default-size "5x2"
1180 "The default size for newly created tables, Columns x Rows."
1184 (defcustom org-table-automatic-realign t
1185 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1186 When nil, aligning is only done with \\[org-table-align], or after column
1191 (defcustom org-table-spaces-around-separators '(1 . 1)
1192 "The number of spaces to be placed before and after separators."
1194 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1196 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1197 "The number of spaces to be placed before and after separators.
1198 This option applies when the column separators have been made invisible."
1200 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1202 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1203 "Regular expression for recognizing numbers in table columns.
1204 If a table column contains mostly numbers, it will be aligned to the
1205 right. If not, it will be aligned to the left.
1207 The default value of this option is a regular expression which allows
1208 anything which looks remotely like a number as used in scientific
1209 context. For example, all of the following will be considered a
1211 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1213 Other options offered by the customize interface are more restrictive."
1216 (const :tag "Positive Integers"
1218 (const :tag "Integers"
1220 (const :tag "Floating Point Numbers"
1221 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1222 (const :tag "Floating Point Number or Integer"
1223 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1224 (const :tag "Exponential, Floating point, Integer"
1225 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1226 (const :tag "Very General Number-Like"
1227 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1228 (string :tag "Regexp:")))
1230 (defcustom org-table-number-fraction 0.5
1231 "Fraction of numbers in a column required to make the column align right.
1232 In a column all non-white fields are considered. If at least this
1233 fraction of fields is matched by `org-table-number-fraction',
1234 alignment to the right border applies."
1238 (defcustom org-export-highlight-first-table-line t
1239 "Non-nil means, highlight the first table line.
1240 In HTML export, this means use <th> instead of <td>.
1241 In tables created with table.el, this applies to the first table line.
1242 In Org-mode tables, all lines before the first horizontal separator
1243 line will be formatted with <th> tags."
1247 (defcustom org-table-tab-recognizes-table.el t
1248 "Non-nil means, TAB will automatically notice a table.el table.
1249 When it sees such a table, it moves point into it and - if necessary -
1250 calls `table-recognize-table'."
1254 (defgroup org-table-calculation nil
1255 "Options concerning tables in Org-mode."
1256 :tag "Org Table Calculation"
1259 (defcustom org-table-copy-increment t
1260 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1261 :group 'org-table-calculation
1264 (defcustom org-calc-default-modes
1265 '(calc-internal-prec 12
1266 calc-float-format (float 5)
1268 calc-prefer-frac nil
1269 calc-symbolic-mode nil
1270 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1271 calc-display-working-message t
1273 "List with Calc mode settings for use in calc-eval for table formulas.
1274 The list must contain alternating symbols (calc modes variables and values.
1275 Don't remove any of the default settings, just change the values. Org-mode
1276 relies on the variables to be present in the list."
1277 :group 'org-table-calculation
1280 (defcustom org-table-formula-evaluate-inline t
1281 "Non-nil means, TAB and RET evaluate a formula in current table field.
1282 If the current field starts with an equal sign, it is assumed to be a formula
1283 which should be evaluated as described in the manual and in the documentation
1284 string of the command `org-table-eval-formula'. This feature requires the
1286 When this variable is nil, formula calculation is only available through
1287 the command \\[org-table-eval-formula]."
1288 :group 'org-table-calculation
1292 (defcustom org-table-formula-use-constants t
1293 "Non-nil means, interpret constants in formulas in tables.
1294 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1295 by the value given in `org-table-formula-constants', or by a value obtained
1296 from the `constants.el' package."
1297 :group 'org-table-calculation
1300 (defcustom org-table-formula-constants nil
1301 "Alist with constant names and values, for use in table formulas.
1302 The car of each element is a name of a constant, without the `$' before it.
1303 The cdr is the value as a string. For example, if you'd like to use the
1304 speed of light in a formula, you would configure
1306 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1308 and then use it in an equation like `$1*$c'."
1309 :group 'org-table-calculation
1311 (cons (string :tag "name")
1312 (string :tag "value"))))
1314 (defcustom org-table-formula-numbers-only nil
1315 "Non-nil means, calculate only with numbers in table formulas.
1316 Then all input fields will be converted to a number, and the result
1317 must also be a number. When nil, calc's full potential is available
1318 in table calculations, including symbolics etc."
1319 :group 'org-table-calculation
1322 (defcustom org-table-allow-automatic-line-recalculation t
1323 "Non-nil means, lines makred with |#| or |*| will be recomputed automatically.
1324 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1325 :group 'org-table-calculation
1328 (defgroup org-export nil
1329 "Options for exporting org-listings."
1333 (defcustom org-export-language-setup
1334 '(("en" "Author" "Date" "Table of Contents")
1335 ("da" "Ophavsmand" "Dato" "Indhold")
1336 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1337 ("es" "Autor" "Fecha" "\xccndice")
1338 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1339 ("it" "Autore" "Data" "Indice")
1340 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1341 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1342 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1343 "Terms used in export text, translated to different languages.
1344 Use the variable `org-export-default-language' to set the language,
1345 or use the +OPTION lines for a per-file setting."
1349 (string :tag "HTML language tag")
1350 (string :tag "Author")
1351 (string :tag "Date")
1352 (string :tag "Table of Contents"))))
1354 (defcustom org-export-default-language "en"
1355 "The default language of HTML export, as a string.
1356 This should have an association in `org-export-language-setup'."
1360 (defcustom org-export-html-style
1361 "<style type=\"text/css\">
1363 font-family: Times, serif;
1366 .title { text-align: center; }
1367 .todo, .deadline { color: red; }
1368 .done { color: green; }
1370 border: 1pt solid #AEBDCC;
1371 background-color: #F3F5F7;
1373 font-family: courier, monospace;
1375 table { border-collapse: collapse; }
1377 vertical-align: top;
1378 border: 1pt solid #ADB9CC;
1381 "The default style specification for exported HTML files.
1382 Since there are different ways of setting style information, this variable
1383 needs to contain the full HTML structure to provide a style, including the
1384 surrounding HTML tags. The style specifications should include definiitons
1385 for new classes todo, done, title, and deadline. For example, legal values
1388 <style type=\"text/css\">
1389 p {font-weight: normal; color: gray; }
1391 .title { text-align: center; }
1392 .todo, .deadline { color: red; }
1393 .done { color: green; }
1396 or, if you want to keep the style in a file,
1398 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1400 As the value of this option simply gets inserted into the HTML <head> header,
1401 you can \"misuse\" it to add arbitrary text to the header."
1405 (defcustom org-export-headline-levels 3
1406 "The last level which is still exported as a headline.
1407 Inferior levels will produce itemize lists when exported.
1408 Note that a numeric prefix argument to an exporter function overrides
1411 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1415 (defcustom org-export-with-section-numbers t
1416 "Non-nil means, add section numbers to headlines when exporting.
1418 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1422 (defcustom org-export-with-toc t
1423 "Non-nil means, create a table of contents in exported files.
1424 The TOC contains headlines with levels up to`org-export-headline-levels'.
1426 Headlines which contain any TODO items will be marked with \"(*)\" in
1427 ASCII export, and with red color in HTML output.
1429 In HTML output, the TOC will be clickable.
1431 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1435 (defcustom org-export-plain-list-max-depth 20
1436 "Maximum depth of hand-formatted lists in HTML export.
1438 Org-mode parses hand-formatted enumeration and bullet lists and
1439 transforms them to HTML open export. Different indentation of the
1440 bullet or number indicates different list nesting levels. To avoid
1441 confusion, only a single level is allowed by default. When this is
1442 larger than 1, deeper indentation leads to deeper list nesting. For
1443 example, the default value of 3 allows the following list to be
1444 formatted correctly in HTML:
1450 2. from South America
1457 (defcustom org-export-preserve-breaks nil
1458 "Non-nil means, preserve all line breaks when exporting.
1459 Normally, in HTML output paragraphs will be reformatted. In ASCII
1460 export, line breaks will always be preserved, regardless of this variable.
1462 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1466 (defcustom org-export-html-inline-images t
1467 "Non-nil means, inline images into exported HTML pages.
1468 The link will still be to the original location of the image file.
1469 So if you are moving the page, lets say to your public HTML site,
1470 you will have to move the image and maybe change the link."
1474 (defcustom org-export-html-expand t
1475 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1476 When nil, these tags will be exported as plain text and therefore
1477 not be interpreted by a browser.
1479 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1483 (defcustom org-export-with-fixed-width t
1484 "Non-nil means, lines starting with \":\" will be in fixed width font.
1485 This can be used to have pre-formatted text, fragments of code etc. For
1487 : ;; Some Lisp examples
1490 will be looking just like this in also HTML. In ASCII export, this option
1493 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1497 (defcustom org-export-with-tables t
1498 "If non-nil, lines starting with \"|\" define a table.
1501 | Name | Address | Birthday |
1502 |-------------+----------+-----------|
1503 | Arthur Dent | England | 29.2.2100 |
1505 In ASCII export, this option has no effect.
1507 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1511 (defcustom org-export-prefer-native-exporter-for-tables nil
1512 "Non-nil means, always export tables created with table.el natively.
1513 Natively means, use the HTML code generator in table.el.
1514 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1515 the table does not use row- or column-spanning). This has the
1516 advantage, that the automatic HTML conversions for math symbols and
1517 sub/superscripts can be applied. Org-mode's HTML generator is also
1522 (defcustom org-export-html-table-tag
1523 "<table border=1 cellspacing=0 cellpadding=6>"
1524 "The HTML tag used to start a table.
1525 This must be a <table> tag, but you may change the options like
1526 borders and spacing."
1530 (defcustom org-export-with-emphasize t
1531 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1532 If the export target supports emphasizing text, the word will be
1533 typeset in bold, italic, or underlined, respectively. Works only for
1534 single words, but you can say: I *really* *mean* *this*.
1535 In ASCII export, this option has no effect.
1537 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1541 (defcustom org-match-sexp-depth 3
1542 "Number of stacked braces for sub/superscript matching.
1543 This has to be set before loading org.el to be effective."
1547 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1548 (defcustom org-export-with-sub-superscripts t
1549 "Non-nil means, interpret \"_\" and \"^\" for export.
1550 When this option is turned on, you can use TeX-like syntax for sub- and
1551 superscripts. Several characters after \"_\" or \"^\" will be
1552 considered as a single item - so grouping with {} is normally not
1553 needed. For example, the following things will be parsed as single
1554 sub- or superscripts.
1556 10^24 or 10^tau several digits will be considered 1 item
1557 10^-12 or 10^-tau a leading sign with digits or a word
1558 x^2-y^3 will be read as x^2 - y^3, because items are
1559 terminated by almost any nonword/nondigit char.
1560 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1562 Still, ambiguity is possible - so when in doubt use {} to enclose the
1564 In ASCII export, this option has no effect.
1566 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1570 (defcustom org-export-with-TeX-macros t
1571 "Non-nil means, interpret simple TeX-like macros when exporting.
1572 For example, HTML export converts \\alpha to α and \\AA to Å.
1573 No only real TeX macros will work here, but the standard HTML entities
1574 for math can be used as macro names as well. For a list of supported
1575 names in HTML export, see the constant `org-html-entities'.
1576 In ASCII export, this option has no effect.
1578 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1582 (defcustom org-export-html-with-timestamp nil
1583 "If non-nil, write `org-export-html-html-helper-timestamp'
1584 into the exported html text. Otherwise, the buffer will just be saved
1589 (defcustom org-export-html-html-helper-timestamp
1590 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1591 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1595 (defcustom org-export-ascii-show-new-buffer t
1596 "Non-nil means, popup buffer containing the exported ASCII text.
1597 Otherwise the buffer will just be saved to a file and stay hidden."
1601 (defcustom org-export-html-show-new-buffer nil
1602 "Non-nil means, popup buffer containing the exported html text.
1603 Otherwise, the buffer will just be saved to a file and stay hidden."
1607 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1608 "The file name for the iCalendar file covering all agenda files.
1609 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1613 (defcustom org-icalendar-include-todo nil
1614 "Non-nil means, export to iCalendar files should also cover TODO items."
1618 (defcustom org-icalendar-combined-name "OrgMode"
1619 "Calendar name for the combined iCalendar representing all agenda files."
1623 (defgroup org-faces nil
1624 "Faces for highlighting in Org-mode."
1628 (defface org-level-1 ;; font-lock-function-name-face
1629 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1630 (((class color) (background light)) (:foreground "Blue"))
1631 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1632 (t (:inverse-video t :bold t)))
1633 "Face used for level 1 headlines."
1636 (defface org-level-2 ;; font-lock-variable-name-face
1637 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1638 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1639 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1640 (t (:bold t :italic t)))
1641 "Face used for level 2 headlines."
1644 (defface org-level-3 ;; font-lock-keyword-face
1645 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1646 (((class color) (background light)) (:foreground "Purple"))
1647 (((class color) (background dark)) (:foreground "Cyan"))
1649 "Face used for level 3 headlines."
1652 (defface org-level-4 ;; font-lock-comment-face
1653 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1654 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1655 (((class color) (background light)) (:foreground "Firebrick"))
1656 (((class color) (background dark)) (:foreground "chocolate1"))
1657 (t (:bold t :italic t)))
1658 "Face used for level 4 headlines."
1661 (defface org-level-5 ;; font-lock-type-face
1662 '((((type tty) (class color)) (:foreground "green"))
1663 (((class color) (background light)) (:foreground "ForestGreen"))
1664 (((class color) (background dark)) (:foreground "PaleGreen"))
1665 (t (:bold t :underline t)))
1666 "Face used for level 5 headlines."
1669 (defface org-level-6 ;; font-lock-constant-face
1670 '((((type tty) (class color)) (:foreground "magenta"))
1671 (((class color) (background light)) (:foreground "CadetBlue"))
1672 (((class color) (background dark)) (:foreground "Aquamarine"))
1673 (t (:bold t :underline t)))
1674 "Face used for level 6 headlines."
1677 (defface org-level-7 ;; font-lock-builtin-face
1678 '((((type tty) (class color)) (:foreground "blue" :weight light))
1679 (((class color) (background light)) (:foreground "Orchid"))
1680 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1682 "Face used for level 7 headlines."
1685 (defface org-level-8 ;; font-lock-string-face
1686 '((((type tty) (class color)) (:foreground "green"))
1687 (((class color) (background light)) (:foreground "RosyBrown"))
1688 (((class color) (background dark)) (:foreground "LightSalmon"))
1690 "Face used for level 8 headlines."
1693 (defface org-special-keyword ;; font-lock-string-face
1694 '((((type tty) (class color)) (:foreground "green"))
1695 (((class color) (background light)) (:foreground "RosyBrown"))
1696 (((class color) (background dark)) (:foreground "LightSalmon"))
1698 "Face used for level 8 headlines."
1701 (defface org-warning ;; font-lock-warning-face
1702 '((((type tty) (class color)) (:foreground "red"))
1703 (((class color) (background light)) (:foreground "Red" :bold t))
1704 (((class color) (background dark)) (:foreground "Red1" :bold t))
1705 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1706 (t (:inverse-video t :bold t)))
1707 "Face for deadlines and TODO keywords."
1710 (defcustom org-fontify-done-headline nil
1711 "Non-nil means, change the face of a headline if it is marked DONE.
1712 Normally, only the TODO/DONE keyword indicates the state of a headline.
1713 When this is non-nil, the headline after the keyword is set to the
1714 `org-headline-done' as an additional indication."
1718 (defface org-headline-done ;; font-lock-string-face
1719 '((((type tty) (class color)) (:foreground "green"))
1720 (((class color) (background light)) (:foreground "RosyBrown"))
1721 (((class color) (background dark)) (:foreground "LightSalmon"))
1723 "Face used to indicate that a headline is DONE. See also the variable
1724 `org-fontify-done-headline'."
1727 ;; Inheritance does not yet work for xemacs. So we just copy...
1729 (defface org-deadline-announce
1730 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1731 (((class color) (background light)) (:foreground "Blue"))
1732 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1733 (t (:inverse-video t :bold t)))
1734 "Face for upcoming deadlines."
1737 (defface org-scheduled-today
1738 '((((type tty) (class color)) (:foreground "green"))
1739 (((class color) (background light)) (:foreground "DarkGreen"))
1740 (((class color) (background dark)) (:foreground "PaleGreen"))
1741 (t (:bold t :underline t)))
1742 "Face for items scheduled for a certain day."
1745 (defface org-scheduled-previously
1746 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1747 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1748 (((class color) (background light)) (:foreground "Firebrick"))
1749 (((class color) (background dark)) (:foreground "chocolate1"))
1750 (t (:bold t :italic t)))
1751 "Face for items scheduled previously, and not yet done."
1754 (defface org-formula
1755 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1756 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1757 (((class color) (background light)) (:foreground "Firebrick"))
1758 (((class color) (background dark)) (:foreground "chocolate1"))
1759 (t (:bold t :italic t)))
1760 "Face for items scheduled previously, and not yet done."
1764 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1765 (((class color) (background light)) (:foreground "Purple"))
1766 (((class color) (background dark)) (:foreground "Cyan"))
1771 (defface org-done ;; font-lock-type-face
1772 '((((type tty) (class color)) (:foreground "green"))
1773 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1774 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1775 (t (:bold t :underline t)))
1776 "Face used for DONE."
1779 (defface org-table ;; font-lock-function-name-face
1780 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1781 (((class color) (background light)) (:foreground "Blue"))
1782 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1783 (t (:inverse-video t :bold t)))
1784 "Face used for tables."
1787 (defface org-time-grid ;; font-lock-variable-name-face
1788 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1789 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1790 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1791 (t (:bold t :italic t)))
1792 "Face used for level 2 headlines."
1795 (defvar org-level-faces
1806 (defvar org-n-levels (length org-level-faces))
1808 (defun org-set-regexps-and-options ()
1809 "Precompute regular expressions for current buffer."
1810 (when (eq major-mode 'org-mode)
1811 (let ((re (org-make-options-regexp
1812 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1813 "STARTUP" "ARCHIVE")))
1815 kwds int key value cat arch)
1819 (goto-char (point-min))
1820 (while (re-search-forward re nil t)
1821 (setq key (match-string 1) value (match-string 2))
1823 ((equal key "CATEGORY")
1824 (if (string-match "[ \t]+$" value)
1825 (setq value (replace-match "" t t value)))
1826 (setq cat (intern value)))
1827 ((equal key "SEQ_TODO")
1829 kwds (append kwds (org-split-string value splitre))))
1830 ((equal key "PRI_TODO")
1832 kwds (append kwds (org-split-string value splitre))))
1833 ((equal key "TYP_TODO")
1835 kwds (append kwds (org-split-string value splitre))))
1836 ((equal key "STARTUP")
1837 (let ((opts (org-split-string value splitre))
1838 (set '(("fold" org-startup-folded t)
1839 ("nofold" org-startup-folded nil)
1840 ("content" org-startup-folded content)
1841 ("dlcheck" org-startup-with-deadline-check t)
1842 ("nodlcheck" org-startup-with-deadline-check nil)))
1844 (while (setq l (assoc (pop opts) set))
1845 (setq var (nth 1 l) val (nth 2 l))
1846 (set (make-local-variable var) val))))
1847 ((equal key "ARCHIVE")
1848 (string-match " *$" value)
1849 (setq arch (replace-match "" t t value))
1850 (remove-text-properties 0 (length arch)
1851 '(face t fontified t) arch)))
1853 (and cat (set (make-local-variable 'org-category) cat))
1854 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
1855 (and arch (set (make-local-variable 'org-archive-location) arch))
1856 (and int (set (make-local-variable 'org-todo-interpretation) int)))
1857 ;; Compute the regular expressions and other local variables
1858 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
1859 org-todo-kwd-max-priority (1- (length org-todo-keywords))
1860 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
1861 (length org-scheduled-string)))
1863 (nth (1- (length org-todo-keywords)) org-todo-keywords)
1865 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
1869 (mapconcat 'regexp-quote
1870 (nreverse (cdr (reverse org-todo-keywords)))
1873 org-todo-line-regexp
1874 (concat "^\\(\\*+\\)[ \t]*\\("
1875 (mapconcat 'regexp-quote org-todo-keywords "\\|")
1878 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
1879 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
1880 org-deadline-regexp (concat "\\<" org-deadline-string)
1881 org-deadline-time-regexp
1882 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
1883 org-deadline-line-regexp
1884 (concat "\\<\\(" org-deadline-string "\\).*")
1885 org-scheduled-regexp
1886 (concat "\\<" org-scheduled-string)
1887 org-scheduled-time-regexp
1888 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
1889 (org-set-font-lock-defaults)))
1891 ;; Tell the compiler about dynamically scoped variables,
1892 ;; and variables from other packages
1894 (defvar zmacs-regions)
1895 (defvar original-date)
1896 (defvar org-transient-mark-mode)
1897 (defvar org-old-auto-fill-inhibit-regexp)
1898 (defvar orgtbl-mode-menu)
1899 (defvar org-html-entities)
1900 (defvar org-goto-start-pos)
1901 (defvar org-cursor-color)
1902 (defvar org-time-was-given)
1903 (defvar org-ts-what)
1904 (defvar mark-active)
1906 (defvar levels-open)
1917 (defvar starting-day)
1918 (defvar include-all-loc)
1919 (defvar vm-message-pointer)
1920 (defvar vm-folder-directory)
1921 (defvar wl-summary-buffer-elmo-folder)
1922 (defvar wl-summary-buffer-folder-name)
1923 (defvar gnus-group-name)
1924 (defvar gnus-article-current)
1925 (defvar w3m-current-url)
1926 (defvar org-selected-point)
1927 (defvar calendar-mode-map)
1928 (defvar remember-save-after-remembering)
1929 (defvar remember-data-file))
1934 (defvar org-mode-map (copy-keymap outline-mode-map)
1935 "Keymap for Org-mode.")
1937 (defvar org-struct-menu)
1938 (defvar org-org-menu)
1939 (defvar org-tbl-menu)
1941 ;; We use a before-change function to check if a table might need
1943 (defvar org-table-may-need-update t
1944 "Indicates of a table might need an update.
1945 This variable is set by `org-before-change-function'. `org-table-align'
1946 sets it back to nil.")
1947 (defvar org-mode-hook nil)
1948 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1949 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
1953 (define-derived-mode org-mode outline-mode "Org"
1954 "Outline-based notes management and organizer, alias
1955 \"Carstens outline-mode for keeping track of everything.\"
1957 Org-mode develops organizational tasks around a NOTES file which
1958 contains information about projects as plain text. Org-mode is
1959 implemented on top of outline-mode, which is ideal to keep the content
1960 of large files well structured. It supports ToDo items, deadlines and
1961 time stamps, which magically appear in the diary listing of the Emacs
1962 calendar. Tables are easily created with a built-in table editor.
1963 Plain text URL-like links connect to websites, emails (VM), Usenet
1964 messages (Gnus), BBDB entries, and any files related to the project.
1965 For printing and sharing of notes, an Org-mode file (or a part of it)
1966 can be exported as a structured ASCII or HTML file.
1968 The following commands are available:
1971 (easy-menu-add org-org-menu)
1972 (easy-menu-add org-tbl-menu)
1973 (org-install-agenda-files-menu)
1974 (setq outline-regexp "\\*+")
1975 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
1976 (setq outline-level 'org-outline-level)
1977 (if org-startup-truncated (setq truncate-lines t))
1978 (org-set-regexps-and-options)
1979 (set (make-local-variable 'font-lock-unfontify-region-function)
1980 'org-unfontify-region)
1981 ;; Activate before-change-function
1982 (set (make-local-variable 'org-table-may-need-update) t)
1983 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1984 (add-hook 'before-change-functions 'org-before-change-function nil
1986 ;; FIXME: The following does not work because isearch-mode-end-hook
1987 ;; is called *before* the visibility overlays as removed.
1988 ;; There should be another hook then for me to be used.
1989 ;; (make-local-hook 'isearch-mode-end-hook) ;; needed for XEmacs
1990 ;; (add-hook 'isearch-mode-end-hook 'org-show-hierarchy-above nil
1992 ;; Paragraphs and auto-filling
1993 (org-set-autofill-regexps)
1994 ;; Settings for Calc embedded mode
1995 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
1996 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
1997 (if (and org-insert-mode-line-in-empty-file
1999 (= (point-min) (point-max)))
2000 (insert " -*- mode: org -*-\n\n"))
2002 ;; Get rid of Outline menus, they are not needed
2003 ;; Need to do this here because define-derived-mode sets up
2004 ;; the keymap so late.
2007 (delete-menu-item '("Headings"))
2008 (delete-menu-item '("Show"))
2009 (delete-menu-item '("Hide"))
2010 (set-menubar-dirty-flag))
2011 (define-key org-mode-map [menu-bar headings] 'undefined)
2012 (define-key org-mode-map [menu-bar hide] 'undefined)
2013 (define-key org-mode-map [menu-bar show] 'undefined))
2015 (unless org-inhibit-startup
2016 (if org-startup-with-deadline-check
2017 (call-interactively 'org-check-deadlines)
2019 ((eq org-startup-folded t)
2021 ((eq org-startup-folded 'content)
2022 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2023 (org-cycle '(4)) (org-cycle '(4))))))))
2025 (defsubst org-current-line (&optional pos)
2026 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2029 ;; FIXME: Do we need to copy?
2030 (defun org-string-props (string &rest properties)
2031 "Add PROPERTIES to string."
2032 (add-text-properties 0 (length string) properties string)
2037 (defvar org-mouse-map (make-sparse-keymap))
2038 (define-key org-mouse-map
2039 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2040 (define-key org-mouse-map
2041 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2042 (when org-tab-follows-link
2043 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2044 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2045 (when org-return-follows-link
2046 (define-key org-mouse-map [(return)] 'org-open-at-point)
2047 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2049 (require 'font-lock)
2051 (defconst org-non-link-chars "\t\n\r|<>\000")
2052 (defconst org-link-regexp
2053 (if org-allow-space-in-links
2055 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2057 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2059 "Regular expression for matching links.")
2060 (defconst org-link-maybe-angles-regexp
2061 (concat "<?\\(" org-link-regexp "\\)>?")
2062 "Matches a link and optionally surrounding angle brackets.")
2063 (defconst org-protected-link-regexp
2064 (concat "\000" org-link-regexp "\000")
2065 "Matches a link and optionally surrounding angle brackets.")
2067 (defconst org-ts-lengths
2068 (cons (length (format-time-string (car org-time-stamp-formats)))
2069 (length (format-time-string (cdr org-time-stamp-formats))))
2070 "This holds the lengths of the two different time formats.")
2071 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2072 "Regular expression for fast time stamp matching.")
2073 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2074 "Regular expression for fast time stamp matching.")
2075 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2076 "Regular expression matching time strings for analysis.")
2077 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2078 "Regular expression matching time stamps, with groups.")
2079 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2080 "Regular expression matching a time stamp range.")
2081 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2082 org-ts-regexp "\\)?")
2083 "Regular expression matching a time stamp or time stamp range.")
2085 (defun org-activate-links (limit)
2086 "Run through the buffer and add overlays to links."
2087 (if (re-search-forward org-link-regexp limit t)
2089 (add-text-properties (match-beginning 0) (match-end 0)
2090 (list 'mouse-face 'highlight
2091 'keymap org-mouse-map))
2094 (defun org-activate-dates (limit)
2095 "Run through the buffer and add overlays to dates."
2096 (if (re-search-forward org-tsr-regexp limit t)
2098 (add-text-properties (match-beginning 0) (match-end 0)
2099 (list 'mouse-face 'highlight
2100 'keymap org-mouse-map))
2103 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2104 "Matches CamelCase words, possibly with a star before it.")
2105 (defun org-activate-camels (limit)
2106 "Run through the buffer and add overlays to dates."
2107 (if (re-search-forward org-camel-regexp limit t)
2109 (add-text-properties (match-beginning 0) (match-end 0)
2110 (list 'mouse-face 'highlight
2111 'keymap org-mouse-map))
2114 (defun org-activate-tags (limit)
2115 (if (re-search-forward "[ \t]\\(:[A-Za-z_:]+:\\)[ \r\n]" limit t)
2117 (add-text-properties (match-beginning 1) (match-end 1)
2118 (list 'mouse-face 'highlight
2119 'keymap org-mouse-map))
2122 (defun org-font-lock-level ()
2124 (org-back-to-heading t)
2125 (- (match-end 0) (match-beginning 0))))
2127 (defun org-outline-level ()
2129 (looking-at outline-regexp)
2130 (if (match-beginning 1)
2131 (+ (org-get-string-indentation (match-string 1)) 1000)
2132 (- (match-end 0) (match-beginning 0)))))
2134 (defvar org-font-lock-keywords nil)
2136 (defun org-set-font-lock-defaults ()
2137 (let ((org-font-lock-extra-keywords
2139 '(org-activate-links (0 'org-link t))
2140 '(org-activate-dates (0 'org-link t))
2141 '(org-activate-camels (0 'org-link t))
2142 '(org-activate-tags (1 'org-link t))
2143 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2144 '(1 'org-warning t))
2145 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2146 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2147 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2148 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2149 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2151 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2153 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2155 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
2156 ; '(1 'org-warning t))
2157 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2158 "\\|" org-quote-string "\\)\\>")
2159 '(1 'org-special-keyword t))
2160 '("^#.*" (0 'font-lock-comment-face t))
2161 (if org-fontify-done-headline
2162 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2163 '(1 'org-done t) '(2 'org-headline-done t))
2164 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2166 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2168 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2169 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2170 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2172 (set (make-local-variable 'org-font-lock-keywords)
2174 (if org-noutline-p ; FIXME: I am not sure if eval will work
2175 ; on XEmacs if noutline is ever ported
2176 `((eval . (list "^\\(\\*+\\).*"
2177 ,(if org-level-color-stars-only 1 0)
2179 (% (- (match-end 1) (match-beginning 1) 1)
2183 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2184 (,(if org-level-color-stars-only 2 0)
2185 (nth (% (- (match-end 2) (match-beginning 2) 1)
2189 org-font-lock-extra-keywords))
2190 (set (make-local-variable 'font-lock-defaults)
2191 '(org-font-lock-keywords t nil nil backward-paragraph))
2192 (kill-local-variable 'font-lock-keywords) nil))
2194 (defun org-unfontify-region (beg end &optional maybe_loudly)
2195 "Remove fontification and activation overlays from links."
2196 (font-lock-default-unfontify-region beg end)
2197 (let* ((buffer-undo-list t)
2198 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2199 (inhibit-modification-hooks t)
2200 deactivate-mark buffer-file-name buffer-file-truename)
2201 (remove-text-properties beg end '(mouse-face nil keymap nil))))
2203 ;;; Visibility cycling
2205 (defvar org-cycle-global-status nil)
2206 (defvar org-cycle-subtree-status nil)
2207 (defun org-cycle (&optional arg)
2208 "Visibility cycling for Org-mode.
2210 - When this function is called with a prefix argument, rotate the entire
2211 buffer through 3 states (global cycling)
2212 1. OVERVIEW: Show only top-level headlines.
2213 2. CONTENTS: Show all headlines of all levels, but no body text.
2214 3. SHOW ALL: Show everything.
2216 - When point is at the beginning of a headline, rotate the subtree started
2217 by this line through 3 different states (local cycling)
2218 1. FOLDED: Only the main headline is shown.
2219 2. CHILDREN: The main headline and the direct children are shown. From
2220 this state, you can move to one of the children and
2222 3. SUBTREE: Show the entire subtree, including body text.
2224 - When there is a numeric prefix, go up to a heading with level ARG, do
2225 a `show-subtree' and return to the previous cursor position. If ARG
2226 is negative, go up that many levels.
2228 - When point is not at the beginning of a headline, execute
2229 `indent-relative', like TAB normally does. See the option
2230 `org-cycle-emulate-tab' for details.
2232 - Special case: if point is the the beginning of the buffer and there is
2233 no headline in line 1, this function will act as if called with prefix arg."
2236 (if (or (and (bobp) (not (looking-at outline-regexp)))
2238 ;; special case: use global cycling
2241 (let ((outline-regexp
2242 (if org-cycle-include-plain-lists
2243 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2248 ((org-at-table-p 'any)
2249 ;; Enter the table or move to the next field in the table
2250 (or (org-table-recognize-table.el)
2252 (org-table-justify-field-maybe)
2253 (org-table-next-field))))
2255 ((eq arg t) ;; Global cycling
2258 ((and (eq last-command this-command)
2259 (eq org-cycle-global-status 'overview))
2260 ;; We just created the overview - now do table of contents
2261 ;; This can be slow in very large buffers, so indicate action
2262 (message "CONTENTS...")
2264 ;; Visit all headings and show their offspring
2265 (goto-char (point-max))
2267 (while (and (progn (condition-case nil
2268 (outline-previous-visible-heading 1)
2269 (error (goto-char (point-min))))
2271 (looking-at outline-regexp))
2273 (if (bobp) (throw 'exit nil))))
2274 (message "CONTENTS...done"))
2275 (setq org-cycle-global-status 'contents)
2276 (run-hook-with-args 'org-cycle-hook 'contents))
2278 ((and (eq last-command this-command)
2279 (eq org-cycle-global-status 'contents))
2280 ;; We just showed the table of contents - now show everything
2282 (message "SHOW ALL")
2283 (setq org-cycle-global-status 'all)
2284 (run-hook-with-args 'org-cycle-hook 'all))
2287 ;; Default action: go to overview
2289 (message "OVERVIEW")
2290 (setq org-cycle-global-status 'overview)
2291 (run-hook-with-args 'org-cycle-hook 'overview))))
2294 ;; Show-subtree, ARG levels up from here.
2296 (org-back-to-heading)
2297 (outline-up-heading (if (< arg 0) (- arg)
2298 (- (outline-level) arg)))
2299 (org-show-subtree)))
2301 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2302 ;; At a heading: rotate between three different views
2303 (org-back-to-heading)
2304 (let ((goal-column 0) eoh eol eos)
2305 ;; First, some boundaries
2307 (org-back-to-heading)
2309 (beginning-of-line 2)
2310 (while (and (not (eobp)) ;; this is like `next-line'
2311 (get-char-property (1- (point)) 'invisible))
2312 (beginning-of-line 2)) (setq eol (point)))
2313 (outline-end-of-heading) (setq eoh (point))
2314 (org-end-of-subtree t) (setq eos (point))
2315 (outline-next-heading))
2316 ;; Find out what to do next and set `this-command'
2319 ;; Nothing is hidden behind this heading
2320 (message "EMPTY ENTRY")
2321 (setq org-cycle-subtree-status nil))
2323 ;; Entire subtree is hidden in one line: open it
2326 (message "CHILDREN")
2327 (setq org-cycle-subtree-status 'children)
2328 (run-hook-with-args 'org-cycle-hook 'children))
2329 ((and (eq last-command this-command)
2330 (eq org-cycle-subtree-status 'children))
2331 ;; We just showed the children, now show everything.
2334 (setq org-cycle-subtree-status 'subtree)
2335 (run-hook-with-args 'org-cycle-hook 'subtree))
2337 ;; Default action: hide the subtree.
2340 (setq org-cycle-subtree-status 'folded)
2341 (run-hook-with-args 'org-cycle-hook 'folded)))))
2344 (buffer-read-only (org-back-to-heading))
2345 ((if (and (eq org-cycle-emulate-tab 'white)
2346 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2348 (eq org-cycle-emulate-tab t))
2349 (if (and (looking-at "[ \n\r\t]")
2350 (string-match "^[ \t]*$" (buffer-substring
2351 (point-at-bol) (point))))
2353 (beginning-of-line 1)
2354 (and (looking-at "[ \t]+") (replace-match ""))))
2358 (org-back-to-heading)
2361 (defun org-optimize-window-after-visibility-change (state)
2362 "Adjust the window after a change in outline visibility.
2363 This function is the default value of the hook `org-cycle-hook'."
2365 ((eq state 'overview) (org-first-headline-recenter 1))
2366 ((eq state 'content) nil)
2367 ((eq state 'all) nil)
2368 ((eq state 'folded) nil)
2369 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2370 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2372 (defun org-subtree-end-visible-p ()
2373 "Is the end of the current subtree visible?"
2374 (pos-visible-in-window-p
2375 (save-excursion (org-end-of-subtree t) (point))))
2377 (defun org-first-headline-recenter (&optional N)
2378 "Move cursor to the first headline and recenter the headline.
2379 Optional argument N means, put the headline into the Nth line of the window."
2380 (goto-char (point-min))
2381 (when (re-search-forward (concat "^" outline-regexp) nil t)
2383 (recenter (prefix-numeric-value N))))
2385 (defvar org-goto-window-configuration nil)
2386 (defvar org-goto-marker nil)
2387 (defvar org-goto-map (make-sparse-keymap))
2388 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2389 (while (setq cmd (pop cmds))
2390 (substitute-key-definition cmd cmd org-goto-map global-map)))
2391 (define-key org-goto-map "\C-m" 'org-goto-ret)
2392 (define-key org-goto-map [(left)] 'org-goto-left)
2393 (define-key org-goto-map [(right)] 'org-goto-right)
2394 (define-key org-goto-map [(?q)] 'org-goto-quit)
2395 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2396 (define-key org-goto-map "\C-i" 'org-cycle)
2397 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2398 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2399 (define-key org-goto-map "n" 'outline-next-visible-heading)
2400 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2401 (define-key org-goto-map "f" 'outline-forward-same-level)
2402 (define-key org-goto-map "b" 'outline-backward-same-level)
2403 (define-key org-goto-map "u" 'outline-up-heading)
2404 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2405 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2406 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2407 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2408 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2409 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2410 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2412 (defconst org-goto-help
2413 "Select a location to jump to, press RET
2414 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2417 "Go to a different location of the document, keeping current visibility.
2419 When you want to go to a different location in a document, the fastest way
2420 is often to fold the entire buffer and then dive into the tree. This
2421 method has the disadvantage, that the previous location will be folded,
2422 which may not be what you want.
2424 This command works around this by showing a copy of the current buffer in
2425 overview mode. You can dive into the tree in that copy, to find the
2426 location you want to reach. When pressing RET, the command returns to the
2427 original buffer in which the visibility is still unchanged. It then jumps
2428 to the new location, making it and the headline hierarchy above it visible."
2430 (let* ((org-goto-start-pos (point))
2432 (org-get-location (current-buffer) org-goto-help)))
2435 (goto-char selected-point)
2436 (if (org-invisible-p) (org-show-hierarchy-above)))
2439 (defun org-get-location (buf help)
2440 "Let the user select a location in the Org-mode buffer BUF.
2441 This function uses a recursive edit. It returns the selected position
2443 (let (org-selected-point)
2445 (save-window-excursion
2446 (delete-other-windows)
2447 (switch-to-buffer (get-buffer-create "*org-goto*"))
2448 (with-output-to-temp-buffer "*Help*"
2450 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2451 (setq buffer-read-only nil)
2453 (insert-buffer-substring buf)
2454 (let ((org-startup-truncated t)
2455 (org-startup-folded t)
2456 (org-startup-with-deadline-check nil))
2458 (setq buffer-read-only t)
2459 (if (boundp 'org-goto-start-pos)
2460 (goto-char org-goto-start-pos)
2461 (goto-char (point-min)))
2462 (org-beginning-of-line)
2463 (message "Select location and press RET")
2464 ;; now we make sure that during selection, ony very few keys work
2465 ;; and that it is impossible to switch to another window.
2466 (let ((gm (current-global-map))
2467 (overriding-local-map org-goto-map))
2470 (use-global-map org-goto-map)
2472 (use-global-map gm)))))
2473 (kill-buffer "*org-goto*")
2474 org-selected-point))
2476 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2477 (defun org-goto-ret (&optional arg)
2478 "Finish org-goto by going to the new location."
2480 (setq org-selected-point (point)
2481 current-prefix-arg arg)
2484 (defun org-goto-left ()
2485 "Finish org-goto by going to the new location."
2487 (if (org-on-heading-p)
2489 (beginning-of-line 1)
2490 (setq org-selected-point (point)
2491 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2493 (error "Not on a heading")))
2495 (defun org-goto-right ()
2496 "Finish org-goto by going to the new location."
2498 (if (org-on-heading-p)
2500 (outline-end-of-subtree)
2501 (or (eobp) (forward-char 1))
2502 (setq org-selected-point (point)
2503 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2505 (error "Not on a heading")))
2507 (defun org-goto-quit ()
2508 "Finish org-goto without cursor motion."
2510 (setq org-selected-point nil)
2513 ;;; Promotion, Demotion, Inserting new headlines
2515 (defvar org-ignore-region nil
2516 "To temporarily disable the active region.")
2518 (defun org-insert-heading (&optional force-heading)
2519 "Insert a new heading or item with same depth at point.
2522 (when (or force-heading (not (org-insert-item)))
2523 (let* ((head (save-excursion
2525 (org-back-to-heading)
2526 (error (outline-next-heading)))
2527 (prog1 (match-string 0)
2528 (funcall outline-level)))))
2529 (unless (bolp) (newline))
2532 (save-excursion (newline-and-indent)))
2533 (unless (equal (char-before) ?\ )
2535 (run-hooks 'org-insert-heading-hook))))
2537 (defun org-insert-item ()
2538 "Insert a new item at the current level.
2539 Return t when tings worked, nil when we are not in an item."
2540 (when (save-excursion
2543 (org-beginning-of-item)
2547 (unless (bolp) (newline))
2548 (insert (match-string 0))
2549 (org-maybe-renumber-ordered-list)
2552 (defun org-insert-todo-heading (arg)
2553 "Insert a new heading with the same level and TODO state as current heading.
2554 If the heading has no TODO state, or if the state is DONE, use the first
2555 state (TODO by default). Also with prefix arg, force first state."
2557 (org-insert-heading)
2559 (org-back-to-heading)
2560 (outline-previous-heading)
2561 (looking-at org-todo-line-regexp))
2563 (not (match-beginning 2))
2564 (equal (match-string 2) org-done-string))
2565 (insert (car org-todo-keywords) " ")
2566 (insert (match-string 2) " ")))
2568 (defun org-promote-subtree ()
2569 "Promote the entire subtree.
2570 See also `org-promote'."
2573 (org-map-tree 'org-promote)))
2575 (defun org-demote-subtree ()
2576 "Demote the entire subtree. See `org-demote'.
2577 See also `org-promote'."
2580 (org-map-tree 'org-demote)))
2582 (defun org-do-promote ()
2583 "Promote the current heading higher up the tree.
2584 If the region is active in `transient-mark-mode', promote all headings
2588 (if (org-region-active-p)
2589 (org-map-region 'org-promote (region-beginning) (region-end))
2591 (org-fix-position-after-promote))
2593 (defun org-do-demote ()
2594 "Demote the current heading lower down the tree.
2595 If the region is active in `transient-mark-mode', demote all headings
2599 (if (org-region-active-p)
2600 (org-map-region 'org-demote (region-beginning) (region-end))
2602 (org-fix-position-after-promote))
2604 (defun org-fix-position-after-promote ()
2605 "Make sure that after pro/demotion cursor position is right."
2606 (and (equal (char-after) ?\ )
2607 (equal (char-before) ?*)
2610 (defun org-promote ()
2611 "Promote the current heading higher up the tree.
2612 If the region is active in `transient-mark-mode', promote all headings
2614 (org-back-to-heading t)
2615 (let* ((level (save-match-data (funcall outline-level)))
2616 (up-head (make-string (1- level) ?*)))
2617 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2618 (replace-match up-head nil t)
2619 ;; Fixup tag positioning
2620 (and org-auto-align-tags (org-set-tags nil t))
2621 (if org-adapt-indentation
2622 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2624 (defun org-demote ()
2625 "Demote the current heading lower down the tree.
2626 If the region is active in `transient-mark-mode', demote all headings
2628 (org-back-to-heading t)
2629 (let* ((level (save-match-data (funcall outline-level)))
2630 (down-head (make-string (1+ level) ?*)))
2631 (replace-match down-head nil t)
2632 ;; Fixup tag positioning
2633 (and org-auto-align-tags (org-set-tags nil t))
2634 (if org-adapt-indentation
2635 (org-fixup-indentation "^ " " " "^\\S-"))))
2637 (defun org-map-tree (fun)
2638 "Call FUN for every heading underneath the current one."
2639 (org-back-to-heading)
2640 (let ((level (outline-level)))
2644 (outline-next-heading)
2645 (> (funcall outline-level) level))
2649 (defun org-map-region (fun beg end)
2650 "Call FUN for every heading between BEG and END."
2651 (let ((org-ignore-region t))
2653 (setq end (copy-marker end))
2655 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2659 (outline-next-heading)
2664 (defun org-fixup-indentation (from to prohibit)
2665 "Change the indentation in the current entry by re-replacing FROM with TO.
2666 However, if the regexp PROHIBIT matches at all, don't do anything.
2667 This is being used to change indentation along with the length of the
2668 heading marker. But if there are any lines which are not indented, nothing
2671 (let ((end (save-excursion (outline-next-heading)
2673 (unless (save-excursion (re-search-forward prohibit end t))
2674 (while (re-search-forward from end t)
2676 (beginning-of-line 2)))
2677 (move-marker end nil))))
2679 ;;; Vertical tree motion, cutting and pasting of subtrees
2681 (defun org-move-subtree-up (&optional arg)
2682 "Move the current subtree up past ARG headlines of the same level."
2684 (org-move-subtree-down (- (prefix-numeric-value arg))))
2686 (defun org-move-subtree-down (&optional arg)
2687 "Move the current subtree down past ARG headlines of the same level."
2689 (setq arg (prefix-numeric-value arg))
2690 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2691 'outline-get-last-sibling))
2692 (ins-point (make-marker))
2696 (org-back-to-heading)
2699 (save-excursion (outline-end-of-heading)
2700 (setq folded (org-invisible-p)))
2701 (outline-end-of-subtree))
2702 (outline-next-heading)
2704 ;; Find insertion point, with error handling
2707 (or (and (funcall movfunc) (looking-at outline-regexp))
2708 (progn (goto-char beg)
2709 (error "Cannot move past superior level or buffer limit")))
2710 (setq cnt (1- cnt)))
2712 ;; Moving forward - still need to move over subtree
2713 (progn (outline-end-of-subtree)
2714 (outline-next-heading)
2715 (if (not (or (looking-at (concat "^" outline-regexp))
2718 (move-marker ins-point (point))
2719 (setq txt (buffer-substring beg end))
2720 (delete-region beg end)
2722 (goto-char ins-point)
2723 (if folded (hide-subtree))
2724 (move-marker ins-point nil)))
2726 (defvar org-subtree-clip ""
2727 "Clipboard for cut and paste of subtrees.
2728 This is actually only a copy of the kill, because we use the normal kill
2729 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2731 (defvar org-subtree-clip-folded nil
2732 "Was the last copied subtree folded?
2733 This is used to fold the tree back after pasting.")
2735 (defun org-cut-subtree ()
2736 "Cut the current subtree into the clipboard.
2737 This is a short-hand for marking the subtree and then cutting it."
2739 (org-copy-subtree 'cut))
2741 (defun org-copy-subtree (&optional cut)
2742 "Cut the current subtree into the clipboard.
2743 This is a short-hand for marking the subtree and then copying it.
2744 If CUT is non nil, actually cut the subtree."
2746 (let (beg end folded)
2747 (org-back-to-heading)
2750 (save-excursion (outline-end-of-heading)
2751 (setq folded (org-invisible-p)))
2752 (outline-end-of-subtree))
2753 (if (equal (char-after) ?\n) (forward-char 1))
2757 (setq org-subtree-clip-folded folded)
2758 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2759 (setq org-subtree-clip (current-kill 0))
2760 (message "%s: Subtree with %d characters"
2761 (if cut "Cut" "Copied")
2762 (length org-subtree-clip)))))
2764 (defun org-paste-subtree (&optional level tree)
2765 "Paste the clipboard as a subtree, with modification of headline level.
2766 The entire subtree is promoted or demoted in order to match a new headline
2767 level. By default, the new level is derived from the visible headings
2768 before and after the insertion point, and taken to be the inferior headline
2769 level of the two. So if the previous visible heading is level 3 and the
2770 next is level 4 (or vice versa), level 4 will be used for insertion.
2771 This makes sure that the subtree remains an independent subtree and does
2772 not swallow low level entries.
2774 You can also force a different level, either by using a numeric prefix
2775 argument, or by inserting the heading marker by hand. For example, if the
2776 cursor is after \"*****\", then the tree will be shifted to level 5.
2778 If you want to insert the tree as is, just use \\[yank].
2780 If optional TREE is given, use this text instead of the kill ring."
2782 (unless (org-kill-is-subtree-p tree)
2784 (substitute-command-keys
2785 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2786 (let* ((txt (or tree (current-kill 0)))
2787 (^re (concat "^\\(" outline-regexp "\\)"))
2788 (re (concat "\\(" outline-regexp "\\)"))
2789 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2791 (old-level (if (string-match ^re txt)
2792 (- (match-end 0) (match-beginning 0))
2794 (force-level (cond (level (prefix-numeric-value level))
2796 ^re_ (buffer-substring (point-at-bol) (point)))
2797 (- (match-end 0) (match-beginning 0)))
2799 (previous-level (save-excursion
2802 (outline-previous-visible-heading 1)
2804 (- (match-end 0) (match-beginning 0))
2807 (next-level (save-excursion
2810 (outline-next-visible-heading 1)
2812 (- (match-end 0) (match-beginning 0))
2815 (new-level (or force-level (max previous-level next-level)))
2816 (shift (if (or (= old-level -1)
2818 (= old-level new-level))
2820 (- new-level old-level)))
2822 (delta (if (> shift 0) -1 1))
2823 (func (if (> shift 0) 'org-demote 'org-promote))
2825 ;; Remove the forces level indicator
2827 (delete-region (point-at-bol) (point)))
2828 ;; Make sure we start at the beginning of an empty line
2829 (if (not (bolp)) (insert "\n"))
2830 (if (not (looking-at "[ \t]*$"))
2831 (progn (insert "\n") (backward-char 1)))
2837 ;; Shift if necessary
2839 (message "Pasted at level %d, without shift" new-level)
2841 (narrow-to-region beg end)
2842 (while (not (= shift 0))
2843 (org-map-region func (point-min) (point-max))
2844 (setq shift (+ delta shift)))
2845 (goto-char (point-min))
2846 (message "Pasted at level %d, with shift by %d levels"
2848 (if (and (eq org-subtree-clip (current-kill 0))
2849 org-subtree-clip-folded)
2850 ;; The tree was folded before it was killed/copied
2853 (defun org-kill-is-subtree-p (&optional txt)
2854 "Check if the current kill is an outline subtree, or a set of trees.
2855 Returns nil if kill does not start with a headline, or if the first
2856 headline level is not the largest headline level in the tree.
2857 So this will actually accept several entries of equal levels as well,
2858 which is OK for `org-paste-subtree'.
2859 If optional TXT is given, check this string instead of the current kill."
2860 (let* ((kill (or txt (current-kill 0) ""))
2861 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2862 (- (match-end 0) (match-beginning 0))))
2863 (re (concat "^" outline-regexp))
2865 (if (not start-level)
2866 nil ;; does not even start with a heading
2868 (while (setq start (string-match re kill (1+ start)))
2869 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2873 ;;; Plain list items
2875 (defun org-at-item-p ()
2876 "Is point in a line starting a hand-formatted item?"
2877 (let ((llt org-plain-list-ordered-item-terminator))
2879 (goto-char (point-at-bol))
2882 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2883 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2884 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2885 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
2887 (defun org-get-indentation ()
2888 "Get the indentation of the current line, ionterpreting tabs."
2890 (beginning-of-line 1)
2891 (skip-chars-forward " \t")
2894 (defun org-beginning-of-item ()
2895 "Go to the beginning of the current hand-formatted item.
2896 If the cursor is not in an item, throw an error."
2898 (limit (save-excursion (org-back-to-heading)
2899 (beginning-of-line 2) (point)))
2902 (beginning-of-line 1)
2903 (beginning-of-line 1)
2904 (skip-chars-forward " \t")
2905 (setq ind (current-column))
2908 (beginning-of-line 0)
2909 (if (< (point) limit) (throw 'exit nil))
2910 (unless (looking-at " \t]*$")
2911 (skip-chars-forward " \t")
2912 (setq ind1 (current-column))
2914 (throw 'exit (org-at-item-p))))))
2917 (error "Not in an item")))))
2919 (defun org-end-of-item ()
2920 "Go to the beginning of the current hand-formatted item.
2921 If the cursor is not in an item, throw an error."
2923 (limit (save-excursion (outline-next-heading) (point)))
2924 (ind (save-excursion
2925 (org-beginning-of-item)
2926 (skip-chars-forward " \t")
2931 (beginning-of-line 2)
2932 (if (>= (point) limit) (throw 'exit t))
2933 (unless (looking-at "[ \t]*$")
2934 (skip-chars-forward " \t")
2935 (setq ind1 (current-column))
2936 (if (<= ind1 ind) (throw 'exit t)))))
2937 (beginning-of-line 1)
2939 (error "Not in an item"))))
2941 (defun org-move-item-down (arg)
2942 "Move the plain list item at point down, i.e. swap with following item.
2943 Subitems (items with larger indentation are considered part of the item,
2944 so this really moves item trees."
2946 (let (beg end ind ind1 (pos (point)) txt)
2947 (org-beginning-of-item)
2949 (setq ind (org-get-indentation))
2952 (setq ind1 (org-get-indentation))
2953 (if (and (org-at-item-p) (= ind ind1))
2956 (setq txt (buffer-substring beg end))
2958 (delete-region beg end))
2962 (org-maybe-renumber-ordered-list))
2964 (error "Cannot move this item further down"))))
2966 (defun org-move-item-up (arg)
2967 "Move the plain list item at point up, i.e. swap with previous item.
2968 Subitems (items with larger indentation are considered part of the item,
2969 so this really moves item trees."
2971 (let (beg end ind ind1 (pos (point)) txt)
2972 (org-beginning-of-item)
2974 (setq ind (org-get-indentation))
2980 (beginning-of-line 0)
2981 (if (looking-at "[ \t]*$")
2983 (if (<= (setq ind1 (org-get-indentation)) ind)
2986 (org-beginning-of-item)
2987 (error (goto-char beg)
2988 (error "Cannot move this item further up")))
2989 (setq ind1 (org-get-indentation))
2990 (if (and (org-at-item-p) (= ind ind1))
2992 (setq txt (buffer-substring beg end))
2994 (delete-region beg end))
2998 (org-maybe-renumber-ordered-list))
3000 (error "Cannot move this item further up"))))
3002 (defun org-maybe-renumber-ordered-list ()
3003 "Renumber the ordered list at point if setup allows it.
3004 This tests the user option `org-auto-renumber-ordered-lists' before
3005 doing the renumbering."
3006 (and org-auto-renumber-ordered-lists
3009 (org-renumber-ordered-list 1)))
3011 (defun org-get-string-indentation (s)
3012 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3013 (let ((n -1) (i 0) (w tab-width) c)
3015 (while (< (setq n (1+ n)) (length s))
3017 (cond ((= c ?\ ) (setq i (1+ i)))
3018 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3019 (t (throw 'exit t)))))
3022 (defun org-renumber-ordered-list (arg)
3023 "Renumber an ordered plain list.
3024 Cursor neext to be in the first line of an item, the line that starts
3025 with something like \"1.\" or \"2)\"."
3027 (unless (and (org-at-item-p)
3028 (match-beginning 3))
3029 (error "This is not an ordered list"))
3030 (let ((line (org-current-line))
3031 (col (current-column))
3032 (ind (org-get-string-indentation
3033 (buffer-substring (point-at-bol) (match-beginning 3))))
3034 ;; (term (substring (match-string 3) -1))
3036 ;; find where this list begins
3040 (beginning-of-line 0)
3041 (if (looking-at "[ \t]*$") (throw 'next t))
3042 (skip-chars-forward " \t") (setq ind1 (current-column))
3043 (if (or (< ind1 ind)
3045 (not (org-at-item-p))))
3047 ;; Walk forward and replace these numbers
3051 (beginning-of-line 2)
3052 (if (eobp) (throw 'exit nil))
3053 (if (looking-at "[ \t]*$") (throw 'next nil))
3054 (skip-chars-forward " \t") (setq ind1 (current-column))
3055 (if (> ind1 ind) (throw 'next t))
3056 (if (< ind1 ind) (throw 'exit t))
3057 (if (not (org-at-item-p)) (throw 'exit nil))
3058 (if (not (match-beginning 3))
3059 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3060 (delete-region (match-beginning 3) (1- (match-end 3)))
3061 (goto-char (match-beginning 3))
3062 (insert (format "%d" (setq n (1+ n)))))))
3064 (move-to-column col)))
3066 (defvar org-last-indent-begin-marker (make-marker))
3067 (defvar org-last-indent-end-marker (make-marker))
3070 (defun org-outdent-item (arg)
3071 "Outdent a local list item."
3073 (org-indent-item (- arg)))
3075 (defun org-indent-item (arg)
3076 "Indent a local list item."
3078 (unless (org-at-item-p)
3079 (error "Not on an item"))
3080 (let (beg end ind ind1)
3081 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3082 (setq beg org-last-indent-begin-marker
3083 end org-last-indent-end-marker)
3084 (org-beginning-of-item)
3085 (setq beg (move-marker org-last-indent-begin-marker (point)))
3087 (setq end (move-marker org-last-indent-end-marker (point))))
3089 (skip-chars-forward " \t") (setq ind (current-column))
3090 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3091 (while (< (point) end)
3092 (beginning-of-line 1)
3093 (skip-chars-forward " \t") (setq ind1 (current-column))
3094 (delete-region (point-at-bol) (point))
3095 (indent-to-column (+ ind1 arg))
3096 (beginning-of-line 2))
3101 (defun org-archive-subtree ()
3102 "Move the current subtree to the archive.
3103 The archive can be a certain top-level heading in the current file, or in
3104 a different file. The tree will be moved to that location, the subtree
3105 heading be marked DONE, and the current time will be added."
3107 ;; Save all relevant TODO keyword-relatex variables
3108 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3109 (tr-org-todo-keywords org-todo-keywords)
3110 (tr-org-todo-interpretation org-todo-interpretation)
3111 (tr-org-done-string org-done-string)
3112 (tr-org-todo-regexp org-todo-regexp)
3113 (tr-org-todo-line-regexp org-todo-line-regexp)
3114 (this-buffer (current-buffer))
3115 file heading buffer level newfile-p)
3116 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3118 (setq file (format (match-string 1 org-archive-location)
3119 (file-name-nondirectory (buffer-file-name)))
3120 heading (match-string 2 org-archive-location)))
3121 (error "Invalid `org-archive-location'"))
3122 (if (> (length file) 0)
3123 (setq newfile-p (not (file-exists-p file))
3124 buffer (find-file-noselect file))
3125 (setq buffer (current-buffer)))
3127 (error "Cannot access file \"%s\"" file))
3128 (if (and (> (length heading) 0)
3129 (string-match "^\\*+" heading))
3130 (setq level (match-end 0))
3131 (setq heading nil level 0))
3133 ;; We first only copy, in case something goes wrong
3134 ;; we need to protect this-command, to avoid kill-region sets it,
3135 ;; which would lead to duplication of subtrees
3136 (let (this-command) (org-copy-subtree))
3138 ;; Enforce org-mode for the archive buffer
3139 (if (not (eq major-mode 'org-mode))
3140 ;; Force the mode for future visits.
3141 (let ((org-insert-mode-line-in-empty-file t))
3142 (call-interactively 'org-mode)))
3144 (goto-char (point-max))
3145 (insert (format "\nArchived entries from file %s\n\n"
3146 (buffer-file-name this-buffer))))
3147 ;; Force the TODO keywords of the original buffer
3148 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3149 (org-todo-keywords tr-org-todo-keywords)
3150 (org-todo-interpretation tr-org-todo-interpretation)
3151 (org-done-string tr-org-done-string)
3152 (org-todo-regexp tr-org-todo-regexp)
3153 (org-todo-line-regexp tr-org-todo-line-regexp))
3154 (goto-char (point-min))
3157 (if (re-search-forward
3158 (concat "\\(^\\|\r\\)"
3159 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3161 (goto-char (match-end 0))
3162 ;; Heading not found, just insert it at the end
3163 (goto-char (point-max))
3164 (or (bolp) (insert "\n"))
3165 (insert "\n" heading "\n")
3167 ;; Make the heading visible, and the following as well
3168 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3169 (if (re-search-forward
3170 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3172 (progn (goto-char (match-beginning 0)) (insert "\n")
3173 (beginning-of-line 0))
3174 (goto-char (point-max)) (insert "\n")))
3175 (goto-char (point-max)) (insert "\n"))
3177 (org-paste-subtree (1+ level))
3178 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3179 (if org-archive-mark-done
3180 (org-todo (length org-todo-keywords)))
3181 ;; Move cursor to right after the TODO keyword
3182 (when org-archive-stamp-time
3183 (beginning-of-line 1)
3184 (looking-at org-todo-line-regexp)
3185 (goto-char (or (match-end 2) (match-beginning 3)))
3186 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3189 ;; Save the buffer, if it is not the same buffer.
3190 (if (not (eq this-buffer buffer)) (save-buffer))))
3191 ;; Here we are back in the original buffer. Everything seems to have
3192 ;; worked. So now cut the tree and finish up.
3193 (let (this-command) (org-cut-subtree))
3194 (if (looking-at "[ \t]*$") (kill-line))
3195 (message "Subtree archived %s"
3196 (if (eq this-buffer buffer)
3197 (concat "under heading: " heading)
3198 (concat "in file: " (abbreviate-file-name file))))))
3202 (defun org-complete (&optional arg)
3203 "Perform completion on word at point.
3204 At the beginning of a headline, this completes TODO keywords as given in
3205 `org-todo-keywords'.
3206 If the current word is preceded by a backslash, completes the TeX symbols
3207 that are supported for HTML support.
3208 If the current word is preceded by \"#+\", completes special words for
3209 setting file options.
3210 At all other locations, this simply calls `ispell-complete-word'."
3213 (let* ((end (point))
3214 (beg1 (save-excursion
3215 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3216 (skip-chars-backward "a-zA-Z_")
3218 (beg (save-excursion
3219 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3220 (skip-chars-backward "a-zA-Z0-9_:$")
3222 (camel (equal (char-before beg) ?*))
3223 (tag (equal (char-before beg1) ?:))
3224 (texp (equal (char-before beg) ?\\))
3225 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3228 (completion-ignore-case opt)
3235 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3236 (cons (match-string 2 x) (match-string 1 x)))
3237 (org-split-string (org-get-current-options) "\n")))
3241 ((string-match "\\`\\*+[ \t]*\\'"
3242 (buffer-substring (point-at-bol) beg))
3244 (mapcar 'list org-todo-keywords))
3248 (goto-char (point-min))
3249 (while (re-search-forward org-todo-line-regexp nil t)
3250 (push (list (org-make-org-heading-camel (match-string 3)))
3253 (tag (setq type :tag beg beg1)
3254 (org-get-buffer-tags))
3255 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3256 (pattern (buffer-substring-no-properties beg end))
3257 (completion (try-completion pattern table)))
3258 (cond ((eq completion t)
3259 (if (equal type :opt)
3260 (insert (substring (cdr (assoc (upcase pattern) table))
3261 (length pattern)))))
3263 (message "Can't find completion for \"%s\"" pattern)
3265 ((not (string= pattern completion))
3266 (delete-region beg end)
3267 (if (string-match " +$" completion)
3268 (setq completion (replace-match "" t t completion)))
3270 (if (get-buffer-window "*Completions*")
3271 (delete-window (get-buffer-window "*Completions*")))
3272 (if (assoc completion table)
3273 (if (eq type :todo) (insert " ")
3274 (if (eq type :tag) (insert ":"))))
3275 (if (and (equal type :opt) (assoc completion table))
3276 (message "%s" (substitute-command-keys
3277 "Press \\[org-complete] again to insert example settings"))))
3279 (message "Making completion list...")
3280 (let ((list (sort (all-completions pattern table) 'string<)))
3281 (with-output-to-temp-buffer "*Completions*"
3282 (display-completion-list list)))
3283 (message "Making completion list...%s" "done"))))))
3285 ;;; Comments, TODO and DEADLINE
3287 (defun org-toggle-comment ()
3288 "Change the COMMENT state of an entry."
3291 (org-back-to-heading)
3292 (if (looking-at (concat outline-regexp
3293 "\\( +\\<" org-comment-string "\\>\\)"))
3294 (replace-match "" t t nil 1)
3295 (if (looking-at outline-regexp)
3297 (goto-char (match-end 0))
3298 (insert " " org-comment-string))))))
3300 (defvar org-last-todo-state-is-todo nil
3301 "This is non-nil when the last TODO state change led to a TODO state.
3302 If the last change removed the TODO tag or switched to DONE, then
3305 (defun org-todo (&optional arg)
3306 "Change the TODO state of an item.
3307 The state of an item is given by a keyword at the start of the heading,
3309 *** TODO Write paper
3312 The different keywords are specified in the variable `org-todo-keywords'. By
3313 default the available states are \"TODO\" and \"DONE\".
3314 So for this example: when the item starts with TODO, it is changed to DONE.
3315 When it starts with DONE, the DONE is removed. And when neither TODO nor
3316 DONE are present, add TODO at the beginning of the heading.
3318 With prefix arg, use completion to determined the new state. With numeric
3319 prefix arg, switch to that state."
3322 (org-back-to-heading)
3323 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3324 (or (looking-at (concat " +" org-todo-regexp " *"))
3326 (let* ((this (match-string 1))
3327 (completion-ignore-case t)
3328 (member (member this org-todo-keywords))
3332 ;; Read a state with completion
3333 (completing-read "State: " (mapcar (lambda(x) (list x))
3338 (if tail (car tail) nil)
3339 (car org-todo-keywords)))
3341 (if (equal member org-todo-keywords)
3344 (nth (- (length org-todo-keywords) (length tail) 2)
3348 ;; user requests a specific state
3349 (nth (1- (prefix-numeric-value arg))
3351 ((null member) (car org-todo-keywords))
3352 ((null tail) nil) ;; -> first entry
3353 ((eq org-todo-interpretation 'sequence)
3355 ((memq org-todo-interpretation '(type priority))
3356 (if (eq this-command last-command)
3358 (if (> (length tail) 0) org-done-string nil)))
3360 (next (if state (concat " " state " ") " ")))
3361 (replace-match next t t)
3362 (setq org-last-todo-state-is-todo
3363 (not (equal state org-done-string)))
3365 (if (equal state org-done-string)
3369 ;; Fixup tag positioning
3370 (and org-auto-align-tags (org-set-tags nil t))
3371 (run-hooks 'org-after-todo-state-change-hook)))
3372 ;; Fixup cursor location if close to the keyword
3373 (if (and (outline-on-heading-p)
3375 (save-excursion (beginning-of-line 1)
3376 (looking-at org-todo-line-regexp))
3377 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3379 (goto-char (or (match-end 2) (match-end 1)))
3382 (defun org-log-done (&optional undone)
3383 "Add a time stamp logging that a TODO entry has been closed.
3384 When UNDONE is non-nil, remove such a time stamg again."
3388 (org-back-to-heading t)
3390 (looking-at (concat outline-regexp " *"))
3391 (goto-char (match-end 0))
3392 (setq col (current-column))
3393 (outline-next-heading)
3396 (when (re-search-forward (concat
3398 (regexp-quote org-closed-string)
3399 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3400 (delete-region (match-beginning 1) (match-end 1)))
3402 (org-back-to-heading t)
3403 (skip-chars-forward "^\n\r")
3404 (goto-char (min (1+ (point)) (point-max)))
3405 (when (not (member (char-before) '(?\r ?\n)))
3408 (insert org-closed-string " "
3410 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3414 (defun org-show-todo-tree (arg)
3415 "Make a compact tree which shows all headlines marked with TODO.
3416 The tree will show the lines where the regexp matches, and all higher
3417 headlines above the match.
3418 With \\[universal-argument] prefix, also show the DONE entries.
3419 With a numeric prefix N, construct a sparse tree for the Nth element
3420 of `org-todo-keywords'."
3422 (let ((case-fold-search nil)
3424 (cond ((null arg) org-not-done-regexp)
3425 ((equal arg '(4)) org-todo-regexp)
3426 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3427 (regexp-quote (nth (1- (prefix-numeric-value arg))
3428 org-todo-keywords)))
3429 (t (error "Invalid prefix argument: %s" arg)))))
3430 (message "%d TODO entries found"
3431 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3433 (defun org-deadline ()
3434 "Insert the DEADLINE: string to make a deadline.
3435 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3436 to modify it to the correct date."
3439 org-deadline-string " "
3440 (format-time-string (car org-time-stamp-formats)
3441 (org-read-date nil 'to-time)))
3442 (message "%s" (substitute-command-keys
3443 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3445 (defun org-schedule ()
3446 "Insert the SCHEDULED: string to schedule a TODO item.
3447 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3448 to modify it to the correct date."
3451 org-scheduled-string " "
3452 (format-time-string (car org-time-stamp-formats)
3453 (org-read-date nil 'to-time)))
3454 (message "%s" (substitute-command-keys
3455 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3458 (defun org-occur (regexp &optional callback)
3459 "Make a compact tree which shows all matches of REGEXP.
3460 The tree will show the lines where the regexp matches, and all higher
3461 headlines above the match. It will also show the heading after the match,
3462 to make sure editing the matching entry is easy.
3463 if CALLBACK is non-nil, it is a function which is called to confirm
3464 that the match should indeed be shown."
3465 (interactive "sRegexp: ")
3466 (org-remove-occur-highlights nil nil t)
3467 (setq regexp (org-check-occur-regexp regexp))
3470 (goto-char (point-min))
3472 (while (re-search-forward regexp nil t)
3473 (when (or (not callback)
3474 (save-match-data (funcall callback)))
3476 (org-highlight-new-match (match-beginning 0) (match-end 0))
3477 (org-show-hierarchy-above))))
3478 (make-local-hook 'before-change-functions) ; needed for XEmacs
3479 (add-hook 'before-change-functions 'org-remove-occur-highlights
3481 (run-hooks 'org-occur-hook)
3483 (message "%d match(es) for regexp %s" cnt regexp))
3486 (defun org-show-hierarchy-above ()
3487 "Make sure point and the headings hierarchy above is visible."
3489 (if (org-on-heading-p t)
3490 (org-flag-heading nil) ; only show the heading
3491 (and (org-invisible-p) (org-show-hidden-entry))) ; show entire entry
3493 (and org-show-following-heading
3494 (outline-next-heading)
3495 (org-flag-heading nil))) ; show the next heading
3496 (when org-show-hierarchy-above
3497 (save-excursion ; show all higher headings
3498 (while (and (condition-case nil
3499 (progn (org-up-heading-all 1) t)
3502 (org-flag-heading nil))))))
3504 ;; Overlay compatibility functions
3505 (defun org-make-overlay (beg end &optional buffer)
3506 (if org-xemacs-p (make-extent beg end buffer) (make-overlay beg end buffer)))
3507 (defun org-delete-overlay (ovl)
3508 (if org-xemacs-p (delete-extent ovl) (delete-overlay ovl)))
3509 (defun org-detatch-overlay (ovl)
3510 (if org-xemacs-p (detach-extent ovl) (delete-overlay ovl)))
3511 (defun org-move-overlay (ovl beg end &optional buffer)
3513 (set-extent-endpoints ovl beg end buffer)
3514 (move-overlay ovl beg end buffer)))
3515 (defun org-overlay-put (ovl prop value)
3517 (set-extent-property ovl prop value)
3518 (overlay-put ovl prop value)))
3520 (defvar org-occur-highlights nil)
3521 (defun org-highlight-new-match (beg end)
3522 "Highlight from BEG to END and mark the highlight is an occur headline."
3523 (let ((ov (org-make-overlay beg end)))
3524 (org-overlay-put ov 'face 'secondary-selection)
3525 (push ov org-occur-highlights)))
3527 (defun org-remove-occur-highlights (&optional beg end noremove)
3528 "Remove the occur highlights from the buffer.
3529 BEG and END are ignored. If NOREMOVE is nil, remove this function
3530 from the before-change-functions in the current buffer."
3532 (mapc 'org-delete-overlay org-occur-highlights)
3533 (setq org-occur-highlights nil)
3535 (remove-hook 'before-change-functions
3536 'org-remove-occur-highlights 'local)))
3540 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3541 "Regular expression matching the priority indicator.")
3543 (defvar org-remove-priority-next-time nil)
3545 (defun org-priority-up ()
3546 "Increase the priority of the current item."
3550 (defun org-priority-down ()
3551 "Decrease the priority of the current item."
3553 (org-priority 'down))
3555 (defun org-priority (&optional action)
3556 "Change the priority of an item by ARG.
3557 ACTION can be set, up, or down."
3559 (setq action (or action 'set))
3560 (let (current new news have remove)
3562 (org-back-to-heading)
3563 (if (looking-at org-priority-regexp)
3564 (setq current (string-to-char (match-string 2))
3566 (setq current org-default-priority))
3569 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3570 (setq new (read-char-exclusive))
3571 (cond ((equal new ?\ ) (setq remove t))
3572 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3573 (error "Priority must be between `%c' and `%c'"
3574 ?A org-lowest-priority))))
3576 (setq new (1- current)))
3578 (setq new (1+ current)))
3579 (t (error "Invalid action")))
3580 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3581 (setq news (format "%c" new))
3584 (replace-match "" t t nil 1)
3585 (replace-match news t t nil 2))
3587 (error "No priority cookie found in line")
3588 (looking-at org-todo-line-regexp)
3591 (goto-char (match-end 2))
3592 (insert " [#" news "]"))
3593 (goto-char (match-beginning 3))
3594 (insert "[#" news "] ")))))
3596 (message "Priority removed")
3597 (message "Priority of current item set to %s" news))))
3600 (defun org-get-priority (s)
3601 "Find priority cookie and return priority."
3603 (if (not (string-match org-priority-regexp s))
3604 (* 1000 (- org-lowest-priority org-default-priority))
3605 (* 1000 (- org-lowest-priority
3606 (string-to-char (match-string 2 s)))))))
3610 (defvar org-last-changed-timestamp nil)
3612 (defun org-time-stamp (arg)
3613 "Prompt for a date/time and insert a time stamp.
3614 If the user specifies a time like HH:MM, or if this command is called
3615 with a prefix argument, the time stamp will contain date and time.
3616 Otherwise, only the date will be included. All parts of a date not
3617 specified by the user will be filled in from the current date/time.
3618 So if you press just return without typing anything, the time stamp
3619 will represent the current date/time. If there is already a timestamp
3620 at the cursor, it will be modified."
3622 (let ((fmt (if arg (cdr org-time-stamp-formats)
3623 (car org-time-stamp-formats)))
3624 (org-time-was-given nil)
3627 ((and (org-at-timestamp-p)
3628 (eq last-command 'org-time-stamp)
3629 (eq this-command 'org-time-stamp))
3631 (setq time (let ((this-command this-command))
3632 (org-read-date arg 'totime)))
3633 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3634 (insert (format-time-string fmt time)))
3635 ((org-at-timestamp-p)
3636 (setq time (let ((this-command this-command))
3637 (org-read-date arg 'totime)))
3638 (and (org-at-timestamp-p) (replace-match
3639 (setq org-last-changed-timestamp
3640 (format-time-string fmt time))
3642 (message "Timestamp updated"))
3644 (setq time (let ((this-command this-command))
3645 (org-read-date arg 'totime)))
3646 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3647 (insert (format-time-string fmt time))))))
3649 (defun org-time-stamp-inactive (&optional arg)
3650 "Insert an inactive time stamp.
3651 An inactive time stamp is enclosed in square brackets instead of angle
3652 brackets. It is inactive in the sense that it does not trigger agenda entries,
3653 does not link to the calendar and cannot be changed with the S-cursor keys.
3654 So these are more for recording a certain time/date."
3655 ;; FIXME: Would it be better not to ask for a date/time here?
3657 (let ((fmt (if arg (cdr org-time-stamp-formats)
3658 (car org-time-stamp-formats)))
3659 (org-time-was-given nil)
3661 (setq time (org-read-date arg 'totime))
3662 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3663 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3664 (insert (format-time-string fmt time))))
3666 (defvar org-date-ovl (org-make-overlay 1 1))
3667 (org-overlay-put org-date-ovl 'face 'org-warning)
3668 (org-detatch-overlay org-date-ovl)
3670 ;;; FIXME: Make the function take "Fri" as "next friday"
3671 ;;; because these are mostly being used to record the current time.
3672 (defun org-read-date (&optional with-time to-time)
3673 "Read a date and make things smooth for the user.
3674 The prompt will suggest to enter an ISO date, but you can also enter anything
3675 which will at least partially be understood by `parse-time-string'.
3676 Unrecognized parts of the date will default to the current day, month ,year,
3677 hour and minute. For example,
3678 3-2-5 --> 2003-02-05
3679 feb 15 --> currentyear-02-15
3680 sep 12 9 --> 2009-09-12
3681 12:45 --> today 12:45
3682 22 sept 0:34 --> currentyear-09-22 0:34
3683 12 --> currentyear-currentmonth-12
3685 The function understands only English month and weekday abbreviations,
3686 but this can be configured with the variables `parse-time-months' and
3687 `parse-time-weekdays'.
3689 While prompting, a calendar is popped up - you can also select the
3690 date with the mouse (button 1). The calendar shows a period of three
3691 month. To scroll it to other months, use the keys `>' and `<'.
3692 If you don't like the calendar, turn it off with
3693 \(setq org-popup-calendar-for-date-prompt nil).
3695 With optional argument TO-TIME, the date will immediately be converted
3696 to an internal time.
3697 With an optional argument WITH-TIME, the prompt will suggest to also
3698 insert a time. Note that when WITH-TIME is not set, you can still
3699 enter a time, and this function will inform the calling routine about
3700 this change. The calling routine may then choose to change the format
3701 used to insert the time stamp into the buffer to include the time."
3702 (let* ((default-time
3703 ;; Default time is either today, or, when entering a range,
3707 (concat org-ts-regexp "--\\=")
3711 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3712 (parse-time-string (match-string 1))))
3714 (calendar-move-hook nil)
3715 (view-diary-entries-initially nil)
3716 (timestr (format-time-string
3717 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3718 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3720 second minute hour day month year tl)
3722 (if org-popup-calendar-for-date-prompt
3723 ;; Also show a calendar for date selection
3724 ;; Copied (with modifications) from planner.el by John Wiegley
3726 (save-window-excursion
3728 (calendar-forward-day (- (time-to-days default-time)
3729 (calendar-absolute-from-gregorian
3730 (calendar-current-date))))
3731 (org-eval-in-calendar nil)
3732 (let* ((old-map (current-local-map))
3733 (map (copy-keymap calendar-mode-map))
3734 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3735 (define-key map (kbd "RET") 'org-calendar-select)
3736 (define-key map (if org-xemacs-p [button1] [mouse-1])
3737 'org-calendar-select-mouse)
3738 (define-key map (if org-xemacs-p [button2] [mouse-2])
3739 'org-calendar-select-mouse)
3740 (define-key minibuffer-local-map [(meta shift left)]
3741 (lambda () (interactive)
3742 (org-eval-in-calendar '(calendar-backward-month 1))))
3743 (define-key minibuffer-local-map [(meta shift right)]
3744 (lambda () (interactive)
3745 (org-eval-in-calendar '(calendar-forward-month 1))))
3746 (define-key minibuffer-local-map [(shift up)]
3747 (lambda () (interactive)
3748 (org-eval-in-calendar '(calendar-backward-week 1))))
3749 (define-key minibuffer-local-map [(shift down)]
3750 (lambda () (interactive)
3751 (org-eval-in-calendar '(calendar-forward-week 1))))
3752 (define-key minibuffer-local-map [(shift left)]
3753 (lambda () (interactive)
3754 (org-eval-in-calendar '(calendar-backward-day 1))))
3755 (define-key minibuffer-local-map [(shift right)]
3756 (lambda () (interactive)
3757 (org-eval-in-calendar '(calendar-forward-day 1))))
3758 (define-key minibuffer-local-map ">"
3759 (lambda () (interactive)
3760 (org-eval-in-calendar '(scroll-calendar-left 1))))
3761 (define-key minibuffer-local-map "<"
3762 (lambda () (interactive)
3763 (org-eval-in-calendar '(scroll-calendar-right 1))))
3767 (setq ans (read-string prompt "" nil nil))
3768 (setq ans (or ans1 ans2 ans)))
3769 (use-local-map old-map)))))
3770 ;; Naked prompt only
3771 (setq ans (read-string prompt "" nil timestr)))
3772 (org-detatch-overlay org-date-ovl)
3775 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3777 (setq year (if (match-end 2)
3778 (string-to-number (match-string 2 ans))
3779 (string-to-number (format-time-string "%Y")))
3780 month (string-to-number (match-string 3 ans))
3781 day (string-to-number (match-string 4 ans)))
3782 (if (< year 100) (setq year (+ 2000 year)))
3783 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3785 (setq tl (parse-time-string ans)
3786 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3787 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3788 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3789 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3790 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3791 second (or (nth 0 tl) 0))
3792 (if (and (boundp 'org-time-was-given)
3794 (setq org-time-was-given t))
3795 (if (< year 100) (setq year (+ 2000 year)))
3797 (encode-time second minute hour day month year)
3798 (if (or (nth 1 tl) (nth 2 tl))
3799 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3800 (format "%04d-%02d-%02d" year month day)))))
3802 (defun org-eval-in-calendar (form)
3803 "Eval FORM in the calendar window and return to current window.
3804 Also, store the cursor date in variable ans2."
3805 (let ((sw (selected-window)))
3806 (select-window (get-buffer-window "*Calendar*"))
3808 (when (calendar-cursor-to-date)
3809 (let* ((date (calendar-cursor-to-date))
3810 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3811 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3812 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
3813 (select-window sw)))
3815 (defun org-calendar-select ()
3816 "Return to `org-read-date' with the date currently selected.
3817 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3819 (when (calendar-cursor-to-date)
3820 (let* ((date (calendar-cursor-to-date))
3821 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3822 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3823 (if (active-minibuffer-window) (exit-minibuffer))))
3825 (defun org-calendar-select-mouse (ev)
3826 "Return to `org-read-date' with the date currently selected.
3827 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3829 (mouse-set-point ev)
3830 (when (calendar-cursor-to-date)
3831 (let* ((date (calendar-cursor-to-date))
3832 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3833 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3834 (if (active-minibuffer-window) (exit-minibuffer))))
3836 (defun org-check-deadlines (ndays)
3837 "Check if there are any deadlines due or past due.
3838 A deadline is considered due if it happens within `org-deadline-warning-days'
3839 days from today's date. If the deadline appears in an entry marked DONE,
3840 it is not shown. The prefix arg NDAYS can be used to test that many
3841 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3843 (let* ((org-warn-days
3845 ((equal ndays '(4)) 100000)
3846 (ndays (prefix-numeric-value ndays))
3847 (t org-deadline-warning-days)))
3848 (case-fold-search nil)
3849 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3852 (and (let ((d1 (time-to-days (current-time)))
3854 (org-time-string-to-time (match-string 1)))))
3855 (< (- d2 d1) org-warn-days))
3856 (not (org-entry-is-done-p))))))
3857 (message "%d deadlines past-due or due within %d days"
3858 (org-occur regexp callback)
3861 (defun org-evaluate-time-range (&optional to-buffer)
3862 "Evaluate a time range by computing the difference between start and end.
3863 Normally the result is just printed in the echo area, but with prefix arg
3864 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3865 If the time range is actually in a table, the result is inserted into the
3867 For time difference computation, a year is assumed to be exactly 365
3868 days in order to avoid rounding problems."
3871 (unless (org-at-date-range-p)
3872 (goto-char (point-at-bol))
3873 (re-search-forward org-tr-regexp (point-at-eol) t))
3874 (if (not (org-at-date-range-p))
3875 (error "Not at a time-stamp range, and none found in current line")))
3876 (let* ((ts1 (match-string 1))
3877 (ts2 (match-string 2))
3878 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3879 (match-end (match-end 0))
3880 (time1 (org-time-string-to-time ts1))
3881 (time2 (org-time-string-to-time ts2))
3882 (t1 (time-to-seconds time1))
3883 (t2 (time-to-seconds time2))
3884 (diff (abs (- t2 t1)))
3885 (negative (< (- t2 t1) 0))
3886 ;; (ys (floor (* 365 24 60 60)))
3889 (fy "%dy %dd %02d:%02d")
3891 (fd "%dd %02d:%02d")
3895 ;; FIXME: Should I re-introduce years, make year refer to same date?
3896 ;; This would be the only useful way to have years, actually.
3898 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3900 d (floor (/ diff ds)) diff (mod diff ds)
3901 h (floor (/ diff hs)) diff (mod diff hs)
3902 m (floor (/ diff 60)))
3903 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3905 d (floor (+ (/ diff ds) 0.5))
3908 (message (org-make-tdiff-string y d h m))
3909 (when (org-at-table-p)
3910 (goto-char match-end)
3912 (and (looking-at " *|") (goto-char (match-end 0))))
3914 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3916 (if negative (insert " -"))
3917 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3918 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3919 (insert " " (format fh h m))))
3920 (if align (org-table-align))
3921 (message "Time difference inserted"))))
3923 (defun org-make-tdiff-string (y d h m)
3926 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3928 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3930 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3932 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3934 (apply 'format fmt (nreverse l))))
3936 (defun org-time-string-to-time (s)
3937 (apply 'encode-time (org-parse-time-string s)))
3939 (defun org-parse-time-string (s &optional nodefault)
3940 "Parse the standard Org-mode time string.
3941 This should be a lot faster than the normal `parse-time-string'.
3942 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3943 hour and minute fields will be nil if not given."
3944 (if (string-match org-ts-regexp1 s)
3946 (if (or (match-beginning 8) (not nodefault))
3947 (string-to-number (or (match-string 8 s) "0")))
3948 (if (or (match-beginning 7) (not nodefault))
3949 (string-to-number (or (match-string 7 s) "0")))
3950 (string-to-number (match-string 4 s))
3951 (string-to-number (match-string 3 s))
3952 (string-to-number (match-string 2 s))
3956 (defun org-timestamp-up (&optional arg)
3957 "Increase the date item at the cursor by one.
3958 If the cursor is on the year, change the year. If it is on the month or
3959 the day, change that.
3960 With prefix ARG, change by that many units."
3962 (org-timestamp-change (prefix-numeric-value arg)))
3964 (defun org-timestamp-down (&optional arg)
3965 "Decrease the date item at the cursor by one.
3966 If the cursor is on the year, change the year. If it is on the month or
3967 the day, change that.
3968 With prefix ARG, change by that many units."
3970 (org-timestamp-change (- (prefix-numeric-value arg))))
3972 (defun org-timestamp-up-day (&optional arg)
3973 "Increase the date in the time stamp by one day.
3974 With prefix ARG, change that many days."
3976 (if (and (not (org-at-timestamp-p))
3979 (org-timestamp-change (prefix-numeric-value arg) 'day)))
3981 (defun org-timestamp-down-day (&optional arg)
3982 "Decrease the date in the time stamp by one day.
3983 With prefix ARG, change that many days."
3985 (if (and (not (org-at-timestamp-p))
3988 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
3990 (defsubst org-pos-in-match-range (pos n)
3991 (and (match-beginning n)
3992 (<= (match-beginning n) pos)
3993 (>= (match-end n) pos)))
3995 (defun org-at-timestamp-p ()
3996 "Determine if the cursor is in or at a timestamp."
3998 (let* ((tsr org-ts-regexp2)
4000 (ans (or (looking-at tsr)
4002 (skip-chars-backward "^<\n\r\t")
4003 (if (> (point) 1) (backward-char 1))
4004 (and (looking-at tsr)
4005 (> (- (match-end 0) pos) -1))))))
4006 (and (boundp 'org-ts-what)
4009 ((org-pos-in-match-range pos 2) 'year)
4010 ((org-pos-in-match-range pos 3) 'month)
4011 ((org-pos-in-match-range pos 7) 'hour)
4012 ((org-pos-in-match-range pos 8) 'minute)
4013 ((or (org-pos-in-match-range pos 4)
4014 (org-pos-in-match-range pos 5)) 'day)
4018 (defun org-timestamp-change (n &optional what)
4019 "Change the date in the time stamp at point.
4020 The date will be changed by N times WHAT. WHAT can be `day', `month',
4021 `year', `minute', `second'. If WHAT is not given, the cursor position
4022 in the timestamp determines what will be changed."
4023 (let ((fmt (car org-time-stamp-formats))
4027 (if (not (org-at-timestamp-p))
4028 (error "Not at a timestamp"))
4029 (setq org-ts-what (or what org-ts-what))
4030 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4031 (- (match-end 0) (match-beginning 0))))
4033 (cdr org-time-stamp-formats)
4034 (car org-time-stamp-formats)))
4035 (setq ts (match-string 0))
4037 (setq time0 (org-parse-time-string ts))
4041 (list (or (car time0) 0))
4042 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4043 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4044 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4045 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4046 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4048 (if (eq what 'calendar)
4052 (set-buffer "*Calendar*")
4053 (calendar-cursor-to-date)))))
4054 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4055 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4056 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4057 (setcar time0 (or (car time0) 0))
4058 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4059 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4060 (setq time (apply 'encode-time time0))))
4061 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4063 ;; Try to recenter the calendar window, if any
4064 (if (and org-calendar-follow-timestamp-change
4065 (get-buffer-window "*Calendar*" t)
4066 (memq org-ts-what '(day month year)))
4067 (org-recenter-calendar (time-to-days time)))))
4069 (defun org-recenter-calendar (date)
4070 "If the calendar is visible, recenter it to DATE."
4071 (let* ((win (selected-window))
4072 (cwin (get-buffer-window "*Calendar*" t))
4073 (calendar-move-hook nil))
4075 (select-window cwin)
4076 (calendar-goto-date (if (listp date) date
4077 (calendar-gregorian-from-absolute date)))
4078 (select-window win))))
4080 (defun org-goto-calendar (&optional arg)
4081 "Go to the Emacs calendar at the current date.
4082 If there is a time stamp in the current line, go to that date.
4083 A prefix ARG can be used force the current date."
4085 (let ((tsr org-ts-regexp) diff
4086 (calendar-move-hook nil)
4087 (view-diary-entries-initially nil))
4088 (if (or (org-at-timestamp-p)
4090 (beginning-of-line 1)
4091 (looking-at (concat ".*" tsr))))
4092 (let ((d1 (time-to-days (current-time)))
4094 (org-time-string-to-time (match-string 1)))))
4095 (setq diff (- d2 d1))))
4097 (calendar-goto-today)
4098 (if (and diff (not arg)) (calendar-forward-day diff))))
4100 (defun org-date-from-calendar ()
4101 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4102 If there is already a time stamp at the cursor position, update it."
4104 (org-timestamp-change 0 'calendar))
4106 ;;; Agenda, and Diary Integration
4110 (defvar org-agenda-mode-map (make-sparse-keymap)
4111 "Keymap for `org-agenda-mode'.")
4113 (defvar org-agenda-menu)
4114 (defvar org-agenda-follow-mode nil)
4115 (defvar org-agenda-show-log nil)
4116 (defvar org-agenda-buffer-name "*Org Agenda*")
4117 (defvar org-agenda-redo-command nil)
4118 (defvar org-agenda-mode-hook nil)
4119 (defvar org-agenda-type nil)
4120 (defvar org-agenda-force-single-file nil)
4123 (defun org-agenda-mode ()
4124 "Mode for time-sorted view on action items in Org-mode files.
4126 The following commands are available:
4128 \\{org-agenda-mode-map}"
4130 (kill-all-local-variables)
4131 (setq major-mode 'org-agenda-mode)
4132 (setq mode-name "Org-Agenda")
4133 (use-local-map org-agenda-mode-map)
4134 (easy-menu-add org-agenda-menu)
4135 (if org-startup-truncated (setq truncate-lines t))
4136 (make-local-hook 'post-command-hook) ; Needed for XEmacs
4137 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4138 (make-local-hook 'pre-command-hook) ; Needed for XEmacs
4139 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4140 (unless org-agenda-keep-modes
4141 (setq org-agenda-follow-mode nil
4142 org-agenda-show-log nil))
4144 '("Agenda") "Agenda Files"
4148 (if (get 'org-agenda-files 'org-restrict)
4149 "Restricted to single file"
4151 '(customize-variable 'org-agenda-files)
4152 (not (get 'org-agenda-files 'org-restrict)))
4154 (mapcar 'org-file-menu-entry (org-agenda-files))))
4155 (org-agenda-set-mode-name)
4157 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4158 (list 'org-agenda-mode-hook)))
4160 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4161 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4162 (define-key org-agenda-mode-map " " 'org-agenda-show)
4163 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4164 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4165 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4166 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4167 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4168 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4169 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4170 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4171 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4172 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4173 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4174 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4176 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4177 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4178 (while l (define-key org-agenda-mode-map
4179 (int-to-string (pop l)) 'digit-argument)))
4181 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4182 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4183 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4184 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4185 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4186 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4187 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4188 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4189 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4190 (define-key org-agenda-mode-map "n" 'next-line)
4191 (define-key org-agenda-mode-map "p" 'previous-line)
4192 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4193 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4194 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4195 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4196 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4197 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4198 (eval-after-load "calendar"
4199 '(define-key calendar-mode-map org-calendar-to-agenda-key
4200 'org-calendar-goto-agenda))
4201 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4202 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4203 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4204 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4205 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4206 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4207 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4208 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4209 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4210 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4211 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4212 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4213 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4214 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4215 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4216 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4217 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4218 "Local keymap for agenda entries from Org-mode.")
4220 (define-key org-agenda-keymap
4221 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4222 (define-key org-agenda-keymap
4223 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4225 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4229 ["Show" org-agenda-show t]
4230 ["Go To (other window)" org-agenda-goto t]
4231 ["Go To (one window)" org-agenda-switch-to t]
4232 ["Follow Mode" org-agenda-follow-mode
4233 :style toggle :selected org-agenda-follow-mode :active t]
4235 ["Cycle TODO" org-agenda-todo t]
4237 ["Show all Tags" org-agenda-show-tags t]
4238 ["Set Tags" org-agenda-set-tags t])
4240 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4241 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4243 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4245 ["Set Priority" org-agenda-priority t]
4246 ["Increase Priority" org-agenda-priority-up t]
4247 ["Decrease Priority" org-agenda-priority-down t]
4248 ["Show Priority" org-agenda-show-priority t])
4250 ;; ["New agenda command" org-agenda t]
4251 ["Rebuild buffer" org-agenda-redo t]
4253 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4254 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4255 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4257 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4258 :style radio :selected (equal org-agenda-ndays 1)]
4259 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4260 :style radio :selected (equal org-agenda-ndays 7)]
4262 ["Show Logbook entries" org-agenda-log-mode
4263 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4264 ["Include Diary" org-agenda-toggle-diary
4265 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4266 ["Use Time Grid" org-agenda-toggle-time-grid
4267 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4269 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4270 ("Calendar Commands"
4271 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4272 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4273 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4274 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4275 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4276 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4278 ["Quit" org-agenda-quit t]
4279 ["Exit and Release Buffers" org-agenda-exit t]
4283 (defun org-agenda (arg)
4284 "Dispatch agenda commands to collect entries to the agenda buffer.
4285 Prompts for a character to select a command. Any prefix arg will be passed
4286 on to the selected command. The default selections are:
4288 a Call `org-agenda' to display the agenda for the current day or week.
4289 t Call `org-todo-list' to display the global todo list.
4290 T Call `org-todo-list' to display the global todo list, select only
4291 entries with a specific TODO keyword (the user get a prompt).
4292 m Call `org-tags-view' to display headlines with tags matching
4293 a condition (the user is prompted for the condition).
4294 M like `m', but select only TODO entries, no ordinary headlines.
4296 More commands can be added by configuring the variable
4297 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4298 searches can be pre-defined in this way.
4300 If the current buffer is in Org-mode and visiting a file, you can also
4301 first press `1' to indicate that the agenda should be temporarily (until the
4302 next use of \\[org-agenda]) restricted to the current file."
4305 (let ((restrict-ok (and (buffer-file-name) (eq major-mode 'org-mode)))
4306 (custom org-agenda-custom-commands)
4307 c entry key type string)
4308 (put 'org-agenda-files 'org-restrict nil)
4309 (save-window-excursion
4310 (delete-other-windows)
4311 (switch-to-buffer-other-window " *Agenda Commands*")
4314 "Press key for an agenda command:
4315 --------------------------------
4316 a Agenda for current week or day
4317 t List of all TODO entries T Entries with special TODO kwd
4318 m Match a TAGS query M Like m, but only TODO entries.
4319 C Configure your own agenda commands")
4320 (while (setq entry (pop custom))
4321 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4322 (insert (format "\n%-4s%-14s: %s"
4325 ((eq type 'tags) "Tags query")
4326 ((eq type 'todo) "TODO keyword")
4327 ((eq type 'tags-tree) "Tags tree")
4328 ((eq type 'todo-tree) "TODO kwd tree")
4329 ((eq type 'occur-tree) "Occur tree")
4331 (org-string-props string 'face 'org-link))))
4332 (goto-char (point-min))
4333 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4334 (message "Press key for agenda command%s"
4335 (if restrict-ok ", or [1] to restrict to current file" ""))
4336 (setq c (read-char-exclusive))
4340 (put 'org-agenda-files 'org-restrict (list (buffer-file-name)))
4341 (error "Cannot restrict agenda to current buffer"))
4342 (message "Press key for agenda command%s"
4343 (if restrict-ok " (restricted to current file)" ""))
4344 (setq c (read-char-exclusive))
4346 (require 'calendar) ; FIXME: can we avoid this for some commands?
4347 ;; For example the todo list should not need it (but does...)
4349 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4350 ((equal c ?a) (call-interactively 'org-agenda-list))
4351 ((equal c ?t) (call-interactively 'org-todo-list))
4353 (setq current-prefix-arg (or arg '(4)))
4354 (call-interactively 'org-todo-list))
4355 ((equal c ?m) (call-interactively 'org-tags-view))
4357 (setq current-prefix-arg (or arg '(4)))
4358 (call-interactively 'org-tags-view))
4359 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4360 (setq type (nth 1 entry) string (nth 2 entry))
4363 (org-tags-view current-prefix-arg string))
4365 (org-todo-list string))
4366 ((eq type 'tags-tree)
4367 (org-check-for-org-mode)
4368 (org-tags-sparse-tree current-prefix-arg string))
4369 ((eq type 'todo-tree)
4370 (org-check-for-org-mode)
4371 (org-occur (concat "^" outline-regexp "[ \t]*"
4372 (regexp-quote string) "\\>")))
4373 ((eq type 'occur-tree)
4374 (org-check-for-org-mode)
4376 (t (error "Invalid custom agenda command type %s" type))))
4377 (t (error "Invalid key"))))))
4379 (defun org-check-for-org-mode ()
4380 "Make sure current buffer is in org-mode. Error if not."
4381 (or (eq major-mode 'org-mode)
4382 (error "Cannot execute org-mode agenda command on buffer in %s."
4385 (defun org-fit-agenda-window ()
4386 "Fit the window to the buffer size."
4387 (and org-fit-agenda-window
4388 (fboundp 'fit-window-to-buffer)
4389 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4390 (/ (frame-height) 2))))
4392 (defun org-agenda-files ()
4393 "Get the list of agenda files."
4394 (or (get 'org-agenda-files 'org-restrict)
4397 (defvar org-agenda-markers nil
4398 "List of all currently active markers created by `org-agenda'.")
4399 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4400 "Creation time of the last agenda marker.")
4402 (defun org-agenda-new-marker (&optional pos)
4403 "Return a new agenda marker.
4404 Org-mode keeps a list of these markers and resets them when they are
4406 (let ((m (copy-marker (or pos (point)))))
4407 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4408 (push m org-agenda-markers)
4411 (defun org-agenda-maybe-reset-markers (&optional force)
4412 "Reset markers created by `org-agenda'. But only if they are old enough."
4414 (> (- (time-to-seconds (current-time))
4415 org-agenda-last-marker-time)
4417 (while org-agenda-markers
4418 (move-marker (pop org-agenda-markers) nil))))
4420 (defvar org-agenda-new-buffers nil
4421 "Buffers created to visit agenda files.")
4423 (defun org-get-agenda-file-buffer (file)
4424 "Get a buffer visiting FILE. If the buffer needs to be created, add
4425 it to the list of buffers which might be released later."
4426 (let ((buf (find-buffer-visiting file)))
4428 buf ; just return it
4429 ;; Make a new buffer and remember it
4430 (setq buf (find-file-noselect file))
4431 (if buf (push buf org-agenda-new-buffers))
4434 (defun org-release-buffers (blist)
4435 "Release all buffers in list, asking the user for confirmation when needed.
4436 When a buffer is unmodified, it is just killed. When modified, it is saved
4437 \(if the user agrees) and then killed."
4439 (while (setq buf (pop blist))
4440 (setq file (buffer-file-name buf))
4441 (when (and (buffer-modified-p buf)
4443 (y-or-n-p (format "Save file %s? " file)))
4444 (with-current-buffer buf (save-buffer)))
4445 (kill-buffer buf))))
4447 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4449 (defun org-timeline (&optional include-all keep-modes)
4450 "Show a time-sorted view of the entries in the current org file.
4451 Only entries with a time stamp of today or later will be listed. With
4452 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4453 under the current date.
4454 If the buffer contains an active region, only check the region for
4458 (org-agenda-maybe-reset-markers 'force)
4459 (org-compile-prefix-format org-timeline-prefix-format)
4461 (dotodo include-all)
4462 (doclosed org-agenda-show-log)
4463 (org-agenda-keep-modes keep-modes)
4464 (entry (buffer-file-name))
4465 (org-agenda-files (list (buffer-file-name)))
4466 (date (calendar-current-date))
4467 (win (selected-window))
4469 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4470 (end (if (org-region-active-p) (region-end) (point-max)))
4471 (day-numbers (org-get-all-dates beg end 'no-ranges
4472 t doclosed)) ; always include today
4473 (today (time-to-days (current-time)))
4474 (org-respect-restriction t)
4478 (setq org-agenda-redo-command
4480 (list 'switch-to-buffer-other-window (current-buffer))
4481 (list 'org-timeline (list 'quote include-all) t)))
4483 ;; Remove past dates from the list of dates.
4484 (setq day-numbers (delq nil (mapcar (lambda(x)
4485 (if (>= x today) x nil))
4487 (switch-to-buffer-other-window
4488 (get-buffer-create org-agenda-buffer-name))
4489 (setq buffer-read-only nil)
4491 (org-agenda-mode) (setq buffer-read-only nil)
4492 (set (make-local-variable 'org-agenda-type) 'timeline)
4493 (if doclosed (push :closed args))
4494 (push :timestamp args)
4495 (if dotodo (push :todo args))
4496 (while (setq d (pop day-numbers))
4497 (if (and (>= d today)
4502 (insert (make-string 79 ?-) "\n")))
4503 (setq date (calendar-gregorian-from-absolute d))
4505 (setq rtn (apply 'org-agenda-get-day-entries
4507 (if (or rtn (equal d today))
4509 (insert (calendar-day-name date) " "
4510 (number-to-string (extract-calendar-day date)) " "
4511 (calendar-month-name (extract-calendar-month date)) " "
4512 (number-to-string (extract-calendar-year date)) "\n")
4513 (put-text-property s (1- (point)) 'face
4516 (put-text-property s (1- (point)) 'org-today t))
4517 (insert (org-finalize-agenda-entries rtn) "\n")
4518 (put-text-property s (1- (point)) 'day d))))
4519 (goto-char (point-min))
4520 (setq buffer-read-only t)
4521 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4523 (when (not org-select-timeline-window)
4528 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4529 "Produce a weekly view from all files in variable `org-agenda-files'.
4530 The view will be for the current week, but from the overview buffer you
4531 will be able to go to other weeks.
4532 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4533 also be shown, under the current date.
4534 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4535 on the days are also shown. See the variable `org-log-done' for how
4537 START-DAY defaults to TODAY, or to the most recent match for the weekday
4538 given in `org-agenda-start-on-weekday'.
4539 NDAYS defaults to `org-agenda-ndays'."
4541 (org-agenda-maybe-reset-markers 'force)
4542 (org-compile-prefix-format org-agenda-prefix-format)
4544 (let* ((org-agenda-start-on-weekday
4545 (if (or (equal ndays 1)
4546 (and (null ndays) (equal 1 org-agenda-ndays)))
4547 nil org-agenda-start-on-weekday))
4548 (org-agenda-keep-modes keep-modes)
4549 (files (copy-sequence (org-agenda-files)))
4550 (win (selected-window))
4551 (today (time-to-days (current-time)))
4552 (sd (or start-day today))
4553 (start (if (or (null org-agenda-start-on-weekday)
4554 (< org-agenda-ndays 7))
4556 (let* ((nt (calendar-day-of-week
4557 (calendar-gregorian-from-absolute sd)))
4558 (n1 org-agenda-start-on-weekday)
4560 (- sd (+ (if (< d 0) 7 0) d)))))
4561 (day-numbers (list start))
4562 (inhibit-redisplay t)
4563 s e rtn rtnall file date d start-pos end-pos todayp nd)
4564 (setq org-agenda-redo-command
4565 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4566 ;; Make the list of days
4567 (setq ndays (or ndays org-agenda-ndays)
4570 (push (1+ (car day-numbers)) day-numbers)
4571 (setq ndays (1- ndays)))
4572 (setq day-numbers (nreverse day-numbers))
4573 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4575 (delete-other-windows)
4576 (switch-to-buffer-other-window
4577 (get-buffer-create org-agenda-buffer-name))))
4578 (setq buffer-read-only nil)
4580 (org-agenda-mode) (setq buffer-read-only nil)
4581 (set (make-local-variable 'org-agenda-type) 'agenda)
4582 (set (make-local-variable 'starting-day) (car day-numbers))
4583 (set (make-local-variable 'include-all-loc) include-all)
4584 (when (and (or include-all org-agenda-include-all-todo)
4585 (member today day-numbers))
4586 (setq files (org-agenda-files)
4588 (while (setq file (pop files))
4590 (org-check-agenda-file file)
4591 (setq date (calendar-gregorian-from-absolute today)
4592 rtn (org-agenda-get-day-entries
4594 (setq rtnall (append rtnall rtn))))
4596 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4597 (add-text-properties (point-min) (1- (point))
4598 (list 'face 'org-link))
4599 (insert (org-finalize-agenda-entries rtnall) "\n")))
4600 (while (setq d (pop day-numbers))
4601 (setq date (calendar-gregorian-from-absolute d)
4603 (if (or (setq todayp (= d today))
4604 (and (not start-pos) (= d sd)))
4605 (setq start-pos (point))
4606 (if (and start-pos (not end-pos))
4607 (setq end-pos (point))))
4608 (setq files (org-agenda-files)
4610 (while (setq file (pop files))
4612 (org-check-agenda-file file)
4613 (if org-agenda-show-log
4614 (setq rtn (org-agenda-get-day-entries
4616 :deadline :scheduled :timestamp :closed))
4617 (setq rtn (org-agenda-get-day-entries
4619 :deadline :scheduled :timestamp)))
4620 (setq rtnall (append rtnall rtn))))
4621 (if org-agenda-include-diary
4623 (require 'diary-lib)
4624 (setq rtn (org-get-entries-from-diary date))
4625 (setq rtnall (append rtnall rtn))))
4626 (if (or rtnall org-agenda-show-all-dates)
4628 (insert (format "%-9s %2d %s %4d\n"
4629 (calendar-day-name date)
4630 (extract-calendar-day date)
4631 (calendar-month-name (extract-calendar-month date))
4632 (extract-calendar-year date)))
4633 (put-text-property s (1- (point)) 'face
4636 (org-finalize-agenda-entries
4637 (org-agenda-add-time-grid-maybe
4640 (put-text-property s (1- (point)) 'day d))))
4641 (goto-char (point-min))
4642 (setq buffer-read-only t)
4643 (org-fit-agenda-window)
4644 (unless (and (pos-visible-in-window-p (point-min))
4645 (pos-visible-in-window-p (point-max)))
4646 (goto-char (1- (point-max)))
4648 (if (not (pos-visible-in-window-p (or start-pos 1)))
4650 (goto-char (or start-pos 1))
4652 (goto-char (or start-pos 1))
4653 (if (not org-select-agenda-window) (select-window win))
4656 (defvar org-select-this-todo-keyword nil)
4659 (defun org-todo-list (arg &optional keep-modes)
4660 "Show all TODO entries from all agenda file in a single list.
4661 The prefix arg can be used to select a specific TODO keyword and limit
4662 the list to these. When using \\[universal-argument], you will be prompted
4663 for a keyword. A numeric prefix directly selects the Nth keyword in
4664 `org-todo-keywords'."
4666 (org-agenda-maybe-reset-markers 'force)
4667 (org-compile-prefix-format org-agenda-prefix-format)
4668 (let* ((org-agenda-keep-modes keep-modes)
4669 (today (time-to-days (current-time)))
4670 (date (calendar-gregorian-from-absolute today))
4671 (win (selected-window))
4672 (kwds org-todo-keywords)
4673 (completion-ignore-case t)
4674 (org-select-this-todo-keyword
4675 (if (stringp arg) arg
4676 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
4677 rtn rtnall files file pos)
4678 (when (equal arg '(4))
4679 (setq org-select-this-todo-keyword
4680 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4682 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4683 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4685 (delete-other-windows)
4686 (switch-to-buffer-other-window
4687 (get-buffer-create org-agenda-buffer-name))))
4688 (setq buffer-read-only nil)
4690 (org-agenda-mode) (setq buffer-read-only nil)
4691 (set (make-local-variable 'org-agenda-type) 'todo)
4692 (set (make-local-variable 'last-arg) arg)
4693 (set (make-local-variable 'org-todo-keywords) kwds)
4694 (set (make-local-variable 'org-agenda-redo-command)
4695 '(org-todo-list (or current-prefix-arg last-arg) t))
4696 (setq files (org-agenda-files)
4698 (while (setq file (pop files))
4700 (org-check-agenda-file file)
4701 (setq rtn (org-agenda-get-day-entries file date :todo))
4702 (setq rtnall (append rtnall rtn))))
4703 (insert "Global list of TODO items of type: ")
4704 (add-text-properties (point-min) (1- (point))
4705 (list 'face 'org-link))
4707 (insert (or org-select-this-todo-keyword "ALL") "\n")
4708 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4711 "Available with `N r': (0)ALL "
4713 (mapconcat (lambda (x)
4714 (format "(%d)%s" (setq n (1+ n)) x))
4715 org-todo-keywords " "))
4717 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4719 (insert (org-finalize-agenda-entries rtnall) "\n"))
4720 (goto-char (point-min))
4721 (setq buffer-read-only t)
4722 (org-fit-agenda-window)
4723 (if (not org-select-agenda-window) (select-window win))))
4725 (defun org-check-agenda-file (file)
4726 "Make sure FILE exists. If not, ask user what to do."
4727 ;; FIXME: this does not correctly change the menus
4728 ;; Could probably be fixed by explicitly going to the buffer where
4729 ;; the call originated.
4730 (when (not (file-exists-p file))
4731 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4733 (let ((r (downcase (read-char-exclusive))))
4736 (org-remove-file file)
4737 (throw 'nextfile t))
4738 (t (error "Abort"))))))
4740 (defun org-agenda-check-type (error &rest types)
4741 "Check if agenda buffer is of allowed type.
4742 If ERROR is non-nil, throw an error, otherwise just return nil."
4743 (if (memq org-agenda-type types)
4746 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
4749 (defun org-agenda-quit ()
4750 "Exit agenda by removing the window or the buffer."
4752 (let ((buf (current-buffer)))
4753 (if (not (one-window-p)) (delete-window))
4755 (org-agenda-maybe-reset-markers 'force)))
4757 (defun org-agenda-exit ()
4758 "Exit agenda by removing the window or the buffer.
4759 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4760 Org-mode buffers visited directly by the user will not be touched."
4762 (org-release-buffers org-agenda-new-buffers)
4763 (setq org-agenda-new-buffers nil)
4766 (defun org-agenda-redo ()
4768 When this is the global TODO list, a prefix argument will be interpreted."
4770 (message "Rebuilding agenda buffer...")
4771 (eval org-agenda-redo-command)
4772 (message "Rebuilding agenda buffer...done"))
4774 (defun org-agenda-goto-today ()
4777 (org-agenda-check-type t 'timeline 'agenda)
4778 (if (boundp 'starting-day)
4779 (let ((cmd (car org-agenda-redo-command))
4780 (iall (nth 1 org-agenda-redo-command))
4781 (nday (nth 3 org-agenda-redo-command))
4782 (keep (nth 4 org-agenda-redo-command)))
4783 (eval (list cmd iall nil nday keep)))
4784 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4787 (defun org-agenda-later (arg)
4788 "Go forward in time by `org-agenda-ndays' days.
4789 With prefix ARG, go forward that many times `org-agenda-ndays'."
4791 (org-agenda-check-type t 'agenda)
4792 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4793 (+ starting-day (* arg org-agenda-ndays)) nil t))
4795 (defun org-agenda-earlier (arg)
4796 "Go back in time by `org-agenda-ndays' days.
4797 With prefix ARG, go back that many times `org-agenda-ndays'."
4799 (org-agenda-check-type t 'agenda)
4800 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4801 (- starting-day (* arg org-agenda-ndays)) nil t))
4803 (defun org-agenda-week-view ()
4804 "Switch to weekly view for agenda."
4806 (org-agenda-check-type t 'agenda)
4807 (setq org-agenda-ndays 7)
4808 (org-agenda-list include-all-loc
4809 (or (get-text-property (point) 'day)
4812 (org-agenda-set-mode-name)
4813 (message "Switched to week view"))
4815 (defun org-agenda-day-view ()
4816 "Switch to weekly view for agenda."
4818 (org-agenda-check-type t 'agenda)
4819 (setq org-agenda-ndays 1)
4820 (org-agenda-list include-all-loc
4821 (or (get-text-property (point) 'day)
4824 (org-agenda-set-mode-name)
4825 (message "Switched to day view"))
4827 (defun org-agenda-next-date-line (&optional arg)
4828 "Jump to the next line indicating a date in agenda buffer."
4830 (org-agenda-check-type t 'agenda 'timeline)
4831 (beginning-of-line 1)
4832 (if (looking-at "^\\S-") (forward-char 1))
4833 (if (not (re-search-forward "^\\S-" nil t arg))
4836 (error "No next date after this line in this buffer")))
4837 (goto-char (match-beginning 0)))
4839 (defun org-agenda-previous-date-line (&optional arg)
4840 "Jump to the next line indicating a date in agenda buffer."
4842 (org-agenda-check-type t 'agenda 'timeline)
4843 (beginning-of-line 1)
4844 (if (not (re-search-backward "^\\S-" nil t arg))
4845 (error "No previous date before this line in this buffer")))
4847 ;; Initialize the highlight
4848 (defvar org-hl (org-make-overlay 1 1))
4849 (org-overlay-put org-hl 'face 'highlight)
4851 (defun org-highlight (begin end &optional buffer)
4852 "Highlight a region with overlay."
4853 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4854 org-hl begin end (or buffer (current-buffer))))
4856 (defun org-unhighlight ()
4857 "Detach overlay INDEX."
4858 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4861 (defun org-agenda-follow-mode ()
4862 "Toggle follow mode in an agenda buffer."
4864 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4865 (org-agenda-set-mode-name)
4866 (message "Follow mode is %s"
4867 (if org-agenda-follow-mode "on" "off")))
4869 (defun org-agenda-log-mode ()
4870 "Toggle follow mode in an agenda buffer."
4872 (org-agenda-check-type t 'agenda 'timeline)
4873 (setq org-agenda-show-log (not org-agenda-show-log))
4874 (org-agenda-set-mode-name)
4876 (message "Log mode is %s"
4877 (if org-agenda-show-log "on" "off")))
4879 (defun org-agenda-toggle-diary ()
4880 "Toggle follow mode in an agenda buffer."
4882 (org-agenda-check-type t 'agenda)
4883 (setq org-agenda-include-diary (not org-agenda-include-diary))
4885 (org-agenda-set-mode-name)
4886 (message "Diary inclusion turned %s"
4887 (if org-agenda-include-diary "on" "off")))
4889 (defun org-agenda-toggle-time-grid ()
4890 "Toggle follow mode in an agenda buffer."
4892 (org-agenda-check-type t 'agenda)
4893 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
4895 (org-agenda-set-mode-name)
4896 (message "Time-grid turned %s"
4897 (if org-agenda-use-time-grid "on" "off")))
4899 (defun org-agenda-set-mode-name ()
4900 "Set the mode name to indicate all the small mode settings."
4902 (concat "Org-Agenda"
4903 (if (equal org-agenda-ndays 1) " Day" "")
4904 (if (equal org-agenda-ndays 7) " Week" "")
4905 (if org-agenda-follow-mode " Follow" "")
4906 (if org-agenda-include-diary " Diary" "")
4907 (if org-agenda-use-time-grid " Grid" "")
4908 (if org-agenda-show-log " Log" "")))
4909 (force-mode-line-update))
4911 (defun org-agenda-post-command-hook ()
4912 (and (eolp) (not (bolp)) (backward-char 1))
4913 (if (and org-agenda-follow-mode
4914 (get-text-property (point) 'org-marker))
4917 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
4919 (defun org-get-entries-from-diary (date)
4920 "Get the (Emacs Calendar) diary entries for DATE."
4921 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4922 (diary-display-hook '(fancy-diary-display))
4923 (list-diary-entries-hook
4924 (cons 'org-diary-default-entry list-diary-entries-hook))
4925 (diary-file-name-prefix-function nil) ; turn this feature off
4926 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
4928 (org-disable-agenda-to-diary t))
4930 (save-window-excursion
4931 (list-diary-entries date 1)))
4932 (if (not (get-buffer fancy-diary-buffer))
4934 (with-current-buffer fancy-diary-buffer
4935 (setq buffer-read-only nil)
4936 (if (= (point-max) 1)
4939 ;; Omit the date and other unnecessary stuff
4940 (org-agenda-cleanup-fancy-diary)
4941 ;; Add prefix to each line and extend the text properties
4942 (if (= (point-max) 1)
4944 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4945 (set-buffer-modified-p nil)
4946 (kill-buffer fancy-diary-buffer)))
4948 (setq entries (org-split-string entries "\n"))
4952 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
4953 ;; Extend the text properties to the beginning of the line
4954 (add-text-properties
4956 (text-properties-at (1- (length x)) x)
4961 (defun org-agenda-cleanup-fancy-diary ()
4962 "Remove unwanted stuff in buffer created by fancy-diary-display.
4963 This gets rid of the date, the underline under the date, and
4964 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4965 date. Itt also removes lines that contain only whitespace."
4966 (goto-char (point-min))
4967 (if (looking-at ".*?:[ \t]*")
4970 (re-search-forward "\n=+$" nil t)
4972 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4973 (re-search-forward "\n=+$" nil t)
4974 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4975 (goto-char (point-min))
4976 (while (re-search-forward "^ +\n" nil t)
4978 (goto-char (point-min))
4979 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4980 (replace-match "")))
4982 ;; Make sure entries from the diary have the right text properties.
4983 (eval-after-load "diary-lib"
4984 '(if (boundp 'diary-modify-entry-list-string-function)
4985 ;; We can rely on the hook, nothing to do
4987 ;; Hook not avaiable, must use advice to make this work
4988 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
4989 "Make the position visible."
4990 (if (and org-disable-agenda-to-diary ;; called from org-agenda
4993 (setq string (org-modify-diary-entry-string string))))))
4995 (defun org-modify-diary-entry-string (string)
4996 "Add text properties to string, allowing org-mode to act on it."
4997 (add-text-properties
4999 (list 'mouse-face 'highlight
5000 'keymap org-agenda-keymap
5003 "mouse-2 or RET jump to diary file %s"
5004 (abbreviate-file-name (buffer-file-name)))
5005 'org-agenda-diary-link t
5006 'org-marker (org-agenda-new-marker (point-at-bol)))
5010 (defun org-diary-default-entry ()
5011 "Add a dummy entry to the diary.
5012 Needed to avoid empty dates which mess up holiday display."
5013 ;; Catch the error if dealing with the new add-to-diary-alist
5014 (when org-disable-agenda-to-diary
5016 (add-to-diary-list original-date "Org-mode dummy" "")
5018 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5020 (defun org-cycle-agenda-files ()
5021 "Cycle through the files in `org-agenda-files'.
5022 If the current buffer visits an agenda file, find the next one in the list.
5023 If the current buffer does not, find the first agenda file."
5025 (let ((files (append org-agenda-files (list (car org-agenda-files))))
5026 (tcf (if (buffer-file-name) (file-truename (buffer-file-name))))
5028 (unless files (error "No agenda files"))
5030 (while (setq file (pop files))
5031 (if (equal (file-truename file) tcf)
5033 (find-file (car files))
5035 (find-file (car org-agenda-files)))))
5037 (defun org-agenda-file-to-end (&optional file)
5038 "Move/add the current file to the end of the agenda fiole list.
5039 I the file is not present in the list, it is appended ot the list. If it is
5040 present, it is moved there."
5042 (org-agenda-file-to-front 'to-end file))
5044 (defun org-agenda-file-to-front (&optional to-end file)
5045 "Move/add the current file to the top of the agenda file list.
5046 If the file is not present in the list, it is added to the front. If it is
5047 present, it is moved there. With optional argument TO-END, add/move to the
5050 (let ((file-alist (mapcar (lambda (x)
5051 (cons (file-truename x) x))
5053 (ctf (file-truename (buffer-file-name)))
5055 (setq x (assoc ctf file-alist) had x)
5057 (if (not x) (setq x (cons ctf (abbreviate-file-name (buffer-file-name)))))
5059 (setq file-alist (append (delq x file-alist) (list x)))
5060 (setq file-alist (cons x (delq x file-alist))))
5061 (setq org-agenda-files (mapcar 'cdr file-alist))
5062 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5063 (customize-save-variable 'org-agenda-files org-agenda-files))
5064 (org-install-agenda-files-menu)
5065 (message "File %s to %s of agenda file list"
5066 (if had "moved" "added") (if to-end "end" "front"))))
5068 (defun org-remove-file (&optional file)
5069 "Remove current file from the list of files in variable `org-agenda-files'.
5070 These are the files which are being checked for agenda entries.
5071 Optional argument FILE means, use this file instead of the current."
5073 (let* ((file (or file (buffer-file-name)))
5074 (true-file (file-truename file))
5075 (afile (abbreviate-file-name file))
5076 (files (delq nil (mapcar
5078 (if (equal true-file
5081 org-agenda-files))))
5082 (if (not (= (length files) (length org-agenda-files)))
5084 (setq org-agenda-files files)
5085 (customize-save-variable 'org-agenda-files org-agenda-files)
5086 (org-install-agenda-files-menu)
5087 (message "Removed file: %s" afile))
5088 (message "File was not in list: %s" afile))))
5090 (defun org-file-menu-entry (file)
5091 (vector file (list 'find-file file) t))
5092 ;; FIXME: Maybe we removed a buffer visited through the menu from
5093 ;; org-agenda-new-buffers, so that the buffer will not be removed
5094 ;; when exiting the agenda????
5096 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5097 "Return a list of all relevant day numbers from BEG to END buffer positions.
5098 If NO-RANGES is non-nil, include only the start and end dates of a range,
5099 not every single day in the range. If FORCE-TODAY is non-nil, make
5100 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5101 inactive time stamps (those in square brackets) are included."
5102 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5103 dates date day day1 day2 ts1 ts2)
5105 (setq dates (list (time-to-days (current-time)))))
5108 (while (re-search-forward re end t)
5109 (setq day (time-to-days (org-time-string-to-time
5110 (substring (match-string 1) 0 10))))
5111 (or (memq day dates) (push day dates)))
5114 (while (re-search-forward org-tr-regexp end t)
5115 (setq ts1 (substring (match-string 1) 0 10)
5116 ts2 (substring (match-string 2) 0 10)
5117 day1 (time-to-days (org-time-string-to-time ts1))
5118 day2 (time-to-days (org-time-string-to-time ts2)))
5119 (while (< (setq day1 (1+ day1)) day2)
5120 (or (memq day1 dates) (push day1 dates)))))
5124 (defun org-diary (&rest args)
5125 "Return diary information from org-files.
5126 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5127 It accesses org files and extracts information from those files to be
5128 listed in the diary. The function accepts arguments specifying what
5129 items should be listed. The following arguments are allowed:
5131 :timestamp List the headlines of items containing a date stamp or
5132 date range matching the selected date. Deadlines will
5133 also be listed, on the expiration day.
5135 :deadline List any deadlines past due, or due within
5136 `org-deadline-warning-days'. The listing occurs only
5137 in the diary for *today*, not at any other date. If
5138 an entry is marked DONE, it is no longer listed.
5140 :scheduled List all items which are scheduled for the given date.
5141 The diary for *today* also contains items which were
5142 scheduled earlier and are not yet marked DONE.
5144 :todo List all TODO items from the org-file. This may be a
5145 long list - so this is not turned on by default.
5146 Like deadlines, these entries only show up in the
5147 diary for *today*, not at any other date.
5149 The call in the diary file should look like this:
5151 &%%(org-diary) ~/path/to/some/orgfile.org
5153 Use a separate line for each org file to check. Or, if you omit the file name,
5154 all files listed in `org-agenda-files' will be checked automatically:
5158 If you don't give any arguments (as in the example above), the default
5159 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5162 &%%(org-diary :deadline :timestamp :scheduled)
5164 The function expects the lisp variables `entry' and `date' to be provided
5165 by the caller, because this is how the calendar works. Don't use this
5166 function from a program - use `org-agenda-get-day-entries' instead."
5167 (org-agenda-maybe-reset-markers)
5168 (org-compile-prefix-format org-agenda-prefix-format)
5169 (setq args (or args '(:deadline :scheduled :timestamp)))
5170 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5174 ;; If this is called during org-agenda, don't return any entries to
5175 ;; the calendar. Org Agenda will list these entries itself.
5176 (if org-disable-agenda-to-diary (setq files nil))
5177 (while (setq file (pop files))
5178 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5179 (setq results (append results rtn)))
5181 (concat (org-finalize-agenda-entries results) "\n"))))
5182 (defvar org-category-table nil)
5183 (defun org-get-category-table ()
5184 "Get the table of categories and positions in current buffer."
5187 (goto-char (point-min))
5188 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5189 (push (cons (point) (org-trim (match-string 2))) tbl)))
5191 (defun org-get-category (&optional pos)
5192 "Get the category applying to position POS."
5193 (if (not org-category-table)
5195 ((null org-category)
5197 (if (buffer-file-name)
5198 (file-name-sans-extension
5199 (file-name-nondirectory (buffer-file-name)))
5201 ((symbolp org-category) (symbol-name org-category))
5203 (let ((tbl org-category-table)
5204 (pos (or pos (point))))
5205 (while (and tbl (> (caar tbl) pos))
5207 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5208 org-category-table))))))
5210 (defun org-agenda-get-day-entries (file date &rest args)
5211 "Does the work for `org-diary' and `org-agenda'.
5212 FILE is the path to a file to be checked for entries. DATE is date like
5213 the one returned by `calendar-current-date'. ARGS are symbols indicating
5214 which kind of entries should be extracted. For details about these, see
5215 the documentation of `org-diary'."
5216 (setq args (or args '(:deadline :scheduled :timestamp)))
5217 (let* ((org-startup-with-deadline-check nil)
5218 (org-startup-folded nil)
5219 (buffer (if (file-exists-p file)
5220 (org-get-agenda-file-buffer file)
5221 (error "No such file %s" file)))
5224 ;; If file does not exist, make sure an error message ends up in diary
5225 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5226 (with-current-buffer buffer
5227 (unless (eq major-mode 'org-mode)
5228 (error "Agenda file %s is not in `org-mode'" file))
5229 (setq org-category-table (org-get-category-table))
5230 (let ((case-fold-search nil))
5233 (if org-respect-restriction
5234 (if (org-region-active-p)
5235 ;; Respect a region to restrict search
5236 (narrow-to-region (region-beginning) (region-end)))
5237 ;; If we work for the calendar or many files,
5238 ;; get rid of any restriction
5240 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5241 (while (setq arg (pop args))
5243 ((and (eq arg :todo)
5244 (equal date (calendar-current-date)))
5245 (setq rtn (org-agenda-get-todos))
5246 (setq results (append results rtn)))
5247 ((eq arg :timestamp)
5248 (setq rtn (org-agenda-get-blocks))
5249 (setq results (append results rtn))
5250 (setq rtn (org-agenda-get-timestamps))
5251 (setq results (append results rtn)))
5252 ((eq arg :scheduled)
5253 (setq rtn (org-agenda-get-scheduled))
5254 (setq results (append results rtn)))
5256 (setq rtn (org-agenda-get-closed))
5257 (setq results (append results rtn)))
5258 ((and (eq arg :deadline)
5259 (equal date (calendar-current-date)))
5260 (setq rtn (org-agenda-get-deadlines))
5261 (setq results (append results rtn))))))))
5264 (defun org-entry-is-done-p ()
5265 "Is the current entry marked DONE?"
5267 (and (re-search-backward "[\r\n]\\*" nil t)
5268 (looking-at org-nl-done-regexp))))
5270 (defun org-at-date-range-p ()
5271 "Is the cursor inside a date range?"
5275 (let ((pos (point)))
5276 (skip-chars-backward "^<\r\n")
5277 (skip-chars-backward "<")
5278 (and (looking-at org-tr-regexp)
5279 (>= (match-end 0) pos)
5281 (skip-chars-backward "^<\r\n")
5282 (skip-chars-backward "<")
5283 (and (looking-at org-tr-regexp)
5284 (>= (match-end 0) pos)
5288 (defun org-get-tags-at (&optional pos)
5289 "Get a list of all headline targs applicable at POS.
5290 POS defaults to point. If tags are inherited, the list contains
5291 the targets in the same sequence as the headlines appear, i.e.
5292 the tags of the current headline come last."
5296 (goto-char (or pos (point)))
5298 (org-back-to-heading t)
5301 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
5302 (setq tags (append (org-split-string (match-string 1) ":") tags)))
5303 (or org-use-tag-inheritance (error ""))
5304 (org-up-heading-all 1))
5309 (defun org-agenda-get-todos ()
5310 "Return the TODO information for agenda display."
5311 (let* ((props (list 'face nil
5312 'done-face 'org-done
5313 'mouse-face 'highlight
5314 'keymap org-agenda-keymap
5316 (format "mouse-2 or RET jump to org file %s"
5317 (abbreviate-file-name (buffer-file-name)))))
5318 (regexp (concat "[\n\r]\\*+ *\\("
5319 (if org-select-this-todo-keyword
5320 (concat "\\<\\(" org-select-this-todo-keyword
5322 org-not-done-regexp)
5324 marker priority category tags
5326 (goto-char (point-min))
5327 (while (re-search-forward regexp nil t)
5328 (goto-char (match-beginning 1))
5329 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5330 category (org-get-category)
5331 tags (org-get-tags-at (point))
5332 txt (org-format-agenda-item "" (match-string 1) category tags)
5334 (+ (org-get-priority txt)
5335 (if org-todo-kwd-priority-p
5336 (- org-todo-kwd-max-priority -2
5338 (member (match-string 2) org-todo-keywords)))
5340 (add-text-properties
5341 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5342 'priority priority 'category category)
5346 (goto-char (match-end 1)))
5349 (defconst org-agenda-no-heading-message
5350 "No heading for this item in buffer or region")
5352 (defun org-agenda-get-timestamps ()
5353 "Return the date stamp information for agenda display."
5354 (let* ((props (list 'face nil
5355 'mouse-face 'highlight
5356 'keymap org-agenda-keymap
5358 (format "mouse-2 or RET jump to org file %s"
5359 (abbreviate-file-name (buffer-file-name)))))
5360 (regexp (regexp-quote
5363 (car org-time-stamp-formats)
5364 (apply 'encode-time ; DATE bound by calendar
5365 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5367 marker hdmarker deadlinep scheduledp donep tmp priority category
5368 ee txt timestr tags)
5369 (goto-char (point-min))
5370 (while (re-search-forward regexp nil t)
5371 (if (not (save-match-data (org-at-date-range-p)))
5373 (setq marker (org-agenda-new-marker (match-beginning 0))
5374 category (org-get-category (match-beginning 0))
5375 tmp (buffer-substring (max (point-min)
5376 (- (match-beginning 0)
5377 org-ds-keyword-length))
5378 (match-beginning 0))
5379 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5380 deadlinep (string-match org-deadline-regexp tmp)
5381 scheduledp (string-match org-scheduled-regexp tmp)
5382 donep (org-entry-is-done-p))
5383 (if (string-match ">" timestr)
5384 ;; substring should only run to end of time stamp
5385 (setq timestr (substring timestr 0 (match-end 0))))
5387 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5389 (goto-char (match-end 1))
5390 (setq hdmarker (org-agenda-new-marker)
5391 tags (org-get-tags-at))
5392 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5393 (setq txt (org-format-agenda-item
5395 (if deadlinep "Deadline: " "")
5396 (if scheduledp "Scheduled: " ""))
5397 (match-string 1) category tags timestr)))
5398 (setq txt org-agenda-no-heading-message))
5399 (setq priority (org-get-priority txt))
5400 (add-text-properties
5401 0 (length txt) (append (list 'org-marker marker
5402 'org-hd-marker hdmarker) props)
5405 (add-text-properties
5408 (if donep 'org-done 'org-warning)
5409 'undone-face 'org-warning
5410 'done-face 'org-done
5412 'priority (+ 100 priority))
5415 (add-text-properties
5417 (list 'face 'org-scheduled-today
5418 'undone-face 'org-scheduled-today
5419 'done-face 'org-done
5421 priority (+ 99 priority))
5423 (add-text-properties
5425 (list 'priority priority 'category category) txt)))
5427 (outline-next-heading))))
5430 (defun org-agenda-get-closed ()
5431 "Return the loggedd TODO entries for agenda display."
5432 (let* ((props (list 'mouse-face 'highlight
5433 'keymap org-agenda-keymap
5435 (format "mouse-2 or RET jump to org file %s"
5436 (abbreviate-file-name (buffer-file-name)))))
5438 "\\<" org-closed-string " *\\["
5442 (car org-time-stamp-formats)
5443 (apply 'encode-time ; DATE bound by calendar
5444 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5446 marker hdmarker priority category tags
5448 (goto-char (point-min))
5449 (while (re-search-forward regexp nil t)
5450 (if (not (save-match-data (org-at-date-range-p)))
5452 (setq marker (org-agenda-new-marker (match-beginning 0))
5453 category (org-get-category (match-beginning 0))
5454 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5455 ;; donep (org-entry-is-done-p)
5457 (if (string-match "\\]" timestr)
5458 ;; substring should only run to end of time stamp
5459 (setq timestr (substring timestr 0 (match-end 0))))
5461 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5463 (goto-char (match-end 1))
5464 (setq hdmarker (org-agenda-new-marker)
5465 tags (org-get-tags-at))
5466 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5467 (setq txt (org-format-agenda-item
5469 (match-string 1) category tags timestr)))
5470 (setq txt org-agenda-no-heading-message))
5471 (setq priority 100000)
5472 (add-text-properties
5473 0 (length txt) (append (list 'org-marker marker
5474 'org-hd-marker hdmarker
5478 'undone-face 'org-warning
5479 'done-face 'org-done) props)
5482 (outline-next-heading))))
5485 (defun org-agenda-get-deadlines ()
5486 "Return the deadline information for agenda display."
5487 (let* ((wdays org-deadline-warning-days)
5488 (props (list 'mouse-face 'highlight
5489 'keymap org-agenda-keymap
5491 (format "mouse-2 or RET jump to org file %s"
5492 (abbreviate-file-name (buffer-file-name)))))
5493 (regexp org-deadline-time-regexp)
5494 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5495 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5496 d2 diff pos pos1 category tags
5498 (goto-char (point-min))
5499 (while (re-search-forward regexp nil t)
5500 (setq pos (1- (match-beginning 1))
5502 (org-time-string-to-time (match-string 1)))
5504 ;; When to show a deadline in the calendar:
5505 ;; If the expiration is within wdays warning time.
5506 ;; Past-due deadlines are only shown on the current date
5507 (if (and (< diff wdays) todayp (not (= diff 0)))
5509 (setq category (org-get-category))
5510 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5512 (goto-char (match-end 0))
5513 (setq pos1 (match-end 1))
5514 (setq tags (org-get-tags-at pos1))
5515 (setq head (buffer-substring-no-properties
5517 (progn (skip-chars-forward "^\r\n")
5519 (if (string-match org-looking-at-done-regexp head)
5521 (setq txt (org-format-agenda-item
5522 (format "In %3d d.: " diff) head category tags))))
5523 (setq txt org-agenda-no-heading-message))
5525 (add-text-properties
5528 (list 'org-marker (org-agenda-new-marker pos)
5529 'org-hd-marker (org-agenda-new-marker pos1)
5530 'priority (+ (- 10 diff) (org-get-priority txt))
5532 'face (cond ((<= diff 0) 'org-warning)
5533 ((<= diff 5) 'org-scheduled-previously)
5536 ((<= diff 0) 'org-warning)
5537 ((<= diff 5) 'org-scheduled-previously)
5539 'done-face 'org-done)
5545 (defun org-agenda-get-scheduled ()
5546 "Return the scheduled information for agenda display."
5547 (let* ((props (list 'face 'org-scheduled-previously
5548 'undone-face 'org-scheduled-previously
5549 'done-face 'org-done
5550 'mouse-face 'highlight
5551 'keymap org-agenda-keymap
5553 (format "mouse-2 or RET jump to org file %s"
5554 (abbreviate-file-name (buffer-file-name)))))
5555 (regexp org-scheduled-time-regexp)
5556 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5557 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5558 d2 diff pos pos1 category tags
5560 (goto-char (point-min))
5561 (while (re-search-forward regexp nil t)
5562 (setq pos (1- (match-beginning 1))
5564 (org-time-string-to-time (match-string 1)))
5566 ;; When to show a scheduled item in the calendar:
5567 ;; If it is on or past the date.
5568 (if (and (< diff 0) todayp)
5570 (setq category (org-get-category))
5571 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5573 (goto-char (match-end 0))
5574 (setq pos1 (match-end 1))
5575 (setq tags (org-get-tags-at))
5576 (setq head (buffer-substring-no-properties
5578 (progn (skip-chars-forward "^\r\n") (point))))
5579 (if (string-match org-looking-at-done-regexp head)
5581 (setq txt (org-format-agenda-item
5582 (format "Sched.%2dx: " (- 1 diff)) head
5584 (setq txt org-agenda-no-heading-message))
5586 (add-text-properties
5588 (append (list 'org-marker (org-agenda-new-marker pos)
5589 'org-hd-marker (org-agenda-new-marker pos1)
5590 'priority (+ (- 5 diff) (org-get-priority txt))
5596 (defun org-agenda-get-blocks ()
5597 "Return the date-range information for agenda display."
5598 (let* ((props (list 'face nil
5599 'mouse-face 'highlight
5600 'keymap org-agenda-keymap
5602 (format "mouse-2 or RET jump to org file %s"
5603 (abbreviate-file-name (buffer-file-name)))))
5604 (regexp org-tr-regexp)
5605 (d0 (calendar-absolute-from-gregorian date))
5606 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
5607 (goto-char (point-min))
5608 (while (re-search-forward regexp nil t)
5609 (setq timestr (match-string 0)
5612 d1 (time-to-days (org-time-string-to-time s1))
5613 d2 (time-to-days (org-time-string-to-time s2)))
5614 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5615 ;; Only allow days between the limits, because the normal
5616 ;; date stamps will catch the limits.
5618 (setq marker (org-agenda-new-marker (point)))
5619 (setq category (org-get-category))
5620 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5622 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5623 (goto-char (match-end 1))
5624 (setq tags (org-get-tags-at))
5625 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5626 (setq txt (org-format-agenda-item
5627 (format (if (= d1 d2) "" "(%d/%d): ")
5628 (1+ (- d0 d1)) (1+ (- d2 d1)))
5629 (match-string 1) category tags
5630 (if (= d0 d1) timestr))))
5631 (setq txt org-agenda-no-heading-message))
5632 (add-text-properties
5633 0 (length txt) (append (list 'org-marker marker
5634 'org-hd-marker hdmarker
5635 'priority (org-get-priority txt)
5640 (outline-next-heading))
5641 ;; Sort the entries by expiration date.
5644 (defconst org-plain-time-of-day-regexp
5647 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5650 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5652 "Regular expression to match a plain time or time range.
5653 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5654 groups carry important information:
5656 1 the first time, range or not
5657 8 the second time, if it is a range.")
5659 (defconst org-stamp-time-of-day-regexp
5661 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5662 "\\([012][0-9]:[0-5][0-9]\\)>"
5664 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5665 "Regular expression to match a timestamp time or time range.
5666 After a match, the following groups carry important information:
5668 1 date plus weekday, for backreferencing to make sure both times on same day
5669 2 the first time, range or not
5670 4 the second time, if it is a range.")
5672 (defvar org-prefix-has-time nil
5673 "A flag, set by `org-compile-prefix-format'.
5674 The flag is set if the currently compiled format contains a `%t'.")
5675 (defvar org-prefix-has-tag nil
5676 "A flag, set by `org-compile-prefix-format'.
5677 The flag is set if the currently compiled format contains a `%T'.")
5679 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
5680 "Format TXT to be inserted into the agenda buffer.
5681 In particular, it adds the prefix and corresponding text properties. EXTRA
5682 must be a string and replaces the `%s' specifier in the prefix format.
5683 CATEGORY (string, symbol or nil) may be used to overule the default
5684 category taken from local variable or file name. It will replace the `%c'
5685 specifier in the format. DOTIME, when non-nil, indicates that a
5686 time-of-day should be extracted from TXT for sorting of this entry, and for
5687 the `%t' specifier in the format. When DOTIME is a string, this string is
5688 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5689 only the correctly processes TXT should be returned - this is used by
5690 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
5692 ;; Diary entries sometimes have extra whitespace at the beginning
5693 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5694 (let* ((category (or category
5696 (if (buffer-file-name)
5697 (file-name-sans-extension
5698 (file-name-nondirectory (buffer-file-name)))
5700 (tag (or (nth (1- (length tags)) tags) ""))
5701 time ;; needed for the eval of the prefix format
5702 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5703 (time-of-day (and dotime (org-get-time-of-day ts)))
5704 stamp plain s0 s1 s2 rtn)
5705 (when (and dotime time-of-day org-prefix-has-time)
5706 ;; Extract starting and ending time and move them to prefix
5707 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5708 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5709 (setq s0 (match-string 0 ts)
5710 s1 (match-string (if plain 1 2) ts)
5711 s2 (match-string (if plain 8 4) ts))
5713 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5714 ;; them, we might want to remove them there to avoid duplication.
5715 ;; The user can turn this off with a variable.
5716 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5717 (string-match (concat (regexp-quote s0) " *") txt)
5718 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5719 (= (match-beginning 0) 0)
5721 (setq txt (replace-match "" nil nil txt))))
5722 ;; Normalize the time(s) to 24 hour
5723 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5724 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5726 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
5727 (and org-agenda-remove-tags-when-in-prefix
5728 org-prefix-has-tag))
5729 (string-match ":[a-zA-Z_:]+:[ \t]*$" txt))
5730 (setq txt (replace-match "" t t txt)))
5732 ;; Create the final string
5735 ;; Prepare the variables needed in the eval of the compiled format
5736 (setq time (cond (s2 (concat s1 "-" s2))
5737 (s1 (concat s1 "......"))
5740 category (if (symbolp category) (symbol-name category) category))
5741 ;; Evaluate the compiled format
5742 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5744 ;; And finally add the text properties
5745 (add-text-properties
5746 0 (length rtn) (list 'category (downcase category)
5748 'prefix-length (- (length rtn) (length txt))
5749 'time-of-day time-of-day
5754 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5756 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5757 ((and todayp (member 'today (car org-agenda-time-grid))))
5758 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5759 ((member 'weekly (car org-agenda-time-grid)))
5760 (t (throw 'exit list)))
5761 (let* ((have (delq nil (mapcar
5762 (lambda (x) (get-text-property 1 'time-of-day x))
5764 (string (nth 1 org-agenda-time-grid))
5765 (gridtimes (nth 2 org-agenda-time-grid))
5766 (req (car org-agenda-time-grid))
5767 (remove (member 'remove-match req))
5769 (if (and (member 'require-timed req) (not have))
5770 ;; don't show empty grid
5772 (while (setq time (pop gridtimes))
5773 (unless (and remove (member time have))
5774 (setq time (int-to-string time))
5775 (push (org-format-agenda-item
5776 nil string "" nil ;; FIXME: put a category for the grid?
5777 (concat (substring time 0 -2) ":" (substring time -2)))
5780 1 (length (car new)) 'face 'org-time-grid (car new))))
5781 (if (member 'time-up org-agenda-sorting-strategy)
5783 (append list new)))))
5785 (defun org-compile-prefix-format (format)
5786 "Compile the prefix format into a Lisp form that can be evaluated.
5787 The resulting form is returned and stored in the variable
5788 `org-prefix-format-compiled'."
5789 (setq org-prefix-has-time nil org-prefix-has-tag nil)
5790 (let ((start 0) varform vars var (s format)e c f opt)
5791 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5793 (setq var (cdr (assoc (match-string 4 s)
5794 '(("c" . category) ("t" . time) ("s" . extra)
5796 c (or (match-string 3 s) "")
5797 opt (match-beginning 1)
5798 start (1+ (match-beginning 0)))
5799 (if (equal var 'time) (setq org-prefix-has-time t))
5800 (if (equal var 'tag) (setq org-prefix-has-tag t))
5801 (setq f (concat "%" (match-string 2 s) "s"))
5804 `(if (equal "" ,var)
5806 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
5807 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
5808 (setq s (replace-match "%s" t nil s))
5809 (push varform vars))
5810 (setq vars (nreverse vars))
5811 (setq org-prefix-format-compiled `(format ,s ,@vars))))
5813 (defun org-get-time-of-day (s &optional string)
5814 "Check string S for a time of day.
5815 If found, return it as a military time number between 0 and 2400.
5816 If not found, return nil.
5817 The optional STRING argument forces conversion into a 5 character wide string
5823 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
5825 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
5826 (let* ((t0 (+ (* 100
5827 (+ (string-to-number (match-string 1 s))
5828 (if (and (match-beginning 4)
5829 (equal (downcase (match-string 4 s)) "pm"))
5831 (if (match-beginning 3)
5832 (string-to-number (match-string 3 s))
5835 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
5836 (int-to-string t0))))
5837 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
5839 (defun org-finalize-agenda-entries (list)
5840 "Sort and concatenate the agenda items."
5841 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
5843 (defsubst org-cmp-priority (a b)
5844 "Compare the priorities of string a and b."
5845 (let ((pa (or (get-text-property 1 'priority a) 0))
5846 (pb (or (get-text-property 1 'priority b) 0)))
5847 (cond ((> pa pb) +1)
5851 (defsubst org-cmp-category (a b)
5852 "Compare the string values of categories of strings a and b."
5853 (let ((ca (or (get-text-property 1 'category a) ""))
5854 (cb (or (get-text-property 1 'category b) "")))
5855 (cond ((string-lessp ca cb) -1)
5856 ((string-lessp cb ca) +1)
5859 (defsubst org-cmp-time (a b)
5860 "Compare the time-of-day values of strings a and b."
5861 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
5862 (ta (or (get-text-property 1 'time-of-day a) def))
5863 (tb (or (get-text-property 1 'time-of-day b) def)))
5864 (cond ((< ta tb) -1)
5868 (defun org-entries-lessp (a b)
5869 "Predicate for sorting agenda entries."
5870 ;; The following variables will be used when the form is evaluated.
5871 (let* ((time-up (org-cmp-time a b))
5872 (time-down (if time-up (- time-up) nil))
5873 (priority-up (org-cmp-priority a b))
5874 (priority-down (if priority-up (- priority-up) nil))
5875 (category-up (org-cmp-category a b))
5876 (category-down (if category-up (- category-up) nil))
5877 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
5879 (eval (cons 'or org-agenda-sorting-strategy))
5880 '((-1 . t) (1 . nil) (nil . nil))))))
5882 (defun org-agenda-show-priority ()
5883 "Show the priority of the current item.
5884 This priority is composed of the main priority given with the [#A] cookies,
5885 and by additional input from the age of a schedules or deadline entry."
5887 (let* ((pri (get-text-property (point-at-bol) 'priority)))
5888 (message "Priority is %d" (if pri pri -1000))))
5890 (defun org-agenda-show-tags ()
5891 "Show the tags applicable to the current item."
5893 (let* ((tags (get-text-property (point-at-bol) 'tags)))
5895 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
5896 (message "No tags associated with this line"))))
5898 (defun org-agenda-goto (&optional highlight)
5899 "Go to the Org-mode file which contains the item at point."
5901 (let* ((marker (or (get-text-property (point) 'org-marker)
5902 (org-agenda-error)))
5903 (buffer (marker-buffer marker))
5904 (pos (marker-position marker)))
5905 (switch-to-buffer-other-window buffer)
5908 (when (eq major-mode 'org-mode)
5909 (org-show-hidden-entry)
5911 (and (outline-next-heading)
5912 (org-flag-heading nil)))) ; show the next heading
5913 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
5915 (defun org-agenda-switch-to ()
5916 "Go to the Org-mode file which contains the item at point."
5918 (let* ((marker (or (get-text-property (point) 'org-marker)
5919 (org-agenda-error)))
5920 (buffer (marker-buffer marker))
5921 (pos (marker-position marker)))
5922 (switch-to-buffer buffer)
5923 (delete-other-windows)
5926 (when (eq major-mode 'org-mode)
5927 (org-show-hidden-entry)
5929 (and (outline-next-heading)
5930 (org-flag-heading nil)))))) ; show the next heading
5932 (defun org-agenda-goto-mouse (ev)
5933 "Go to the Org-mode file which contains the item at the mouse click."
5935 (mouse-set-point ev)
5938 (defun org-agenda-show ()
5939 "Display the Org-mode file which contains the item at point."
5941 (let ((win (selected-window)))
5943 (select-window win)))
5945 (defun org-agenda-recenter (arg)
5946 "Display the Org-mode file which contains the item at point and recenter."
5948 (let ((win (selected-window)))
5951 (select-window win)))
5953 (defun org-agenda-show-mouse (ev)
5954 "Display the Org-mode file which contains the item at the mouse click."
5956 (mouse-set-point ev)
5959 (defun org-agenda-check-no-diary ()
5960 "Check if the entry is a diary link and abort if yes."
5961 (if (get-text-property (point) 'org-agenda-diary-link)
5962 (org-agenda-error)))
5964 (defun org-agenda-error ()
5965 (error "Command not allowed in this line"))
5967 (defvar org-last-heading-marker (make-marker)
5968 "Marker pointing to the headline that last changed its TODO state
5969 by a remote command from the agenda.")
5971 (defun org-agenda-todo (&optional arg)
5972 "Cycle TODO state of line at point, also in Org-mode file.
5973 This changes the line at point, all other lines in the agenda referring to
5974 the same tree node, and the headline of the tree node in the Org-mode file."
5976 (org-agenda-check-no-diary)
5977 (let* ((col (current-column))
5978 (marker (or (get-text-property (point) 'org-marker)
5979 (org-agenda-error)))
5980 (buffer (marker-buffer marker))
5981 (pos (marker-position marker))
5982 (hdmarker (get-text-property (point) 'org-hd-marker))
5983 (buffer-read-only nil)
5985 (with-current-buffer buffer
5988 (org-show-hidden-entry)
5990 (and (outline-next-heading)
5991 (org-flag-heading nil))) ; show the next heading
5994 (setq newhead (org-get-heading))
5996 (org-back-to-heading)
5997 (move-marker org-last-heading-marker (point))))
5998 (beginning-of-line 1)
6000 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6001 (move-to-column col)))
6003 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6004 "Change all lines in the agenda buffer which match hdmarker.
6005 The new content of the line will be NEWHEAD (as modified by
6006 `org-format-agenda-item'). HDMARKER is checked with
6007 `equal' against all `org-hd-marker' text properties in the file.
6008 If FIXFACE is non-nil, the face of each item is modified acording to
6009 the new TODO state."
6010 (let* (props m pl undone-face done-face finish new dotime cat tags)
6011 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6013 (goto-char (point-max))
6014 (beginning-of-line 1)
6016 (setq finish (bobp))
6017 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6019 (setq props (text-properties-at (point))
6020 dotime (get-text-property (point) 'dotime)
6021 cat (get-text-property (point) 'category)
6022 tags (get-text-property (point) 'tags)
6023 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6024 pl (get-text-property (point) 'prefix-length)
6025 undone-face (get-text-property (point) 'undone-face)
6026 done-face (get-text-property (point) 'done-face))
6028 (if (looking-at ".*")
6030 (replace-match new t t)
6031 (beginning-of-line 1)
6032 (add-text-properties (point-at-bol) (point-at-eol) props)
6034 (add-text-properties
6035 (point-at-bol) (point-at-eol)
6037 (if org-last-todo-state-is-todo
6038 undone-face done-face))))
6039 (beginning-of-line 1))
6040 (error "Line update did not work")))
6041 (beginning-of-line 0)))))
6043 (defun org-agenda-priority-up ()
6044 "Increase the priority of line at point, also in Org-mode file."
6046 (org-agenda-priority 'up))
6048 (defun org-agenda-priority-down ()
6049 "Decrease the priority of line at point, also in Org-mode file."
6051 (org-agenda-priority 'down))
6053 (defun org-agenda-priority (&optional force-direction)
6054 "Set the priority of line at point, also in Org-mode file.
6055 This changes the line at point, all other lines in the agenda referring to
6056 the same tree node, and the headline of the tree node in the Org-mode file."
6058 (org-agenda-check-no-diary)
6059 (let* ((marker (or (get-text-property (point) 'org-marker)
6060 (org-agenda-error)))
6061 (buffer (marker-buffer marker))
6062 (pos (marker-position marker))
6063 (hdmarker (get-text-property (point) 'org-hd-marker))
6064 (buffer-read-only nil)
6066 (with-current-buffer buffer
6069 (org-show-hidden-entry)
6071 (and (outline-next-heading)
6072 (org-flag-heading nil))) ; show the next heading
6073 (funcall 'org-priority force-direction)
6075 (setq newhead (org-get-heading)))
6076 (org-agenda-change-all-lines newhead hdmarker)
6077 (beginning-of-line 1)))
6079 (defun org-agenda-set-tags ()
6080 "Set tags for the current headline."
6082 (org-agenda-check-no-diary)
6083 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6084 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6085 (org-agenda-error)))
6086 (buffer (marker-buffer hdmarker))
6087 (pos (marker-position hdmarker))
6088 (buffer-read-only nil)
6090 (with-current-buffer buffer
6093 (org-show-hidden-entry)
6095 (and (outline-next-heading)
6096 (org-flag-heading nil))) ; show the next heading
6097 (call-interactively 'org-set-tags)
6099 (setq newhead (org-get-heading)))
6100 (org-agenda-change-all-lines newhead hdmarker)
6101 (beginning-of-line 1)))
6103 (defun org-agenda-date-later (arg &optional what)
6104 "Change the date of this item to one day later."
6106 (org-agenda-check-type t 'agenda 'timeline)
6107 (org-agenda-check-no-diary)
6108 (let* ((marker (or (get-text-property (point) 'org-marker)
6109 (org-agenda-error)))
6110 (buffer (marker-buffer marker))
6111 (pos (marker-position marker)))
6112 (with-current-buffer buffer
6115 (if (not (org-at-timestamp-p))
6116 (error "Cannot find time stamp"))
6117 (org-timestamp-change arg (or what 'day))
6118 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6120 (defun org-agenda-date-earlier (arg &optional what)
6121 "Change the date of this item to one day earlier."
6123 (org-agenda-date-later (- arg) what))
6125 (defun org-agenda-date-prompt (arg)
6126 "Change the date of this item. Date is prompted for, with default today.
6127 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6128 be used to request time specification in the time stamp."
6130 (org-agenda-check-type t 'agenda 'timeline)
6131 (org-agenda-check-no-diary)
6132 (let* ((marker (or (get-text-property (point) 'org-marker)
6133 (org-agenda-error)))
6134 (buffer (marker-buffer marker))
6135 (pos (marker-position marker)))
6136 (with-current-buffer buffer
6139 (if (not (org-at-timestamp-p))
6140 (error "Cannot find time stamp"))
6141 (org-time-stamp arg)
6142 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6144 (defun org-get-heading ()
6145 "Return the heading of the current entry, without the stars."
6147 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6148 ;;FIXME???????? (and (bolp) (end-of-line 1))
6149 (if (and (re-search-backward "[\r\n]\\*" nil t)
6150 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6154 (defun org-agenda-diary-entry ()
6155 "Make a diary entry, like the `i' command from the calendar.
6156 All the standard commands work: block, weekly etc"
6158 (org-agenda-check-type t 'agenda 'timeline)
6159 (require 'diary-lib)
6161 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6162 (read-char-exclusive)))
6163 (cmd (cdr (assoc char
6164 '((?d . insert-diary-entry)
6165 (?w . insert-weekly-diary-entry)
6166 (?m . insert-monthly-diary-entry)
6167 (?y . insert-yearly-diary-entry)
6168 (?a . insert-anniversary-diary-entry)
6169 (?b . insert-block-diary-entry)
6170 (?c . insert-cyclic-diary-entry)))))
6171 (oldf (symbol-function 'calendar-cursor-to-date))
6173 (mark (or (mark t) (point))))
6175 (error "No command associated with <%c>" char))
6176 (unless (and (get-text-property point 'day)
6177 (or (not (equal ?b char))
6178 (get-text-property mark 'day)))
6179 (error "Don't know which date to use for diary entry"))
6180 ;; We implement this by hacking the `calendar-cursor-to-date' function
6181 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6182 (let ((calendar-mark-ring
6183 (list (calendar-gregorian-from-absolute
6184 (or (get-text-property mark 'day)
6185 (get-text-property point 'day))))))
6188 (fset 'calendar-cursor-to-date
6189 (lambda (&optional error)
6190 (calendar-gregorian-from-absolute
6191 (get-text-property point 'day))))
6192 (call-interactively cmd))
6193 (fset 'calendar-cursor-to-date oldf)))))
6196 (defun org-agenda-execute-calendar-command (cmd)
6197 "Execute a calendar command from the agenda, with the date associated to
6198 the cursor position."
6199 (org-agenda-check-type t 'agenda 'timeline)
6200 (require 'diary-lib)
6201 (unless (get-text-property (point) 'day)
6202 (error "Don't know which date to use for calendar command"))
6203 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6205 (date (calendar-gregorian-from-absolute
6206 (get-text-property point 'day)))
6207 (displayed-day (extract-calendar-day date))
6208 (displayed-month (extract-calendar-month date))
6209 (displayed-year (extract-calendar-year date)))
6212 (fset 'calendar-cursor-to-date
6213 (lambda (&optional error)
6214 (calendar-gregorian-from-absolute
6215 (get-text-property point 'day))))
6216 (call-interactively cmd))
6217 (fset 'calendar-cursor-to-date oldf))))
6219 (defun org-agenda-phases-of-moon ()
6220 "Display the phases of the moon for the 3 months around the cursor date."
6222 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6224 (defun org-agenda-holidays ()
6225 "Display the holidays for the 3 months around the cursor date."
6227 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6229 (defun org-agenda-sunrise-sunset (arg)
6230 "Display sunrise and sunset for the cursor date.
6231 Latitude and longitude can be specified with the variables
6232 `calendar-latitude' and `calendar-longitude'. When called with prefix
6233 argument, latitude and longitude will be prompted for."
6235 (let ((calendar-longitude (if arg nil calendar-longitude))
6236 (calendar-latitude (if arg nil calendar-latitude))
6237 (calendar-location-name
6238 (if arg "the given coordinates" calendar-location-name)))
6239 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6241 (defun org-agenda-goto-calendar ()
6242 "Open the Emacs calendar with the date at the cursor."
6244 (org-agenda-check-type t 'agenda 'timeline)
6245 (let* ((day (or (get-text-property (point) 'day)
6246 (error "Don't know which date to open in calendar")))
6247 (date (calendar-gregorian-from-absolute day))
6248 (calendar-move-hook nil)
6249 (view-diary-entries-initially nil))
6251 (calendar-goto-date date)))
6253 (defun org-calendar-goto-agenda ()
6254 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6255 This is a command that has to be installed in `calendar-mode-map'."
6257 (org-agenda-list nil (calendar-absolute-from-gregorian
6258 (calendar-cursor-to-date))
6261 (defun org-agenda-convert-date ()
6263 (org-agenda-check-type t 'agenda 'timeline)
6264 (let ((day (get-text-property (point) 'day))
6267 (error "Don't know which date to convert"))
6268 (setq date (calendar-gregorian-from-absolute day))
6270 "Gregorian: " (calendar-date-string date) "\n"
6271 "ISO: " (calendar-iso-date-string date) "\n"
6272 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6273 "Julian: " (calendar-julian-date-string date) "\n"
6274 "Astron. JD: " (calendar-astro-date-string date)
6275 " (Julian date number at noon UTC)\n"
6276 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6277 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6278 "French: " (calendar-french-date-string date) "\n"
6279 "Mayan: " (calendar-mayan-date-string date) "\n"
6280 "Coptic: " (calendar-coptic-date-string date) "\n"
6281 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6282 "Persian: " (calendar-persian-date-string date) "\n"
6283 "Chinese: " (calendar-chinese-date-string date) "\n"))
6284 (with-output-to-temp-buffer "*Dates*"
6286 (if (fboundp 'fit-window-to-buffer)
6287 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6291 (defun org-scan-tags (action matcher &optional todo-only)
6292 "Scan headline tags with inheritance and produce output ACTION.
6293 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6294 evaluated, testing if a given set of tags qualifies a headline for
6295 inclusion. When TODO-ONLY is non-nil, only lines with a TDOD keyword
6296 d are included in the output."
6297 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6298 (mapconcat 'regexp-quote
6299 (nreverse (cdr (reverse org-todo-keywords)))
6301 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_:]+:\\)?[ \t]*[\n\r]"))
6302 (props (list 'face nil
6303 'done-face 'org-done
6305 'mouse-face 'highlight
6306 'keymap org-agenda-keymap
6308 (format "mouse-2 or RET jump to org file %s"
6309 (abbreviate-file-name (buffer-file-name)))))
6311 tags tags-list tags-alist (llast 0) rtn level category i txt
6315 (goto-char (point-min))
6316 (when (eq action 'sparse-tree) (hide-sublevels 1))
6317 (while (re-search-forward re nil t)
6318 (setq todo (if (match-end 1) (match-string 2))
6319 tags (if (match-end 4) (match-string 4)))
6320 (goto-char (setq lspos (1+ (match-beginning 0))))
6321 (setq level (outline-level)
6322 category (org-get-category))
6323 (setq i llast llast level)
6324 ;; remove tag lists from same and sublevels
6326 (when (setq entry (assoc i tags-alist))
6327 (setq tags-alist (delete entry tags-alist)))
6331 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6333 (cons (cons level tags) tags-alist)))
6334 ;; compile tags for current headline
6336 (if org-use-tag-inheritance
6337 (apply 'append (mapcar 'cdr tags-alist))
6339 (when (and (or (not todo-only) todo)
6341 ;; list this headline
6342 (if (eq action 'sparse-tree)
6344 (org-show-hierarchy-above))
6345 (setq txt (org-format-agenda-item
6348 (if org-tags-match-list-sublevels
6349 (make-string (1- level) ?.) "")
6351 category tags-list))
6353 (setq marker (org-agenda-new-marker))
6354 (add-text-properties
6356 (append (list 'org-marker marker 'org-hd-marker marker
6361 ;; if we are to skip sublevels, jump to end of subtree
6363 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6366 (defun org-tags-sparse-tree (&optional arg match)
6367 "Create a sparse tree according to tags search string MATCH.
6368 MATCH can contain positive and negative selection of tags, like
6369 \"+WORK+URGENT-WITHBOSS\"."
6371 (let ((org-show-following-heading nil)
6372 (org-show-hierarchy-above nil))
6373 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6375 (defun org-make-tags-matcher (match)
6376 "Create the TAGS matcher form for the tags-selecting string MATCH."
6378 ;; Get a new match request, with completion
6379 (setq org-last-tags-completion-table
6380 (or (org-get-buffer-tags)
6381 org-last-tags-completion-table))
6382 (setq match (completing-read
6383 "Tags: " 'org-tags-completion-function nil nil nil
6384 'org-tags-history)))
6385 ;; parse the string and create a lisp form
6386 (let ((match0 match) minus tag mm matcher orterms term orlist)
6387 (setq orterms (org-split-string match "|"))
6388 (while (setq term (pop orterms))
6389 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_]+\\)" term)
6390 (setq minus (and (match-end 1)
6391 (equal (match-string 1 term) "-"))
6392 tag (match-string 2 term)
6393 term (substring term (match-end 0))
6394 mm (list 'member (downcase tag) 'tags-list)
6395 mm (if minus (list 'not mm) mm))
6397 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6400 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6401 ;; Return the string and lisp forms of the matcher
6402 (cons match0 matcher)))
6405 (defun org-tags-view (&optional todo-only match keep-modes)
6406 "Show all headlines for all `org-agenda-files' matching a TAGS criterions.
6407 The prefix arg TODO-ONLY limits the search to TODO entries."
6409 (org-agenda-maybe-reset-markers 'force)
6410 (org-compile-prefix-format org-agenda-prefix-format)
6411 (let* ((org-agenda-keep-modes keep-modes)
6412 (org-tags-match-list-sublevels
6413 (if todo-only t org-tags-match-list-sublevels))
6414 (win (selected-window))
6415 (completion-ignore-case t)
6416 rtn rtnall files file pos matcher
6418 (setq matcher (org-make-tags-matcher match)
6419 match (car matcher) matcher (cdr matcher))
6420 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6422 (delete-other-windows)
6423 (switch-to-buffer-other-window
6424 (get-buffer-create org-agenda-buffer-name))))
6425 (setq buffer-read-only nil)
6427 (org-agenda-mode) (setq buffer-read-only nil)
6428 (set (make-local-variable 'org-agenda-type) 'tags)
6429 (set (make-local-variable 'org-agenda-redo-command)
6430 (list 'org-tags-view (list 'quote todo-only)
6431 (list 'if 'current-prefix-arg nil match) t))
6432 (setq files (org-agenda-files)
6434 (while (setq file (pop files))
6436 (org-check-agenda-file file)
6437 (setq buffer (if (file-exists-p file)
6438 (org-get-agenda-file-buffer file)
6439 (error "No such file %s" file)))
6441 ;; If file does not exist, merror message to agenda
6443 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6444 rtnall (append rtnall rtn))
6445 (with-current-buffer buffer
6446 (unless (eq major-mode 'org-mode)
6447 (error "Agenda file %s is not in `org-mode'" file))
6450 (if org-respect-restriction
6451 (if (org-region-active-p)
6452 ;; Respect a region to restrict search
6453 (narrow-to-region (region-beginning) (region-end)))
6454 ;; If we work for the calendar or many files,
6455 ;; get rid of any restriction
6457 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6458 (setq rtnall (append rtnall rtn))))))))
6459 (insert "Headlines with TAGS match: ")
6460 (add-text-properties (point-min) (1- (point))
6461 (list 'face 'org-link))
6464 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6466 (insert "Press `C-u r' to search again with new search string\n")
6467 (add-text-properties pos (1- (point)) (list 'face 'org-link))
6469 (insert (mapconcat 'identity rtnall "\n")))
6470 (goto-char (point-min))
6471 (setq buffer-read-only t)
6472 (org-fit-agenda-window)
6473 (if (not org-select-agenda-window) (select-window win))))
6475 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
6476 (defun org-set-tags (&optional arg just-align)
6477 "Set the tags for the current headline.
6478 With prefix ARG, realign all tags in headings in the current buffer."
6480 (let* (;(inherit (org-get-inherited-tags))
6481 (re (concat "^" outline-regexp))
6482 (col (current-column))
6483 (current (org-get-tags))
6487 (goto-char (point-min))
6488 (while (re-search-forward re nil t)
6489 (org-set-tags nil t))
6490 (message "All tags realigned to column %d" org-tags-column))
6493 (setq org-last-tags-completion-table
6494 (or (org-get-buffer-tags)
6495 org-last-tags-completion-table))
6497 (let ((org-add-colon-after-tag-completion t))
6498 (completing-read "Tags: " 'org-tags-completion-function
6499 nil nil current 'org-tags-history)))
6500 (while (string-match "[-+&]+" tags)
6501 (setq tags (replace-match ":" t t tags)))
6502 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
6503 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
6504 (unless (string-match "^:" tags) (setq tags (concat ":" tags)))))
6505 (if (equal current "")
6508 (or empty (insert " ")))
6509 (beginning-of-line 1)
6510 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
6511 (setq hd (match-string 1))
6512 (delete-region (match-beginning 0) (match-end 0))
6513 (insert (org-trim hd) (if empty "" " ")))
6514 (unless (equal tags "")
6515 (move-to-column (max (current-column)
6516 (if (> org-tags-column 0)
6518 (- (- org-tags-column) (length tags))))
6521 (move-to-column col))))
6523 (defun org-tags-completion-function (string predicate &optional flag)
6524 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
6525 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
6526 (setq s1 (match-string 1 string)
6527 s2 (match-string 2 string))
6528 (setq s1 "" s2 string))
6532 (setq rtn (try-completion s2 ctable))
6534 (concat s1 s2 (substring rtn (length s2))
6535 (if (and org-add-colon-after-tag-completion
6541 (all-completions s2 ctable)
6548 (defun org-get-tags ()
6549 "Get the TAGS string in the current headline."
6550 (unless (org-on-heading-p)
6551 (error "Not on a heading"))
6553 (beginning-of-line 1)
6554 (if (looking-at ".*[ \t]\\(:[A-Za-z_:]+:\\)[ \t]*\\(\r\\|$\\)")
6558 (defun org-get-buffer-tags ()
6559 "Get a table of all tags used in the buffer, for completion."
6562 (goto-char (point-min))
6563 (while (re-search-forward "[ \t]:\\([A-Za-z_:]+\\):[ \t\r\n]" nil t)
6564 (mapc (lambda (x) (add-to-list 'tags x))
6565 (org-split-string (match-string 1) ":"))))
6566 (mapcar 'list tags)))
6570 (defun org-find-file-at-mouse (ev)
6571 "Open file link or URL at mouse."
6573 (mouse-set-point ev)
6574 (org-open-at-point 'in-emacs))
6576 (defun org-open-at-mouse (ev)
6577 "Open file link or URL at mouse."
6579 (mouse-set-point ev)
6580 (org-open-at-point))
6582 (defun org-open-at-point (&optional in-emacs)
6583 "Open link at or after point.
6584 If there is no link at point, this function will search forward up to
6585 the end of the current subtree.
6586 Normally, files will be opened by an appropriate application. If the
6587 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6589 (org-remove-occur-highlights nil nil t)
6590 (if (org-at-timestamp-p)
6591 (org-agenda-list nil (time-to-days (org-time-string-to-time
6592 (substring (match-string 1) 0 10)))
6594 (let (type path line search (pos (point)))
6597 (skip-chars-backward
6598 (concat (if org-allow-space-in-links "^" "^ ")
6599 org-non-link-chars))
6600 (when (or (looking-at org-link-regexp)
6601 (and (re-search-forward org-link-regexp (point-at-eol) t)
6602 (<= (match-beginning 0) pos)
6603 (>= (match-end 0) pos)))
6604 (setq type (match-string 1)
6605 path (match-string 2))
6608 (skip-chars-backward "^ \t\n\r")
6609 (when (looking-at "\\(:[A-Za-z_:]+\\):[ \t\r\n]")
6611 path (match-string 1))
6612 (while (string-match ":" path)
6613 (setq path (replace-match "+" t t path)))
6616 (skip-chars-backward "a-zA-Z_")
6617 (when (looking-at org-camel-regexp)
6618 (setq type "camel" path (match-string 0))
6619 (if (equal (char-before) ?*)
6620 (setq path (concat "*" path))))
6623 (when (re-search-forward
6627 (progn (outline-end-of-subtree) (max pos (point)))
6628 (error (end-of-line 1) (point))))
6630 (setq type (match-string 1)
6631 path (match-string 2)))))
6633 (error "No link found"))
6634 ;; Remove any trailing spaces in path
6635 (if (string-match " +\\'" path)
6636 (setq path (replace-match "" t t path)))
6640 ((string= type "tags")
6641 (org-tags-view in-emacs path))
6642 ((string= type "camel")
6645 (cond ((equal in-emacs '(4)) 'occur)
6646 ((equal in-emacs '(16)) 'org-occur)
6649 ((string= type "file")
6650 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
6651 (setq line (string-to-number (match-string 1 path))
6652 path (substring path 0 (match-beginning 0)))
6653 (if (string-match "::\\(.+\\)\\'" path)
6654 (setq search (match-string 1 path)
6655 path (substring path 0 (match-beginning 0)))))
6656 (org-open-file path in-emacs line search))
6658 ((string= type "news")
6659 (org-follow-gnus-link path))
6661 ((string= type "bbdb")
6662 (org-follow-bbdb-link path))
6664 ((string= type "gnus")
6665 (let (group article)
6666 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6667 (error "Error in Gnus link"))
6668 (setq group (match-string 1 path)
6669 article (match-string 3 path))
6670 (org-follow-gnus-link group article)))
6672 ((string= type "vm")
6673 (let (folder article)
6674 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6675 (error "Error in VM link"))
6676 (setq folder (match-string 1 path)
6677 article (match-string 3 path))
6678 ;; in-emacs is the prefix arg, will be interpreted as read-only
6679 (org-follow-vm-link folder article in-emacs)))
6681 ((string= type "wl")
6682 (let (folder article)
6683 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6684 (error "Error in Wanderlust link"))
6685 (setq folder (match-string 1 path)
6686 article (match-string 3 path))
6687 (org-follow-wl-link folder article)))
6689 ((string= type "rmail")
6690 (let (folder article)
6691 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6692 (error "Error in RMAIL link"))
6693 (setq folder (match-string 1 path)
6694 article (match-string 3 path))
6695 (org-follow-rmail-link folder article)))
6697 ((string= type "shell")
6699 (while (string-match "@{" cmd)
6700 (setq cmd (replace-match "<" t t cmd)))
6701 (while (string-match "@}" cmd)
6702 (setq cmd (replace-match ">" t t cmd)))
6703 (if (or (not org-confirm-shell-links)
6704 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
6709 (browse-url-at-point))))))
6711 (defun org-link-search (s &optional type)
6712 "Search for a link search option.
6713 When S is a CamelCaseWord, search for a target, or for a sentence containing
6714 the words. If S is surrounded by forward slashes, it is interpreted as a
6715 regular expression. In org-mode files, this will create an `org-occur'
6716 sparse tree. In ordinary files, `occur' will be used to list matched.
6717 If the current buffer is in `dired-mode', grep will be used to search
6719 (let ((case-fold-search t)
6723 words re0 re1 re2 re3 re4 re5 reall)
6724 (cond ((string-match "^/\\(.*\\)/$" s)
6725 ;; A regular expression
6727 ((eq major-mode 'org-mode)
6728 (org-occur (match-string 1 s)))
6729 ;;((eq major-mode 'dired-mode)
6730 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6731 (t (org-do-occur (match-string 1 s)))))
6732 ((string-match (concat "^" org-camel-regexp) s)
6734 (if (equal (string-to-char s) ?*)
6735 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
6738 (remove-text-properties
6740 '(face nil mouse-face nil keymap nil fontified nil) s)
6741 ;; Make a series of regular expressions to find a match
6742 (setq words (org-camel-to-words s)
6743 re0 (concat "<<" (regexp-quote s0) ">>")
6744 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
6745 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
6746 re1 (concat pre re2 post)
6747 re3 (concat pre re4 post)
6748 re5 (concat pre ".*" re4)
6749 re2 (concat pre re2)
6750 re4 (concat pre re4)
6751 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6752 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6756 ((eq type 'org-occur) (org-occur reall))
6757 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6758 (t (goto-char (point-min))
6759 (if (or (re-search-forward re0 nil t)
6760 (re-search-forward re1 nil t)
6761 (re-search-forward re2 nil t)
6762 (re-search-forward re3 nil t)
6763 (re-search-forward re4 nil t)
6764 (re-search-forward re5 nil t))
6765 (goto-char (match-beginning 0))
6767 (error "No match")))))
6769 ;; Normal string-search
6770 (goto-char (point-min))
6771 (if (search-forward s nil t)
6772 (goto-char (match-beginning 0))
6773 (error "No match"))))))
6775 (defun org-do-occur (regexp &optional cleanup)
6776 "Call the Emacs command `occur'.
6777 If CLEANUP is non-nil, remove the printout of the regular expression
6778 in the *Occur* buffer. This is useful if the regex is long and not useful
6782 (let ((cwin (selected-window)) win beg end)
6783 (when (setq win (get-buffer-window "*Occur*"))
6784 (select-window win))
6785 (goto-char (point-min))
6786 (when (re-search-forward "match[a-z]+" nil t)
6787 (setq beg (match-end 0))
6788 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6789 (setq end (1- (match-beginning 0)))))
6790 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
6791 (goto-char (point-min))
6792 (select-window cwin))))
6794 (defun org-camel-to-words (s)
6795 "Split \"CamelCaseWords\" to (\"Camel \" \"Case\" \"Words\")."
6796 (let ((case-fold-search nil)
6798 (while (string-match "[a-z][A-Z]" s)
6799 (push (substring s 0 (1+ (match-beginning 0))) words)
6800 (setq s (substring s (1+ (match-beginning 0)))))
6801 (nreverse (cons s words))))
6803 (defun org-follow-bbdb-link (name)
6804 "Follow a BBDB link to NAME."
6806 (let ((inhibit-redisplay t))
6808 ;; Exact match on name
6809 (bbdb-name (concat "\\`" name "\\'") nil)
6810 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6811 ;; Exact match on name
6812 (bbdb-company (concat "\\`" name "\\'") nil)
6813 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6814 ;; Partial match on name
6815 (bbdb-name name nil)
6816 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6817 ;; Partial match on company
6818 (bbdb-company name nil)
6819 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6820 ;; General match including network address and notes
6822 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
6823 (delete-window (get-buffer-window "*BBDB*"))
6824 (error "No matching BBDB record")))))
6826 (defun org-follow-gnus-link (&optional group article)
6827 "Follow a Gnus link to GROUP and ARTICLE."
6829 (funcall (cdr (assq 'gnus org-link-frame-setup)))
6830 (if group (gnus-fetch-group group))
6832 (or (gnus-summary-goto-article article nil 'force)
6833 (if (fboundp 'gnus-summary-insert-cached-articles)
6835 (gnus-summary-insert-cached-articles)
6836 (gnus-summary-goto-article article nil 'force))
6837 (message "Message could not be found.")))))
6839 (defun org-follow-vm-link (&optional folder article readonly)
6840 "Follow a VM link to FOLDER and ARTICLE."
6842 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
6843 ;; ange-ftp or efs or tramp access
6844 (let ((user (or (match-string 1 folder) (user-login-name)))
6845 (host (match-string 2 folder))
6846 (file (match-string 3 folder)))
6849 ;; use tramp to access the file
6851 (setq folder (format "[%s@%s]%s" user host file))
6852 (setq folder (format "/%s@%s:%s" user host file))))
6854 ;; use ange-ftp or efs
6855 (require (if org-xemacs-p 'efs 'ange-ftp))
6856 (setq folder (format "/%s@%s:%s" user host file))))))
6858 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
6861 (vm-select-folder-buffer)
6863 (let ((case-fold-search t))
6864 (goto-char (point-min))
6865 (if (not (re-search-forward
6866 (concat "^" "message-id: *" (regexp-quote article))))
6867 (error "Could not find the specified message in this folder"))
6870 (vm-beginning-of-message)
6873 (defun org-follow-wl-link (folder article)
6874 "Follow a Wanderlust link to FOLDER and ARTICLE."
6875 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
6876 (if article (wl-summary-jump-to-msg-by-message-id article))
6877 (wl-summary-redisplay))
6879 (defun org-follow-rmail-link (folder article)
6880 "Follow an RMAIL link to FOLDER and ARTICLE."
6881 (let (message-number)
6883 (save-window-excursion
6884 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6885 (setq message-number
6888 (goto-char (point-max))
6889 (if (re-search-backward
6890 (concat "^Message-ID:\\s-+" (regexp-quote
6893 (rmail-what-message))))))
6896 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6897 (rmail-show-message message-number)
6899 (error "Message not found"))))
6901 (defun org-open-file (path &optional in-emacs line search)
6902 "Open the file at PATH.
6903 First, this expands any special file name abbreviations. Then the
6904 configuration variable `org-file-apps' is checked if it contains an
6905 entry for this file type, and if yes, the corresponding command is launched.
6906 If no application is found, Emacs simply visits the file.
6907 With optional argument IN-EMACS, Emacs will visit the file.
6908 Optional LINE specifies a line to go to, optional SEARCH a string to
6909 search for. If LINE or SEARCH is given, the file will always be
6911 If the file does not exist, an error is thrown."
6912 (setq in-emacs (or in-emacs line search))
6913 (let* ((file (if (equal path "")
6915 (convert-standard-filename (org-expand-file-name path))))
6916 (dfile (downcase file))
6918 (if (and (not (file-exists-p file))
6919 (not org-open-non-existing-files))
6920 (error "No such file: %s" file))
6921 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
6922 (setq ext (match-string 1 dfile))
6923 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
6924 (setq ext (match-string 1 dfile))))
6925 (setq apps (append org-file-apps (org-default-apps)))
6928 (setq cmd (or (cdr (assoc ext apps))
6929 (cdr (assoc t apps)))))
6930 (when (eq cmd 'mailcap)
6932 (mailcap-parse-mailcaps)
6933 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
6934 (command (mailcap-mime-info mime-type)))
6935 (if (stringp command)
6937 (setq cmd 'emacs))))
6939 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
6940 (setq cmd (format cmd (concat "\"" file "\"")))
6941 (save-window-excursion
6942 (shell-command (concat cmd " &"))))
6945 (unless (equal (file-truename file) (file-truename (buffer-file-name)))
6946 (funcall (cdr (assq 'file org-link-frame-setup)) file))
6947 (if line (goto-line line)
6948 (if search (org-link-search search))))
6951 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
6953 (defun org-default-apps ()
6954 "Return the default applications for this operating system."
6956 ((eq system-type 'darwin)
6957 org-file-apps-defaults-macosx)
6958 ((eq system-type 'windows-nt)
6959 org-file-apps-defaults-windowsnt)
6960 (t org-file-apps-defaults-gnu)))
6962 (defun org-expand-file-name (path)
6963 "Replace special path abbreviations and expand the file name."
6964 (expand-file-name path))
6967 (defvar org-insert-link-history nil
6968 "Minibuffer history for links inserted with `org-insert-link'.")
6970 (defvar org-stored-links nil
6971 "Contains the links stored with `org-store-link'.")
6974 (defun org-store-link (arg)
6975 "\\<org-mode-map>Store an org-link to the current location.
6976 This link can later be inserted into an org-buffer with
6977 \\[org-insert-link].
6978 For some link types, a prefix arg is interpreted:
6979 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6980 For file links, arg negates `org-context-in-file-links'."
6985 ((eq major-mode 'bbdb-mode)
6986 (setq cpltxt (concat
6988 (or (bbdb-record-name (bbdb-current-record))
6989 (bbdb-record-company (bbdb-current-record))))
6990 link (org-make-link cpltxt)))
6992 ((eq major-mode 'calendar-mode)
6993 (let ((cd (calendar-cursor-to-date)))
6996 (car org-time-stamp-formats)
6998 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7001 ((or (eq major-mode 'vm-summary-mode)
7002 (eq major-mode 'vm-presentation-mode))
7003 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7004 (vm-follow-summary-cursor)
7006 (vm-select-folder-buffer)
7007 (let* ((message (car vm-message-pointer))
7008 (folder (buffer-file-name))
7009 (subject (vm-su-subject message))
7010 (author (vm-su-full-name message))
7011 (message-id (vm-su-message-id message)))
7012 (setq folder (abbreviate-file-name folder))
7013 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7015 (setq folder (replace-match "" t t folder)))
7016 (setq cpltxt (concat author " on: " subject))
7017 (setq link (concat cpltxt "\n "
7019 "vm:" folder "#" message-id))))))
7021 ((eq major-mode 'wl-summary-mode)
7022 (let* ((msgnum (wl-summary-message-number))
7023 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7024 msgnum 'message-id))
7025 (wl-message-entity (elmo-msgdb-overview-get-entity
7026 msgnum (wl-summary-buffer-msgdb)))
7027 (author (wl-summary-line-from)) ; FIXME: how to get author name?
7028 (subject "???")) ; FIXME: How to get subject of email?
7029 (setq cpltxt (concat author " on: " subject))
7030 (setq link (concat cpltxt "\n "
7032 "wl:" wl-summary-buffer-folder-name
7035 ((eq major-mode 'rmail-mode)
7038 (rmail-narrow-to-non-pruned-header)
7039 (let ((folder (buffer-file-name))
7040 (message-id (mail-fetch-field "message-id"))
7041 (author (mail-fetch-field "from"))
7042 (subject (mail-fetch-field "subject")))
7043 (setq cpltxt (concat author " on: " subject))
7044 (setq link (concat cpltxt "\n "
7046 "rmail:" folder "#" message-id)))))))
7048 ((eq major-mode 'gnus-group-mode)
7049 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7050 (gnus-group-group-name)) ; version
7051 ((fboundp 'gnus-group-name)
7054 (setq cpltxt (concat
7055 (if (org-xor arg org-usenet-links-prefer-google)
7056 "http://groups.google.com/groups?group="
7059 link (org-make-link cpltxt))))
7061 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7062 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7063 (gnus-summary-beginning-of-article)
7064 (let* ((group (car gnus-article-current))
7065 (article (cdr gnus-article-current))
7066 (header (gnus-summary-article-header article))
7067 (author (mail-header-from header))
7068 (message-id (mail-header-id header))
7069 (date (mail-header-date header))
7070 (subject (gnus-summary-subject-string)))
7071 (setq cpltxt (concat author " on: " subject))
7072 (if (org-xor arg org-usenet-links-prefer-google)
7076 (format "http://groups.google.com/groups?as_umsgid=%s"
7077 (org-fixup-message-id-for-http message-id))))
7078 (setq link (concat cpltxt "\n"
7081 "#" (number-to-string article)))))))
7083 ((eq major-mode 'w3-mode)
7084 (setq cpltxt (url-view-url t)
7085 link (org-make-link cpltxt)))
7086 ((eq major-mode 'w3m-mode)
7087 (setq cpltxt w3m-current-url
7088 link (org-make-link cpltxt)))
7090 ((eq major-mode 'org-mode)
7091 ;; Just link to current headline
7092 (setq cpltxt (concat "file:"
7093 (abbreviate-file-name (buffer-file-name))))
7094 ;; Add a context search string
7095 (when (org-xor org-context-in-file-links arg)
7097 (skip-chars-backward "a-zA-Z<")
7098 (looking-at (concat "<<\\(" org-camel-regexp "\\)>>")))
7099 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7102 (org-make-org-heading-camel
7104 ((org-on-heading-p) nil)
7105 ((org-region-active-p)
7106 (buffer-substring (region-beginning) (region-end)))
7107 (t (buffer-substring (point-at-bol) (point-at-eol))))
7109 (setq link (org-make-link cpltxt)))
7112 ;; Just link to this file here.
7113 (setq cpltxt (concat "file:"
7114 (abbreviate-file-name (buffer-file-name))))
7115 ;; Add a context string
7116 (when (org-xor org-context-in-file-links arg)
7119 (org-make-org-heading-camel
7120 (if (org-region-active-p)
7121 (buffer-substring (region-beginning) (region-end))
7122 (buffer-substring (point-at-bol) (point-at-eol)))))))
7123 (setq link (org-make-link cpltxt)))
7126 (error "Cannot link to a buffer which is not visiting a file"))
7128 (t (setq link nil)))
7130 (if (and (interactive-p) link)
7132 (setq org-stored-links
7133 (cons (cons (or cpltxt link) link) org-stored-links))
7134 (message "Stored: %s" (or cpltxt link)))
7137 (defun org-make-org-heading-camel (&optional string)
7138 "Make a CamelCase string for S or the current headline."
7140 (let ((s (or string (org-get-heading))))
7142 ;; We are using a headline, clean up garbage in there.
7143 (if (string-match org-todo-regexp s)
7144 (setq s (replace-match "" t t s)))
7145 (setq s (org-trim s))
7146 (if (string-match (concat "^\\(" org-quote-string "\\|"
7147 org-comment-string "\\)") s)
7148 (setq s (replace-match "" t t s)))
7149 (while (string-match org-ts-regexp s)
7150 (setq s (replace-match "" t t s))))
7151 (while (string-match "[^a-zA-Z_ \t]+" s)
7152 (setq s (replace-match " " t t s)))
7153 (or string (setq s (concat "*" s))) ; Add * for headlines
7154 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7156 (defun org-make-link (&rest strings)
7157 "Concatenate STRINGS, format resulting string with `org-link-format'."
7158 (format org-link-format (apply 'concat strings)))
7160 (defun org-xor (a b)
7164 (defun org-get-header (header)
7165 "Find a header field in the current buffer."
7167 (goto-char (point-min))
7168 (let ((case-fold-search t) s)
7171 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7172 (setq s (match-string 1)))
7173 (while (string-match "\"" s)
7174 (setq s (replace-match "" t t s)))
7175 (if (string-match "[<(].*" s)
7176 (setq s (replace-match "" t t s))))
7177 ((eq header 'message-id)
7178 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7179 (setq s (match-string 1))))
7180 ((eq header 'subject)
7181 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7182 (setq s (match-string 1)))))
7183 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7184 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7188 (defun org-fixup-message-id-for-http (s)
7189 "Replace special characters in a message id, so it can be used in an http query."
7190 (while (string-match "<" s)
7191 (setq s (replace-match "%3C" t t s)))
7192 (while (string-match ">" s)
7193 (setq s (replace-match "%3E" t t s)))
7194 (while (string-match "@" s)
7195 (setq s (replace-match "%40" t t s)))
7198 (defun org-insert-link (&optional complete-file)
7199 "Insert a link. At the prompt, enter the link.
7201 Completion can be used to select a link previously stored with
7202 `org-store-link'. When the empty string is entered (i.e. if you just
7203 press RET at the prompt), the link defaults to the most recently
7204 stored link. As SPC triggers completion in the minibuffer, you need to
7205 use M-SPC or C-q SPC to force the insertion of a space character.
7207 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7208 selected using completion. The path to the file will be relative to
7209 the current directory if the file is in the current directory or a
7210 subdirectory. Otherwise, the link will be the absolute path as
7211 completed in the minibuffer (i.e. normally ~/path/to/file).
7213 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7214 is in the current directory or below."
7216 (let ((link (if complete-file
7217 (read-file-name "File: ")
7219 "Link: " org-stored-links nil nil nil
7220 org-insert-link-history
7221 (or (car (car org-stored-links))))))
7223 (if (or (not link) (equal link ""))
7224 (error "No links available"))
7226 (let ((pwd (file-name-as-directory (expand-file-name "."))))
7228 ((equal complete-file '(16))
7231 "file:" (abbreviate-file-name (expand-file-name link)))))
7232 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7233 (expand-file-name link))
7236 "file:" (match-string 1 (expand-file-name link)))))
7237 (t (insert (org-make-link "file:" link)))))
7238 (setq linktxt (cdr (assoc link org-stored-links)))
7239 (if (not org-keep-stored-link-after-insertion)
7240 (setq org-stored-links (delq (assoc link org-stored-links)
7242 (if (not linktxt) (setq link (org-make-link link)))
7243 (setq link (or linktxt link))
7244 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
7245 (let* ((path (match-string 1 link))
7246 (case-fold-search nil)
7247 (search (match-string 2 link)))
7248 (when (save-match-data
7249 (equal (file-truename (buffer-file-name))
7250 (file-truename path)))
7251 (if (save-match-data
7252 (string-match (concat "^" org-camel-regexp "$") search))
7253 (setq link (replace-match search t t link)
7255 (setq link (replace-match (concat "<file:::" search ">")
7257 (let ((lines (org-split-string link "\n")))
7258 (insert (car lines))
7259 (setq matched (or matched (string-match org-link-regexp (car lines))))
7260 (setq lines (cdr lines))
7264 (beginning-of-line 0)
7265 (looking-at "[ \t]+\\S-"))
7267 (setq matched (or matched
7268 (string-match org-link-regexp (car lines))))
7269 (insert (car lines))
7270 (setq lines (cdr lines))))
7272 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
7274 ;;; Hooks for remember.el
7276 (defun org-remember-annotation ()
7277 "Return a link to the current location as an annotation for remember.el.
7278 If you are using Org-mode files as target for data storage with
7279 remember.el, then the annotations should include a link compatible with the
7280 conventions in Org-mode. This function returns such a link."
7281 (org-store-link nil))
7283 (defconst org-remember-help
7284 "Select a destination location for the note.
7285 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
7286 RET at beg-of-buf -> Append to file as level 2 headline
7287 RET on headline -> Store as sublevel entry to current headline
7288 <left>/<right> -> before/after current headline, same headings level")
7291 (defun org-remember-handler ()
7292 "Store stuff from remember.el into an org file.
7293 First prompts for an org file. If the user just presses return, the value
7294 of `org-default-notes-file' is used.
7295 Then the command offers the headings tree of the selected file in order to
7296 file the text at a specific location.
7297 You can either immediately press RET to get the note appended to the
7298 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
7299 find a better place. Then press RET or <left> or <right> in insert the note.
7301 Key Cursor position Note gets inserted
7302 -----------------------------------------------------------------------------
7303 RET buffer-start as level 2 heading at end of file
7304 RET on headline as sublevel of the heading at cursor
7305 RET no heading at cursor position, level taken from context.
7306 Or use prefix arg to specify level manually.
7307 <left> on headline as same level, before current heading
7308 <right> on headline as same level, after current heading
7310 So the fastest way to store the note is to press RET RET to append it to
7311 the default file. This way your current train of thought is not
7312 interrupted, in accordance with the principles of remember.el. But with
7313 little extra effort, you can push it directly to the correct location.
7315 Before being stored away, the function ensures that the text has a
7316 headline, i.e. a first line that starts with a \"*\". If not, a headline
7317 is constructed from the current date and some additional data.
7319 If the variable `org-adapt-indentation' is non-nil, the entire text is
7320 also indented so that it starts in the same column as the headline
7321 \(i.e. after the stars).
7323 See also the variable `org-reverse-note-order'."
7325 (let* ((txt (buffer-substring (point-min) (point-max)))
7326 (fastp current-prefix-arg)
7327 (file (if fastp org-default-notes-file (org-get-org-file)))
7328 (visiting (find-buffer-visiting file))
7329 (org-startup-with-deadline-check nil)
7330 (org-startup-folded nil)
7331 spos level indent reversed)
7332 ;; Modify text so that it becomes a nice subtree which can be inserted
7333 ;; into an org tree.
7334 (let* ((lines (split-string txt "\n"))
7336 (lines (cdr lines)))
7337 (if (string-match "^\\*+" first)
7338 ;; Is already a headline
7339 (setq indent (make-string (- (match-end 0) (match-beginning 0)
7341 ;; We need to add a headline: Use time and first buffer line
7342 (setq lines (cons first lines)
7343 first (concat "* " (current-time-string)
7344 " (" (remember-buffer-desc) ")")
7346 (if org-adapt-indentation
7347 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
7348 (setq txt (concat first "\n"
7349 (mapconcat 'identity lines "\n"))))
7352 (find-file-noselect file))
7353 (with-current-buffer (get-file-buffer file)
7354 (setq reversed (org-notes-order-reversed-p))
7358 ;; Ask the User for a location
7359 (setq spos (if fastp 1 (org-get-location
7361 org-remember-help)))
7362 (if (not spos) (throw 'quit nil)) ; return nil to show we did
7363 ; not handle this note
7366 ;; Put it at the start or end, as level 2
7369 (goto-char (if reversed (point-min) (point-max)))
7370 (if (not (bolp)) (newline))
7371 (org-paste-subtree (or current-prefix-arg 2) txt)))
7372 ((and (org-on-heading-p nil) (not current-prefix-arg))
7373 ;; Put it below this entry, at the beg/end of the subtree
7374 (org-back-to-heading)
7375 (setq level (outline-level))
7377 (outline-end-of-heading)
7378 (outline-end-of-subtree))
7379 (if (not (bolp)) (newline))
7380 (beginning-of-line 1)
7381 (org-paste-subtree (1+ level) txt))
7383 ;; Put it right there, with automatic level determined by
7384 ;; org-paste-subtree or from prefix arg
7385 (org-paste-subtree current-prefix-arg txt)))
7386 (when remember-save-after-remembering
7388 (if (not visiting) (kill-buffer (current-buffer)))))))))
7389 t) ;; return t to indicate that we took care of this note.
7391 (defun org-get-org-file ()
7392 "Read a filename, with default directory `org-directory'."
7393 (let ((default (or org-default-notes-file remember-data-file)))
7394 (read-file-name (format "File name [%s]: " default)
7395 (file-name-as-directory org-directory)
7398 (defun org-notes-order-reversed-p ()
7399 "Check if the current file should receive notes in reversed order."
7401 ((not org-reverse-note-order) nil)
7402 ((eq t org-reverse-note-order) t)
7403 ((not (listp org-reverse-note-order)) nil)
7405 (let ((all org-reverse-note-order)
7407 (while (setq entry (pop all))
7408 (if (string-match (car entry) (buffer-file-name))
7409 (throw 'exit (cdr entry))))
7414 ;; Watch out: Here we are talking about two different kind of tables.
7415 ;; Most of the code is for the tables created with the Org-mode table editor.
7416 ;; Sometimes, we talk about tables created and edited with the table.el
7417 ;; Emacs package. We call the former org-type tables, and the latter
7418 ;; table.el-type tables.
7421 (defun org-before-change-function (beg end)
7422 "Every change indicates that a table might need an update."
7423 (setq org-table-may-need-update t))
7425 (defconst org-table-line-regexp "^[ \t]*|"
7426 "Detects an org-type table line.")
7427 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7428 "Detects an org-type table line.")
7429 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7430 "Detects a table line marked for automatic recalculation.")
7431 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7432 "Detects a table line marked for automatic recalculation.")
7433 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7434 "Detects a table line marked for automatic recalculation.")
7435 (defconst org-table-hline-regexp "^[ \t]*|-"
7436 "Detects an org-type table hline.")
7437 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7438 "Detects a table-type table hline.")
7439 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7440 "Detects an org-type or table-type table.")
7441 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7442 "Searching from within a table (any type) this finds the first line
7443 outside the table.")
7444 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7445 "Searching from within a table (any type) this finds the first line
7446 outside the table.")
7448 (defun org-table-create-with-table.el ()
7449 "Use the table.el package to insert a new table.
7450 If there is already a table at point, convert between Org-mode tables
7451 and table.el tables."
7455 ((org-at-table.el-p)
7456 (if (y-or-n-p "Convert table to Org-mode table? ")
7457 (org-table-convert)))
7459 (if (y-or-n-p "Convert table to table.el table? ")
7460 (org-table-convert)))
7461 (t (call-interactively 'table-insert))))
7463 (defun org-table-create (&optional size)
7464 "Query for a size and insert a table skeleton.
7465 SIZE is a string Columns x Rows like for example \"3x2\"."
7468 (setq size (read-string
7469 (concat "Table size Columns x Rows [e.g. "
7470 org-table-default-size "]: ")
7471 "" nil org-table-default-size)))
7473 (let* ((pos (point))
7474 (indent (make-string (current-column) ?\ ))
7475 (split (org-split-string size " *x *"))
7476 (rows (string-to-number (nth 1 split)))
7477 (columns (string-to-number (car split)))
7478 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7480 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7481 (point-at-bol) (point)))
7482 (beginning-of-line 1)
7484 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7485 (dotimes (i rows) (insert line))
7488 ;; Insert a hline after the first row.
7495 (defun org-table-convert-region (beg0 end0 nspace)
7496 "Convert region to a table.
7497 The region goes from BEG0 to END0, but these borders will be moved
7498 slightly, to make sure a beginning of line in the first line is included.
7499 When NSPACE is non-nil, it indicates the minimum number of spaces that
7500 separate columns (default: just one space)"
7501 (let* ((beg (min beg0 end0))
7502 (end (max beg0 end0))
7506 (beginning-of-line 1)
7507 (setq beg (move-marker (make-marker) (point)))
7509 (if (bolp) (backward-char 1) (end-of-line 1))
7510 (setq end (move-marker (make-marker) (point)))
7511 ;; Lets see if this is tab-separated material. If every nonempty line
7512 ;; contains a tab, we will assume that it is tab-separated material
7516 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
7517 (if nspace (setq tabsep nil))
7520 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
7521 (max 1 (prefix-numeric-value nspace)))))
7523 (while (re-search-forward re end t)
7524 (replace-match "|" t t))
7529 (defun org-table-import (file arg)
7530 "Import FILE as a table.
7531 The file is assumed to be tab-separated. Such files can be produced by most
7532 spreadsheet and database applications. If no tabs (at least one per line)
7533 are found, lines will be split on whitespace into fields."
7534 (interactive "f\nP")
7535 (or (bolp) (newline))
7538 (insert-file-contents file)
7539 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7541 (defun org-table-export ()
7542 "Export table as a tab-separated file.
7543 Such a file can be imported into a spreadsheet program like Excel."
7545 (let* ((beg (org-table-begin))
7546 (end (org-table-end))
7547 (table (buffer-substring beg end))
7548 (file (read-file-name "Export table to: "))
7550 (unless (or (not (file-exists-p file))
7551 (y-or-n-p (format "Overwrite file %s? " file)))
7553 (with-current-buffer (find-file-noselect file)
7554 (setq buf (current-buffer))
7558 (goto-char (point-min))
7559 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7560 (replace-match "" t t)
7562 (goto-char (point-min))
7563 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7564 (replace-match "" t t)
7565 (goto-char (min (1+ (point)) (point-max))))
7566 (goto-char (point-min))
7567 (while (re-search-forward "^-[-+]*$" nil t)
7569 (if (looking-at "\n")
7571 (goto-char (point-min))
7572 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7573 (replace-match "\t" t t))
7577 (defvar org-table-aligned-begin-marker (make-marker)
7578 "Marker at the beginning of the table last aligned.
7579 Used to check if cursor still is in that table, to minimize realignment.")
7580 (defvar org-table-aligned-end-marker (make-marker)
7581 "Marker at the end of the table last aligned.
7582 Used to check if cursor still is in that table, to minimize realignment.")
7583 (defvar org-table-last-alignment nil
7584 "List of flags for flushright alignment, from the last re-alignment.
7585 This is being used to correctly align a single field after TAB or RET.")
7586 ;; FIXME: The following is currently not used.
7587 (defvar org-table-last-column-widths nil
7588 "List of max width of fields in each column.
7589 This is being used to correctly align a single field after TAB or RET.")
7591 (defvar org-last-recalc-line nil)
7593 (defun org-table-align ()
7594 "Align the table at point by aligning all vertical bars."
7596 ;; (message "align") (sit-for 2)
7599 (beg (org-table-begin))
7600 (end (org-table-end))
7601 ;; Current cursor position
7602 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7603 (colpos (org-table-current-column))
7604 (winstart (window-start))
7605 text lines (new "") lengths l typenums ty fields maxfields i
7607 (indent "") cnt frac
7609 (spaces (if (org-in-invisibility-spec-p '(org-table))
7610 org-table-spaces-around-invisible-separators
7611 org-table-spaces-around-separators))
7615 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7617 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7620 ;; (message "Aligning table...")
7622 (setq lines (org-split-string
7623 (buffer-substring-no-properties beg end) "\n"))
7624 ;; Store the indentation of the first line
7625 (if (string-match "^ *" (car lines))
7626 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7628 (setq lines (mapcar (lambda (l)
7629 (if (string-match "^ *|-" l)
7631 (if (string-match "[ \t]+$" l)
7632 (substring l 0 (match-beginning 0))
7635 ;; Get the data fields
7636 (setq fields (mapcar
7638 (org-split-string l " *| *"))
7639 (delq nil (copy-sequence lines))))
7640 ;; How many fields in the longest line?
7642 (setq maxfields (apply 'max (mapcar 'length fields)))
7644 (kill-region beg end)
7645 (org-table-create org-table-default-size)
7646 (error "Empty table - created default table")))
7647 ;; A list of empty string to fill any short rows on output
7648 (setq emptystrings (make-list maxfields ""))
7649 ;; Get the maximum length of a field and the most common datatype
7652 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7653 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7655 (push (apply 'max 1 (mapcar 'string-width column)) lengths)
7656 ;; compute the fraction stepwise, ignoring empty fields
7657 (setq cnt 0 frac 0.0)
7662 (setq frac ( / (+ (* frac cnt)
7663 (if (string-match org-table-number-regexp x) 1 0))
7664 (setq cnt (1+ cnt))))))
7666 (push (>= frac org-table-number-fraction) typenums))
7667 (setq lengths (nreverse lengths)
7668 typenums (nreverse typenums))
7669 (setq org-table-last-alignment typenums
7670 org-table-last-column-widths lengths)
7671 ;; Compute the formats needed for output of the table
7672 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7673 (while (setq l (pop lengths))
7674 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7675 (setq rfmt (concat rfmt (format rfmt1 ty l))
7676 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7677 (setq rfmt (concat rfmt "\n")
7678 hfmt (concat (substring hfmt 0 -1) "|\n"))
7679 ;; Produce the new table
7681 ;; (setq l (pop lines))
7683 ;; (setq new (concat new (apply 'format rfmt
7684 ;; (append (pop fields) emptystrings))))
7685 ;; (setq new (concat new hfmt))))
7686 (setq new (mapconcat
7688 (if l (apply 'format rfmt
7689 (append (pop fields) emptystrings))
7692 ;; Replace the old one
7693 (delete-region beg end)
7694 (move-marker end nil)
7695 (move-marker org-table-aligned-begin-marker (point))
7697 (move-marker org-table-aligned-end-marker (point))
7698 ;; Try to move to the old location (approximately)
7700 (set-window-start (selected-window) winstart 'noforce)
7701 (org-table-goto-column colpos)
7702 (setq org-table-may-need-update nil)
7703 (if (org-in-invisibility-spec-p '(org-table))
7704 (org-table-add-invisible-to-vertical-lines))
7707 (defun org-table-begin (&optional table-type)
7708 "Find the beginning of the table and return its position.
7709 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7711 (if (not (re-search-backward
7712 (if table-type org-table-any-border-regexp
7713 org-table-border-regexp)
7715 (error "Can't find beginning of table")
7716 (goto-char (match-beginning 0))
7717 (beginning-of-line 2)
7720 (defun org-table-end (&optional table-type)
7721 "Find the end of the table and return its position.
7722 With argument TABLE-TYPE, go to the end of a table.el-type table."
7724 (if (not (re-search-forward
7725 (if table-type org-table-any-border-regexp
7726 org-table-border-regexp)
7728 (goto-char (point-max))
7729 (goto-char (match-beginning 0)))
7732 (defun org-table-justify-field-maybe (&optional new)
7733 "Justify the current field, text to left, number to right.
7734 Optional argument NEW may specify text to replace the current field content."
7736 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7737 ((org-at-table-hline-p)
7738 ;; FIXME: I used to enforce realign here, but I think this is not needed.
7739 ;; (setq org-table-may-need-update t)
7742 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7744 (< (point) org-table-aligned-begin-marker)
7745 (>= (point) org-table-aligned-end-marker)))
7746 ;; This is not the same table, force a full re-align
7747 (setq org-table-may-need-update t))
7748 (t ;; realign the current field, based on previous full realign
7749 (let* ((pos (point)) s
7750 (col (org-table-current-column))
7751 (num (nth (1- col) org-table-last-alignment))
7754 (skip-chars-backward "^|\n")
7755 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7757 (setq s (match-string 1)
7759 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7760 e (not (= (match-beginning 2) (match-end 2))))
7761 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7762 l (if e "|" (setq org-table-may-need-update t) ""))
7765 (if (<= (length new) l)
7766 (setq n (format f new t t)) ;; FIXME: why t t?????
7767 (setq n (concat new "|") org-table-may-need-update t)))
7769 (let (org-table-may-need-update)
7770 (replace-match n))))
7771 (setq org-table-may-need-update t))
7772 (goto-char pos))))))
7774 (defun org-table-next-field ()
7775 "Go to the next field in the current table, creating new lines as needed.
7776 Before doing so, re-align the table if necessary."
7778 (org-table-maybe-eval-formula)
7779 (org-table-maybe-recalculate-line)
7780 (if (and org-table-automatic-realign
7781 org-table-may-need-update)
7783 (let ((end (org-table-end)))
7784 (if (org-at-table-hline-p)
7788 (re-search-forward "|" end)
7789 (if (looking-at "[ \t]*$")
7790 (re-search-forward "|" end))
7791 (if (and (looking-at "-")
7792 org-table-tab-jumps-over-hlines
7793 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7794 (goto-char (match-beginning 1)))
7795 (if (looking-at "-")
7797 (beginning-of-line 0)
7798 (org-table-insert-row 'below))
7799 (if (looking-at " ") (forward-char 1))))
7801 (org-table-insert-row 'below)))))
7803 (defun org-table-previous-field ()
7804 "Go to the previous field in the table.
7805 Before doing so, re-align the table if necessary."
7807 (org-table-justify-field-maybe)
7808 (org-table-maybe-recalculate-line)
7809 (if (and org-table-automatic-realign
7810 org-table-may-need-update)
7812 (if (org-at-table-hline-p)
7814 (re-search-backward "|" (org-table-begin))
7815 (re-search-backward "|" (org-table-begin))
7816 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7817 (re-search-backward "|" (org-table-begin)))
7818 (if (looking-at "| ?")
7819 (goto-char (match-end 0))))
7821 (defun org-table-next-row ()
7822 "Go to the next row (same column) in the current table.
7823 Before doing so, re-align the table if necessary."
7825 (org-table-maybe-eval-formula)
7826 (org-table-maybe-recalculate-line)
7827 (if (or (looking-at "[ \t]*$")
7828 (save-excursion (skip-chars-backward " \t") (bolp)))
7830 (if (and org-table-automatic-realign
7831 org-table-may-need-update)
7833 (let ((col (org-table-current-column)))
7834 (beginning-of-line 2)
7835 (if (or (not (org-at-table-p))
7836 (org-at-table-hline-p))
7838 (beginning-of-line 0)
7839 (org-table-insert-row 'below)))
7840 (org-table-goto-column col)
7841 (skip-chars-backward "^|\n\r")
7842 (if (looking-at " ") (forward-char 1)))))
7844 (defun org-table-copy-down (n)
7845 "Copy a field down in the current column.
7846 If the field at the cursor is empty, copy into it the content of the nearest
7847 non-empty field above. With argument N, use the Nth non-empty field.
7848 If the current field is not empty, it is copied down to the next row, and
7849 the cursor is moved with it. Therefore, repeating this command causes the
7850 column to be filled row-by-row.
7851 If the variable `org-table-copy-increment' is non-nil and the field is an
7852 integer, it will be incremented while copying."
7854 (let* ((colpos (org-table-current-column))
7855 (field (org-table-get-field))
7856 (non-empty (string-match "[^ \t]" field))
7857 (beg (org-table-begin))
7859 (org-table-check-inside-data-field)
7862 (setq txt (org-trim field))
7863 (org-table-next-row)
7864 (org-table-blank-field))
7868 (while (progn (beginning-of-line 1)
7869 (re-search-backward org-table-dataline-regexp
7871 (org-table-goto-column colpos t)
7872 (if (and (looking-at
7873 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7874 (= (setq n (1- n)) 0))
7875 (throw 'exit (match-string 1))))))))
7878 (if (and org-table-copy-increment
7879 (string-match "^[0-9]+$" txt))
7880 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7882 (org-table-maybe-recalculate-line)
7884 (error "No non-empty field found"))))
7886 (defun org-table-check-inside-data-field ()
7887 "Is point inside a table data field?
7888 I.e. not on a hline or before the first or after the last column?
7889 This actually throws an error, so it aborts the current command."
7890 (if (or (not (org-at-table-p))
7891 (= (org-table-current-column) 0)
7892 (org-at-table-hline-p)
7893 (looking-at "[ \t]*$"))
7894 (error "Not in table data field")))
7896 (defvar org-table-clip nil
7897 "Clipboard for table regions.")
7899 (defun org-table-blank-field ()
7900 "Blank the current table field or active region."
7902 (org-table-check-inside-data-field)
7903 (if (and (interactive-p) (org-region-active-p))
7904 (let (org-table-clip)
7905 (org-table-cut-region (region-beginning) (region-end)))
7906 (skip-chars-backward "^|")
7908 (if (looking-at "|[^|\n]+")
7909 (let* ((pos (match-beginning 0))
7910 (match (match-string 0))
7911 (len (string-width match)))
7912 (replace-match (concat "|" (make-string (1- len) ?\ )))
7913 (goto-char (+ 2 pos))
7914 (substring match 1)))))
7916 (defun org-table-get-field (&optional n replace)
7917 "Return the value of the field in column N of current row.
7918 N defaults to current field.
7919 If REPLACE is a string, replace field with this value. The return value
7920 is always the old value."
7921 (and n (org-table-goto-column n))
7922 (skip-chars-backward "^|\n")
7924 (if (looking-at "|[^|\r\n]*")
7925 (let* ((pos (match-beginning 0))
7926 (val (buffer-substring (1+ pos) (match-end 0))))
7928 (replace-match (concat "|" replace)))
7929 (goto-char (min (point-at-eol) (+ 2 pos)))
7931 (forward-char 1) ""))
7933 (defun org-table-current-column ()
7934 "Find out which column we are in.
7935 When called interactively, column is also displayed in echo area."
7937 (if (interactive-p) (org-table-check-inside-data-field))
7939 (let ((cnt 0) (pos (point)))
7940 (beginning-of-line 1)
7941 (while (search-forward "|" pos t)
7942 (setq cnt (1+ cnt)))
7943 (if (interactive-p) (message "This is table column %d" cnt))
7946 (defun org-table-goto-column (n &optional on-delim force)
7947 "Move the cursor to the Nth column in the current table line.
7948 With optional argument ON-DELIM, stop with point before the left delimiter
7950 If there are less than N fields, just go to after the last delimiter.
7951 However, when FORCE is non-nil, create new columns if necessary."
7953 (let ((pos (point-at-eol)))
7954 (beginning-of-line 1)
7956 (while (and (> (setq n (1- n)) -1)
7957 (or (search-forward "|" pos t)
7959 (progn (end-of-line 1)
7960 (skip-chars-backward "^|")
7962 ; (backward-char 2) t)))))
7963 (when (and force (not (looking-at ".*|")))
7964 (save-excursion (end-of-line 1) (insert " | ")))
7967 (if (looking-at " ") (forward-char 1))))))
7969 (defun org-at-table-p (&optional table-type)
7970 "Return t if the cursor is inside an org-type table.
7971 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7972 (if org-enable-table-editor
7974 (beginning-of-line 1)
7975 (looking-at (if table-type org-table-any-line-regexp
7976 org-table-line-regexp)))
7979 (defun org-at-table.el-p ()
7980 "Return t if and only if we are at a table.el table."
7981 (and (org-at-table-p 'any)
7983 (goto-char (org-table-begin 'any))
7984 (looking-at org-table1-hline-regexp))))
7986 (defun org-table-recognize-table.el ()
7987 "If there is a table.el table nearby, recognize it and move into it."
7988 (if org-table-tab-recognizes-table.el
7989 (if (org-at-table.el-p)
7991 (beginning-of-line 1)
7992 (if (looking-at org-table-dataline-regexp)
7994 (if (looking-at org-table1-hline-regexp)
7996 (beginning-of-line 2)
7997 (if (looking-at org-table-any-border-regexp)
7998 (beginning-of-line -1)))))
7999 (if (re-search-forward "|" (org-table-end t) t)
8002 (if (table--at-cell-p (point))
8004 (message "recognizing table.el table...")
8005 (table-recognize-table)
8006 (message "recognizing table.el table...done")))
8007 (error "This should not happen..."))
8012 (defun org-at-table-hline-p ()
8013 "Return t if the cursor is inside a hline in a table."
8014 (if org-enable-table-editor
8016 (beginning-of-line 1)
8017 (looking-at org-table-hline-regexp))
8020 (defun org-table-insert-column ()
8021 "Insert a new column into the table."
8023 (if (not (org-at-table-p))
8024 (error "Not at a table"))
8025 (org-table-find-dataline)
8026 (let* ((col (max 1 (org-table-current-column)))
8027 (beg (org-table-begin))
8028 (end (org-table-end))
8029 ;; Current cursor position
8030 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8033 (while (< (point) end)
8034 (if (org-at-table-hline-p)
8036 (org-table-goto-column col t)
8038 (beginning-of-line 2))
8039 (move-marker end nil)
8041 (org-table-goto-column colpos)
8043 (org-table-modify-formulas 'insert col)))
8045 (defun org-table-find-dataline ()
8046 "Find a dataline in the current table, which is needed for column commands."
8047 (if (and (org-at-table-p)
8048 (not (org-at-table-hline-p)))
8050 (let ((col (current-column))
8051 (end (org-table-end)))
8052 (move-to-column col)
8053 (while (and (< (point) end)
8054 (or (not (= (current-column) col))
8055 (org-at-table-hline-p)))
8056 (beginning-of-line 2)
8057 (move-to-column col))
8058 (if (and (org-at-table-p)
8059 (not (org-at-table-hline-p)))
8062 "Please position cursor in a data line for column operations")))))
8064 (defun org-table-delete-column ()
8065 "Delete a column into the table."
8067 (if (not (org-at-table-p))
8068 (error "Not at a table"))
8069 (org-table-find-dataline)
8070 (org-table-check-inside-data-field)
8071 (let* ((col (org-table-current-column))
8072 (beg (org-table-begin))
8073 (end (org-table-end))
8074 ;; Current cursor position
8075 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8078 (while (< (point) end)
8079 (if (org-at-table-hline-p)
8081 (org-table-goto-column col t)
8082 (and (looking-at "|[^|\n]+|")
8083 (replace-match "|")))
8084 (beginning-of-line 2))
8085 (move-marker end nil)
8087 (org-table-goto-column colpos)
8089 (org-table-modify-formulas 'remove col)))
8091 (defun org-table-move-column-right ()
8092 "Move column to the right."
8094 (org-table-move-column nil))
8095 (defun org-table-move-column-left ()
8096 "Move column to the left."
8098 (org-table-move-column 'left))
8100 (defun org-table-move-column (&optional left)
8101 "Move the current column to the right. With arg LEFT, move to the left."
8103 (if (not (org-at-table-p))
8104 (error "Not at a table"))
8105 (org-table-find-dataline)
8106 (org-table-check-inside-data-field)
8107 (let* ((col (org-table-current-column))
8108 (col1 (if left (1- col) col))
8109 (beg (org-table-begin))
8110 (end (org-table-end))
8111 ;; Current cursor position
8112 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8113 (colpos (if left (1- col) (1+ col))))
8114 (if (and left (= col 1))
8115 (error "Cannot move column further left"))
8116 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8117 (error "Cannot move column further right"))
8119 (while (< (point) end)
8120 (if (org-at-table-hline-p)
8122 (org-table-goto-column col1 t)
8123 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8124 (replace-match "|\\2|\\1|")))
8125 (beginning-of-line 2))
8126 (move-marker end nil)
8128 (org-table-goto-column colpos)
8130 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
8132 (defun org-table-move-row-down ()
8133 "move table row down."
8135 (org-table-move-row nil))
8136 (defun org-table-move-row-up ()
8137 "move table row up."
8139 (org-table-move-row 'up))
8141 (defun org-table-move-row (&optional up)
8142 "Move the current table line down. With arg UP, move it up."
8144 (let ((col (current-column))
8148 (beginning-of-line tonew)
8149 (if (not (org-at-table-p))
8152 (error "Cannot move row further")))
8154 (beginning-of-line 1)
8156 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8157 (delete-region (point) (1+ (point-at-eol)))
8158 (beginning-of-line tonew)
8160 (beginning-of-line 0)
8161 (move-to-column col)))
8163 (defun org-table-insert-row (&optional arg)
8164 "Insert a new row above the current line into the table.
8165 With prefix ARG, insert below the current line."
8167 (if (not (org-at-table-p))
8168 (error "Not at a table"))
8170 (org-expand-wide-chars
8171 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8173 (if (string-match "^[ \t]*|-" line)
8174 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
8175 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
8176 ;; Fix the first field if necessary
8177 (setq new (concat new))
8178 (if (string-match "^[ \t]*| *[#$] *|" line)
8179 (setq new (replace-match (match-string 0 line) t t new)))
8180 (beginning-of-line (if arg 2 1))
8181 (let (org-table-may-need-update)
8182 (insert-before-markers new)
8183 (insert-before-markers "\n"))
8184 (beginning-of-line 0)
8185 (re-search-forward "| ?" (point-at-eol) t)
8186 (and org-table-may-need-update (org-table-align))))
8188 (defun org-table-insert-hline (&optional arg)
8189 "Insert a horizontal-line below the current line into the table.
8190 With prefix ARG, insert above the current line."
8192 (if (not (org-at-table-p))
8193 (error "Not at a table"))
8195 (org-expand-wide-chars
8196 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8197 (col (current-column))
8199 (if (string-match "^[ \t]*|-" line)
8201 (mapcar (lambda (x) (if (member x '(?| ?+))
8202 (prog1 (if start ?+ ?|) (setq start t))
8206 (mapcar (lambda (x) (if (equal x ?|)
8207 (prog1 (if start ?+ ?|) (setq start t))
8210 (beginning-of-line (if arg 1 2))
8211 (apply 'insert line)
8212 (if (equal (char-before (point)) ?+)
8213 (progn (backward-delete-char 1) (insert "|")))
8215 (beginning-of-line (if arg 1 -1))
8216 (move-to-column col)))
8218 (defun org-expand-wide-chars (s)
8219 "Expand wide characters to spaces."
8223 (if (> (setq w (string-width (setq a (char-to-string x)))) 1)
8228 (defun org-table-kill-row ()
8229 "Delete the current row or horizontal line from the table."
8231 (if (not (org-at-table-p))
8232 (error "Not at a table"))
8233 (let ((col (current-column)))
8234 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8235 (if (not (org-at-table-p)) (beginning-of-line 0))
8236 (move-to-column col)))
8238 (defun org-table-sort-lines (beg end numericp)
8239 "Sort table lines in region.
8240 Point and mark define the first and last line to include. Both point and
8241 mark should be in the column that is used for sorting. For example, to
8242 sort according to column 3, put the mark in the first line to sort, in
8243 table column 3. Put point into the last line to be included in the sorting,
8244 also in table column 3. The command will prompt for the sorting method (n for
8245 numerical, a for alphanumeric)."
8246 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
8247 (setq numericp (string-match "[nN]" numericp))
8248 (org-table-align) ;; Just to be safe
8249 (let* (bcol ecol cmp column lns)
8251 (org-table-check-inside-data-field)
8252 (setq column (org-table-current-column)
8253 beg (move-marker (make-marker) (point-at-bol)))
8255 (org-table-check-inside-data-field)
8256 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
8259 (org-table-goto-column column)
8260 (skip-chars-backward "^|")
8261 (setq bcol (current-column))
8262 (org-table-goto-column (1+ column))
8263 (skip-chars-backward "^|")
8264 (setq ecol (1- (current-column)))
8265 (setq cmp (if numericp
8266 (lambda (a b) (< (car a) (car b)))
8267 (lambda (a b) (string< (car a) (car b)))))
8268 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8269 (split-string (buffer-substring beg end) "\n")))
8271 (setq lns (mapcar (lambda(x)
8272 (cons (string-to-number (car x)) (cdr x)))
8274 (delete-region beg end)
8275 (move-marker beg nil)
8276 (move-marker end nil)
8277 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
8278 (message "%d lines sorted %s based on column %d"
8280 (if numericp "numerically" "alphabetically") column)))
8282 (defun org-table-cut-region (beg end)
8283 "Copy region in table to the clipboard and blank all relevant fields."
8285 (org-table-copy-region beg end 'cut))
8287 (defun org-table-copy-region (beg end &optional cut)
8288 "Copy rectangular region in table to clipboard.
8289 A special clipboard is used which can only be accessed
8290 with `org-table-paste-rectangle'"
8292 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8294 (rpl (if cut " " nil)))
8296 (org-table-check-inside-data-field)
8297 (setq l01 (count-lines (point-min) (point))
8298 c01 (org-table-current-column))
8300 (org-table-check-inside-data-field)
8301 (setq l02 (count-lines (point-min) (point))
8302 c02 (org-table-current-column))
8303 (setq l1 (min l01 l02) l2 (max l01 l02)
8304 c1 (min c01 c02) c2 (max c01 c02))
8308 (if (> l1 l2) (throw 'exit t))
8310 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8311 (setq cols nil ic1 c1 ic2 c2)
8312 (while (< ic1 (1+ ic2))
8313 (push (org-table-get-field ic1 rpl) cols)
8314 (setq ic1 (1+ ic1)))
8315 (push (nreverse cols) region)
8316 (setq l1 (1+ l1)))))
8317 (setq org-table-clip (nreverse region))
8318 (if cut (org-table-align))
8321 (defun org-table-paste-rectangle ()
8322 "Paste a rectangular region into a table.
8323 The upper right corner ends up in the current field. All involved fields
8324 will be overwritten. If the rectangle does not fit into the present table,
8325 the table is enlarged as needed. The process ignores horizontal separator
8328 (unless (and org-table-clip (listp org-table-clip))
8329 (error "First cut/copy a region to paste!"))
8330 (org-table-check-inside-data-field)
8331 (let* ((clip org-table-clip)
8332 (line (count-lines (point-min) (point)))
8333 (col (org-table-current-column))
8334 (org-enable-table-editor t)
8335 (org-table-automatic-realign nil)
8337 (while (setq cols (pop clip))
8338 (while (org-at-table-hline-p) (beginning-of-line 2))
8339 (if (not (org-at-table-p))
8340 (progn (end-of-line 0) (org-table-next-field)))
8342 (while (setq field (pop cols))
8343 (org-table-goto-column c nil 'force)
8344 (org-table-get-field nil field)
8346 (beginning-of-line 2))
8348 (org-table-goto-column col)
8351 (defun org-table-convert ()
8352 "Convert from `org-mode' table to table.el and back.
8353 Obviously, this only works within limits. When an Org-mode table is
8354 converted to table.el, all horizontal separator lines get lost, because
8355 table.el uses these as cell boundaries and has no notion of horizontal lines.
8356 A table.el table can be converted to an Org-mode table only if it does not
8357 do row or column spanning. Multiline cells will become multiple cells.
8358 Beware, Org-mode does not test if the table can be successfully converted - it
8359 blindly applies a recipe that works for simple tables."
8362 (if (org-at-table.el-p)
8363 ;; convert to Org-mode table
8364 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8365 (end (move-marker (make-marker) (org-table-end t))))
8366 (table-unrecognize-region beg end)
8368 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8371 (if (org-at-table-p)
8372 ;; convert to table.el table
8373 (let ((beg (move-marker (make-marker) (org-table-begin)))
8374 (end (move-marker (make-marker) (org-table-end))))
8375 ;; first, get rid of all horizontal lines
8377 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8379 ;; insert a hline before first
8381 (org-table-insert-hline 'above)
8382 (beginning-of-line -1)
8383 ;; insert a hline after each line
8384 (while (progn (beginning-of-line 3) (< (point) end))
8385 (org-table-insert-hline))
8387 (setq end (move-marker end (org-table-end)))
8388 ;; replace "+" at beginning and ending of hlines
8389 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8390 (replace-match "\\1+-"))
8392 (while (re-search-forward "-|[ \t]*$" end t)
8393 (replace-match "-+"))
8396 (defun org-table-wrap-region (arg)
8397 "Wrap several fields in a column like a paragraph.
8398 This is useful if you'd like to spread the contents of a field over several
8399 lines, in order to keep the table compact.
8401 If there is an active region, and both point and mark are in the same column,
8402 the text in the column is wrapped to minimum width for the given number of
8403 lines. Generally, this makes the table more compact. A prefix ARG may be
8404 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8405 formats the selected text to two lines. If the region was longer than 2
8406 lines, the remaining lines remain empty. A negative prefix argument reduces
8407 the current number of lines by that amount. The wrapped text is pasted back
8408 into the table. If you formatted it to more lines than it was before, fields
8409 further down in the table get overwritten - so you might need to make space in
8412 If there is no region, the current field is split at the cursor position and
8413 the text fragment to the right of the cursor is prepended to the field one
8416 If there is no region, but you specify a prefix ARG, the current field gets
8417 blank, and the content is appended to the field above."
8419 (org-table-check-inside-data-field)
8420 (if (org-region-active-p)
8421 ;; There is a region: fill as a paragraph
8422 (let ((beg (region-beginning))
8424 (org-table-cut-region (region-beginning) (region-end))
8425 (if (> (length (car org-table-clip)) 1)
8426 (error "Region must be limited to single column"))
8427 (setq nlines (if arg
8429 (+ (length org-table-clip) arg)
8431 (length org-table-clip)))
8432 (setq org-table-clip
8433 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8436 (org-table-paste-rectangle))
8437 ;; No region, split the current field at point
8439 ;; combine with field above
8440 (let ((s (org-table-blank-field))
8441 (col (org-table-current-column)))
8442 (beginning-of-line 0)
8443 (while (org-at-table-hline-p) (beginning-of-line 0))
8444 (org-table-goto-column col)
8445 (skip-chars-forward "^|")
8446 (skip-chars-backward " ")
8447 (insert " " (org-trim s))
8450 (when (looking-at "\\([^|]+\\)+|")
8451 (let ((s (match-string 1)))
8452 (replace-match " |")
8453 (goto-char (match-beginning 0))
8454 (org-table-next-row)
8455 (insert (org-trim s) " ")
8456 (org-table-align))))))
8459 "Remove whitespace at beginning and end of string."
8460 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
8461 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
8464 (defun org-wrap (string &optional width lines)
8465 "Wrap string to either a number of lines, or a width in characters.
8466 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8467 that costs. If there is a word longer than WIDTH, the text is actually
8468 wrapped to the length of that word.
8469 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8470 many lines, whatever width that takes.
8471 The return value is a list of lines, without newlines at the end."
8472 (let* ((words (org-split-string string "[ \t\n]+"))
8473 (maxword (apply 'max (mapcar 'string-width words)))
8476 (org-do-wrap words (max maxword width)))
8479 (setq ll (org-do-wrap words maxword))
8480 (if (<= (length ll) lines)
8483 (while (> (length ll) lines)
8485 (setq ll (org-do-wrap words w)))
8487 (t (error "Cannot wrap this")))))
8490 (defun org-do-wrap (words width)
8491 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8494 (setq line (pop words))
8495 (while (and words (< (+ (length line) (length (car words))) width))
8496 (setq line (concat line " " (pop words))))
8497 (setq lines (push line lines)))
8500 ;; FIXME: I think I can make this more efficient
8501 (defun org-split-string (string &optional separators)
8502 "Splits STRING into substrings at SEPARATORS.
8503 No empty strings are returned if there are matches at the beginning
8505 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8509 (while (and (string-match rexp string
8511 (= start (match-beginning 0))
8512 (< start (length string)))
8514 (< (match-beginning 0) (length string)))
8516 (or (eq (match-beginning 0) 0)
8517 (and (eq (match-beginning 0) (match-end 0))
8518 (eq (match-beginning 0) start))
8520 (cons (substring string start (match-beginning 0))
8522 (setq start (match-end 0)))
8523 (or (eq start (length string))
8525 (cons (substring string start)
8529 (defun org-table-add-invisible-to-vertical-lines ()
8530 "Add an `invisible' property to vertical lines of current table."
8532 (let* ((beg (org-table-begin))
8533 (end (org-table-end))
8537 (while (< (point) end)
8538 (setq end1 (point-at-eol))
8539 (if (looking-at org-table-dataline-regexp)
8540 (while (re-search-forward "|" end1 t)
8541 (add-text-properties (1- (point)) (point)
8542 '(invisible org-table)))
8543 (while (re-search-forward "[+|]" end1 t)
8544 (add-text-properties (1- (point)) (point)
8545 '(invisible org-table))))
8546 (beginning-of-line 2)))))
8548 (defun org-table-toggle-vline-visibility (&optional arg)
8549 "Toggle the visibility of table vertical lines.
8550 The effect is immediate and on all tables in the file.
8551 With prefix ARG, make lines invisible when ARG is positive, make lines
8552 visible when ARG is not positive"
8555 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
8556 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
8557 (t (if (org-in-invisibility-spec-p '(org-table))
8560 (if (eq action 'off)
8562 (org-remove-from-invisibility-spec '(org-table))
8563 (org-table-map-tables 'org-table-align)
8564 (message "Vertical table lines visible")
8565 (if (org-at-table-p)
8567 (org-add-to-invisibility-spec '(org-table))
8568 (org-table-map-tables 'org-table-align)
8569 (message "Vertical table lines invisible"))
8570 (redraw-frame (selected-frame))))
8572 (defun org-table-map-tables (function)
8573 "Apply FUNCTION to the start of all tables in the buffer."
8577 (goto-char (point-min))
8578 (while (re-search-forward org-table-any-line-regexp nil t)
8579 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8580 (beginning-of-line 1)
8581 (if (looking-at org-table-line-regexp)
8582 (save-excursion (funcall function)))
8583 (re-search-forward org-table-any-border-regexp nil 1)))))
8585 (defun org-table-sum (&optional beg end nlast)
8586 "Sum numbers in region of current table column.
8587 The result will be displayed in the echo area, and will be available
8588 as kill to be inserted with \\[yank].
8590 If there is an active region, it is interpreted as a rectangle and all
8591 numbers in that rectangle will be summed. If there is no active
8592 region and point is located in a table column, sum all numbers in that
8595 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8596 numbers are assumed to be times as well (in decimal hours) and the
8597 numbers are added as such.
8599 If NLAST is a number, only the NLAST fields will actually be summed."
8602 (let (col (timecnt 0) diff h m s org-table-clip)
8604 ((and beg end)) ; beg and end given explicitly
8605 ((org-region-active-p)
8606 (setq beg (region-beginning) end (region-end)))
8608 (setq col (org-table-current-column))
8609 (goto-char (org-table-begin))
8610 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8611 (error "No table data"))
8612 (org-table-goto-column col)
8613 ;not needed? (skip-chars-backward "^|")
8615 (goto-char (org-table-end))
8616 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8617 (error "No table data"))
8618 (org-table-goto-column col)
8619 ;not needed? (skip-chars-forward "^|")
8620 (setq end (point))))
8621 (let* ((items (apply 'append (org-table-copy-region beg end)))
8622 (items1 (cond ((not nlast) items)
8623 ((>= nlast (length items)) items)
8624 (t (setq items (reverse items))
8625 (setcdr (nthcdr (1- nlast) items) nil)
8627 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8629 (res (apply '+ numbers))
8630 (sres (if (= timecnt 0)
8632 (setq diff (* 3600 res)
8633 h (floor (/ diff 3600)) diff (mod diff 3600)
8634 m (floor (/ diff 60)) diff (mod diff 60)
8636 (format "%d:%02d:%02d" h m s))))
8640 (substitute-command-keys
8641 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8642 (length numbers) sres))))
8645 (defun org-table-get-number-for-summing (s)
8647 (if (string-match "^ *|? *" s)
8648 (setq s (replace-match "" nil nil s)))
8649 (if (string-match " *|? *$" s)
8650 (setq s (replace-match "" nil nil s)))
8651 (setq n (string-to-number s))
8653 ((and (string-match "0" s)
8654 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8655 ((string-match "\\`[ \t]+\\'" s) nil)
8656 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8657 (let ((h (string-to-number (or (match-string 1 s) "0")))
8658 (m (string-to-number (or (match-string 2 s) "0")))
8659 (s (string-to-number (or (match-string 4 s) "0"))))
8660 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
8661 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8665 (defun org-table-get-vertical-vector (desc &optional tbeg col)
8666 "Get a calc vector from a column, accorting to desctiptor DESC.
8667 Optional arguments TBEG and COL can give the beginning of the table and
8668 the current column, to avoid unnecessary parsing."
8670 (or tbeg (setq tbeg (org-table-begin)))
8671 (or col (setq col (org-table-current-column)))
8672 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
8674 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
8675 (setq n1 (- (match-end 1) (match-beginning 1)))
8676 (if (match-beginning 3)
8677 (setq n2 (- (match-end 2) (match-beginning 3))))
8678 (setq n (if n2 (max n1 n2) n1))
8679 (setq n1 (if n2 (min n1 n2)))
8681 (while (and (> nn 0)
8682 (re-search-backward org-table-hline-regexp tbeg t))
8683 (push (org-current-line) hline-list)
8685 (setq hline-list (nreverse hline-list))
8686 (goto-line (nth (1- n) hline-list))
8687 (when (re-search-forward org-table-dataline-regexp)
8688 (org-table-goto-column col)
8690 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
8691 (when (re-search-backward org-table-dataline-regexp)
8692 (org-table-goto-column col)
8694 (setq l (apply 'append (org-table-copy-region beg end)))
8695 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
8696 (if (equal x "") "0" x))
8698 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
8699 (setq n1 (string-to-number (match-string 1 desc))
8700 n2 (string-to-number (match-string 2 desc)))
8701 (beginning-of-line 1)
8703 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
8704 (org-table-goto-column col)
8705 (setq beg (point))))
8706 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
8707 (org-table-goto-column col)
8709 (setq l (apply 'append (org-table-copy-region beg end)))
8710 (concat "[" (mapconcat
8711 (lambda (x) (setq x (org-trim x))
8712 (if (equal x "") "0" x))
8714 ((string-match "\\([0-9]+\\)" desc)
8715 (beginning-of-line 1)
8716 (when (re-search-backward org-table-dataline-regexp tbeg t
8717 (string-to-number (match-string 0 desc)))
8718 (org-table-goto-column col)
8719 (org-trim (org-table-get-field))))))))
8721 (defvar org-table-formula-history nil)
8723 (defvar org-table-column-names nil
8724 "Alist with column names, derived from the `!' line.")
8725 (defvar org-table-column-name-regexp nil
8726 "Regular expression matching the current column names.")
8727 (defvar org-table-local-parameters nil
8728 "Alist with parameter names, derived from the `$' line.")
8729 (defvar org-table-named-field-locations nil
8730 "Alist with locations of named fields.")
8732 (defun org-table-get-formula (&optional equation named)
8733 "Read a formula from the minibuffer, offer stored formula as default."
8734 (let* ((name (car (rassoc (list (org-current-line)
8735 (org-table-current-column))
8736 org-table-named-field-locations)))
8739 (error "Not in a named field"))
8740 (int-to-string (org-table-current-column))))
8741 (dummy (and name (not named)
8742 (not (y-or-n-p "Replace named-field formula with column equation? " ))
8744 (org-table-may-need-update nil)
8745 (stored-list (org-table-get-stored-formulas))
8746 (stored (cdr (assoc scol stored-list)))
8748 ((and stored equation (string-match "^ *=? *$" equation))
8753 (format "%s formula $%s=" (if named "Field" "Column") scol)
8754 (or stored "") 'org-table-formula-history
8758 (when (not (string-match "\\S-" eq))
8760 (setq stored-list (delq (assoc scol stored-list) stored-list))
8761 (org-table-store-formulas stored-list)
8762 (error "Formula removed"))
8763 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8764 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8765 (if (and name (not named))
8766 ;; We set the column equation, delete the named one.
8767 (setq stored-list (delq (assoc name stored-list) stored-list)
8770 (setcdr (assoc scol stored-list) eq)
8771 (setq stored-list (cons (cons scol eq) stored-list)))
8772 (if (or mustsave (not (equal stored eq)))
8773 (org-table-store-formulas stored-list))
8776 (defun org-table-store-formulas (alist)
8777 "Store the list of formulas below the current table."
8778 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
8780 (goto-char (org-table-end))
8781 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
8782 (delete-region (point) (match-end 0)))
8784 (mapconcat (lambda (x)
8785 (concat "$" (car x) "=" (cdr x)))
8789 (defun org-table-get-stored-formulas ()
8790 "Return an alist with the t=stored formulas directly after current table."
8792 (let (scol eq eq-alist strings string seen)
8794 (goto-char (org-table-end))
8795 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8796 (setq strings (org-split-string (match-string 2) " *:: *"))
8797 (while (setq string (pop strings))
8798 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
8799 (setq scol (match-string 1 string)
8800 eq (match-string 2 string)
8801 eq-alist (cons (cons scol eq) eq-alist))
8802 (if (member scol seen)
8803 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8804 (push scol seen))))))
8805 (nreverse eq-alist)))
8807 (defun org-table-modify-formulas (action &rest columns)
8808 "Modify the formulas stored below the current table.
8809 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
8810 expected, for the other action only a single column number is needed."
8811 (let ((list (org-table-get-stored-formulas))
8812 (nmax (length (org-split-string
8813 (buffer-substring (point-at-bol) (point-at-eol))
8815 col col1 col2 scol si sc1 sc2)
8817 ((null list)) ; No action needed if there are no stored formulas
8818 ((eq action 'remove)
8819 (setq col (car columns)
8820 scol (int-to-string col))
8821 (org-table-replace-in-formulas list scol "INVALID")
8822 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
8823 (loop for i from (1+ col) upto nmax by 1 do
8824 (setq si (int-to-string i))
8825 (org-table-replace-in-formulas list si (int-to-string (1- i)))
8826 (if (assoc si list) (setcar (assoc si list)
8827 (int-to-string (1- i))))))
8828 ((eq action 'insert)
8829 (setq col (car columns))
8830 (loop for i from nmax downto col by 1 do
8831 (setq si (int-to-string i))
8832 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
8833 (if (assoc si list) (setcar (assoc si list)
8834 (int-to-string (1+ i))))))
8836 (setq col1 (car columns) col2 (nth 1 columns)
8837 sc1 (int-to-string col1) sc2 (int-to-string col2))
8838 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
8839 (org-table-replace-in-formulas list sc1 "ZqZ")
8840 (org-table-replace-in-formulas list sc2 sc1)
8841 (org-table-replace-in-formulas list "ZqZ" sc2)
8842 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
8843 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
8844 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
8845 (t (error "Invalid action in `org-table-modify-formulas'")))
8846 (if list (org-table-store-formulas list))))
8848 (defun org-table-replace-in-formulas (list s1 s2)
8850 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
8851 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
8852 re (concat (regexp-quote s1) "\\>"))
8853 (while (setq elt (pop list))
8855 (while (string-match re s)
8856 (setq s (replace-match s2 t t s)))
8859 (defun org-table-get-specials ()
8860 "Get the column nmaes and local parameters for this table."
8862 (let ((beg (org-table-begin)) (end (org-table-end))
8863 names name fields fields1 field cnt c v line col)
8864 (setq org-table-column-names nil
8865 org-table-local-parameters nil
8866 org-table-named-field-locations nil)
8868 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8869 (setq names (org-split-string (match-string 1) " *| *")
8871 (while (setq name (pop names))
8873 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8874 (push (cons name (int-to-string cnt)) org-table-column-names))))
8875 (setq org-table-column-names (nreverse org-table-column-names))
8876 (setq org-table-column-name-regexp
8877 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8879 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8880 (setq fields (org-split-string (match-string 1) " *| *"))
8881 (while (setq field (pop fields))
8882 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8883 (push (cons (match-string 1 field) (match-string 2 field))
8884 org-table-local-parameters))))
8886 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8887 (setq c (match-string 1)
8888 fields (org-split-string (match-string 2) " *| *"))
8890 (beginning-of-line (if (equal c "_") 2 0))
8891 (setq line (org-current-line) col 1)
8892 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8893 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8894 (while (and fields1 (setq field (pop fields)))
8895 (setq v (pop fields1) col (1+ col))
8896 (when (and (stringp field) (stringp v)
8897 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8898 (push (cons field v) org-table-local-parameters)
8899 (push (list field line col) org-table-named-field-locations)))))))
8901 (defun org-this-word ()
8902 ;; Get the current word
8904 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
8905 (end (progn (skip-chars-forward "^ \t\n") (point))))
8906 (buffer-substring-no-properties beg end))))
8908 (defun org-table-maybe-eval-formula ()
8909 "Check if the current field starts with \"=\" or \":=\".
8910 If yes, store the formula and apply it."
8911 ;; We already know we are in a table. Get field will only return a formula
8912 ;; when appropriate. It might return a separator line, but no problem.
8913 (when org-table-formula-evaluate-inline
8914 (let* ((field (org-trim (or (org-table-get-field) "")))
8916 (when (string-match "^:?=\\(.*\\)" field)
8917 (setq named (equal (string-to-char field) ?:)
8918 eq (match-string 1 field))
8919 (if (fboundp 'calc-eval)
8920 (org-table-eval-formula (if named '(4) nil) eq))))))
8922 (defvar org-recalc-commands nil
8923 "List of commands triggering the reccalculation of a line.
8924 Will be filled automatically during use.")
8926 (defvar org-recalc-marks
8927 '((" " . "Unmarked: no special line, no automatic recalculation")
8928 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
8929 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
8930 ("!" . "Column name definition line. Reference in formula as $name.")
8931 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8932 ("_" . "Names for values in row below this one.")
8933 ("^" . "Names for values in row above this one.")))
8935 (defun org-table-rotate-recalc-marks (&optional newchar)
8936 "Rotate the recalculation mark in the first column.
8937 If in any row, the first field is not consistent with a mark,
8938 insert a new column for the makers.
8939 When there is an active region, change all the lines in the region,
8940 after prompting for the marking character.
8941 After each change, a message will be displayed indication the meaning
8944 (unless (org-at-table-p) (error "Not at a table"))
8945 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8946 (beg (org-table-begin))
8947 (end (org-table-end))
8948 (l (org-current-line))
8949 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8950 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8954 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8955 (col (org-table-current-column))
8956 (forcenew (car (assoc newchar org-recalc-marks)))
8959 (message "Change region to what mark? Type # * ! $ or SPC: ")
8960 (setq newchar (char-to-string (read-char-exclusive))
8961 forcenew (car (assoc newchar org-recalc-marks))))
8962 (if (and newchar (not forcenew))
8963 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8965 (if l1 (goto-line l1))
8967 (beginning-of-line 1)
8968 (unless (looking-at org-table-dataline-regexp)
8969 (error "Not at a table data line")))
8971 (org-table-goto-column 1)
8972 (org-table-insert-column)
8973 (org-table-goto-column (1+ col)))
8974 (setq epos (point-at-eol))
8976 (beginning-of-line 1)
8977 (org-table-get-field
8978 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8980 (setq new (or forcenew
8981 (cadr (member (match-string 1) marks))))
8987 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8988 (and (looking-at org-table-dataline-regexp)
8989 (org-table-get-field 1 (concat " " new " "))))
8991 (if (not (= epos (point-at-eol))) (org-table-align))
8993 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
8995 (defun org-table-maybe-recalculate-line ()
8996 "Recompute the current line if marked for it, and if we haven't just done it."
8998 (and org-table-allow-automatic-line-recalculation
8999 (not (and (memq last-command org-recalc-commands)
9000 (equal org-last-recalc-line (org-current-line))))
9001 (save-excursion (beginning-of-line 1)
9002 (looking-at org-table-auto-recalculate-regexp))
9003 (fboundp 'calc-eval)
9004 (org-table-recalculate) t))
9006 (defvar org-table-formula-debug nil
9007 "Non-nil means, debug table formulas.
9008 When nil, simply write \"#ERROR\" in corrupted fields.")
9011 (defsubst org-set-calc-mode (var &optional value)
9013 (setq var (assoc var '(("D" calc-angle-mode deg)
9014 ("R" calc-angle-mode rad)
9015 ("F" calc-prefer-frac t)
9016 ("S" calc-symbolic-mode t)))
9017 value (nth 2 var) var (nth 1 var)))
9018 (if (memq var modes)
9019 (setcar (cdr (memq var modes)) value)
9020 (cons var (cons value modes)))
9023 (defun org-table-eval-formula (&optional arg equation
9024 suppress-align suppress-const
9026 "Replace the table field value at the cursor by the result of a calculation.
9028 This function makes use of Dave Gillespie's calc package, in my view the
9029 most exciting program ever written for GNU Emacs. So you need to have calc
9030 installed in order to use this function.
9032 In a table, this command replaces the value in the current field with the
9033 result of a formula. It also installes the formula as the \"current\" column
9034 formula, by storing it in a special line below the table. When called
9035 with a `C-u' prefix, the current field must ba a named field, and the
9036 formula is installed as valid in only this specific field.
9038 When called, the command first prompts for a formula, which is read in
9039 the minibuffer. Previously entered formulas are available through the
9040 history list, and the last used formula is offered as a default.
9041 These stored formulas are adapted correctly when moving, inserting, or
9042 deleting columns with the corresponding commands.
9044 The formula can be any algebraic expression understood by the calc package.
9045 For details, see the Org-mode manual.
9047 This function can also be called from Lisp programs and offers
9048 additional Arguments: EQUATION can be the formula to apply. If this
9049 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9050 used to speed-up recursive calls by by-passing unnecessary aligns.
9051 SUPPRESS-CONST suppresses the interpretation of constants in the
9052 formula, assuming that this has been done already outside the fuction.
9053 SUPPRESS-STORE means the formula should not be stored, either because
9054 it is already stored, or because it is a modified equation that should
9055 not overwrite the stored one."
9058 (org-table-check-inside-data-field)
9059 (org-table-get-specials)
9061 (ndown (if (integerp arg) arg 1))
9062 (org-table-automatic-realign nil)
9063 (case-fold-search nil)
9065 (formula (if (and equation suppress-store)
9067 (org-table-get-formula equation (equal arg '(4)))))
9068 (n0 (org-table-current-column))
9069 (modes (copy-sequence org-calc-default-modes))
9070 n form fmt x ev orig c)
9071 ;; Parse the format string. Since we have a lot of modes, this is
9072 ;; a lot of work. However, I think calc still uses most of the time.
9073 (if (string-match ";" formula)
9074 (let ((tmp (org-split-string formula ";")))
9075 (setq formula (car tmp)
9076 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9078 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
9079 (setq c (string-to-char (match-string 1 fmt))
9080 n (string-to-number (or (match-string 1 fmt) "")))
9081 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
9082 (setq modes (org-set-calc-mode
9084 (list (cdr (assoc c '((?n. float) (?f. fix)
9085 (?s. sci) (?e. eng))))
9087 (setq fmt (replace-match "" t t fmt)))
9088 (while (string-match "[DRFS]" fmt)
9089 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9090 (setq fmt (replace-match "" t t fmt)))
9091 (unless (string-match "\\S-" fmt)
9093 (if (and (not suppress-const) org-table-formula-use-constants)
9094 (setq formula (org-table-formula-substitute-names formula)))
9095 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9097 (setq fields (org-split-string
9099 (point-at-bol) (point-at-eol)) " *| *"))
9100 (if org-table-formula-numbers-only
9101 (setq fields (mapcar
9102 (lambda (x) (number-to-string (string-to-number x)))
9104 (setq ndown (1- ndown))
9105 (setq form (copy-sequence formula))
9106 ;; Insert the references to fields in same row
9107 (while (string-match "\\$\\([0-9]+\\)?" form)
9108 (setq n (if (match-beginning 1)
9109 (string-to-number (match-string 1 form))
9111 x (nth (1- n) fields))
9112 (unless x (error "Invalid field specifier \"%s\""
9113 (match-string 0 form)))
9114 (if (equal x "") (setq x "0"))
9115 (setq form (replace-match (concat "(" x ")") t t form)))
9116 ;; Insert ranges in current column
9117 (while (string-match "\\&[-I0-9]+" form)
9118 (setq form (replace-match
9120 (org-table-get-vertical-vector (match-string 0 form)
9123 (setq ev (calc-eval (cons form modes)
9124 (if org-table-formula-numbers-only 'num)))
9126 (when org-table-formula-debug
9127 (with-output-to-temp-buffer "*Help*"
9128 (princ (format "Substitution history of formula
9131 $1-> %s\n" orig formula form))
9133 (princ (format " %s^\nError: %s"
9134 (make-string (car ev) ?\-) (nth 1 ev)))
9135 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9137 (if fmt (format fmt (string-to-number ev)) ev)))))
9138 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
9139 (unless (and (interactive-p) (not ndown))
9140 (unless (let (inhibit-redisplay)
9141 (y-or-n-p "Debugging Formula. Continue to next? "))
9144 (delete-window (get-buffer-window "*Help*"))
9146 (if (listp ev) (setq fmt nil ev "#ERROR"))
9147 (org-table-justify-field-maybe
9148 (if fmt (format fmt (string-to-number ev)) ev))
9149 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9150 (call-interactively 'org-return)
9152 (and down (org-table-maybe-recalculate-line))
9153 (or suppress-align (and org-table-may-need-update
9154 (org-table-align)))))
9156 (defun org-table-recalculate (&optional all noalign)
9157 "Recalculate the current table line by applying all stored formulas."
9159 (or (memq this-command org-recalc-commands)
9160 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9161 (unless (org-at-table-p) (error "Not at a table"))
9162 (org-table-get-specials)
9163 (let* ((eqlist (sort (org-table-get-stored-formulas)
9164 (lambda (a b) (string< (car a) (car b)))))
9165 (inhibit-redisplay t)
9166 (line-re org-table-dataline-regexp)
9167 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9168 (thiscol (org-table-current-column))
9169 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
9170 ;; Insert constants in all formulas
9173 (setcdr x (org-table-formula-substitute-names (cdr x)))
9176 ;; Split the equation list
9177 (while (setq eq (pop eqlist))
9178 (if (<= (string-to-char (car eq)) ?9)
9181 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9184 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9185 (goto-char (setq beg (org-table-begin)))
9186 (if (re-search-forward org-table-calculate-mark-regexp end t)
9187 ;; This is a table with marked lines, only compute selected lines
9188 (setq line-re org-table-recalculate-regexp)
9189 ;; Move forward to the first non-header line
9190 (if (and (re-search-forward org-table-dataline-regexp end t)
9191 (re-search-forward org-table-hline-regexp end t)
9192 (re-search-forward org-table-dataline-regexp end t))
9193 (setq beg (match-beginning 0))
9194 nil))) ;; just leave beg where it is
9195 (setq beg (point-at-bol)
9196 end (move-marker (make-marker) (1+ (point-at-eol)))))
9198 (and all (message "Re-applying formulas to full table..."))
9199 (while (re-search-forward line-re end t)
9200 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
9201 ;; Unprotected line, recalculate
9202 (and all (message "Re-applying formulas to full table...(line %d)"
9203 (setq cnt (1+ cnt))))
9204 (setq org-last-recalc-line (org-current-line))
9206 (while (setq entry (pop eql))
9207 (goto-line org-last-recalc-line)
9208 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9209 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
9210 (goto-line thisline)
9211 (org-table-goto-column thiscol)
9212 (or noalign (and org-table-may-need-update (org-table-align))
9213 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9214 ;; Now do the names fields
9215 (while (setq eq (pop eqlname))
9217 a (assoc name org-table-named-field-locations))
9219 (message "Re-applying formula to named field: %s" name)
9220 (goto-line (nth 1 a))
9221 (org-table-goto-column (nth 2 a))
9222 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
9223 ;; back to initial position
9224 (goto-line thisline)
9225 (org-table-goto-column thiscol)
9226 (or noalign (and org-table-may-need-update (org-table-align))
9227 (and all (message "Re-applying formulas...done")))))
9229 (defun org-table-formula-substitute-names (f)
9230 "Replace $const with values in string F."
9231 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
9232 ;; First, check for column names
9233 (while (setq start (string-match org-table-column-name-regexp f start))
9234 (setq start (1+ start))
9235 (setq a (assoc (match-string 1 f) org-table-column-names))
9236 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9237 ;; Expand ranges to vectors
9238 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
9239 (setq n1 (string-to-number (match-string 1 f))
9240 n2 (string-to-number (match-string 2 f))
9241 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
9242 s (concat "[($" (number-to-string (1- nn1)) ")"))
9243 (loop for i from nn1 upto nn2 do
9244 (setq s (concat s ",($" (int-to-string i) ")")))
9245 (setq s (concat s "]"))
9246 (if (< n2 n1) (setq s (concat "rev(" s ")")))
9247 (setq f (replace-match s t t f)))
9248 ;; Parameters and constants
9250 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
9251 (setq start (1+ start))
9252 (if (setq a (save-match-data
9253 (org-table-get-constant (match-string 1 f))))
9254 (setq f (replace-match (concat "(" a ")") t t f))))
9255 (if org-table-formula-debug
9256 (put-text-property 0 (length f) :orig-formula f1 f))
9259 (defun org-table-get-constant (const)
9260 "Find the value for a parameter or constant in a formula.
9261 Parameters get priority."
9262 (or (cdr (assoc const org-table-local-parameters))
9263 (cdr (assoc const org-table-formula-constants))
9264 (and (fboundp 'constants-get) (constants-get const))
9267 (defvar org-edit-formulas-map (make-sparse-keymap))
9268 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
9269 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
9270 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
9273 (defvar org-window-configuration)
9275 (defun org-table-edit-formulas ()
9276 "Edit the formulas of the current table in a separate buffer."
9278 (unless (org-at-table-p)
9279 (error "Not at a table"))
9280 (org-table-get-specials)
9281 (let ((eql (org-table-get-stored-formulas))
9282 (pos (move-marker (make-marker) (point)))
9283 (wc (current-window-configuration))
9285 (switch-to-buffer-other-window "*Edit Formulas*")
9288 (set (make-local-variable 'org-pos) pos)
9289 (set (make-local-variable 'org-window-configuration) wc)
9290 (use-local-map org-edit-formulas-map)
9291 (setq s "# Edit formulas and finish with `C-c C-c'.
9292 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
9293 # Use `C-c ?' to get information about $name at point.
9294 # To cancel editing, press `C-c C-q'.\n")
9295 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9297 (while (setq entry (pop eql))
9298 (when (setq loc (assoc (car entry) org-table-named-field-locations))
9299 (setq s (format "# Named formula, referring to column %d in line %d\n"
9300 (nth 2 loc) (nth 1 loc)))
9301 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9303 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
9304 (remove-text-properties 0 (length s) '(face nil) s)
9306 (goto-char (point-min))
9307 (message "Edit formulas and finish with `C-c C-c'.")))
9309 (defun org-show-variable ()
9310 "Show the location/value of the $ expression at point."
9312 (let (var (pos org-pos) (win (selected-window)) e)
9314 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
9315 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
9316 (setq var (match-string 1))
9317 (error "No variable at point")))
9319 ((setq e (assoc var org-table-named-field-locations))
9320 (switch-to-buffer-other-window (marker-buffer pos))
9321 (goto-line (nth 1 e))
9322 (org-table-goto-column (nth 2 e))
9324 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9325 ((setq e (assoc var org-table-column-names))
9326 (switch-to-buffer-other-window (marker-buffer pos))
9328 (goto-char (org-table-begin))
9329 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9332 (goto-char (match-beginning 1))
9333 (message "Named column (column %s)" (cdr e)))
9334 (error "Column name not found"))
9335 (select-window win))
9336 ((string-match "^[0-9]$" var)
9338 (switch-to-buffer-other-window (marker-buffer pos))
9340 (goto-char (org-table-begin))
9342 (if (re-search-forward org-table-dataline-regexp
9345 (goto-char (match-beginning 0))
9346 (org-table-goto-column (string-to-number var))
9347 (message "Column %s" var))
9348 (error "Column name not found"))
9349 (select-window win))
9350 ((setq e (assoc var org-table-local-parameters))
9351 (switch-to-buffer-other-window (marker-buffer pos))
9353 (goto-char (org-table-begin))
9354 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9356 (goto-char (match-beginning 1))
9357 (message "Local parameter."))
9358 (error "Parameter not found"))
9359 (select-window win))
9362 ((setq e (assoc var org-table-formula-constants))
9363 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
9364 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9365 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
9366 (t (error "Undefined name $%s" var)))))))
9368 (defun org-finish-edit-formulas (&optional arg)
9369 "Parse the buffer for formula definitions and install them.
9370 With prefix ARG, apply the new formulas to the table."
9372 (let ((pos org-pos) eql)
9373 (goto-char (point-min))
9374 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
9375 (push (cons (match-string 1) (match-string 2)) eql))
9376 (set-window-configuration org-window-configuration)
9377 (select-window (get-buffer-window (marker-buffer pos)))
9379 (unless (org-at-table-p)
9380 (error "Lost table position - cannot install formulae"))
9381 (org-table-store-formulas eql)
9382 (move-marker pos nil)
9383 (kill-buffer "*Edit Formulas*")
9385 (org-table-recalculate 'all)
9386 (message "New formulas installed - press C-u C-c C-c to apply."))))
9388 (defun org-abort-edit-formulas ()
9389 "Abort editing formulas, without installing the changes."
9391 (let ((pos org-pos))
9392 (set-window-configuration org-window-configuration)
9393 (select-window (get-buffer-window (marker-buffer pos)))
9395 (message "Formula editing aborted without installing changes")))
9397 ;;; The orgtbl minor mode
9399 ;; Define a minor mode which can be used in other modes in order to
9400 ;; integrate the org-mode table editor.
9402 ;; This is really a hack, because the org-mode table editor uses several
9403 ;; keys which normally belong to the major mode, for example the TAB and
9404 ;; RET keys. Here is how it works: The minor mode defines all the keys
9405 ;; necessary to operate the table editor, but wraps the commands into a
9406 ;; function which tests if the cursor is currently inside a table. If that
9407 ;; is the case, the table editor command is executed. However, when any of
9408 ;; those keys is used outside a table, the function uses `key-binding' to
9409 ;; look up if the key has an associated command in another currently active
9410 ;; keymap (minor modes, major mode, global), and executes that command.
9411 ;; There might be problems if any of the keys used by the table editor is
9412 ;; otherwise used as a prefix key.
9414 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9415 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9416 ;; addresses this by checking explicitly for both bindings.
9418 ;; The optimized version (see variable `orgtbl-optimized') takes over
9419 ;; all keys which are bound to `self-insert-command' in the *global map*.
9420 ;; Some modes bind other commands to simple characters, for example
9421 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9422 ;; active, this binding is ignored inside tables and replaced with a
9423 ;; modified self-insert.
9425 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
9426 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
9427 In the optimized version, the table editor takes over all simple keys that
9428 normally just insert a character. In tables, the characters are inserted
9429 in a way to minimize disturbing the table structure (i.e. in overwrite mode
9430 for empty fields). Outside tables, the correct binding of the keys is
9433 The default for this option is t if the optimized version is also used in
9434 Org-mode. See the variable `org-enable-table-editor' for details. Changing
9435 this variable requires a restart of Emacs to become effective."
9439 (defvar orgtbl-mode nil
9440 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9441 table editor in arbitrary modes.")
9442 (make-variable-buffer-local 'orgtbl-mode)
9444 (defvar orgtbl-mode-map (make-keymap)
9445 "Keymap for `orgtbl-mode'.")
9448 (defun turn-on-orgtbl ()
9449 "Unconditionally turn on `orgtbl-mode'."
9453 (defun orgtbl-mode (&optional arg)
9454 "The `org-mode' table editor as a minor mode for use in other modes."
9456 (if (eq major-mode 'org-mode)
9457 ;; Exit without error, in case some hook functions calls this
9458 ;; by accident in org-mode.
9459 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9461 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9464 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9465 ;; Make sure we are first in minor-mode-map-alist
9466 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9467 (and c (setq minor-mode-map-alist
9468 (cons c (delq c minor-mode-map-alist)))))
9469 (set (make-local-variable (quote org-table-may-need-update)) t)
9470 (make-local-hook (quote before-change-functions)) ; needed for XEmacs
9471 (add-hook 'before-change-functions 'org-before-change-function
9473 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
9474 auto-fill-inhibit-regexp)
9475 (set (make-local-variable 'auto-fill-inhibit-regexp)
9476 (if auto-fill-inhibit-regexp
9477 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
9479 (easy-menu-add orgtbl-mode-menu)
9480 (run-hooks 'orgtbl-mode-hook))
9481 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9482 (remove-hook 'before-change-functions 'org-before-change-function t)
9483 (easy-menu-remove orgtbl-mode-menu)
9484 (force-mode-line-update 'all))))
9486 ;; Install it as a minor mode.
9487 (put 'orgtbl-mode :included t)
9488 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9489 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9491 (defun orgtbl-make-binding (fun n &rest keys)
9492 "Create a function for binding in the table minor mode.
9493 FUN is the command to call inside a table. N is used to create a unique
9494 command name. KEYS are keys that should be checked in for a command
9495 to execute outside of tables."
9498 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9500 (concat "In tables, run `" (symbol-name fun) "'.\n"
9501 "Outside of tables, run the binding of `"
9502 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9507 (list 'call-interactively (list 'quote fun))
9508 (list 'let '(orgtbl-mode)
9509 (list 'call-interactively
9512 (list 'key-binding k))
9514 '('orgtbl-error))))))))
9516 (defun orgtbl-error ()
9517 "Error when there is no default binding for a table key."
9519 (error "This key is has no function outside tables"))
9521 (defun orgtbl-setup ()
9522 "Setup orgtbl keymaps."
9526 '([(meta shift left)] org-table-delete-column)
9527 '([(meta left)] org-table-move-column-left)
9528 '([(meta right)] org-table-move-column-right)
9529 '([(meta shift right)] org-table-insert-column)
9530 '([(meta shift up)] org-table-kill-row)
9531 '([(meta shift down)] org-table-insert-row)
9532 '([(meta up)] org-table-move-row-up)
9533 '([(meta down)] org-table-move-row-down)
9534 '("\C-c\C-w" org-table-cut-region)
9535 '("\C-c\M-w" org-table-copy-region)
9536 '("\C-c\C-y" org-table-paste-rectangle)
9537 '("\C-c-" org-table-insert-hline)
9538 ; '([(shift tab)] org-table-previous-field)
9539 '("\C-m" org-table-next-row)
9540 (list (org-key 'S-return) 'org-table-copy-down)
9541 '([(meta return)] org-table-wrap-region)
9542 '("\C-c\C-q" org-table-wrap-region)
9543 '("\C-c?" org-table-current-column)
9544 '("\C-c " org-table-blank-field)
9545 '("\C-c+" org-table-sum)
9546 '("\C-c|" org-table-toggle-vline-visibility)
9547 '("\C-c=" org-table-eval-formula)
9548 '("\C-c'" org-table-edit-formulas)
9549 '("\C-c*" org-table-recalculate)
9550 '("\C-c^" org-table-sort-lines)
9551 '([(control ?#)] org-table-rotate-recalc-marks)))
9553 (while (setq elt (pop bindings))
9554 (setq nfunc (1+ nfunc))
9557 cmd (orgtbl-make-binding fun nfunc key))
9558 (define-key orgtbl-mode-map key cmd))
9559 ;; Special treatment needed for TAB and RET
9560 (define-key orgtbl-mode-map [(return)]
9561 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
9562 (define-key orgtbl-mode-map "\C-m"
9563 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
9564 (define-key orgtbl-mode-map [(tab)]
9565 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
9566 (define-key orgtbl-mode-map "\C-i"
9567 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
9568 (define-key orgtbl-mode-map "\C-i"
9569 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
9570 (define-key orgtbl-mode-map "\C-c\C-c"
9571 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
9572 (when orgtbl-optimized
9573 ;; If the user wants maximum table support, we need to hijack
9574 ;; some standard editing functions
9575 (org-remap orgtbl-mode-map
9576 'self-insert-command 'orgtbl-self-insert-command
9577 'delete-char 'orgtbl-delete-char
9578 'delete-backward-char 'orgtbl-delete-backward-char)
9579 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
9580 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
9582 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
9583 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
9584 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
9585 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
9587 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
9588 ["Copy Field from Above"
9589 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
9592 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
9593 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
9594 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
9595 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
9597 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
9598 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
9599 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
9600 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
9601 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
9603 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
9605 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
9606 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
9607 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
9608 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
9610 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
9611 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9612 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
9613 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
9614 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
9615 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
9616 ["Sum Column/Rectangle" org-table-sum
9617 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
9618 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
9620 (setq org-table-formula-debug (not org-table-formula-debug))
9621 :style toggle :selected org-table-formula-debug]
9625 (defun orgtbl-tab ()
9626 "Justification and field motion for `orgtbl-mode'."
9628 (org-table-justify-field-maybe)
9629 (org-table-next-field))
9631 (defun orgtbl-ret ()
9632 "Justification and field motion for `orgtbl-mode'."
9634 (org-table-justify-field-maybe)
9635 (org-table-next-row))
9637 (defun orgtbl-self-insert-command (N)
9638 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9639 If the cursor is in a table looking at whitespace, the whitespace is
9640 overwritten, and the table is not marked as requiring realignment."
9642 (if (and (org-at-table-p)
9644 (and org-table-auto-blank-field
9645 (member last-command
9646 '(orgtbl-hijacker-command-100
9647 orgtbl-hijacker-command-101
9648 orgtbl-hijacker-command-102
9649 orgtbl-hijacker-command-103
9650 orgtbl-hijacker-command-104
9651 orgtbl-hijacker-command-105))
9652 (org-table-blank-field))
9655 (looking-at "[^|\n]* +|"))
9656 (let (org-table-may-need-update)
9657 (goto-char (1- (match-end 0)))
9658 (delete-backward-char 1)
9659 (goto-char (match-beginning 0))
9660 (self-insert-command N))
9661 (setq org-table-may-need-update t)
9663 (call-interactively (key-binding (vector last-input-event))))))
9665 (defun org-force-self-insert (N)
9666 "Needed to enforce self-insert under remapping."
9668 (self-insert-command N))
9670 (defun orgtbl-delete-backward-char (N)
9671 "Like `delete-backward-char', insert whitespace at field end in tables.
9672 When deleting backwards, in tables this function will insert whitespace in
9673 front of the next \"|\" separator, to keep the table aligned. The table will
9674 still be marked for re-alignment, because a narrow field may lead to a
9675 reduced column width."
9677 (if (and (org-at-table-p)
9679 (string-match "|" (buffer-substring (point-at-bol) (point)))
9680 (looking-at ".*?|"))
9681 (let ((pos (point)))
9682 (backward-delete-char N)
9683 (skip-chars-forward "^|")
9685 (goto-char (1- pos)))
9686 (delete-backward-char N)))
9688 (defun orgtbl-delete-char (N)
9689 "Like `delete-char', but insert whitespace at field end in tables.
9690 When deleting characters, in tables this function will insert whitespace in
9691 front of the next \"|\" separator, to keep the table aligned. The table
9692 will still be marked for re-alignment, because a narrow field may lead to
9693 a reduced column width."
9695 (if (and (org-at-table-p)
9697 (not (= (char-after) ?|))
9699 (if (looking-at ".*?|")
9700 (let ((pos (point)))
9701 (replace-match (concat
9702 (substring (match-string 0) 1 -1)
9709 (defconst org-level-max 20)
9711 (defun org-export-find-first-heading-line (list)
9712 "Remove all lines from LIST which are before the first headline."
9713 (let ((orig-list list)
9714 (re (concat "^" outline-regexp)))
9716 (not (string-match re (car list))))
9718 (or list orig-list)))
9720 (defun org-skip-comments (lines)
9721 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
9722 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
9723 (re2 "^\\(\\*+\\)[ \t\n\r]")
9725 (while (setq line (pop lines))
9727 ((and (string-match re1 line)
9728 (setq level (- (match-end 1) (match-beginning 1))))
9729 ;; Beginning of a COMMENT subtree. Skip it.
9730 (while (and (setq line (pop lines))
9731 (or (not (string-match re2 line))
9732 (> (- (match-end 1) (match-beginning 1)) level))))
9733 (setq lines (cons line lines)))
9734 ((string-match "^#" line)
9735 ;; an ordinary comment line
9737 (t (setq rtn (cons line rtn)))))
9742 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
9743 "Characters for underlining headings in ASCII export.")
9745 (defconst org-html-entities
9785 ("Aring") ("AA"."Å")
9874 ("varepsilon"."ε")
9887 ("sigmaf") ("varsigma"."ς")
9895 ("thetasym") ("vartheta"."ϑ")
9898 ("bull") ("bullet"."•")
9899 ("hellip") ("dots"."…")
9909 ("larr") ("leftarrow"."←") ("gets"."←")
9910 ("uarr") ("uparrow"."↑")
9911 ("rarr") ("to"."→") ("rightarrow"."→")
9912 ("darr")("downarrow"."↓")
9913 ("harr") ("leftrightarrow"."↔")
9914 ("crarr") ("hookleftarrow"."↵") ; has round hook, not quite CR
9915 ("lArr") ("Leftarrow"."⇐")
9916 ("uArr") ("Uparrow"."⇑")
9917 ("rArr") ("Rightarrow"."⇒")
9918 ("dArr") ("Downarrow"."⇓")
9919 ("hArr") ("Leftrightarrow"."⇔")
9921 ("part") ("partial"."∂")
9922 ("exist") ("exists"."∃")
9923 ("empty") ("emptyset"."∅")
9925 ("isin") ("in"."∈")
9931 ("lowast") ("ast"."∗")
9933 ("prop") ("proptp"."∝")
9934 ("infin") ("infty"."∞")
9935 ("ang") ("angle"."∠")
9936 ("and") ("vee"."∧")
9937 ("or") ("wedge"."∨")
9943 ("cong") ("simeq"."≅")
9944 ("asymp")("approx"."≈")
9945 ("ne") ("neq"."≠")
9949 ("sub") ("subset"."⊂")
9950 ("sup") ("supset"."⊃")
9957 ("sdot") ("cdot"."⋅")
9964 ("loz") ("Diamond"."◊")
9965 ("spades") ("spadesuit"."♠")
9966 ("clubs") ("clubsuit"."♣")
9967 ("hearts") ("diamondsuit"."♥")
9968 ("diams") ("diamondsuit"."♦")
10002 ("arccos"."arccos")
10003 ("arcsin"."arcsin")
10004 ("arctan"."arctan")
10021 ("liminf"."liminf")
10022 ("limsup"."limsup")
10035 "Entities for TeX->HTML translation.
10036 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
10037 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
10038 In that case, \"\\ent\" will be translated to \"&other;\".
10039 The list contains HTML entities for Latin-1, Greek and other symbols.
10040 It is supplemented by a number of commonly used TeX macros with appropriate
10041 translations. There is currently no way for users to extend this.")
10043 (defvar org-last-level nil) ; dynamically scoped variable
10045 (defun org-export-as-ascii (arg)
10046 "Export the outline as a pretty ASCII file.
10047 If there is an active region, export only the region.
10048 The prefix ARG specifies how many levels of the outline should become
10049 underlined headlines. The default is 3."
10051 (setq-default org-todo-line-regexp org-todo-line-regexp)
10054 (if (org-region-active-p) (region-beginning) (point-min))
10055 (if (org-region-active-p) (region-end) (point-max))))
10056 (lines (org-export-find-first-heading-line
10057 (org-skip-comments (org-split-string region "[\r\n]"))))
10058 (org-startup-with-deadline-check nil)
10061 (case-fold-search nil)
10062 (filename (concat (file-name-sans-extension (buffer-file-name))
10064 (buffer (find-file-noselect filename))
10065 (levels-open (make-vector org-level-max nil))
10066 (date (format-time-string "%Y/%m/%d" (current-time)))
10067 (time (format-time-string "%X" (current-time)))
10068 (author user-full-name)
10069 (title (buffer-name))
10071 (email user-mail-address)
10072 (language org-export-default-language)
10077 (setq org-last-level 1)
10078 (org-init-section-numbers)
10080 (find-file-noselect filename)
10082 ;; Search for the export key lines
10083 (org-parse-key-lines)
10085 (setq lang-words (or (assoc language org-export-language-setup)
10086 (assoc "en" org-export-language-setup)))
10087 (if org-export-ascii-show-new-buffer
10088 (switch-to-buffer-other-window buffer)
10089 (set-buffer buffer))
10092 (if options (org-parse-export-options options))
10093 (setq umax (if arg (prefix-numeric-value arg)
10094 org-export-headline-levels))
10097 (if title (org-insert-centered title ?=))
10099 (if (or author email)
10100 (insert (concat (nth 1 lang-words) ": " (or author "")
10101 (if email (concat " <" email ">") "")
10103 (if (and date time)
10104 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
10105 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
10109 (if org-export-with-toc
10111 (insert (nth 3 lang-words) "\n"
10112 (make-string (length (nth 3 lang-words)) ?=) "\n")
10113 (mapcar '(lambda (line)
10114 (if (string-match org-todo-line-regexp
10116 ;; This is a headline
10118 (setq level (- (match-end 1) (match-beginning 1))
10119 txt (match-string 3 line)
10121 (or (and (match-beginning 2)
10122 (not (equal (match-string 2 line)
10125 (and (= level umax)
10126 (org-search-todo-below
10127 line lines level))))
10128 (setq txt (org-html-expand-for-ascii txt))
10130 (if org-export-with-section-numbers
10131 (setq txt (concat (org-section-number level)
10133 (if (<= level umax)
10136 (make-string (* (1- level) 4) ?\ )
10137 (format (if todo "%s (*)\n" "%s\n") txt))
10138 (setq org-last-level level))
10142 (org-init-section-numbers)
10143 (while (setq line (pop lines))
10144 ;; Remove the quoted HTML tags.
10145 (setq line (org-html-expand-for-ascii line))
10147 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10149 (setq level (- (match-end 1) (match-beginning 1))
10150 txt (match-string 2 line))
10151 (org-ascii-level-start level txt umax))
10152 (t (insert line "\n"))))
10155 (goto-char (point-min))))
10157 (defun org-search-todo-below (line lines level)
10158 "Search the subtree below LINE for any TODO entries."
10159 (let ((rest (cdr (memq line lines)))
10160 (re org-todo-line-regexp)
10163 (while (setq line (pop rest))
10164 (if (string-match re line)
10166 (setq lv (- (match-end 1) (match-beginning 1))
10167 todo (and (match-beginning 2)
10168 (not (equal (match-string 2 line)
10169 org-done-string))))
10171 (if (<= lv level) (throw 'exit nil))
10172 (if todo (throw 'exit t))))))))
10174 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
10175 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
10176 (defun org-html-expand-for-ascii (line)
10177 "Handle quoted HTML for ASCII export."
10178 (if org-export-html-expand
10179 (while (string-match "@<[^<>\n]*>" line)
10180 ;; We just remove the tags for now.
10181 (setq line (replace-match "" nil nil line))))
10184 (defun org-insert-centered (s &optional underline)
10185 "Insert the string S centered and underline it with character UNDERLINE."
10186 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
10187 (insert (make-string ind ?\ ) s "\n")
10189 (insert (make-string ind ?\ )
10190 (make-string (length s) underline)
10193 (defun org-ascii-level-start (level title umax)
10194 "Insert a new level in ASCII export."
10197 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
10198 (if (or (not (equal (char-before) ?\n))
10199 (not (equal (char-before (1- (point))) ?\n)))
10201 (setq char (nth (- umax level) (reverse org-ascii-underline)))
10202 (if org-export-with-section-numbers
10203 (setq title (concat (org-section-number level) " " title)))
10204 (insert title "\n" (make-string (string-width title) char) "\n"))))
10206 (defun org-export-copy-visible ()
10207 "Copy the visible part of the buffer to another buffer, for printing.
10208 Also removes the first line of the buffer if it specifies a mode,
10209 and all options lines."
10211 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
10213 (buffer (find-file-noselect filename))
10215 (org-make-options-regexp
10216 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
10217 "STARTUP" "ARCHIVE"
10218 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
10219 (if org-noutline-p "\\(\n\\|$\\)" "")))
10221 (with-current-buffer buffer
10225 (setq s (goto-char (point-min)))
10226 (while (not (= (point) (point-max)))
10227 (goto-char (org-find-invisible))
10228 (append-to-buffer buffer s (point))
10229 (setq s (goto-char (org-find-visible)))))
10230 (switch-to-buffer-other-window buffer)
10232 (goto-char (point-min))
10233 (if (looking-at ".*-\\*- mode:.*\n")
10234 (replace-match ""))
10235 (while (re-search-forward ore nil t)
10236 (replace-match ""))
10237 (goto-char (point-min))))
10239 (defun org-find-visible ()
10240 (if (featurep 'noutline)
10242 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10243 (get-char-property s 'invisible)))
10245 (skip-chars-forward "^\n")
10247 (defun org-find-invisible ()
10248 (if (featurep 'noutline)
10250 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10251 (not (get-char-property s 'invisible))))
10253 (skip-chars-forward "^\r")
10258 (defun org-get-current-options ()
10259 "Return a string with current options as keyword options.
10260 Does include HTML export options as well as TODO and CATEGORY stuff."
10266 #+TEXT: Some descriptive text to be emitted. Several lines OK.
10267 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
10274 (buffer-name) (user-full-name) user-mail-address org-export-default-language
10275 org-export-headline-levels
10276 org-export-with-section-numbers
10277 org-export-with-toc
10278 org-export-preserve-breaks
10279 org-export-html-expand
10280 org-export-with-fixed-width
10281 org-export-with-tables
10282 org-export-with-sub-superscripts
10283 org-export-with-emphasize
10284 org-export-with-TeX-macros
10285 (file-name-nondirectory (buffer-file-name))
10286 (if (equal org-todo-interpretation 'sequence)
10287 (mapconcat 'identity org-todo-keywords " ")
10288 "TODO FEEDBACK VERIFY DONE")
10289 (if (equal org-todo-interpretation 'type)
10290 (mapconcat 'identity org-todo-keywords " ")
10291 "Me Jason Marie DONE")
10292 (cdr (assoc org-startup-folded
10293 '((nil . "nofold")(t . "fold")(content . "content"))))
10294 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
10295 org-archive-location
10298 (defun org-insert-export-options-template ()
10299 "Insert into the buffer a template with information for exporting."
10301 (if (not (bolp)) (newline))
10302 (let ((s (org-get-current-options)))
10303 (and (string-match "#\\+CATEGORY" s)
10304 (setq s (substring s 0 (match-beginning 0))))
10307 (defun org-toggle-fixed-width-section (arg)
10308 "Toggle the fixed-width export.
10309 If there is no active region, the QUOTE keyword at the current headline is
10310 inserted or removed. When present, it causes the text between this headline
10311 and the next to be exported as fixed-width text, and unmodified.
10312 If there is an active region, this command adds or removes a colon as the
10313 first character of this line. If the first character of a line is a colon,
10314 this line is also exported in fixed-width font."
10317 (regionp (org-region-active-p))
10318 (beg (if regionp (region-beginning) (point)))
10319 (end (if regionp (region-end)))
10320 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
10321 (re "[ \t]*\\(:\\)")
10326 (setq cc (current-column))
10327 (beginning-of-line 1)
10328 (setq off (looking-at re))
10329 (while (> nlines 0)
10330 (setq nlines (1- nlines))
10331 (beginning-of-line 1)
10334 (move-to-column cc t)
10337 ((and off (looking-at re))
10338 (replace-match "" t t nil 1))
10339 ((not off) (move-to-column cc t) (insert ":")))
10342 (org-back-to-heading)
10343 (if (looking-at (concat outline-regexp
10344 "\\( +\\<" org-quote-string "\\>\\)"))
10345 (replace-match "" t t nil 1)
10346 (if (looking-at outline-regexp)
10348 (goto-char (match-end 0))
10349 (insert " " org-quote-string))))))))
10351 (defun org-export-as-html-and-open (arg)
10352 "Export the outline as HTML and immediately open it with a browser.
10353 If there is an active region, export only the region.
10354 The prefix ARG specifies how many levels of the outline should become
10355 headlines. The default is 3. Lower levels will become bulleted lists."
10357 (org-export-as-html arg 'hidden)
10358 (org-open-file (buffer-file-name)))
10360 (defun org-export-as-html-batch ()
10361 "Call `org-export-as-html', may be used in batch processing as
10363 --load=$HOME/lib/emacs/org.el
10364 --eval \"(setq org-export-headline-levels 2)\"
10365 --visit=MyFile --funcall org-export-as-html-batch"
10366 (org-export-as-html org-export-headline-levels 'hidden))
10368 (defun org-export-as-html (arg &optional hidden)
10369 "Export the outline as a pretty HTML file.
10370 If there is an active region, export only the region.
10371 The prefix ARG specifies how many levels of the outline should become
10372 headlines. The default is 3. Lower levels will become bulleted lists."
10374 (setq-default org-todo-line-regexp org-todo-line-regexp)
10375 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
10376 (setq-default org-done-string org-done-string)
10377 (let* ((style org-export-html-style)
10378 (region-p (org-region-active-p))
10381 (if region-p (region-beginning) (point-min))
10382 (if region-p (region-end) (point-max))))
10384 (org-skip-comments (org-split-string region "[\r\n]")))
10385 (lines (org-export-find-first-heading-line all_lines))
10386 (level 0) (line "") (origline "") txt todo
10388 (filename (concat (file-name-sans-extension (buffer-file-name))
10390 (buffer (find-file-noselect filename))
10391 (levels-open (make-vector org-level-max nil))
10392 (date (format-time-string "%Y/%m/%d" (current-time)))
10393 (time (format-time-string "%X" (current-time)))
10394 (author user-full-name)
10395 (title (buffer-name))
10397 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
10400 (in-local-list nil)
10401 (local-list-num nil)
10402 (local-list-indent nil)
10403 (llt org-plain-list-ordered-item-terminator)
10404 (email user-mail-address)
10405 (language org-export-default-language)
10410 ;; FIXME: The following returns always nil under XEmacs
10411 (coding-system (and (fboundp 'coding-system-get)
10412 (boundp 'buffer-file-coding-system)
10413 buffer-file-coding-system))
10414 (coding-system-for-write (or coding-system coding-system-for-write))
10415 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
10416 (charset (and coding-system
10417 (coding-system-get coding-system 'mime-charset)))
10419 table-buffer table-orig-buffer
10420 ind start-is-num starter
10422 (message "Exporting...")
10424 (setq org-last-level 1)
10425 (org-init-section-numbers)
10427 ;; Search for the export key lines
10428 (org-parse-key-lines)
10429 (setq lang-words (or (assoc language org-export-language-setup)
10430 (assoc "en" org-export-language-setup)))
10432 ;; Switch to the output buffer
10433 (if (or hidden (not org-export-html-show-new-buffer))
10434 (set-buffer buffer)
10435 (switch-to-buffer-other-window buffer))
10438 (let ((case-fold-search nil))
10439 (if options (org-parse-export-options options))
10440 (setq umax (if arg (prefix-numeric-value arg)
10441 org-export-headline-levels))
10445 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
10446 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
10447 <html lang=\"%s\"><head>
10449 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
10450 <meta name=generator content=\"Org-mode\">
10451 <meta name=generated content=\"%s %s\">
10452 <meta name=author content=\"%s\">
10456 language (org-html-expand title) (or charset "iso-8859-1")
10457 date time author style))
10458 (if title (insert (concat "<H1 class=\"title\">"
10459 (org-html-expand title) "</H1>\n")))
10460 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
10461 (if email (insert (concat "<a href=\"mailto:" email "\"><"
10462 email "></a>\n")))
10463 (if (or author email) (insert "<br>\n"))
10464 (if (and date time) (insert (concat (nth 2 lang-words) ": "
10465 date " " time "<br>\n")))
10466 (if text (insert (concat "<p>\n" (org-html-expand text))))
10467 (if org-export-with-toc
10469 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
10471 (mapcar '(lambda (line)
10472 (if (string-match org-todo-line-regexp line)
10473 ;; This is a headline
10475 (setq level (- (match-end 1) (match-beginning 1))
10476 txt (save-match-data
10478 (match-string 3 line)))
10480 (or (and (match-beginning 2)
10481 (not (equal (match-string 2 line)
10484 (and (= level umax)
10485 (org-search-todo-below
10486 line lines level))))
10487 (if org-export-with-section-numbers
10488 (setq txt (concat (org-section-number level)
10490 (if (<= level umax)
10492 (setq head-count (+ head-count 1))
10493 (if (> level org-last-level)
10495 (setq cnt (- level org-last-level))
10496 (while (>= (setq cnt (1- cnt)) 0)
10499 (if (< level org-last-level)
10501 (setq cnt (- org-last-level level))
10502 (while (>= (setq cnt (1- cnt)) 0)
10508 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
10509 "<li><a href=\"#sec-%d\">%s</a>\n")
10511 (setq org-last-level level))
10514 (while (> org-last-level 0)
10515 (setq org-last-level (1- org-last-level))
10516 (insert "</ul>\n"))
10518 (setq head-count 0)
10519 (org-init-section-numbers)
10521 (while (setq line (pop lines) origline line)
10524 ;; end of quote section?
10525 (when (and inquote (string-match "^\\*+" line))
10526 (insert "</pre>\n")
10527 (setq inquote nil))
10528 ;; inside a quote section?
10530 (insert (org-html-protect line) "\n")
10531 (throw 'nextline nil))
10534 (when (and org-export-with-fixed-width
10535 (string-match "^[ \t]*:\\(.*\\)" line))
10536 (when (not infixed)
10538 (insert "<pre>\n"))
10539 (insert (org-html-protect (match-string 1 line)) "\n")
10541 (not (string-match "^[ \t]*\\(:.*\\)"
10544 (insert "</pre>\n"))
10545 (throw 'nextline nil))
10547 ;; Protect the links
10549 (while (string-match org-link-maybe-angles-regexp line start)
10550 (setq start (match-end 0))
10551 (setq line (replace-match
10552 (concat "\000" (match-string 1 line) "\000")
10555 ;; replace "&" by "&", "<" and ">" by "<" and ">"
10556 ;; handle @<..> HTML tags (replace "@>..<" by "<..>")
10557 (setq line (org-html-expand line))
10559 ;; Format the links
10561 (while (string-match org-protected-link-regexp line start)
10562 (setq start (- (match-end 0) 2))
10563 (setq type (match-string 1 line))
10565 ((member type '("http" "https" "ftp" "mailto" "news"))
10567 (setq line (replace-match
10568 ; "<a href=\"\\1:\\2\"><\\1:\\2></a>"
10569 "<a href=\"\\1:\\2\">\\1:\\2</a>"
10571 ((string= type "file")
10573 (let* ((filename (match-string 2 line))
10574 (abs-p (file-name-absolute-p filename))
10575 (thefile (if abs-p (expand-file-name filename) filename))
10576 (thefile (save-match-data
10577 (if (string-match ":[0-9]+$" thefile)
10578 (replace-match "" t t thefile)
10582 (string-match (org-image-file-name-regexp) thefile))))
10583 (setq line (replace-match
10584 (if (and org-export-html-inline-images
10586 (concat "<img src=\"" thefile "\"/>")
10587 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
10590 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
10591 (setq line (replace-match
10592 "<i><\\1:\\2></i>" nil nil line)))))
10595 (if (and (string-match org-todo-line-regexp line)
10596 (match-beginning 2))
10597 (if (equal (match-string 2 line) org-done-string)
10598 (setq line (replace-match
10599 "<span class=\"done\">\\2</span>"
10601 (setq line (replace-match "<span class=\"todo\">\\2</span>"
10605 (if (string-match org-deadline-line-regexp line)
10607 (if (save-match-data
10608 (string-match "<a href"
10609 (substring line 0 (match-beginning 0))))
10610 nil ; Don't do the replacement - it is inside a link
10611 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
10612 nil nil line 1)))))
10614 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10615 ;; This is a headline
10616 (setq level (- (match-end 1) (match-beginning 1))
10617 txt (match-string 2 line))
10618 (if (<= level umax) (setq head-count (+ head-count 1)))
10619 (when in-local-list
10620 ;; Close any local lists before inserting a new header line
10621 (while local-list-num
10622 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
10623 (pop local-list-num))
10624 (setq local-list-indent nil
10625 in-local-list nil))
10626 (org-html-level-start level txt umax
10627 (and org-export-with-toc (<= level umax))
10630 (when (string-match quote-re line)
10634 ((and org-export-with-tables
10635 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
10636 (if (not table-open)
10637 ;; New table starts
10638 (setq table-open t table-buffer nil table-orig-buffer nil))
10639 ;; Accumulate lines
10640 (setq table-buffer (cons line table-buffer)
10641 table-orig-buffer (cons origline table-orig-buffer))
10642 (when (or (not lines)
10643 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
10645 (setq table-open nil
10646 table-buffer (nreverse table-buffer)
10647 table-orig-buffer (nreverse table-orig-buffer))
10648 (insert (org-format-table-html table-buffer table-orig-buffer))))
10651 (when (and (> org-export-plain-list-max-depth 0)
10654 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10655 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10656 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10657 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
10659 (setq ind (org-get-string-indentation line)
10660 start-is-num (match-beginning 4)
10661 starter (if (match-beginning 2) (match-string 2 line))
10662 line (substring line (match-beginning 5)))
10663 (unless (string-match "[^ \t]" line)
10664 ;; empty line. Pretend indentation is large.
10665 (setq ind (1+ (or (car local-list-indent) 1))))
10666 (while (and in-local-list
10667 (or (and (= ind (car local-list-indent))
10669 (< ind (car local-list-indent))))
10670 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
10671 (pop local-list-num) (pop local-list-indent)
10672 (setq in-local-list local-list-indent))
10675 (or (not in-local-list)
10676 (> ind (car local-list-indent)))
10677 (< (length local-list-indent)
10678 org-export-plain-list-max-depth))
10679 ;; Start new (level of ) list
10680 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
10681 (push start-is-num local-list-num)
10682 (push ind local-list-indent)
10683 (setq in-local-list t))
10685 ;; continue current list
10686 (insert "<li>\n"))))
10687 ;; Empty lines start a new paragraph. If hand-formatted lists
10688 ;; are not fully interpreted, lines starting with "-", "+", "*"
10689 ;; also start a new paragraph.
10690 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
10691 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
10693 (if org-export-html-with-timestamp
10694 (insert org-export-html-html-helper-timestamp))
10695 (insert "</body>\n</html>\n")
10698 (goto-char (point-min)))))
10700 (defun org-format-table-html (lines olines)
10701 "Find out which HTML converter to use and return the HTML code."
10702 (if (string-match "^[ \t]*|" (car lines))
10703 ;; A normal org table
10704 (org-format-org-table-html lines)
10705 ;; Table made by table.el - test for spanning
10706 (let* ((hlines (delq nil (mapcar
10708 (if (string-match "^[ \t]*\\+-" x) x
10711 (first (car hlines))
10712 (ll (and (string-match "\\S-+" first)
10713 (match-string 0 first)))
10714 (re (concat "^[ \t]*" (regexp-quote ll)))
10715 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
10717 (if (and (not spanning)
10718 (not org-export-prefer-native-exporter-for-tables))
10719 ;; We can use my own converter with HTML conversions
10720 (org-format-table-table-html lines)
10721 ;; Need to use the code generator in table.el, with the original text.
10722 (org-format-table-table-html-using-table-generate-source olines)))))
10724 (defun org-format-org-table-html (lines)
10725 "Format a table into html."
10726 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10727 (setq lines (nreverse lines))
10728 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10729 (setq lines (nreverse lines))
10730 (let ((head (and org-export-highlight-first-table-line
10732 (lambda (x) (string-match "^[ \t]*|-" x))
10735 (setq html (concat org-export-html-table-tag "\n"))
10736 (while (setq line (pop lines))
10738 (if (string-match "^[ \t]*|-" line)
10740 (setq head nil) ;; head ends here, first time around
10741 ;; ignore this line
10742 (throw 'next-line t)))
10743 ;; Break the line into fields
10744 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10748 (mapconcat (lambda (x)
10750 (concat "<th>" x "</th>")
10751 (concat "<td>" x "</td>")))
10754 (setq html (concat html "</table>\n"))
10757 (defun org-fake-empty-table-line (line)
10758 "Replace everything except \"|\" with spaces."
10759 (let ((i (length line))
10760 (newstr (copy-sequence line)))
10763 (if (not (eq (aref newstr i) ?|))
10764 (aset newstr i ?\ )))
10767 (defun org-format-table-table-html (lines)
10768 "Format a table generated by table.el into html.
10769 This conversion does *not* use `table-generate-source' from table.el.
10770 This has the advantage that Org-mode's HTML conversions can be used.
10771 But it has the disadvantage, that no cell- or row-spanning is allowed."
10772 (let (line field-buffer
10773 (head org-export-highlight-first-table-line)
10775 (setq html (concat org-export-html-table-tag "\n"))
10776 (while (setq line (pop lines))
10777 (setq empty " ")
10779 (if (string-match "^[ \t]*\\+-" line)
10788 (if (equal x "") (setq x empty))
10790 (concat "<th>" x "</th>\n")
10791 (concat "<td>" x "</td>\n")))
10795 (setq field-buffer nil)))
10796 ;; Ignore this line
10797 (throw 'next-line t)))
10798 ;; Break the line into fields and store the fields
10799 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10801 (setq field-buffer (mapcar
10803 (concat x "<br>" (pop fields)))
10805 (setq field-buffer fields))))
10806 (setq html (concat html "</table>\n"))
10809 (defun org-format-table-table-html-using-table-generate-source (lines)
10810 "Format a table into html, using `table-generate-source' from table.el.
10811 This has the advantage that cell- or row-spanning is allowed.
10812 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
10814 (with-current-buffer (get-buffer-create " org-tmp1 ")
10816 (insert (mapconcat 'identity lines "\n"))
10817 (goto-char (point-min))
10818 (if (not (re-search-forward "|[^+]" nil t))
10819 (error "Error processing table"))
10820 (table-recognize-table)
10821 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
10822 (table-generate-source 'html " org-tmp2 ")
10823 (set-buffer " org-tmp2 ")
10824 (buffer-substring (point-min) (point-max))))
10826 (defun org-html-protect (s)
10827 ;; convert & to &, < to < and > to >
10829 (while (string-match "&" s start)
10830 (setq s (replace-match "&" t t s)
10831 start (1+ (match-beginning 0))))
10832 (while (string-match "<" s)
10833 (setq s (replace-match "<" t t s)))
10834 (while (string-match ">" s)
10835 (setq s (replace-match ">" t t s))))
10838 (defun org-html-expand (string)
10839 "Prepare STRING for HTML export. Applies all active conversions."
10840 ;; First check if there is a link in the line - if yes, apply conversions
10841 ;; only before the start of the link.
10842 ;; FIXME: This is no longer correct, because links now have an end.
10843 (let* ((m (string-match org-link-regexp string))
10844 (s (if m (substring string 0 m) string))
10845 (r (if m (substring string m) "")))
10846 ;; convert & to &, < to < and > to >
10847 (setq s (org-html-protect s))
10848 (if org-export-html-expand
10849 (while (string-match "@<\\([^&]*\\)>" s)
10850 (setq s (replace-match "<\\1>" nil nil s))))
10851 (if org-export-with-emphasize
10852 (setq s (org-export-html-convert-emphasize s)))
10853 (if org-export-with-sub-superscripts
10854 (setq s (org-export-html-convert-sub-super s)))
10855 (if org-export-with-TeX-macros
10856 (let ((start 0) wd ass)
10857 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
10858 (setq wd (match-string 1 s))
10859 (if (setq ass (assoc wd org-html-entities))
10860 (setq s (replace-match (or (cdr ass)
10861 (concat "&" (car ass) ";"))
10863 (setq start (+ start (length wd)))))))
10866 (defun org-create-multibrace-regexp (left right n)
10867 "Create a regular expression which will match a balanced sexp.
10868 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
10869 as single character strings.
10870 The regexp returned will match the entire expression including the
10871 delimiters. It will also define a single group which contains the
10872 match except for the outermost delimiters. The maximum depth of
10873 stacked delimiters is N. Escaping delimiters is not possible."
10874 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
10877 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
10880 re (concat re or next)
10881 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
10882 (concat left "\\(" re "\\)" right)))
10884 (defvar org-match-substring-regexp
10886 "\\([^\\]\\)\\([_^]\\)\\("
10887 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
10889 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
10891 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
10892 "The regular expression matching a sub- or superscript.")
10894 (defun org-export-html-convert-sub-super (string)
10895 "Convert sub- and superscripts in STRING to HTML."
10897 (while (string-match org-match-substring-regexp string)
10898 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
10899 (setq c (or (match-string 8 string)
10900 (match-string 6 string)
10901 (match-string 5 string)))
10902 (setq string (replace-match
10903 (concat (match-string 1 string)
10904 "<" key ">" c "</" key ">")
10906 (while (string-match "\\\\\\([_^]\\)" string)
10907 (setq string (replace-match (match-string 1 string) t t string))))
10910 (defun org-export-html-convert-emphasize (string)
10911 (while (string-match
10912 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
10914 (setq string (replace-match
10915 (concat "<b>" (match-string 3 string) "</b>")
10917 (while (string-match
10918 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
10920 (setq string (replace-match
10921 (concat "<i>" (match-string 3 string) "</i>")
10923 (while (string-match
10924 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
10926 (setq string (replace-match
10927 (concat "<u>" (match-string 3 string) "</u>")
10931 (defun org-parse-key-lines ()
10932 "Find the special key lines with the information for exporters."
10935 (let ((re (org-make-options-regexp
10936 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
10938 (while (re-search-forward re nil t)
10939 (setq key (match-string 1))
10940 (cond ((string-equal key "TITLE")
10941 (setq title (match-string 2)))
10942 ((string-equal key "AUTHOR")
10943 (setq author (match-string 2)))
10944 ((string-equal key "EMAIL")
10945 (setq email (match-string 2)))
10946 ((string-equal key "LANGUAGE")
10947 (setq language (match-string 2)))
10948 ((string-equal key "TEXT")
10949 (setq text (concat text "\n" (match-string 2))))
10950 ((string-equal key "OPTIONS")
10951 (setq options (match-string 2))))))))
10953 (defun org-parse-export-options (s)
10954 "Parse the export options line."
10955 (let ((op '(("H" . org-export-headline-levels)
10956 ("num" . org-export-with-section-numbers)
10957 ("toc" . org-export-with-toc)
10958 ("\\n" . org-export-preserve-breaks)
10959 ("@" . org-export-html-expand)
10960 (":" . org-export-with-fixed-width)
10961 ("|" . org-export-with-tables)
10962 ("^" . org-export-with-sub-superscripts)
10963 ("*" . org-export-with-emphasize)
10964 ("TeX" . org-export-with-TeX-macros)))
10966 (while (setq o (pop op))
10967 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
10969 (set (make-local-variable (cdr o))
10970 (car (read-from-string (match-string 1 s))))))))
10972 (defun org-html-level-start (level title umax with-toc head-count)
10973 "Insert a new level in HTML export."
10974 (let ((l (1+ (max level umax))))
10975 (while (<= l org-level-max)
10976 (if (aref levels-open (1- l))
10978 (org-html-level-close l)
10979 (aset levels-open (1- l) nil)))
10983 (if (aref levels-open (1- level))
10984 (insert "<li>" title "<p>\n")
10985 (aset levels-open (1- level) t)
10986 (insert "<ul><li>" title "<p>\n")))
10987 (if org-export-with-section-numbers
10988 (setq title (concat (org-section-number level) " " title)))
10989 (setq level (+ level 1))
10991 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
10992 level head-count title level))
10993 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
10995 (defun org-html-level-close (&rest args)
10996 "Terminate one level in HTML export."
10999 ;; Variable holding the vector with section numbers
11000 (defvar org-section-numbers (make-vector org-level-max 0))
11002 (defun org-init-section-numbers ()
11003 "Initialize the vector for the section numbers."
11005 (numbers (nreverse (org-split-string "" "\\.")))
11006 (depth (1- (length org-section-numbers)))
11007 (i depth) number-string)
11010 (aset org-section-numbers i 0)
11011 (setq number-string (or (car numbers) "0"))
11012 (if (string-match "\\`[A-Z]\\'" number-string)
11013 (aset org-section-numbers i
11014 (- (string-to-char number-string) ?A -1))
11015 (aset org-section-numbers i (string-to-number number-string)))
11019 (defun org-section-number (&optional level)
11020 "Return a string with the current section number.
11021 When LEVEL is non-nil, increase section numbers on that level."
11022 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
11025 (aset org-section-numbers
11026 level (1+ (aref org-section-numbers level))))
11027 (setq idx (1+ level))
11028 (while (<= idx depth)
11029 (if (not (= idx 1))
11030 (aset org-section-numbers idx 0))
11031 (setq idx (1+ idx))))
11033 (while (<= idx depth)
11034 (setq n (aref org-section-numbers idx))
11035 (setq string (concat string (if (not (string= string "")) "." "")
11036 (int-to-string n)))
11037 (setq idx (1+ idx)))
11039 (if (string-match "\\`\\([@0]\\.\\)+" string)
11040 (setq string (replace-match "" nil nil string)))
11041 (if (string-match "\\(\\.0\\)+\\'" string)
11042 (setq string (replace-match "" nil nil string))))
11046 (defun org-export-icalendar-this-file ()
11047 "Export current file as an iCalendar file.
11048 The iCalendar file will be located in the same directory as the Org-mode
11049 file, but with extension `.ics'."
11051 (org-export-icalendar nil (buffer-file-name)))
11054 (defun org-export-icalendar-all-agenda-files ()
11055 "Export all files in `org-agenda-files' to iCalendar .ics files.
11056 Each iCalendar file will be located in the same directory as the Org-mode
11057 file, but with extension `.ics'."
11059 (apply 'org-export-icalendar nil org-agenda-files))
11062 (defun org-export-icalendar-combine-agenda-files ()
11063 "Export all files in `org-agenda-files' to a single combined iCalendar file.
11064 The file is stored under the name `org-combined-agenda-icalendar-file'."
11066 (apply 'org-export-icalendar t org-agenda-files))
11068 (defun org-export-icalendar (combine &rest files)
11069 "Create iCalendar files for all elements of FILES.
11070 If COMBINE is non-nil, combine all calendar entries into a single large
11071 file and store it under the name `org-combined-agenda-icalendar-file'."
11073 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
11075 (setq ical-file org-combined-agenda-icalendar-file
11076 ical-buffer (org-get-agenda-file-buffer ical-file))
11077 (set-buffer ical-buffer) (erase-buffer))
11078 (while (setq file (pop files))
11080 (org-check-agenda-file file)
11082 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
11083 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
11084 (set-buffer ical-buffer) (erase-buffer))
11085 (set-buffer (org-get-agenda-file-buffer file))
11086 (setq category (or org-category
11087 (file-name-sans-extension
11088 (file-name-nondirectory (buffer-file-name)))))
11089 (if (symbolp category) (setq category (symbol-name category)))
11090 (let ((standard-output ical-buffer))
11092 (and (not started) (setq started t)
11093 (org-start-icalendar-file org-icalendar-combined-name))
11094 (org-start-icalendar-file category))
11095 (org-print-icalendar-entries combine category)
11096 (when (or (and combine (not files)) (not combine))
11097 (org-finish-icalendar-file)
11098 (set-buffer ical-buffer)
11100 (run-hooks 'org-after-save-iCalendar-file-hook)))))
11101 (org-release-buffers org-agenda-new-buffers))))
11103 (defvar org-after-save-iCalendar-file-hook nil
11104 "Hook run after an iCalendar file has been saved.
11105 The iCalendar buffer is still current when this hook is run.
11106 A good way to use this is to tell a desktop calenndar application to re-read
11107 the iCalendar file.")
11109 (defun org-print-icalendar-entries (&optional combine category)
11110 "Print iCalendar entries for the current Org-mode file to `standard-output'.
11111 When COMBINE is non nil, add the category to each line."
11112 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
11113 (dts (org-ical-ts-to-string
11114 (format-time-string (cdr org-time-stamp-formats) (current-time))
11116 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
11118 (goto-char (point-min))
11119 (while (re-search-forward org-ts-regexp nil t)
11120 (setq pos (match-beginning 0)
11121 ts (match-string 0)
11123 hd (org-get-heading))
11124 (if (looking-at re2)
11126 (goto-char (match-end 0))
11127 (setq ts2 (match-string 1) inc nil))
11129 tmp (buffer-substring (max (point-min)
11130 (- pos org-ds-keyword-length))
11132 deadlinep (string-match org-deadline-regexp tmp)
11133 scheduledp (string-match org-scheduled-regexp tmp)
11134 ;; donep (org-entry-is-done-p)
11136 (if (or (string-match org-tr-regexp hd)
11137 (string-match org-ts-regexp hd))
11138 (setq hd (replace-match "" t t hd)))
11140 (setq hd (concat hd " (category " category ")")))
11141 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
11142 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
11143 (princ (format "BEGIN:VEVENT
11148 (org-ical-ts-to-string ts "DTSTART")
11149 (org-ical-ts-to-string ts2 "DTEND" inc)
11151 (when org-icalendar-include-todo
11152 (goto-char (point-min))
11153 (while (re-search-forward org-todo-line-regexp nil t)
11154 (setq state (match-string 1))
11155 (unless (equal state org-done-string)
11156 (setq hd (match-string 3))
11157 (if (string-match org-priority-regexp hd)
11158 (setq pri (string-to-char (match-string 2 hd))
11159 hd (concat (substring hd 0 (match-beginning 1))
11160 (substring hd (- (match-end 1)))))
11161 (setq pri org-default-priority))
11162 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
11163 (- org-lowest-priority ?A))))))
11165 (princ (format "BEGIN:VTODO
11173 (defun org-start-icalendar-file (name)
11174 "Start an iCalendar file by inserting the header."
11175 (let ((user user-full-name)
11176 (name (or name "unknown"))
11177 (timezone (cadr (current-time-zone))))
11179 (format "BEGIN:VCALENDAR
11182 PRODID:-//%s//Emacs with Org-mode//EN
11184 CALSCALE:GREGORIAN\n" name user timezone))))
11186 (defun org-finish-icalendar-file ()
11187 "Finish an iCalendar file by inserting the END statement."
11188 (princ "END:VCALENDAR\n"))
11190 (defun org-ical-ts-to-string (s keyword &optional inc)
11191 "Take a time string S and convert it to iCalendar format.
11192 KEYWORD is added in front, to make a complete line like DTSTART....
11193 When INC is non-nil, increase the hour by two (if time string contains
11194 a time), or the day by one (if it does not contain a time)."
11195 (let ((t1 (org-parse-time-string s 'nodefault))
11196 t2 fmt have-time time)
11197 (if (and (car t1) (nth 1 t1) (nth 2 t1))
11198 (setq t2 t1 have-time t)
11199 (setq t2 (org-parse-time-string s)))
11200 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
11201 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
11203 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
11204 (setq time (encode-time s mi h d m y)))
11205 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
11206 (concat keyword (format-time-string fmt time))))
11211 ;; - Bindings in Org-mode map are currently
11212 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
11213 ;; abcd fgh j lmnopqrstuvwxyz!? #$ -+*/= [] ; |,.<>~ \t necessary bindings
11214 ;; e (?) useful from outline-mode
11215 ;; i k @ expendable from outline-mode
11216 ;; 0123456789 %^& ()_{} " `' free
11218 ;; Make `C-c C-x' a prefix key
11219 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
11221 ;; TAB key with modifiers
11222 (define-key org-mode-map "\C-i" 'org-cycle)
11223 (define-key org-mode-map [(meta tab)] 'org-complete)
11224 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
11225 ;; The following line is necessary under Suse GNU/Linux
11226 (unless org-xemacs-p
11227 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
11228 (define-key org-mode-map [(shift tab)] 'org-shifttab)
11230 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
11231 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
11232 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11233 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
11234 (define-key org-mode-map [(meta return)] 'org-meta-return)
11235 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
11236 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
11238 ;; Cursor keys with modifiers
11239 (define-key org-mode-map [(meta left)] 'org-metaleft)
11240 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
11241 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
11242 (define-key org-mode-map [(meta right)] 'org-metaright)
11243 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
11244 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
11245 (define-key org-mode-map [(meta up)] 'org-metaup)
11246 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
11247 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
11248 (define-key org-mode-map [(meta down)] 'org-metadown)
11249 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
11250 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
11252 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11253 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
11254 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
11255 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
11256 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
11257 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
11258 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
11259 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
11260 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
11261 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
11262 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
11263 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
11264 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
11265 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
11266 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
11267 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
11269 ;; All the other keys
11270 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
11271 (define-key org-mode-map "\C-c\C-j" 'org-goto)
11272 (define-key org-mode-map "\C-c\C-t" 'org-todo)
11273 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
11274 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
11275 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
11276 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11277 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
11278 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
11279 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11280 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
11281 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
11282 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
11283 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
11284 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
11285 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11286 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11287 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11288 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11289 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
11290 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
11291 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11292 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
11293 (define-key org-mode-map "\C-c]" 'org-remove-file)
11294 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
11295 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
11296 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
11297 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11298 (define-key org-mode-map "\C-m" 'org-return)
11299 (define-key org-mode-map "\C-c?" 'org-table-current-column)
11300 (define-key org-mode-map "\C-c " 'org-table-blank-field)
11301 (define-key org-mode-map "\C-c+" 'org-table-sum)
11302 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
11303 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
11304 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
11305 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
11306 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11307 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
11308 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11309 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
11310 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
11311 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
11312 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
11313 ;; OPML support is only an option for the future
11314 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
11315 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
11316 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
11317 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
11318 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
11319 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
11320 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
11321 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11322 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
11323 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
11324 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
11326 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11327 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11328 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11330 (defsubst org-table-p () (org-at-table-p))
11332 (defun org-self-insert-command (N)
11333 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11334 If the cursor is in a table looking at whitespace, the whitespace is
11335 overwritten, and the table is not marked as requiring realignment."
11337 (if (and (org-table-p)
11339 (and org-table-auto-blank-field
11340 (member last-command
11341 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11342 (org-table-blank-field))
11345 (looking-at "[^|\n]* +|"))
11346 (let (org-table-may-need-update)
11347 (goto-char (1- (match-end 0)))
11348 (delete-backward-char 1)
11349 (goto-char (match-beginning 0))
11350 (self-insert-command N))
11351 (setq org-table-may-need-update t)
11352 (self-insert-command N)))
11355 ;; The following two functions might still be optimized to trigger
11356 ;; re-alignment less frequently.
11358 (defun org-delete-backward-char (N)
11359 "Like `delete-backward-char', insert whitespace at field end in tables.
11360 When deleting backwards, in tables this function will insert whitespace in
11361 front of the next \"|\" separator, to keep the table aligned. The table will
11362 still be marked for re-alignment, because a narrow field may lead to a
11363 reduced column width."
11365 (if (and (org-table-p)
11367 (string-match "|" (buffer-substring (point-at-bol) (point)))
11368 (looking-at ".*?|"))
11369 (let ((pos (point)))
11370 (backward-delete-char N)
11371 (skip-chars-forward "^|")
11373 (goto-char (1- pos)))
11374 (backward-delete-char N)))
11376 (defun org-delete-char (N)
11377 "Like `delete-char', but insert whitespace at field end in tables.
11378 When deleting characters, in tables this function will insert whitespace in
11379 front of the next \"|\" separator, to keep the table aligned. The table
11380 will still be marked for re-alignment, because a narrow field may lead to
11381 a reduced column width."
11383 (if (and (org-table-p)
11385 (not (= (char-after) ?|))
11387 (if (looking-at ".*?|")
11388 (let ((pos (point)))
11389 (replace-match (concat
11390 (substring (match-string 0) 1 -1)
11395 ;; How to do this: Measure non-white length of current string
11396 ;; If equal to column width, we should realign.
11398 (defun org-remap (map &rest commands)
11399 "In MAP, remap the functions given in COMMANDS.
11400 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11403 (setq old (pop commands) new (pop commands))
11404 (if (fboundp 'command-remapping)
11405 (define-key map (vector 'remap old) new)
11406 (substitute-key-definition old new map global-map)))))
11408 (when (eq org-enable-table-editor 'optimized)
11409 ;; If the user wants maximum table support, we need to hijack
11410 ;; some standard editing functions
11411 (org-remap org-mode-map
11412 'self-insert-command 'org-self-insert-command
11413 'delete-char 'org-delete-char
11414 'delete-backward-char 'org-delete-backward-char)
11415 (define-key org-mode-map "|" 'org-force-self-insert))
11417 (defun org-shiftcursor-error ()
11418 "Throw an error because Shift-Cursor command was applied in wrong context."
11419 (error "This command is active in special context like tables, headlines or timestamps"))
11421 (defun org-shifttab ()
11422 "Global visibility cycling or move to previous table field.
11423 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
11424 See the individual commands for more information."
11427 ((org-at-table-p) (org-table-previous-field))
11428 (t (org-cycle '(4)))))
11430 (defun org-shiftmetaleft ()
11431 "Promote subtree or delete table column.
11432 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
11433 See the individual commands for more information."
11436 ((org-at-table-p) (org-table-delete-column))
11437 ((org-on-heading-p) (org-promote-subtree))
11438 ((org-at-item-p) (call-interactively 'org-outdent-item))
11439 (t (org-shiftcursor-error))))
11441 (defun org-shiftmetaright ()
11442 "Demote subtree or insert table column.
11443 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
11444 See the individual commands for more information."
11447 ((org-at-table-p) (org-table-insert-column))
11448 ((org-on-heading-p) (org-demote-subtree))
11449 ((org-at-item-p) (call-interactively 'org-indent-item))
11450 (t (org-shiftcursor-error))))
11452 (defun org-shiftmetaup (&optional arg)
11453 "Move subtree up or kill table row.
11454 Calls `org-move-subtree-up' or `org-table-kill-row' or
11455 `org-move-item-up' depending on context. See the individual commands
11456 for more information."
11459 ((org-at-table-p) (org-table-kill-row))
11460 ((org-on-heading-p) (org-move-subtree-up arg))
11461 ((org-at-item-p) (org-move-item-up arg))
11462 (t (org-shiftcursor-error))))
11463 (defun org-shiftmetadown (&optional arg)
11464 "Move subtree down or insert table row.
11465 Calls `org-move-subtree-down' or `org-table-insert-row' or
11466 `org-move-item-down', depending on context. See the individual
11467 commands for more information."
11470 ((org-at-table-p) (org-table-insert-row arg))
11471 ((org-on-heading-p) (org-move-subtree-down arg))
11472 ((org-at-item-p) (org-move-item-down arg))
11473 (t (org-shiftcursor-error))))
11475 (defun org-metaleft (&optional arg)
11476 "Promote heading or move table column to left.
11477 Calls `org-do-promote' or `org-table-move-column', depending on context.
11478 With no specific context, calls the Emacs default `backward-word'.
11479 See the individual commands for more information."
11482 ((org-at-table-p) (org-table-move-column 'left))
11483 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
11484 (t (backward-word (prefix-numeric-value arg)))))
11486 (defun org-metaright (&optional arg)
11487 "Demote subtree or move table column to right.
11488 Calls `org-do-demote' or `org-table-move-column', depending on context.
11489 With no specific context, calls the Emacs default `forward-word'.
11490 See the individual commands for more information."
11493 ((org-at-table-p) (org-table-move-column nil))
11494 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
11495 (t (forward-word (prefix-numeric-value arg)))))
11497 (defun org-metaup (&optional arg)
11498 "Move subtree up or move table row up.
11499 Calls `org-move-subtree-up' or `org-table-move-row' or
11500 `org-move-item-up', depending on context. See the individual commands
11501 for more information."
11504 ((org-at-table-p) (org-table-move-row 'up))
11505 ((org-on-heading-p) (org-move-subtree-up arg))
11506 ((org-at-item-p) (org-move-item-up arg))
11507 (t (org-shiftcursor-error))))
11509 (defun org-metadown (&optional arg)
11510 "Move subtree down or move table row down.
11511 Calls `org-move-subtree-down' or `org-table-move-row' or
11512 `org-move-item-down', depending on context. See the individual
11513 commands for more information."
11516 ((org-at-table-p) (org-table-move-row nil))
11517 ((org-on-heading-p) (org-move-subtree-down arg))
11518 ((org-at-item-p) (org-move-item-down arg))
11519 (t (org-shiftcursor-error))))
11521 (defun org-shiftup (&optional arg)
11522 "Increase item in timestamp or increase priority of current item.
11523 Calls `org-timestamp-up' or `org-priority-up', depending on context.
11524 See the individual commands for more information."
11527 ((org-at-timestamp-p) (org-timestamp-up arg))
11528 (t (org-priority-up))))
11530 (defun org-shiftdown (&optional arg)
11531 "Decrease item in timestamp or decrease priority of current item.
11532 Calls `org-timestamp-down' or `org-priority-down', depending on context.
11533 See the individual commands for more information."
11536 ((org-at-timestamp-p) (org-timestamp-down arg))
11537 (t (org-priority-down))))
11539 (defun org-shiftright ()
11540 "Next TODO keyword or timestamp one day later, depending on context."
11543 ((org-at-timestamp-p) (org-timestamp-up-day))
11544 ((org-on-heading-p) (org-todo 'right))
11545 (t (org-shiftcursor-error))))
11547 (defun org-shiftleft ()
11548 "Previous TODO keyword or timestamp one day earlier, depending on context."
11551 ((org-at-timestamp-p) (org-timestamp-down-day))
11552 ((org-on-heading-p) (org-todo 'left))
11553 (t (org-shiftcursor-error))))
11555 (defun org-copy-special ()
11556 "Copy region in table or copy current subtree.
11557 Calls `org-table-copy' or `org-copy-subtree', depending on context.
11558 See the individual commands for more information."
11560 (call-interactively
11561 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
11563 (defun org-cut-special ()
11564 "Cut region in table or cut current subtree.
11565 Calls `org-table-copy' or `org-cut-subtree', depending on context.
11566 See the individual commands for more information."
11568 (call-interactively
11569 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
11571 (defun org-paste-special (arg)
11572 "Paste rectangular region into table, or past subtree relative to level.
11573 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
11574 See the individual commands for more information."
11576 (if (org-at-table-p)
11577 (org-table-paste-rectangle)
11578 (org-paste-subtree arg)))
11580 (defun org-ctrl-c-ctrl-c (&optional arg)
11581 "Call realign table, or recognize a table.el table, or update keywords.
11582 When the cursor is inside a table created by the table.el package,
11583 activate that table. Otherwise, if the cursor is at a normal table
11584 created with org.el, re-align that table. This command works even if
11585 the automatic table editor has been turned off.
11587 If the cursor is in a headline, prompt for tags and insert them into
11588 the current line, aligned to `org-tags-column'. When in a headline and
11589 called with prefix arg, realign all tags in the current buffer.
11591 If the cursor is in one of the special #+KEYWORD lines, this triggers
11592 scanning the buffer for these lines and updating the information.
11593 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
11595 (let ((org-enable-table-editor t))
11597 ((org-on-heading-p) (org-set-tags arg))
11598 ((org-at-table.el-p)
11600 (beginning-of-line 1)
11601 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
11602 (table-recognize-table))
11604 (org-table-maybe-eval-formula)
11606 (org-table-recalculate t)
11607 (org-table-maybe-recalculate-line))
11610 (org-renumber-ordered-list (prefix-numeric-value arg)))
11611 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
11613 ((equal (match-string 1) "TBLFM")
11614 ;; Recalculate the table before this line
11616 (beginning-of-line 1)
11617 (skip-chars-backward " \r\n\t")
11618 (if (org-at-table-p) (org-table-recalculate t))))
11620 (org-mode-restart))))
11621 ((org-region-active-p)
11622 (org-table-convert-region (region-beginning) (region-end) arg))
11623 ((condition-case nil
11624 (and (region-beginning) (region-end))
11626 (if (y-or-n-p "Convert inactive region to table? ")
11627 (org-table-convert-region (region-beginning) (region-end) arg)
11629 (t (error "C-c C-c can do nothing useful at this location.")))))
11631 (defun org-mode-restart ()
11632 "Restart Org-mode, to scan again for special lines.
11633 Also updates the keyword regular expressions."
11635 (let ((org-inhibit-startup t)) (org-mode))
11636 (message "Org-mode restarted to refresh keyword and special line setup"))
11638 (defun org-return ()
11639 "Goto next table row or insert a newline.
11640 Calls `org-table-next-row' or `newline', depending on context.
11641 See the individual commands for more information."
11645 (org-table-justify-field-maybe)
11646 (org-table-next-row))
11649 (defun org-meta-return (&optional arg)
11650 "Insert a new heading or wrap a region in a table.
11651 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
11652 See the individual commands for more information."
11656 (org-table-wrap-region arg))
11657 (t (org-insert-heading arg))))
11661 ;; Define the Org-mode menus
11662 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
11664 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
11665 ["Next Field" org-cycle (org-at-table-p)]
11666 ["Previous Field" org-shifttab (org-at-table-p)]
11667 ["Next Row" org-return (org-at-table-p)]
11669 ["Blank Field" org-table-blank-field (org-at-table-p)]
11670 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
11673 ["Move Column Left" org-metaleft (org-at-table-p)]
11674 ["Move Column Right" org-metaright (org-at-table-p)]
11675 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
11676 ["Insert Column" org-shiftmetaright (org-at-table-p)])
11678 ["Move Row Up" org-metaup (org-at-table-p)]
11679 ["Move Row Down" org-metadown (org-at-table-p)]
11680 ["Delete Row" org-shiftmetaup (org-at-table-p)]
11681 ["Insert Row" org-shiftmetadown (org-at-table-p)]
11682 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
11684 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
11686 ["Copy Rectangle" org-copy-special (org-at-table-p)]
11687 ["Cut Rectangle" org-cut-special (org-at-table-p)]
11688 ["Paste Rectangle" org-paste-special (org-at-table-p)]
11689 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
11692 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
11693 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11694 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
11696 ["Recalculate line" org-table-recalculate (org-at-table-p)]
11697 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
11698 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
11700 ["Sum Column/Rectangle" org-table-sum
11701 (or (org-at-table-p) (org-region-active-p))]
11702 ["Which Column?" org-table-current-column (org-at-table-p)])
11704 (setq org-table-formula-debug (not org-table-formula-debug))
11705 :style toggle :selected org-table-formula-debug]
11707 ["Invisible Vlines" org-table-toggle-vline-visibility
11708 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
11710 ["Create" org-table-create (and (not (org-at-table-p))
11711 org-enable-table-editor)]
11712 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
11713 ["Import from File" org-table-import (not (org-at-table-p))]
11714 ["Export to File" org-table-export (org-at-table-p)]
11716 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
11718 (easy-menu-define org-org-menu org-mode-map "Org menu"
11720 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
11721 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
11722 ["Sparse Tree" org-occur t]
11723 ["Show All" show-all t]
11725 ["New Heading" org-insert-heading t]
11726 ("Navigate Headings"
11727 ["Up" outline-up-heading t]
11728 ["Next" outline-next-visible-heading t]
11729 ["Previous" outline-previous-visible-heading t]
11730 ["Next Same Level" outline-forward-same-level t]
11731 ["Previous Same Level" outline-backward-same-level t]
11733 ["Jump" org-goto t])
11735 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
11736 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
11738 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
11739 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
11740 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
11742 ["Promote Heading" org-metaleft (not (org-at-table-p))]
11743 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
11744 ["Demote Heading" org-metaright (not (org-at-table-p))]
11745 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
11747 ["Archive Subtree" org-archive-subtree t])
11750 ["TODO/DONE/-" org-todo t]
11751 ["Show TODO Tree" org-show-todo-tree t]
11752 ["Global TODO list" org-todo-list t]
11754 ["Set Priority" org-priority t]
11755 ["Priority Up" org-shiftup t]
11756 ["Priority Down" org-shiftdown t])
11757 ("Dates and Scheduling"
11758 ["Timestamp" org-time-stamp t]
11759 ["Timestamp (inactive)" org-time-stamp-inactive t]
11761 ["1 Day Later" org-timestamp-up-day t]
11762 ["1 Day Earlier" org-timestamp-down-day t]
11763 ["1 ... Later" org-shiftup t]
11764 ["1 ... Earlier" org-shiftdown t])
11765 ["Compute Time Range" org-evaluate-time-range t]
11766 ["Schedule Item" org-schedule t]
11767 ["Deadline" org-deadline t]
11769 ["Goto Calendar" org-goto-calendar t]
11770 ["Date from Calendar" org-date-from-calendar t])
11772 ["Agenda Command" org-agenda t]
11773 ("File List for Agenda")
11774 ("Special views current file"
11775 ["TODO Tree" org-show-todo-tree t]
11776 ["Check Deadlines" org-check-deadlines t]
11777 ["Timeline" org-timeline t]
11778 ["Tags Tree" org-tags-sparse-tree t])
11781 ["Store Link (Global)" org-store-link t]
11782 ["Insert Link" org-insert-link t]
11783 ["Follow Link" org-open-at-point t])
11786 ["ASCII" org-export-as-ascii t]
11787 ["Extract Visible Text" org-export-copy-visible t]
11788 ["HTML" org-export-as-html t]
11789 ["HTML and Open" org-export-as-html-and-open t]
11790 ; ["OPML" org-export-as-opml nil]
11792 ["iCalendar this file" org-export-icalendar-this-file t]
11793 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
11794 :active t :keys "C-c C-x C-i"]
11795 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
11797 ["Option Template" org-insert-export-options-template t]
11798 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
11801 ["Show Version" org-version t]
11802 ["Info Documentation" org-info t])
11804 ["Browse Org Group" org-customize t]
11806 ["Build Full Customize Menu" org-create-customize-menu
11807 (fboundp 'customize-menu-create)])
11809 ["Refresh setup" org-mode-restart t]
11812 (defun org-info (&optional node)
11813 "Read documentation for Org-mode in the info system.
11814 With optional NODE, go directly to that node."
11817 (Info-goto-node (format "(org)%s" (or node ""))))
11819 (defun org-install-agenda-files-menu ()
11821 '("Org") "File List for Agenda"
11824 ["Edit File List" (customize-variable 'org-agenda-files) t]
11825 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
11826 ["Remove Current File from List" org-remove-file t]
11827 ["Cycle through agenda files" org-cycle-agenda-files t]
11829 (mapcar 'org-file-menu-entry org-agenda-files))))
11833 (defun org-customize ()
11834 "Call the customize function with org as argument."
11836 (customize-browse 'org))
11838 (defun org-create-customize-menu ()
11839 "Create a full customization menu for Org-mode, insert it into the menu."
11841 (if (fboundp 'customize-menu-create)
11844 '("Org") "Customize"
11845 `(["Browse Org group" org-customize t]
11847 ,(customize-menu-create 'org)
11848 ["Set" Custom-set t]
11849 ["Save" Custom-save t]
11850 ["Reset to Current" Custom-reset-current t]
11851 ["Reset to Saved" Custom-reset-saved t]
11852 ["Reset to Standard Settings" Custom-reset-standard t]))
11853 (message "\"Org\"-menu now contains full customization menu"))
11854 (error "Cannot expand menu (outdated version of cus-edit.el)")))
11856 ;;; Miscellaneous stuff
11858 (defun org-move-line-down (arg)
11859 "Move the current line down. With prefix argument, move it past ARG lines."
11861 (let ((col (current-column))
11863 (beginning-of-line 1) (setq beg (point))
11864 (beginning-of-line 2) (setq end (point))
11865 (beginning-of-line (+ 1 arg))
11866 (setq pos (move-marker (make-marker) (point)))
11867 (insert (delete-and-extract-region beg end))
11869 (move-to-column col)))
11871 (defun org-move-line-up (arg)
11872 "Move the current line up. With prefix argument, move it past ARG lines."
11874 (let ((col (current-column))
11876 (beginning-of-line 1) (setq beg (point))
11877 (beginning-of-line 2) (setq end (point))
11878 (beginning-of-line (- arg))
11879 (setq pos (move-marker (make-marker) (point)))
11880 (insert (delete-and-extract-region beg end))
11882 (move-to-column col)))
11884 ;; Paragraph filling stuff.
11885 ;; We want this to be just right, so use the full arsenal.
11886 ;; FIXME: This very likely does not work correctly for XEmacs, because the
11887 ;; filladapt package works slightly differently.
11889 (defun org-set-autofill-regexps ()
11891 ;; In the paragraph separator we include headlines, because filling
11892 ;; text in a line directly attached to a headline would otherwise
11893 ;; fill the headline as well.
11894 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
11895 ;; The paragraph starter includes hand-formatted lists.
11896 (set (make-local-variable 'paragraph-start)
11897 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
11898 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
11899 ;; But only if the user has not turned off tables or fixed-width regions
11900 (set (make-local-variable 'auto-fill-inhibit-regexp)
11902 (if (or org-enable-table-editor org-enable-fixed-width-editor)
11905 (if org-enable-table-editor "|" "")
11906 (if org-enable-fixed-width-editor ":" "")
11908 ;; We use our own fill-paragraph function, to make sure that tables
11909 ;; and fixed-width regions are not wrapped. That function will pass
11910 ;; through to `fill-paragraph' when appropriate.
11911 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
11912 ;; Adaptive filling: To get full control, first make sure that
11913 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
11914 (setq adaptive-fill-regexp "\000")
11915 (setq adaptive-fill-function 'org-adaptive-fill-function))
11917 (defun org-fill-paragraph (&optional justify)
11918 "Re-align a table, pass through to fill-paragraph if no table."
11919 (let ((table-p (org-at-table-p))
11920 (table.el-p (org-at-table.el-p)))
11921 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
11922 (table.el-p t) ; skip table.el tables
11923 (table-p (org-table-align) t) ; align org-mode tables
11924 (t nil)))) ; call paragraph-fill
11926 ;; For reference, this is the default value of adaptive-fill-regexp
11927 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
11929 (defun org-adaptive-fill-function ()
11930 "Return a fill prefix for org-mode files.
11931 In particular, this makes sure hanging paragraphs for hand-formatted lists
11933 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
11934 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
11936 ;; Functions needed for Emacs/XEmacs region compatibility
11938 (defun org-region-active-p ()
11939 "Is `transient-mark-mode' on and the region active?
11940 Works on both Emacs and XEmacs."
11941 (if org-ignore-region
11944 (and zmacs-regions (region-active-p))
11945 (and transient-mark-mode mark-active))))
11947 (defun org-add-to-invisibility-spec (arg)
11948 "Add elements to `buffer-invisibility-spec'.
11949 See documentation for `buffer-invisibility-spec' for the kind of elements
11950 that can be added."
11952 ((fboundp 'add-to-invisibility-spec)
11953 (add-to-invisibility-spec arg))
11954 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
11955 (setq buffer-invisibility-spec (list arg)))
11957 (setq buffer-invisibility-spec
11958 (cons arg buffer-invisibility-spec)))))
11960 (defun org-remove-from-invisibility-spec (arg)
11961 "Remove elements from `buffer-invisibility-spec'."
11962 (if (fboundp 'remove-from-invisibility-spec)
11963 (remove-from-invisibility-spec arg)
11964 (if (consp buffer-invisibility-spec)
11965 (setq buffer-invisibility-spec
11966 (delete arg buffer-invisibility-spec)))))
11968 (defun org-in-invisibility-spec-p (arg)
11969 "Is ARG a member of `buffer-invisibility-spec'?."
11970 (if (consp buffer-invisibility-spec)
11971 (member arg buffer-invisibility-spec)
11974 (defun org-image-file-name-regexp ()
11975 "Return regexp matching the file names of images."
11976 (if (fboundp 'image-file-name-regexp)
11977 (image-file-name-regexp)
11978 (let ((image-file-name-extensions
11979 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
11980 "xbm" "xpm" "pbm" "pgm" "ppm")))
11982 (regexp-opt (nconc (mapcar 'upcase
11983 image-file-name-extensions)
11984 image-file-name-extensions)
11988 ;; Functions needed for compatibility with old outline.el.
11990 ;; Programming for the old outline.el (that uses selective display
11991 ;; instead of `invisible' text properties) is a nightmare, mostly
11992 ;; because regular expressions can no longer be anchored at
11993 ;; beginning/end of line. Therefore a number of function need special
11994 ;; treatment when the old outline.el is being used.
11996 ;; The following functions capture almost the entire compatibility code
11997 ;; between the different versions of outline-mode. The only other
11998 ;; places where this is important are the font-lock-keywords, and in
11999 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
12001 ;; C-a should go to the beginning of a *visible* line, also in the
12002 ;; new outline.el. I guess this should be patched into Emacs?
12003 (defun org-beginning-of-line ()
12004 "Go to the beginning of the current line. If that is invisible, continue
12005 to a visible line beginning. This makes the function of C-a more intuitive."
12007 (beginning-of-line 1)
12011 (if (org-invisible-p)
12012 (while (and (not (bobp)) (org-invisible-p))
12014 (beginning-of-line 1))
12015 (forward-char 1))))
12017 (when org-noutline-p
12018 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
12019 ;; FIXME: should I use substitute-key-definition to reach other bindings
12020 ;; of beginning-of-line?
12022 (defun org-invisible-p ()
12023 "Check if point is at a character currently not visible."
12025 ;; Early versions of noutline don't have `outline-invisible-p'.
12026 (if (fboundp 'outline-invisible-p)
12027 (outline-invisible-p)
12028 (get-char-property (point) 'invisible))
12030 (skip-chars-backward "^\r\n")
12031 (equal (char-before) ?\r))))
12033 (defun org-back-to-heading (&optional invisible-ok)
12034 "Move to previous heading line, or beg of this line if it's a heading.
12035 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
12037 (outline-back-to-heading invisible-ok)
12038 (if (and (memq (char-before) '(?\n ?\r))
12039 (looking-at outline-regexp))
12041 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
12045 (progn (goto-char (match-end 1))
12046 (looking-at outline-regexp)))
12047 (error "Before first heading")))))
12049 (defun org-on-heading-p (&optional invisible-ok)
12050 "Return t if point is on a (visible) heading line.
12051 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
12053 (outline-on-heading-p 'invisible-ok)
12055 (skip-chars-backward "^\n\r")
12056 (and (looking-at outline-regexp)
12059 (equal (char-before) ?\n))))))
12061 (defun org-up-heading-all (arg)
12062 "Move to the heading line of which the present line is a subheading.
12063 This function considers both visible and invisible heading lines.
12064 With argument, move up ARG levels."
12066 (if (fboundp 'outline-up-heading-all)
12067 (outline-up-heading-all arg) ; emacs 21 version of outline.el
12068 (outline-up-heading arg t)) ; emacs 22 version of outline.el
12069 (org-back-to-heading t)
12070 (looking-at outline-regexp)
12071 (if (<= (- (match-end 0) (match-beginning 0)) arg)
12072 (error "Cannot move up %d levels" arg)
12073 (re-search-backward
12074 (concat "[\n\r]" (regexp-quote
12075 (make-string (- (match-end 0) (match-beginning 0) arg)
12078 (forward-char 1))))
12080 (defun org-show-hidden-entry ()
12081 "Show an entry where even the heading is hidden."
12083 (if (not org-noutline-p)
12085 (org-back-to-heading t)
12086 (org-flag-heading nil)))
12089 (defun org-check-occur-regexp (regexp)
12090 "If REGEXP starts with \"^\", modify it to check for \\r as well.
12091 Of course, only for the old outline mode."
12094 (if (string-match "^\\^" regexp)
12095 (concat "[\n\r]" (substring regexp 1))
12098 (defun org-flag-heading (flag &optional entry)
12099 "Flag the current heading. FLAG non-nil means make invisible.
12100 When ENTRY is non-nil, show the entire entry."
12102 (org-back-to-heading t)
12103 (if (not org-noutline-p)
12104 ;; Make the current headline visible
12105 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
12106 ;; Check if we should show the entire entry
12110 (save-excursion ;; FIXME: Is this the fix for points in the -|
12111 ;; middle of text? |
12112 (and (outline-next-heading) ;; |
12113 (org-flag-heading nil)))) ; show the next heading _|
12114 (outline-flag-region (max 1 (1- (point)))
12115 (save-excursion (outline-end-of-heading) (point))
12118 (if flag ?\r ?\n))))))
12120 (defun org-end-of-subtree (&optional invisible-OK)
12121 ;; This is an exact copy of the original function, but it uses
12122 ;; `org-back-to-heading', to make it work also in invisible
12123 ;; trees. And is uses an invisible-OK argument.
12124 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
12125 (org-back-to-heading invisible-OK)
12127 (level (funcall outline-level)))
12128 (while (and (not (eobp))
12129 (or first (> (funcall outline-level) level)))
12131 (outline-next-heading))
12132 (if (memq (preceding-char) '(?\n ?\^M))
12134 ;; Go to end of line before heading
12136 (if (memq (preceding-char) '(?\n ?\^M))
12137 ;; leave blank line before heading
12138 (forward-char -1))))))
12140 (defun org-show-subtree ()
12141 "Show everything after this heading at deeper levels."
12142 (outline-flag-region
12145 (outline-end-of-subtree) (outline-next-heading) (point))
12146 (if org-noutline-p nil ?\n)))
12148 (defun org-show-entry ()
12149 "Show the body directly following this heading.
12150 Show the heading too, if it is currently invisible."
12153 (org-back-to-heading t)
12154 (outline-flag-region
12157 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
12158 (or (match-beginning 1) (point-max)))
12159 (if org-noutline-p nil ?\n))))
12162 (defun org-make-options-regexp (kwds)
12163 "Make a regular expression for keyword lines."
12165 (if org-noutline-p "^" "[\n\r]")
12167 (mapconcat 'regexp-quote kwds "\\|")
12169 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
12171 ;; Make `bookmark-jump' show the jump location if it was hidden.
12172 (eval-after-load "bookmark"
12173 '(if (boundp 'bookmark-after-jump-hook)
12174 ;; We can use the hook
12175 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
12176 ;; Hook not available, use advice
12177 (defadvice bookmark-jump (after org-make-visible activate)
12178 "Make the position visible."
12179 (org-bookmark-jump-unhide))))
12181 (defun org-bookmark-jump-unhide ()
12182 "Unhide the current position, to show the bookmark location."
12183 (and (eq major-mode 'org-mode)
12184 (or (org-invisible-p)
12185 (save-excursion (goto-char (max (point-min) (1- (point))))
12186 (org-invisible-p)))
12187 (org-show-hierarchy-above)))
12193 (run-hooks 'org-load-hook)
12195 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
12196 ;;; org.el ends here