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, Inc.
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 ;; - HTML exporter treats targeted internal links.
89 ;; - Changes to internal link system (thanks to David Wainberg for ideas).
90 ;; - in-file links: [[Search String]] instead of <file:::Search String>
91 ;; - automatic links to "radio targets".
92 ;; - CamelCase not longer active by default, configure org-activate-camels
93 ;; if you want to turn it back on.
94 ;; - After following a link, `C-c &' jumps back to it.
95 ;; - MH-E link support (thanks to Thomas Baumann).
96 ;; - Special table lines are no longer exported.
97 ;; - Bug fixes and minor improvements.
100 ;; - Cleanup tags display in agenda.
104 ;; - Table alignment fixed for use with wide characters.
105 ;; - `C-c -' leaves cursor in current table line.
106 ;; - The current TAG can be incorporated into the agenda prefix.
107 ;; See option `org-agenda-prefix-format' for details.
110 ;; - Minor bug fixes and improvements around tag searches.
111 ;; - XEmacs compatibility fixes.
114 ;; - Tags can also be set remotely from agenda buffer.
115 ;; - Boolean logic for tag searches.
116 ;; - Additional agenda commands can be configured through the variable
117 ;; `org-agenda-custom-commands'.
118 ;; - Minor bug fixes.
122 (eval-when-compile (require 'cl) (require 'calendar))
127 (defvar calc-embedded-close-formula)
128 (defvar calc-embedded-open-formula)
129 (defvar font-lock-unfontify-region-function)
131 ;;; Customization variables
133 (defvar org-version "4.06"
134 "The version number of the file org.el.")
135 (defun org-version ()
137 (message "Org-mode version %s" org-version))
139 ;; The following two constants are for compatibility with different Emacs
140 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
141 ;; The compatibility code in org.el is based on these two constants.
142 (defconst org-xemacs-p (featurep 'xemacs)
143 "Are we running XEmacs?")
144 (defconst org-noutline-p (featurep 'noutline)
145 "Are we using the new outline mode?")
148 "Outline-based notes management and organizer."
154 (defgroup org-startup nil
155 "Options concerning startup of Org-mode."
159 (defcustom org-CUA-compatible nil
160 "Non-nil means use alternative key bindings for S-<cursor movement>.
161 Org-mode used S-<cursor movement> for changing timestamps and priorities.
162 S-<cursor movement> is also used for example by `CUA-mode' to select text.
163 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
164 alternative bindings. Setting this variable to t will replace the following
165 keys both in Org-mode and in the Org-agenda buffer.
173 If you do not like the alternative keys, take a look at the variable
176 This option is only relevant at load-time of Org-mode. Changing it requires
177 a restart of Emacs to become effective."
181 (defvar org-disputed-keys
182 '((S-up [(shift up)] [(meta ?p)])
183 (S-down [(shift down)] [(meta ?n)])
184 (S-left [(shift left)] [(meta ?-)])
185 (S-right [(shift right)] [(meta ?+)])
186 (S-return [(shift return)] [(control shift return)]))
187 "Keys for which Org-mode and other modes compete.
188 This is an alist, cars are symbols for lookup, 1st element is the default key,
189 second element will be used when `org-CUA-compatible' is t.")
192 "Select a key according to `org-CUA-compatible'."
193 (nth (if org-CUA-compatible 2 1)
194 (or (assq key org-disputed-keys)
195 (error "Invalid Key %s in `org-key'" key))))
197 (defcustom org-startup-folded t
198 "Non-nil means, entering Org-mode will switch to OVERVIEW.
199 This can also be configured on a per-file basis by adding one of
200 the following lines anywhere in the buffer:
207 (const :tag "nofold: show all" nil)
208 (const :tag "fold: overview" t)
209 (const :tag "content: all headlines" content)))
211 (defcustom org-startup-truncated t
212 "Non-nil means, entering Org-mode will set `truncate-lines'.
213 This is useful since some lines containing links can be very long and
214 uninteresting. Also tables look terrible when wrapped."
218 (defcustom org-startup-with-deadline-check nil
219 "Non-nil means, entering Org-mode will run the deadline check.
220 This means, if you start editing an org file, you will get an
221 immediate reminder of any due deadlines.
222 This can also be configured on a per-file basis by adding one of
223 the following lines anywhere in the buffer:
226 #+STARTUP: nodlcheck"
230 (defcustom org-insert-mode-line-in-empty-file nil
231 "Non-nil means insert the first line setting Org-mode in empty files.
232 When the function `org-mode' is called interactively in an empty file, this
233 normally means that the file name does not automatically trigger Org-mode.
234 To ensure that the file will always be in Org-mode in the future, a
235 line enforcing Org-mode will be inserted into the buffer, if this option
240 (defgroup org-keywords nil
241 "Options concerning TODO items in Org-mode."
245 (defcustom org-todo-keywords '("TODO" "DONE")
246 "List of TODO entry keywords.
247 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
248 considered to mean that the entry is \"done\". All the other mean that
249 action is required, and will make the entry show up in todo lists, diaries
251 The command \\[org-todo] cycles an entry through these states, and an
252 additional state where no keyword is present. For details about this
253 cycling, see also the variable `org-todo-interpretation'
254 Changes become only effective after restarting Emacs."
256 :type '(repeat (string :tag "Keyword")))
258 (defcustom org-todo-interpretation 'sequence
259 "Controls how TODO keywords are interpreted.
260 \\<org-mode-map>Possible values are `sequence' and `type'.
261 This variable is only relevant if `org-todo-keywords' contains more than two
262 states. There are two ways how these keywords can be used:
264 - As a sequence in the process of working on a TODO item, for example
265 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
266 org-todo-interpretation 'sequence)
268 - As different types of TODO items, for example
269 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
270 org-todo-interpretation 'type)
272 When the states are interpreted as a sequence, \\[org-todo] always cycles
273 to the next state, in order to walk through all different states. So with
274 \\[org-todo], you turn an empty entry into the state TODO. When you started
275 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
276 later to VERIFY and finally to DONE.
278 When the states are interpreted as types, \\[org-todo] still cycles through
279 when it is called several times in direct succession, in order to initially
280 select the type. However, if not called immediately after a previous
281 \\[org-todo], it switches from each type directly to DONE. So with the
282 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
283 RELAXED. If you later return to this entry and press \\[org-todo] again,
284 RELAXED will not be changed REMIND, but directly to DONE.
286 You can create a large number of types. To initially select a
287 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
288 type with completion. Of course, you can also type the keyword
289 directly into the buffer. M-TAB completes TODO keywords at the
290 beginning of a headline."
292 :type '(choice (const sequence)
295 (defcustom org-default-priority ?B
296 "The default priority of TODO items.
297 This is the priority an item get if no explicit priority is given."
301 (defcustom org-lowest-priority ?C
302 "The lowest priority of TODO items. A character like ?A, ?B etc."
306 (defcustom org-deadline-string "DEADLINE:"
307 "String to mark deadline entries.
308 A deadline is this string, followed by a time stamp. Should be a word,
309 terminated by a colon. You can insert a schedule keyword and
310 a timestamp with \\[org-deadline].
311 Changes become only effective after restarting Emacs."
315 (defcustom org-scheduled-string "SCHEDULED:"
316 "String to mark scheduled TODO entries.
317 A schedule is this string, followed by a time stamp. Should be a word,
318 terminated by a colon. You can insert a schedule keyword and
319 a timestamp with \\[org-schedule].
320 Changes become only effective after restarting Emacs."
324 (defcustom org-closed-string "CLOSED:"
325 "String used as the prefix for timestamps logging closing a TODO entry."
329 (defcustom org-comment-string "COMMENT"
330 "Entries starting with this keyword will never be exported.
331 An entry can be toggled between COMMENT and normal with
332 \\[org-toggle-comment].
333 Changes become only effective after restarting Emacs."
337 (defcustom org-quote-string "QUOTE"
338 "Entries starting with this keyword will be exported in fixed-width font.
339 Quoting applies only to the text in the entry following the headline, and does
340 not extend beyond the next headline, even if that is lower level.
341 An entry can be toggled between QUOTE and normal with
342 \\[org-toggle-fixed-width-section]."
346 (defcustom org-after-todo-state-change-hook nil
347 "Hook which is run after the state of a TODO item was changed.
348 The new state (a string with a TODO keyword, or nil) is available in the
349 Lisp variable `state'."
353 ;; Variables for pre-computed regular expressions, all buffer local
354 (defvar org-todo-kwd-priority-p nil
355 "Do TODO items have priorities?")
356 (make-variable-buffer-local 'org-todo-kwd-priority-p)
357 (defvar org-todo-kwd-max-priority nil
358 "Maximum priority of TODO items.")
359 (make-variable-buffer-local 'org-todo-kwd-max-priority)
360 (defvar org-ds-keyword-length 12
361 "Maximum length of the Deadline and SCHEDULED keywords.")
362 (make-variable-buffer-local 'org-ds-keyword-length)
363 (defvar org-done-string nil
364 "The last string in `org-todo-keywords', indicating an item is DONE.")
365 (make-variable-buffer-local 'org-done-string)
366 (defvar org-todo-regexp nil
367 "Matches any of the TODO state keywords.")
368 (make-variable-buffer-local 'org-todo-regexp)
369 (defvar org-not-done-regexp nil
370 "Matches any of the TODO state keywords except the last one.")
371 (make-variable-buffer-local 'org-not-done-regexp)
372 (defvar org-todo-line-regexp nil
373 "Matches a headline and puts TODO state into group 2 if present.")
374 (make-variable-buffer-local 'org-todo-line-regexp)
375 (defvar org-nl-done-regexp nil
376 "Matches newline followed by a headline with the DONE keyword.")
377 (make-variable-buffer-local 'org-nl-done-regexp)
378 (defvar org-looking-at-done-regexp nil
379 "Matches the DONE keyword a point.")
380 (make-variable-buffer-local 'org-looking-at-done-regexp)
381 (defvar org-deadline-regexp nil
382 "Matches the DEADLINE keyword.")
383 (make-variable-buffer-local 'org-deadline-regexp)
384 (defvar org-deadline-time-regexp nil
385 "Matches the DEADLINE keyword together with a time stamp.")
386 (make-variable-buffer-local 'org-deadline-time-regexp)
387 (defvar org-deadline-line-regexp nil
388 "Matches the DEADLINE keyword and the rest of the line.")
389 (make-variable-buffer-local 'org-deadline-line-regexp)
390 (defvar org-scheduled-regexp nil
391 "Matches the SCHEDULED keyword.")
392 (make-variable-buffer-local 'org-scheduled-regexp)
393 (defvar org-scheduled-time-regexp nil
394 "Matches the SCHEDULED keyword together with a time stamp.")
395 (make-variable-buffer-local 'org-scheduled-time-regexp)
397 (defvar org-category nil
398 "Variable used by org files to set a category for agenda display.
399 Such files should use a file variable to set it, for example
401 -*- mode: org; org-category: \"ELisp\"
403 or contain a special line
407 If the file does not specify a category, then file's base name
409 (make-variable-buffer-local 'org-category)
411 (defgroup org-time nil
412 "Options concerning time stamps and deadlines in Org-mode."
416 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
417 "Formats for `format-time-string' which are used for time stamps.
418 It is not recommended to change this constant.")
421 (defcustom org-deadline-warning-days 30
422 "No. of days before expiration during which a deadline becomes active.
423 This variable governs the display in the org file."
427 (defcustom org-popup-calendar-for-date-prompt t
428 "Non-nil means, pop up a calendar when prompting for a date.
429 In the calendar, the date can be selected with mouse-1. However, the
430 minibuffer will also be active, and you can simply enter the date as well.
431 When nil, only the minibuffer will be available."
435 (defcustom org-calendar-follow-timestamp-change t
436 "Non-nil means, make the calendar window follow timestamp changes.
437 When a timestamp is modified and the calendar window is visible, it will be
438 moved to the new date."
442 (defcustom org-log-done nil
443 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
444 When the state of an entry is changed from nothing to TODO, remove a previous
449 (defgroup org-agenda nil
450 "Options concerning agenda display Org-mode."
454 (defcustom org-agenda-files nil
455 "A list of org files for agenda/diary display.
456 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
457 \\[org-remove-file]. You can also use customize to edit the list."
459 :type '(repeat file))
461 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
462 "Custom commands for the agenda.
463 These commands will be offered on the splash screen displayed by the
464 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
466 key The key (a single char as a string) to be associated with the command.
467 type The command type, any of the following symbols:
468 todo Entries with a specific TODO keyword, in all agenda files.
469 tags Tags match in all agenda files.
470 todo-tree Sparse tree of specific TODO keyword in *current* file.
471 tags-tree Sparse tree with all tags matches in *current* file.
472 occur-tree Occur sparse tree for current file.
473 match What to search for:
474 - a single keyword for TODO keyword searches
475 - a tags match expression for tags searches
476 - a regular expression for occur searches"
479 (list (string :tag "Key")
481 (const :tag "Tags search in all agenda files" tags)
482 (const :tag "TODO keyword search in all agenda files" todo)
483 (const :tag "Tags sparse tree in current buffer" tags-tree)
484 (const :tag "TODO keyword tree in current buffer" todo-tree)
485 (const :tag "Occur tree in current buffer" occur-tree))
486 (string :tag "Match"))))
488 (defcustom org-select-timeline-window t
489 "Non-nil means, after creating a timeline, move cursor into Timeline window.
490 When nil, cursor will remain in the current window."
494 (defcustom org-select-agenda-window t
495 "Non-nil means, after creating an agenda, move cursor into Agenda window.
496 When nil, cursor will remain in the current window."
500 (defcustom org-fit-agenda-window t
501 "Non-nil means, change window size of agenda to fit content."
505 (defcustom org-agenda-show-all-dates t
506 "Non-nil means, `org-agenda' shows every day in the selected range.
507 When nil, only the days which actually have entries are shown."
511 ;; FIXME: First day of month works only for current month because it would
512 ;; require a variable ndays treatment.
513 (defcustom org-agenda-start-on-weekday 1
514 "Non-nil means, start the overview always on the specified weekday.
515 0 Denotes Sunday, 1 denotes Monday etc.
516 When nil, always start on the current day."
518 :type '(choice (const :tag "Today" nil)
519 (const :tag "First day of month" t)
520 (number :tag "Weekday No.")))
522 (defcustom org-agenda-ndays 7
523 "Number of days to include in overview display."
527 (defcustom org-agenda-include-all-todo t
528 "Non-nil means, the agenda will always contain all TODO entries.
529 When nil, date-less entries will only be shown if `org-agenda' is called
530 with a prefix argument.
531 When non-nil, the TODO entries will be listed at the top of the agenda, before
532 the entries for specific days."
536 (defcustom org-agenda-include-diary nil
537 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
541 (defcustom org-calendar-to-agenda-key [?c]
542 "The key to be installed in `calendar-mode-map' for switching to the agenda.
543 The command `org-calendar-goto-agenda' will be bound to this key. The
544 default is the character `c' because then `c' can be used to switch back and
545 forth between agenda and calendar."
549 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
550 "Sorting structure for the agenda items of a single day.
551 This is a list of symbols which will be used in sequence to determine
552 if an entry should be listed before another entry. The following
553 symbols are recognized:
555 time-up Put entries with time-of-day indications first, early first
556 time-down Put entries with time-of-day indications first, late first
557 category-keep Keep the default order of categories, corresponding to the
558 sequence in `org-agenda-files'.
559 category-up Sort alphabetically by category, A-Z.
560 category-down Sort alphabetically by category, Z-A.
561 priority-up Sort numerically by priority, high priority last.
562 priority-down Sort numerically by priority, high priority first.
564 The different possibilities will be tried in sequence, and testing stops
565 if one comparison returns a \"not-equal\". For example, the default
566 '(time-up category-keep priority-down)
567 means: Pull out all entries having a specified time of day and sort them,
568 in order to make a time schedule for the current day the first thing in the
569 agenda listing for the day. Of the entries without a time indication, keep
570 the grouped in categories, don't sort the categories, but keep them in
571 the sequence given in `org-agenda-files'. Within each category sort by
574 Leaving out `category-keep' would mean that items will be sorted across
575 categories by priority."
581 (const category-keep)
583 (const category-down)
585 (const priority-down))))
587 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
588 "Format specification for the prefix of items in the agenda buffer.
589 This format works similar to a printf format, with the following meaning:
591 %c the category of the item, \"Diary\" for entries from the diary, or
592 as given by the CATEGORY keyword or derived from the file name.
593 %T the first tag of the item.
594 %t the time-of-day specification if one applies to the entry, in the
596 %s Scheduling/Deadline information, a short string
598 All specifiers work basically like the standard `%s' of printf, but may
599 contain two additional characters: A question mark just after the `%' and
600 a whitespace/punctuation character just before the final letter.
602 If the first character after `%' is a question mark, the entire field
603 will only be included if the corresponding value applies to the
604 current entry. This is useful for fields which should have fixed
605 width when present, but zero width when absent. For example,
606 \"%?-12t\" will result in a 12 character time field if a time of the
607 day is specified, but will completely disappear in entries which do
610 If there is punctuation or whitespace character just before the final
611 format letter, this character will be appended to the field value if
612 the value is not empty. For example, the format \"%-12:c\" leads to
613 \"Diary: \" if the category is \"Diary\". If the category were be
614 empty, no additional colon would be interted.
616 The default value of this option is \" %-12:c%?-12t% s\", meaning:
617 - Indent the line with two space characters
618 - Give the category in a 12 chars wide field, padded with whitespace on
619 the right (because of `-'). Append a colon if there is a category
621 - If there is a time-of-day, put it into a 12 chars wide field. If no
622 time, don't put in an empty field, just skip it (because of '?').
623 - Finally, put the scheduling information and append a whitespace.
625 As another example, if you don't want the time-of-day of entries in
626 the prefix, you could use:
628 (setq org-agenda-prefix-format \" %-11:c% s\")
630 See also the variables `org-agenda-remove-times-when-in-prefix' and
631 `org-agenda-remove-tags-when-in-prefix'."
635 (defcustom org-timeline-prefix-format " % s"
636 "Like `org-agenda-prefix-format', but for the timeline of a single file."
640 (defvar org-prefix-format-compiled nil
641 "The compiled version of the most recently used prefix format.
642 Depending on which command was used last, this may be the compiled version
643 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
645 (defcustom org-agenda-use-time-grid t
646 "Non-nil means, show a time grid in the agenda schedule.
647 A time grid is a set of lines for specific times (like every two hours between
648 8:00 and 20:00). The items scheduled for a day at specific times are
649 sorted in between these lines.
650 For details about when the grid will be shown, and what it will look like, see
651 the variable `org-agenda-time-grid'."
655 (defcustom org-agenda-time-grid
656 '((daily today require-timed)
658 (800 1000 1200 1400 1600 1800 2000))
660 "The settings for time grid for agenda display.
661 This is a list of three items. The first item is again a list. It contains
662 symbols specifying conditions when the grid should be displayed:
664 daily if the agenda shows a single day
665 weekly if the agenda shows an entire week
666 today show grid on current date, independent of daily/weekly display
667 require-timed show grid only if at least on item has a time specification
669 The second item is a string which will be places behing the grid time.
671 The third item is a list of integers, indicating the times that should have
676 (set :greedy t :tag "Grid Display Options"
677 (const :tag "Show grid in single day agenda display" daily)
678 (const :tag "Show grid in weekly agenda display" weekly)
679 (const :tag "Always show grid for today" today)
680 (const :tag "Show grid only if any timed entries are present"
682 (const :tag "Skip grid times already present in an entry"
684 (string :tag "Grid String")
685 (repeat :tag "Grid Times" (integer :tag "Time"))))
687 (defcustom org-agenda-remove-times-when-in-prefix t
688 "Non-nil means, remove duplicate time specifications in agenda items.
689 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
690 time-of-day specification in a headline or diary entry is extracted and
691 placed into the prefix. If this option is non-nil, the original specification
692 \(a timestamp or -range, or just a plain time(range) specification like
693 11:30-4pm) will be removed for agenda display. This makes the agenda less
695 The option can be t or nil. It may also be the symbol `beg', indicating
696 that the time should only be removed what it is located at the beginning of
697 the headline/diary entry."
700 (const :tag "Always" t)
701 (const :tag "Never" nil)
702 (const :tag "When at beginning of entry" beg)))
704 (defcustom org-sort-agenda-notime-is-late t
705 "Non-nil means, items without time are considered late.
706 This is only relevant for sorting. When t, items which have no explicit
707 time like 15:30 will be considered as 24:01, i.e. later than any items which
708 do have a time. When nil, the default time is before 0:00. You can use this
709 option to decide if the schedule for today should come before or after timeless
714 (defcustom org-agenda-remove-tags-when-in-prefix nil
715 "Non-nil means, the tags from copy of headline in agenda.
716 When this is the symbol `prefix', only remove tags when
717 `org-agenda-prefix-format' contains a `%T' specifier."
720 (const :tag "Always" t)
721 (const :tag "Never" nil)
722 (const :tag "When prefix format contains %T" prefix)))
724 (defgroup org-structure nil
725 "Options concerning structure editing in Org-mode."
729 (defcustom org-cycle-include-plain-lists nil
730 "Non-nil means, include plain lists into visibility cycling.
731 This means that during cycling, plain list items will *temporarily* be
732 interpreted as outline headlines with a level given by 1000+i where i is the
733 indentation of the bullet. In all other operations, plain list items are
734 not seen as headlines. For example, you cannot assign a TODO keyword to
736 :group 'org-structure
739 (defcustom org-cycle-emulate-tab t
740 "Where should `org-cycle' emulate TAB.
742 white Only in completely white lines
743 t Everywhere except in headlines"
744 :group 'org-structure
745 :type '(choice (const :tag "Never" nil)
746 (const :tag "Only in completely white lines" white)
747 (const :tag "Everywhere except in headlines" t)
750 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
751 "Hook that is run after `org-cycle' has changed the buffer visibility.
752 The function(s) in this hook must accept a single argument which indicates
753 the new state that was set by the most recent `org-cycle' command. The
754 argument is a symbol. After a global state change, it can have the values
755 `overview', `content', or `all'. After a local state change, it can have
756 the values `folded', `children', or `subtree'."
757 :group 'org-structure
760 (defcustom org-highlight-sparse-tree-matches t
761 "Non-nil means, highlight all matches that define a sparse tree.
762 The highlights will automatically disappear the next time the buffer is
763 changed by an edit command."
764 :group 'org-structure
767 (defcustom org-show-hierarchy-above t
768 "Non-nil means, show full hierarchy when showing a spot in the tree.
769 Turning this off makes sparse trees more compact, but also less clear."
770 :group 'org-structure
773 (defcustom org-show-following-heading t
774 "Non-nil means, show heading following match in `org-occur'.
775 When doing an `org-occur' it is useful to show the headline which
776 follows the match, even if they do not match the regexp. This makes it
777 easier to edit directly inside the sparse tree. However, if you use
778 `org-occur' mainly as an overview, the following headlines are
779 unnecessary clutter."
780 :group 'org-structure
783 (defcustom org-occur-hook '(org-first-headline-recenter)
784 "Hook that is run after `org-occur' has constructed a sparse tree.
785 This can be used to recenter the window to show as much of the structure
787 :group 'org-structure
790 (defcustom org-level-color-stars-only nil
791 "Non-nil means fontify only the stars in each headline.
792 When nil, the entire headline is fontified.
793 Changing it requires restart of Emacs to become effective."
794 :group 'org-structure
797 (defcustom org-adapt-indentation t
798 "Non-nil means, adapt indentation when promoting and demoting.
799 When this is set and the *entire* text in an entry is indented, the
800 indentation is increased by one space in a demotion command, and
801 decreased by one in a promotion command. If any line in the entry
802 body starts at column 0, indentation is not changed at all."
803 :group 'org-structure
806 (defcustom org-plain-list-ordered-item-terminator t
807 "The character that makes a line with leading number an ordered list item.
808 Valid values are ?. and ?\). To get both terminators, use t. While
809 ?. may look nicer, it creates the danger that a line with leading
810 number may be incorrectly interpreted as an item. ?\) therefore is
812 :group 'org-structure
813 :type '(choice (const :tag "dot like in \"2.\"" ?.)
814 (const :tag "paren like in \"2)\"" ?\))
815 (const :tab "both" t)))
817 (defcustom org-auto-renumber-ordered-lists t
818 "Non-nil means, automatically renumber ordered plain lists.
819 Renumbering happens when the sequence have been changed with
820 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
821 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
822 :group 'org-structure
825 (defcustom org-enable-fixed-width-editor t
826 "Non-nil means, lines starting with \":\" are treated as fixed-width.
827 This currently only means, they are never auto-wrapped.
828 When nil, such lines will be treated like ordinary lines.
829 See also the QUOTE keyword."
830 :group 'org-structure
833 (defcustom org-archive-location "%s_archive::"
834 "The location where subtrees should be archived.
835 This string consists of two parts, separated by a double-colon.
837 The first part is a file name - when omitted, archiving happens in the same
838 file. %s will be replaced by the current file name (without directory part).
839 Archiving to a different file is useful to keep archived entries from
840 contributing to the Org-mode Agenda.
842 The part after the double colon is a headline. The archived entries will be
843 filed under that headline. When omitted, the subtrees are simply filed away
844 at the end of the file, as top-level entries.
846 Here are a few examples:
848 If the current file is Projects.org, archive in file
849 Projects.org_archive, as top-level trees. This is the default.
851 \"::* Archived Tasks\"
852 Archive in the current file, under the top-level headline
853 \"* Archived Tasks\".
855 \"~/org/archive.org::\"
856 Archive in file ~/org/archive.org (absolute path), as top-level trees.
858 \"basement::** Finished Tasks\"
859 Archive in file ./basement (relative path), as level 3 trees
860 below the level 2 heading \"** Finished Tasks\".
862 You may set this option on a per-file basis by adding to the buffer a
865 #+ARCHIVE: basement::** Finished Tasks"
866 :group 'org-structure
869 (defcustom org-archive-mark-done t
870 "Non-nil means, mark archived entries as DONE."
871 :group 'org-structure
874 (defcustom org-archive-stamp-time t
875 "Non-nil means, add a time stamp to archived entries.
876 The time stamp will be added directly after the TODO state keyword in the
877 first line, so it is probably best to use this in combinations with
878 `org-archive-mark-done'."
879 :group 'org-structure
882 (defgroup org-tags nil
883 "Options concerning startup of Org-mode."
887 (defcustom org-tags-column 48
888 "The column to which tags should be indented in a headline.
889 If this number is positive, it specifies the column. If it is negative,
890 it means that the tags should be flushright to that column. For example,
891 -79 works well for a normal 80 character screen."
895 (defcustom org-auto-align-tags t
896 "Non-nil means, realign tags after pro/demotion of TODO state change.
897 These operations change the length of a headline and therefore shift
898 the tags around. With this options turned on, after each such operation
899 the tags are again aligned to `org-tags-column'."
903 (defcustom org-use-tag-inheritance t
904 "Non-nil means, tags in levels apply also for sublevels.
905 When nil, only the tags directly given in a specific line apply there.
906 If you turn off this option, you very likely want to turn on the
907 companion option `org-tags-match-list-sublevels'."
911 (defcustom org-tags-match-list-sublevels nil
912 "Non-nil means list also sublevels of headlines matching tag search.
913 Because of tag inheritance (see variable `org-use-tag-inheritance'),
914 the sublevels of a headline matching a tag search often also match
915 the same search. Listing all of them can create very long lists.
916 Setting this variable to nil causes subtrees to be skipped.
917 This option is off by default, because inheritance in on. If you turn
918 inheritance off, you very likely want to turn this option on.
920 As a special case, if the tag search is restricted to TODO items, the
921 value of this variable is ignored and sublevels are always checked, to
922 make sure all corresponding TODO items find their way into the list."
926 (defvar org-tags-history nil
927 "History of minibuffer reads for tags.")
928 (defvar org-last-tags-completion-table nil
929 "The last used completion table for tags.")
931 (defgroup org-link nil
932 "Options concerning links in Org-mode."
936 (defcustom org-tab-follows-link nil
937 "Non-nil means, on links TAB will follow the link.
938 Needs to be set before org.el is loaded."
942 (defcustom org-return-follows-link nil
943 "Non-nil means, on links RET will follow the link.
944 Needs to be set before org.el is loaded."
948 (defcustom org-mark-ring-length 4
949 "Number of different positions to be recorded in the ring
950 Changing this requires a restart of Emacs to work correctly."
954 (defcustom org-link-format "<%s>"
955 "Default format for linkes in the buffer.
956 This is a format string for printf, %s will be replaced by the link text.
957 If you want to make sure that your link is always properly terminated,
958 include angle brackets into this format, like \"<%s>\". Some people also
959 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
962 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
963 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
964 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
965 (string :tag "Other" :value "<%s>")))
967 (defcustom org-allow-space-in-links t
968 "Non-nil means, file names in links may contain space characters.
969 When nil, it becomes possible to put several links into a line.
970 Note that in tables, a link never extends accross fields, so in a table
971 it is always possible to put several links into a line.
972 Changing this variable requires a restart of Emacs of become effective."
976 (defcustom org-radio-targets t
977 "Non-nil means activate text matching a link target.
978 Radio targets are strings in triple angular brackets, like <<<My Target>>>.
979 When this option is set, any occurrence of \"my target\" in normal text
984 (defcustom org-activate-camels nil
985 "Non-nil means, treat words in CamelCase as in-file links.
986 Changing this requires restart of Emacs to become effective."
990 (defcustom org-context-in-file-links t
991 "Non-nil means, file links from `org-store-link' contain context.
992 A search string will be added to the file name with :: as separator and
993 used to find the context when the link is activated by the command
995 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
996 negates this setting for the duration of the command."
1000 (defcustom org-file-link-context-use-camel-case nil
1001 "Non-nil means, use CamelCase to store a search context in a file link.
1002 When nil, the search string simply consists of the words of the string."
1006 (defcustom org-keep-stored-link-after-insertion nil
1007 "Non-nil means, keep link in list for entire session.
1009 The command `org-store-link' adds a link pointing to the current
1010 location to an internal list. These links accumulate during a session.
1011 The command `org-insert-link' can be used to insert links into any
1012 Org-mode file (offering completion for all stored links). When this
1013 option is nil, every link which has been inserted once using \\[org-insert-link]
1014 will be removed from the list, to make completing the unused links
1019 (defcustom org-link-frame-setup
1020 '((vm . vm-visit-folder-other-frame)
1021 (gnus . gnus-other-frame)
1022 (file . find-file-other-window))
1023 "Setup the frame configuration for following links.
1024 When following a link with Emacs, it may often be useful to display
1025 this link in another window or frame. This variable can be used to
1026 set this up for the different types of links.
1029 `vm-visit-folder-other-frame'
1030 For Gnus, use any of
1033 For FILE, use any of
1035 `find-file-other-window'
1036 `find-file-other-frame'
1037 For the calendar, use the variable `calendar-setup'.
1038 For BBDB, it is currently only possible to display the matches in
1044 (const vm-visit-folder)
1045 (const vm-visit-folder-other-window)
1046 (const vm-visit-folder-other-frame)))
1050 (const gnus-other-frame)))
1054 (const find-file-other-window)
1055 (const find-file-other-frame)))))
1057 (defcustom org-usenet-links-prefer-google nil
1058 "Non-nil means, `org-store-link' will create web links to Google groups.
1059 When nil, Gnus will be used for such links.
1060 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1061 negates this setting for the duration of the command."
1065 (defcustom org-open-non-existing-files nil
1066 "Non-nil means, `org-open-file' will open non-existing file.
1067 When nil, an error will be generated."
1071 (defcustom org-confirm-shell-links t
1072 "Non-nil means, ask for confirmation before executing shell links.
1073 The default is true, to keep new users from shooting into their own foot."
1077 (defconst org-file-apps-defaults-gnu
1079 "Default file applications on a UNIX or GNU/Linux system.
1080 See `org-file-apps'.")
1082 (defconst org-file-apps-defaults-macosx
1087 ("eps.gz" . "gv %s")
1089 ("fig" . "xfig %s"))
1090 "Default file applications on a MacOS X system.
1091 The system \"open\" is known as a default, but we use X11 applications
1092 for some files for which the OS does not have a good default.
1093 See `org-file-apps'.")
1095 (defconst org-file-apps-defaults-windowsnt
1096 '((t . (w32-shell-execute "open" file)))
1097 "Default file applications on a Windows NT system.
1098 The system \"open\" is used for most files.
1099 See `org-file-apps'.")
1101 (defcustom org-file-apps
1109 "External applications for opening `file:path' items in a document.
1110 Org-mode uses system defaults for different file types, but
1111 you can use this variable to set the application for a given file
1112 extension. The entries in this list are cons cells with a file extension
1113 and the corresponding command. Possible values for the command are:
1114 `emacs' The file will be visited by the current Emacs process.
1115 `default' Use the default application for this file type.
1116 string A command to be executed by a shell; %s will be replaced
1117 by the path to the file.
1118 sexp A Lisp form which will be evaluated. The file path will
1119 be available in the Lisp variable `file'.
1120 For more examples, see the system specific constants
1121 `org-file-apps-defaults-macosx'
1122 `org-file-apps-defaults-windowsnt'
1123 `org-file-apps-defaults-gnu'."
1126 (cons (choice :value ""
1127 (string :tag "Extension")
1128 (const :tag "Default for unrecognized files" t)
1129 (const :tag "Links to a directory" directory))
1131 (const :tag "Visit with Emacs" emacs)
1132 (const :tag "Use system default" default)
1133 (string :tag "Command")
1134 (sexp :tag "Lisp form")))))
1136 (defgroup org-remember nil
1137 "Options concerning interaction with remember.el."
1141 (defcustom org-directory "~/org"
1142 "Directory with org files.
1143 This directory will be used as default to prompt for org files.
1144 Used by the hooks for remember.el."
1145 :group 'org-remember
1148 (defcustom org-default-notes-file "~/.notes"
1149 "Default target for storing notes.
1150 Used by the hooks for remember.el. This can be a string, or nil to mean
1151 the value of `remember-data-file'."
1152 :group 'org-remember
1154 (const :tag "Default from remember-data-file" nil)
1157 (defcustom org-reverse-note-order nil
1158 "Non-nil means, store new notes at the beginning of a file or entry.
1159 When nil, new notes will be filed to the end of a file or entry."
1160 :group 'org-remember
1162 (const :tag "Reverse always" t)
1163 (const :tag "Reverse never" nil)
1164 (repeat :tag "By file name regexp"
1165 (cons regexp boolean))))
1167 (defgroup org-table nil
1168 "Options concerning tables in Org-mode."
1172 (defcustom org-enable-table-editor 'optimized
1173 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1174 When nil, such lines will be treated like ordinary lines.
1176 When equal to the symbol `optimized', the table editor will be optimized to
1178 - Use automatic overwrite mode in front of whitespace in table fields.
1179 This make the structure of the table stay in tact as long as the edited
1180 field does not exceed the column width.
1181 - Minimize the number of realigns. Normally, the table is aligned each time
1182 TAB or RET are pressed to move to another field. With optimization this
1183 happens only if changes to a field might have changed the column width.
1184 Optimization requires replacing the functions `self-insert-command',
1185 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1186 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1187 very good at guessing when a re-align will be necessary, but you can always
1188 force one with \\[org-ctrl-c-ctrl-c].
1190 If you would like to use the optimized version in Org-mode, but the
1191 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1193 This variable can be used to turn on and off the table editor during a session,
1194 but in order to toggle optimization, a restart is required.
1196 See also the variable `org-table-auto-blank-field'."
1199 (const :tag "off" nil)
1201 (const :tag "on, optimized" optimized)))
1203 ;; FIXME: We could have a third option which makes it jump only over the first
1204 ;; hline in a table.
1205 (defcustom org-table-tab-jumps-over-hlines t
1206 "Non-nil means, tab in the last column of a table with jump over a hline.
1207 If a horizontal separator line is following the current line,
1208 `org-table-next-field' can either create a new row before that line, or jump
1209 over the line. When this option is nil, a new line will be created before
1214 (defcustom org-table-auto-blank-field t
1215 "Non-nil means, automatically blank table field when starting to type into it.
1216 This only happens when typing immediately after a field motion
1217 command (TAB, S-TAB or RET).
1218 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1222 (defcustom org-table-default-size "5x2"
1223 "The default size for newly created tables, Columns x Rows."
1227 (defcustom org-table-automatic-realign t
1228 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1229 When nil, aligning is only done with \\[org-table-align], or after column
1234 (defcustom org-table-spaces-around-separators '(1 . 1)
1235 "The number of spaces to be placed before and after separators."
1237 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1239 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1240 "The number of spaces to be placed before and after separators.
1241 This option applies when the column separators have been made invisible."
1243 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1245 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1246 "Regular expression for recognizing numbers in table columns.
1247 If a table column contains mostly numbers, it will be aligned to the
1248 right. If not, it will be aligned to the left.
1250 The default value of this option is a regular expression which allows
1251 anything which looks remotely like a number as used in scientific
1252 context. For example, all of the following will be considered a
1254 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1256 Other options offered by the customize interface are more restrictive."
1259 (const :tag "Positive Integers"
1261 (const :tag "Integers"
1263 (const :tag "Floating Point Numbers"
1264 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1265 (const :tag "Floating Point Number or Integer"
1266 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1267 (const :tag "Exponential, Floating point, Integer"
1268 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1269 (const :tag "Very General Number-Like"
1270 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1271 (string :tag "Regexp:")))
1273 (defcustom org-table-number-fraction 0.5
1274 "Fraction of numbers in a column required to make the column align right.
1275 In a column all non-white fields are considered. If at least this
1276 fraction of fields is matched by `org-table-number-fraction',
1277 alignment to the right border applies."
1281 (defcustom org-export-highlight-first-table-line t
1282 "Non-nil means, highlight the first table line.
1283 In HTML export, this means use <th> instead of <td>.
1284 In tables created with table.el, this applies to the first table line.
1285 In Org-mode tables, all lines before the first horizontal separator
1286 line will be formatted with <th> tags."
1290 (defcustom org-table-tab-recognizes-table.el t
1291 "Non-nil means, TAB will automatically notice a table.el table.
1292 When it sees such a table, it moves point into it and - if necessary -
1293 calls `table-recognize-table'."
1297 (defgroup org-table-calculation nil
1298 "Options concerning tables in Org-mode."
1299 :tag "Org Table Calculation"
1302 (defcustom org-table-copy-increment t
1303 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1304 :group 'org-table-calculation
1307 (defcustom org-calc-default-modes
1308 '(calc-internal-prec 12
1309 calc-float-format (float 5)
1311 calc-prefer-frac nil
1312 calc-symbolic-mode nil
1313 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1314 calc-display-working-message t
1316 "List with Calc mode settings for use in calc-eval for table formulas.
1317 The list must contain alternating symbols (Calc modes variables and values).
1318 Don't remove any of the default settings, just change the values. Org-mode
1319 relies on the variables to be present in the list."
1320 :group 'org-table-calculation
1323 (defcustom org-table-formula-evaluate-inline t
1324 "Non-nil means, TAB and RET evaluate a formula in current table field.
1325 If the current field starts with an equal sign, it is assumed to be a formula
1326 which should be evaluated as described in the manual and in the documentation
1327 string of the command `org-table-eval-formula'. This feature requires the
1329 When this variable is nil, formula calculation is only available through
1330 the command \\[org-table-eval-formula]."
1331 :group 'org-table-calculation
1335 (defcustom org-table-formula-use-constants t
1336 "Non-nil means, interpret constants in formulas in tables.
1337 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1338 by the value given in `org-table-formula-constants', or by a value obtained
1339 from the `constants.el' package."
1340 :group 'org-table-calculation
1343 (defcustom org-table-formula-constants nil
1344 "Alist with constant names and values, for use in table formulas.
1345 The car of each element is a name of a constant, without the `$' before it.
1346 The cdr is the value as a string. For example, if you'd like to use the
1347 speed of light in a formula, you would configure
1349 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1351 and then use it in an equation like `$1*$c'."
1352 :group 'org-table-calculation
1354 (cons (string :tag "name")
1355 (string :tag "value"))))
1357 (defcustom org-table-formula-numbers-only nil
1358 "Non-nil means, calculate only with numbers in table formulas.
1359 Then all input fields will be converted to a number, and the result
1360 must also be a number. When nil, calc's full potential is available
1361 in table calculations, including symbolics etc."
1362 :group 'org-table-calculation
1365 (defcustom org-table-allow-automatic-line-recalculation t
1366 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1367 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1368 :group 'org-table-calculation
1371 (defgroup org-export nil
1372 "Options for exporting org-listings."
1376 (defcustom org-export-language-setup
1377 '(("en" "Author" "Date" "Table of Contents")
1378 ("da" "Ophavsmand" "Dato" "Indhold")
1379 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1380 ("es" "Autor" "Fecha" "\xccndice")
1381 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1382 ("it" "Autore" "Data" "Indice")
1383 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1384 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1385 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1386 "Terms used in export text, translated to different languages.
1387 Use the variable `org-export-default-language' to set the language,
1388 or use the +OPTION lines for a per-file setting."
1392 (string :tag "HTML language tag")
1393 (string :tag "Author")
1394 (string :tag "Date")
1395 (string :tag "Table of Contents"))))
1397 (defcustom org-export-default-language "en"
1398 "The default language of HTML export, as a string.
1399 This should have an association in `org-export-language-setup'."
1403 (defcustom org-export-html-style
1404 "<style type=\"text/css\">
1406 font-family: Times, serif;
1409 .title { text-align: center; }
1410 .todo, .deadline { color: red; }
1411 .done { color: green; }
1413 border: 1pt solid #AEBDCC;
1414 background-color: #F3F5F7;
1416 font-family: courier, monospace;
1418 table { border-collapse: collapse; }
1420 vertical-align: top;
1421 border: 1pt solid #ADB9CC;
1424 "The default style specification for exported HTML files.
1425 Since there are different ways of setting style information, this variable
1426 needs to contain the full HTML structure to provide a style, including the
1427 surrounding HTML tags. The style specifications should include definitions
1428 for new classes todo, done, title, and deadline. For example, legal values
1431 <style type=\"text/css\">
1432 p { font-weight: normal; color: gray; }
1433 h1 { color: black; }
1434 .title { text-align: center; }
1435 .todo, .deadline { color: red; }
1436 .done { color: green; }
1439 or, if you want to keep the style in a file,
1441 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1443 As the value of this option simply gets inserted into the HTML <head> header,
1444 you can \"misuse\" it to add arbitrary text to the header."
1448 (defcustom org-export-headline-levels 3
1449 "The last level which is still exported as a headline.
1450 Inferior levels will produce itemize lists when exported.
1451 Note that a numeric prefix argument to an exporter function overrides
1454 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1458 (defcustom org-export-with-section-numbers t
1459 "Non-nil means, add section numbers to headlines when exporting.
1461 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1465 (defcustom org-export-with-toc t
1466 "Non-nil means, create a table of contents in exported files.
1467 The TOC contains headlines with levels up to`org-export-headline-levels'.
1469 Headlines which contain any TODO items will be marked with \"(*)\" in
1470 ASCII export, and with red color in HTML output.
1472 In HTML output, the TOC will be clickable.
1474 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1478 (defcustom org-export-plain-list-max-depth 20
1479 "Maximum depth of hand-formatted lists in HTML export.
1481 Org-mode parses hand-formatted enumeration and bullet lists and
1482 transforms them to HTML open export. Different indentation of the
1483 bullet or number indicates different list nesting levels. To avoid
1484 confusion, only a single level is allowed by default. When this is
1485 larger than 1, deeper indentation leads to deeper list nesting. For
1486 example, the default value of 3 allows the following list to be
1487 formatted correctly in HTML:
1493 2. from South America
1500 (defcustom org-export-preserve-breaks nil
1501 "Non-nil means, preserve all line breaks when exporting.
1502 Normally, in HTML output paragraphs will be reformatted. In ASCII
1503 export, line breaks will always be preserved, regardless of this variable.
1505 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1509 (defcustom org-export-html-inline-images t
1510 "Non-nil means, inline images into exported HTML pages.
1511 The link will still be to the original location of the image file.
1512 So if you are moving the page, lets say to your public HTML site,
1513 you will have to move the image and maybe change the link."
1517 (defcustom org-export-html-expand t
1518 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1519 When nil, these tags will be exported as plain text and therefore
1520 not be interpreted by a browser.
1522 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1526 (defcustom org-export-with-fixed-width t
1527 "Non-nil means, lines starting with \":\" will be in fixed width font.
1528 This can be used to have pre-formatted text, fragments of code etc. For
1530 : ;; Some Lisp examples
1533 will be looking just like this in also HTML. In ASCII export, this option
1536 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1540 (defcustom org-export-with-tables t
1541 "If non-nil, lines starting with \"|\" define a table.
1544 | Name | Address | Birthday |
1545 |-------------+----------+-----------|
1546 | Arthur Dent | England | 29.2.2100 |
1548 In ASCII export, this option has no effect.
1550 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1554 (defcustom org-export-table-remove-special-lines t
1555 "Remove special lines and marking characters in calculating tables.
1556 This removes the special marking character column from tables that are set
1557 up for spreadsheet calculations. It also removes the entire lines
1558 marked with `!', `_', or `^'. The lines with `$' are kept, because
1559 the values of constants may be useful to have."
1563 (defcustom org-export-prefer-native-exporter-for-tables nil
1564 "Non-nil means, always export tables created with table.el natively.
1565 Natively means, use the HTML code generator in table.el.
1566 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1567 the table does not use row- or column-spanning). This has the
1568 advantage, that the automatic HTML conversions for math symbols and
1569 sub/superscripts can be applied. Org-mode's HTML generator is also
1574 (defcustom org-export-html-table-tag
1575 "<table border=1 cellspacing=0 cellpadding=6>"
1576 "The HTML tag used to start a table.
1577 This must be a <table> tag, but you may change the options like
1578 borders and spacing."
1582 (defcustom org-export-with-emphasize t
1583 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1584 If the export target supports emphasizing text, the word will be
1585 typeset in bold, italic, or underlined, respectively. Works only for
1586 single words, but you can say: I *really* *mean* *this*.
1587 In ASCII export, this option has no effect.
1589 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1593 (defcustom org-match-sexp-depth 3
1594 "Number of stacked braces for sub/superscript matching.
1595 This has to be set before loading org.el to be effective."
1599 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1600 (defcustom org-export-with-sub-superscripts t
1601 "Non-nil means, interpret \"_\" and \"^\" for export.
1602 When this option is turned on, you can use TeX-like syntax for sub- and
1603 superscripts. Several characters after \"_\" or \"^\" will be
1604 considered as a single item - so grouping with {} is normally not
1605 needed. For example, the following things will be parsed as single
1606 sub- or superscripts.
1608 10^24 or 10^tau several digits will be considered 1 item.
1609 10^-12 or 10^-tau a leading sign with digits or a word
1610 x^2-y^3 will be read as x^2 - y^3, because items are
1611 terminated by almost any nonword/nondigit char.
1612 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1614 Still, ambiguity is possible - so when in doubt use {} to enclose the
1616 In ASCII export, this option has no effect.
1618 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1622 (defcustom org-export-with-TeX-macros t
1623 "Non-nil means, interpret simple TeX-like macros when exporting.
1624 For example, HTML export converts \\alpha to α and \\AA to Å.
1625 No only real TeX macros will work here, but the standard HTML entities
1626 for math can be used as macro names as well. For a list of supported
1627 names in HTML export, see the constant `org-html-entities'.
1628 In ASCII export, this option has no effect.
1630 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1634 (defcustom org-export-html-with-timestamp nil
1635 "If non-nil, write `org-export-html-html-helper-timestamp'
1636 into the exported html text. Otherwise, the buffer will just be saved
1641 (defcustom org-export-html-html-helper-timestamp
1642 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1643 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1647 (defcustom org-export-ascii-show-new-buffer t
1648 "Non-nil means, popup buffer containing the exported ASCII text.
1649 Otherwise the buffer will just be saved to a file and stay hidden."
1653 (defcustom org-export-html-show-new-buffer nil
1654 "Non-nil means, popup buffer containing the exported HTML text.
1655 Otherwise, the buffer will just be saved to a file and stay hidden."
1659 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1660 "The file name for the iCalendar file covering all agenda files.
1661 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1665 (defcustom org-icalendar-include-todo nil
1666 "Non-nil means, export to iCalendar files should also cover TODO items."
1670 (defcustom org-icalendar-combined-name "OrgMode"
1671 "Calendar name for the combined iCalendar representing all agenda files."
1675 (defgroup org-faces nil
1676 "Faces for highlighting in Org-mode."
1680 (defface org-level-1 ;; font-lock-function-name-face
1681 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1682 (((class color) (background light)) (:foreground "Blue"))
1683 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1684 (t (:inverse-video t :bold t)))
1685 "Face used for level 1 headlines."
1688 (defface org-level-2 ;; font-lock-variable-name-face
1689 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1690 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1691 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1692 (t (:bold t :italic t)))
1693 "Face used for level 2 headlines."
1696 (defface org-level-3 ;; font-lock-keyword-face
1697 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1698 (((class color) (background light)) (:foreground "Purple"))
1699 (((class color) (background dark)) (:foreground "Cyan"))
1701 "Face used for level 3 headlines."
1704 (defface org-level-4 ;; font-lock-comment-face
1705 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1706 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1707 (((class color) (background light)) (:foreground "Firebrick"))
1708 (((class color) (background dark)) (:foreground "chocolate1"))
1709 (t (:bold t :italic t)))
1710 "Face used for level 4 headlines."
1713 (defface org-level-5 ;; font-lock-type-face
1714 '((((type tty) (class color)) (:foreground "green"))
1715 (((class color) (background light)) (:foreground "ForestGreen"))
1716 (((class color) (background dark)) (:foreground "PaleGreen"))
1717 (t (:bold t :underline t)))
1718 "Face used for level 5 headlines."
1721 (defface org-level-6 ;; font-lock-constant-face
1722 '((((type tty) (class color)) (:foreground "magenta"))
1723 (((class color) (background light)) (:foreground "CadetBlue"))
1724 (((class color) (background dark)) (:foreground "Aquamarine"))
1725 (t (:bold t :underline t)))
1726 "Face used for level 6 headlines."
1729 (defface org-level-7 ;; font-lock-builtin-face
1730 '((((type tty) (class color)) (:foreground "blue" :weight light))
1731 (((class color) (background light)) (:foreground "Orchid"))
1732 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1734 "Face used for level 7 headlines."
1737 (defface org-level-8 ;; font-lock-string-face
1738 '((((type tty) (class color)) (:foreground "green"))
1739 (((class color) (background light)) (:foreground "RosyBrown"))
1740 (((class color) (background dark)) (:foreground "LightSalmon"))
1742 "Face used for level 8 headlines."
1745 (defface org-special-keyword ;; font-lock-string-face
1746 '((((type tty) (class color)) (:foreground "green"))
1747 (((class color) (background light)) (:foreground "RosyBrown"))
1748 (((class color) (background dark)) (:foreground "LightSalmon"))
1750 "Face used for special keywords."
1753 (defface org-warning ;; font-lock-warning-face
1754 '((((type tty) (class color)) (:foreground "red"))
1755 (((class color) (background light)) (:foreground "Red" :bold t))
1756 (((class color) (background dark)) (:foreground "Red1" :bold t))
1757 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1758 (t (:inverse-video t :bold t)))
1759 "Face for deadlines and TODO keywords."
1762 (defcustom org-fontify-done-headline nil
1763 "Non-nil means, change the face of a headline if it is marked DONE.
1764 Normally, only the TODO/DONE keyword indicates the state of a headline.
1765 When this is non-nil, the headline after the keyword is set to the
1766 `org-headline-done' as an additional indication."
1770 (defface org-headline-done ;; font-lock-string-face
1771 '((((type tty) (class color)) (:foreground "green"))
1772 (((class color) (background light)) (:foreground "RosyBrown"))
1773 (((class color) (background dark)) (:foreground "LightSalmon"))
1775 "Face used to indicate that a headline is DONE. See also the variable
1776 `org-fontify-done-headline'."
1779 ;; Inheritance does not yet work for xemacs. So we just copy...
1781 (defface org-deadline-announce
1782 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1783 (((class color) (background light)) (:foreground "Blue"))
1784 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1785 (t (:inverse-video t :bold t)))
1786 "Face for upcoming deadlines."
1789 (defface org-scheduled-today
1790 '((((type tty) (class color)) (:foreground "green"))
1791 (((class color) (background light)) (:foreground "DarkGreen"))
1792 (((class color) (background dark)) (:foreground "PaleGreen"))
1793 (t (:bold t :underline t)))
1794 "Face for items scheduled for a certain day."
1797 (defface org-scheduled-previously
1798 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1799 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1800 (((class color) (background light)) (:foreground "Firebrick"))
1801 (((class color) (background dark)) (:foreground "chocolate1"))
1802 (t (:bold t :italic t)))
1803 "Face for items scheduled previously, and not yet done."
1806 (defface org-formula
1807 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1808 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1809 (((class color) (background light)) (:foreground "Firebrick"))
1810 (((class color) (background dark)) (:foreground "chocolate1"))
1811 (t (:bold t :italic t)))
1812 "Face for formulas."
1816 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1817 (((class color) (background light)) (:foreground "Purple"))
1818 (((class color) (background dark)) (:foreground "Cyan"))
1823 (defface org-done ;; font-lock-type-face
1824 '((((type tty) (class color)) (:foreground "green"))
1825 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1826 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1827 (t (:bold t :underline t)))
1828 "Face used for DONE."
1831 (defface org-table ;; font-lock-function-name-face
1832 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1833 (((class color) (background light)) (:foreground "Blue"))
1834 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1835 (t (:inverse-video t :bold t)))
1836 "Face used for tables."
1839 (defface org-time-grid ;; font-lock-variable-name-face
1840 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1841 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1842 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1843 (t (:bold t :italic t)))
1844 "Face used for time grids."
1847 (defvar org-level-faces
1858 (defvar org-n-levels (length org-level-faces))
1860 (defun org-set-regexps-and-options ()
1861 "Precompute regular expressions for current buffer."
1862 (when (eq major-mode 'org-mode)
1863 (let ((re (org-make-options-regexp
1864 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1865 "STARTUP" "ARCHIVE")))
1867 kwds int key value cat arch)
1871 (goto-char (point-min))
1872 (while (re-search-forward re nil t)
1873 (setq key (match-string 1) value (match-string 2))
1875 ((equal key "CATEGORY")
1876 (if (string-match "[ \t]+$" value)
1877 (setq value (replace-match "" t t value)))
1878 (setq cat (intern value)))
1879 ((equal key "SEQ_TODO")
1881 kwds (append kwds (org-split-string value splitre))))
1882 ((equal key "PRI_TODO")
1884 kwds (append kwds (org-split-string value splitre))))
1885 ((equal key "TYP_TODO")
1887 kwds (append kwds (org-split-string value splitre))))
1888 ((equal key "STARTUP")
1889 (let ((opts (org-split-string value splitre))
1890 (set '(("fold" org-startup-folded t)
1891 ("nofold" org-startup-folded nil)
1892 ("content" org-startup-folded content)
1893 ("dlcheck" org-startup-with-deadline-check t)
1894 ("nodlcheck" org-startup-with-deadline-check nil)))
1896 (while (setq l (assoc (pop opts) set))
1897 (setq var (nth 1 l) val (nth 2 l))
1898 (set (make-local-variable var) val))))
1899 ((equal key "ARCHIVE")
1900 (string-match " *$" value)
1901 (setq arch (replace-match "" t t value))
1902 (remove-text-properties 0 (length arch)
1903 '(face t fontified t) arch)))
1905 (and cat (set (make-local-variable 'org-category) cat))
1906 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
1907 (and arch (set (make-local-variable 'org-archive-location) arch))
1908 (and int (set (make-local-variable 'org-todo-interpretation) int)))
1909 ;; Compute the regular expressions and other local variables
1910 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
1911 org-todo-kwd-max-priority (1- (length org-todo-keywords))
1912 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
1913 (length org-scheduled-string)))
1915 (nth (1- (length org-todo-keywords)) org-todo-keywords)
1917 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
1921 (mapconcat 'regexp-quote
1922 (nreverse (cdr (reverse org-todo-keywords)))
1925 org-todo-line-regexp
1926 (concat "^\\(\\*+\\)[ \t]*\\("
1927 (mapconcat 'regexp-quote org-todo-keywords "\\|")
1930 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
1931 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
1932 org-deadline-regexp (concat "\\<" org-deadline-string)
1933 org-deadline-time-regexp
1934 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
1935 org-deadline-line-regexp
1936 (concat "\\<\\(" org-deadline-string "\\).*")
1937 org-scheduled-regexp
1938 (concat "\\<" org-scheduled-string)
1939 org-scheduled-time-regexp
1940 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
1941 (org-set-font-lock-defaults)))
1943 ;; Tell the compiler about dynamically scoped variables,
1944 ;; and variables from other packages
1946 (defvar zmacs-regions)
1947 (defvar original-date)
1948 (defvar org-transient-mark-mode)
1949 (defvar org-old-auto-fill-inhibit-regexp)
1950 (defvar orgtbl-mode-menu)
1951 (defvar org-html-entities)
1952 (defvar org-goto-start-pos)
1953 (defvar org-cursor-color)
1954 (defvar org-time-was-given)
1955 (defvar org-ts-what)
1956 (defvar mark-active)
1958 (defvar levels-open)
1969 (defvar starting-day)
1970 (defvar include-all-loc)
1971 (defvar vm-message-pointer)
1972 (defvar vm-folder-directory)
1973 (defvar wl-summary-buffer-elmo-folder)
1974 (defvar wl-summary-buffer-folder-name)
1975 (defvar gnus-group-name)
1976 (defvar gnus-article-current)
1977 (defvar w3m-current-url)
1979 (defvar mh-current-folder)
1980 (defvar mh-show-folder-buffer)
1981 (defvar mh-index-folder)
1982 (defvar org-selected-point)
1983 (defvar calendar-mode-map)
1984 (defvar remember-save-after-remembering)
1985 (defvar remember-data-file)
1991 (defvar org-mode-map (copy-keymap outline-mode-map)
1992 "Keymap for Org-mode.")
1994 (defvar org-struct-menu)
1995 (defvar org-org-menu)
1996 (defvar org-tbl-menu)
1998 ;; We use a before-change function to check if a table might need
2000 (defvar org-table-may-need-update t
2001 "Indicates that a table might need an update.
2002 This variable is set by `org-before-change-function'.
2003 `org-table-align'sets it back to nil.")
2004 (defvar org-mode-hook nil)
2005 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2006 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2010 (define-derived-mode org-mode outline-mode "Org"
2011 "Outline-based notes management and organizer, alias
2012 \"Carsten's outline-mode for keeping track of everything.\"
2014 Org-mode develops organizational tasks around a NOTES file which
2015 contains information about projects as plain text. Org-mode is
2016 implemented on top of outline-mode, which is ideal to keep the content
2017 of large files well structured. It supports ToDo items, deadlines and
2018 time stamps, which magically appear in the diary listing of the Emacs
2019 calendar. Tables are easily created with a built-in table editor.
2020 Plain text URL-like links connect to websites, emails (VM), Usenet
2021 messages (Gnus), BBDB entries, and any files related to the project.
2022 For printing and sharing of notes, an Org-mode file (or a part of it)
2023 can be exported as a structured ASCII or HTML file.
2025 The following commands are available:
2028 (easy-menu-add org-org-menu)
2029 (easy-menu-add org-tbl-menu)
2030 (org-install-agenda-files-menu)
2031 (setq outline-regexp "\\*+")
2032 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2033 (setq outline-level 'org-outline-level)
2034 (if org-startup-truncated (setq truncate-lines t))
2035 (org-set-regexps-and-options)
2036 (set (make-local-variable 'font-lock-unfontify-region-function)
2037 'org-unfontify-region)
2038 ;; Activate before-change-function
2039 (set (make-local-variable 'org-table-may-need-update) t)
2040 (org-add-hook 'before-change-functions 'org-before-change-function nil
2042 ;; Paragraphs and auto-filling
2043 (org-set-autofill-regexps)
2044 (org-update-radio-target-regexp)
2045 ;; Settings for Calc embedded mode
2046 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2047 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2048 (if (and org-insert-mode-line-in-empty-file
2050 (= (point-min) (point-max)))
2051 (insert " -*- mode: org -*-\n\n"))
2053 ;; Get rid of Outline menus, they are not needed
2054 ;; Need to do this here because define-derived-mode sets up
2055 ;; the keymap so late.
2058 (delete-menu-item '("Headings"))
2059 (delete-menu-item '("Show"))
2060 (delete-menu-item '("Hide"))
2061 (set-menubar-dirty-flag))
2062 (define-key org-mode-map [menu-bar headings] 'undefined)
2063 (define-key org-mode-map [menu-bar hide] 'undefined)
2064 (define-key org-mode-map [menu-bar show] 'undefined))
2066 (unless org-inhibit-startup
2067 (if org-startup-with-deadline-check
2068 (call-interactively 'org-check-deadlines)
2070 ((eq org-startup-folded t)
2072 ((eq org-startup-folded 'content)
2073 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2074 (org-cycle '(4)) (org-cycle '(4))))))))
2076 (defsubst org-current-line (&optional pos)
2077 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2080 ;; FIXME: Do we need to copy?
2081 (defun org-string-props (string &rest properties)
2082 "Add PROPERTIES to string."
2083 (add-text-properties 0 (length string) properties string)
2088 (defvar org-mouse-map (make-sparse-keymap))
2089 (define-key org-mouse-map
2090 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2091 (define-key org-mouse-map
2092 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2093 (when org-tab-follows-link
2094 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2095 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2096 (when org-return-follows-link
2097 (define-key org-mouse-map [(return)] 'org-open-at-point)
2098 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2100 (require 'font-lock)
2102 (defconst org-non-link-chars "\t\n\r|<>\000")
2103 (defconst org-link-regexp
2104 (if org-allow-space-in-links
2106 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|mhe\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2108 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|mhe\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2110 "Regular expression for matching links.")
2111 (defconst org-link-maybe-angles-regexp
2112 (concat "<?\\(" org-link-regexp "\\)>?")
2113 "Matches a link and optionally surrounding angle brackets.")
2114 (defconst org-protected-link-regexp
2115 (concat "\000" org-link-regexp "\000")
2116 "Matches a link and optionally surrounding angle brackets.")
2118 (defconst org-bracket-link-regexp
2119 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2120 "Matches a link in double brackets.")
2122 (defconst org-ts-lengths
2123 (cons (length (format-time-string (car org-time-stamp-formats)))
2124 (length (format-time-string (cdr org-time-stamp-formats))))
2125 "This holds the lengths of the two different time formats.")
2126 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2127 "Regular expression for fast time stamp matching.")
2128 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2129 "Regular expression for fast time stamp matching.")
2130 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2131 "Regular expression matching time strings for analysis.")
2132 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2133 "Regular expression matching time stamps, with groups.")
2134 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2135 "Regular expression matching a time stamp range.")
2136 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2137 org-ts-regexp "\\)?")
2138 "Regular expression matching a time stamp or time stamp range.")
2140 (defun org-activate-links (limit)
2141 "Run through the buffer and add overlays to links."
2142 (if (re-search-forward org-link-regexp limit t)
2144 (add-text-properties (match-beginning 0) (match-end 0)
2145 (list 'mouse-face 'highlight
2146 'keymap org-mouse-map))
2149 (defun org-activate-links2 (limit)
2150 "Run through the buffer and add overlays to links."
2151 (if (re-search-forward org-bracket-link-regexp limit t)
2153 (add-text-properties (match-beginning 0) (match-end 0)
2154 (list 'mouse-face 'highlight
2155 'keymap org-mouse-map))
2158 (defun org-activate-dates (limit)
2159 "Run through the buffer and add overlays to dates."
2160 (if (re-search-forward org-tsr-regexp limit t)
2162 (add-text-properties (match-beginning 0) (match-end 0)
2163 (list 'mouse-face 'highlight
2164 'keymap org-mouse-map))
2167 (defvar org-target-link-regexp nil
2168 "Regular expression matching radio targets in plain text.")
2169 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2170 "Regular expression matching a link target.")
2171 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2172 "Regular expression matching a link target.")
2174 (defun org-activate-target-links (limit)
2175 "Run through the buffer and add overlays to target matches."
2176 (when org-radio-targets
2177 (let ((case-fold-search t))
2178 (if (re-search-forward org-target-link-regexp limit t)
2180 (add-text-properties (match-beginning 0) (match-end 0)
2181 (list 'mouse-face 'highlight
2182 'keymap org-mouse-map
2183 'org-linked-text t))
2186 (defun org-update-radio-target-regexp ()
2187 "Find all radio targets in this file and update the regular expression."
2189 (when org-radio-targets
2190 (setq org-target-link-regexp
2191 (org-make-target-link-regexp (org-all-targets 'radio)))
2193 (font-lock-mode 1)))
2195 (defun org-all-targets (&optional radio)
2196 "Return a list of all targets in this file.
2197 With optional argument RADIO, only find radio targets."
2198 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2201 (goto-char (point-min))
2202 (while (re-search-forward re nil t)
2203 (add-to-list 'rtn (downcase (match-string-no-properties 1))))
2206 (defun org-make-target-link-regexp (targets)
2207 "Make regular expression matching all strings in TARGETS.
2208 The regular expression finds the targets also if there is a line break
2214 (while (string-match " +" x)
2215 (setq x (replace-match "\\s-+" t t x)))
2221 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2222 "Matches CamelCase words, possibly with a star before it.")
2224 (defun org-activate-camels (limit)
2225 "Run through the buffer and add overlays to dates."
2226 (if org-activate-camels
2227 (if (re-search-forward org-camel-regexp limit t)
2229 (add-text-properties (match-beginning 0) (match-end 0)
2230 (list 'mouse-face 'highlight
2231 'keymap org-mouse-map))
2234 (defun org-activate-tags (limit)
2235 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2237 (add-text-properties (match-beginning 1) (match-end 1)
2238 (list 'mouse-face 'highlight
2239 'keymap org-mouse-map))
2242 (defun org-font-lock-level ()
2244 (org-back-to-heading t)
2245 (- (match-end 0) (match-beginning 0))))
2247 (defun org-outline-level ()
2249 (looking-at outline-regexp)
2250 (if (match-beginning 1)
2251 (+ (org-get-string-indentation (match-string 1)) 1000)
2252 (- (match-end 0) (match-beginning 0)))))
2254 (defvar org-font-lock-keywords nil)
2256 (defun org-set-font-lock-defaults ()
2257 (let ((org-font-lock-extra-keywords
2259 '(org-activate-links (0 'org-link t))
2260 '(org-activate-links2 (0 'org-link t))
2261 '(org-activate-target-links (0 'org-link t))
2262 '(org-activate-dates (0 'org-link t))
2263 '(org-activate-camels (0 'org-link t))
2264 '(org-activate-tags (1 'org-link t))
2265 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2266 '(1 'org-warning t))
2267 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2268 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2269 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2270 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2271 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2273 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2275 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2277 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
2278 ; '(1 'org-warning t))
2279 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2280 "\\|" org-quote-string "\\)\\>")
2281 '(1 'org-special-keyword t))
2282 '("^#.*" (0 'font-lock-comment-face t))
2283 (if org-fontify-done-headline
2284 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2285 '(1 'org-done t) '(2 'org-headline-done t))
2286 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2288 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2290 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2291 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2292 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2294 (set (make-local-variable 'org-font-lock-keywords)
2296 (if org-noutline-p ; FIXME: I am not sure if eval will work
2297 ; on XEmacs if noutline is ever ported
2298 `((eval . (list "^\\(\\*+\\).*"
2299 ,(if org-level-color-stars-only 1 0)
2301 (% (- (match-end 1) (match-beginning 1) 1)
2305 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2306 (,(if org-level-color-stars-only 2 0)
2307 (nth (% (- (match-end 2) (match-beginning 2) 1)
2311 org-font-lock-extra-keywords))
2312 (set (make-local-variable 'font-lock-defaults)
2313 '(org-font-lock-keywords t nil nil backward-paragraph))
2314 (kill-local-variable 'font-lock-keywords) nil))
2316 (defun org-unfontify-region (beg end &optional maybe_loudly)
2317 "Remove fontification and activation overlays from links."
2318 (font-lock-default-unfontify-region beg end)
2319 (let* ((buffer-undo-list t)
2320 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2321 (inhibit-modification-hooks t)
2322 deactivate-mark buffer-file-name buffer-file-truename)
2323 (remove-text-properties beg end
2324 '(mouse-face nil keymap nil org-linked-text nil))))
2326 ;;; Visibility cycling
2328 (defvar org-cycle-global-status nil)
2329 (defvar org-cycle-subtree-status nil)
2330 (defun org-cycle (&optional arg)
2331 "Visibility cycling for Org-mode.
2333 - When this function is called with a prefix argument, rotate the entire
2334 buffer through 3 states (global cycling)
2335 1. OVERVIEW: Show only top-level headlines.
2336 2. CONTENTS: Show all headlines of all levels, but no body text.
2337 3. SHOW ALL: Show everything.
2339 - When point is at the beginning of a headline, rotate the subtree started
2340 by this line through 3 different states (local cycling)
2341 1. FOLDED: Only the main headline is shown.
2342 2. CHILDREN: The main headline and the direct children are shown.
2343 From this state, you can move to one of the children
2344 and zoom in further.
2345 3. SUBTREE: Show the entire subtree, including body text.
2347 - When there is a numeric prefix, go up to a heading with level ARG, do
2348 a `show-subtree' and return to the previous cursor position. If ARG
2349 is negative, go up that many levels.
2351 - When point is not at the beginning of a headline, execute
2352 `indent-relative', like TAB normally does. See the option
2353 `org-cycle-emulate-tab' for details.
2355 - Special case: if point is the the beginning of the buffer and there is
2356 no headline in line 1, this function will act as if called with prefix arg."
2359 (if (or (and (bobp) (not (looking-at outline-regexp)))
2361 ;; special case: use global cycling
2364 (let ((outline-regexp
2365 (if org-cycle-include-plain-lists
2366 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2371 ((org-at-table-p 'any)
2372 ;; Enter the table or move to the next field in the table
2373 (or (org-table-recognize-table.el)
2375 (org-table-justify-field-maybe)
2376 (org-table-next-field))))
2378 ((eq arg t) ;; Global cycling
2381 ((and (eq last-command this-command)
2382 (eq org-cycle-global-status 'overview))
2383 ;; We just created the overview - now do table of contents
2384 ;; This can be slow in very large buffers, so indicate action
2385 (message "CONTENTS...")
2387 ;; Visit all headings and show their offspring
2388 (goto-char (point-max))
2390 (while (and (progn (condition-case nil
2391 (outline-previous-visible-heading 1)
2392 (error (goto-char (point-min))))
2394 (looking-at outline-regexp))
2396 (if (bobp) (throw 'exit nil))))
2397 (message "CONTENTS...done"))
2398 (setq org-cycle-global-status 'contents)
2399 (run-hook-with-args 'org-cycle-hook 'contents))
2401 ((and (eq last-command this-command)
2402 (eq org-cycle-global-status 'contents))
2403 ;; We just showed the table of contents - now show everything
2405 (message "SHOW ALL")
2406 (setq org-cycle-global-status 'all)
2407 (run-hook-with-args 'org-cycle-hook 'all))
2410 ;; Default action: go to overview
2412 (message "OVERVIEW")
2413 (setq org-cycle-global-status 'overview)
2414 (run-hook-with-args 'org-cycle-hook 'overview))))
2417 ;; Show-subtree, ARG levels up from here.
2419 (org-back-to-heading)
2420 (outline-up-heading (if (< arg 0) (- arg)
2421 (- (outline-level) arg)))
2422 (org-show-subtree)))
2424 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2425 ;; At a heading: rotate between three different views
2426 (org-back-to-heading)
2427 (let ((goal-column 0) eoh eol eos)
2428 ;; First, some boundaries
2430 (org-back-to-heading)
2432 (beginning-of-line 2)
2433 (while (and (not (eobp)) ;; this is like `next-line'
2434 (get-char-property (1- (point)) 'invisible))
2435 (beginning-of-line 2)) (setq eol (point)))
2436 (outline-end-of-heading) (setq eoh (point))
2437 (org-end-of-subtree t) (setq eos (point))
2438 (outline-next-heading))
2439 ;; Find out what to do next and set `this-command'
2442 ;; Nothing is hidden behind this heading
2443 (message "EMPTY ENTRY")
2444 (setq org-cycle-subtree-status nil))
2446 ;; Entire subtree is hidden in one line: open it
2449 (message "CHILDREN")
2450 (setq org-cycle-subtree-status 'children)
2451 (run-hook-with-args 'org-cycle-hook 'children))
2452 ((and (eq last-command this-command)
2453 (eq org-cycle-subtree-status 'children))
2454 ;; We just showed the children, now show everything.
2457 (setq org-cycle-subtree-status 'subtree)
2458 (run-hook-with-args 'org-cycle-hook 'subtree))
2460 ;; Default action: hide the subtree.
2463 (setq org-cycle-subtree-status 'folded)
2464 (run-hook-with-args 'org-cycle-hook 'folded)))))
2467 (buffer-read-only (org-back-to-heading))
2468 ((if (and (eq org-cycle-emulate-tab 'white)
2469 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2471 (eq org-cycle-emulate-tab t))
2472 (if (and (looking-at "[ \n\r\t]")
2473 (string-match "^[ \t]*$" (buffer-substring
2474 (point-at-bol) (point))))
2476 (beginning-of-line 1)
2477 (and (looking-at "[ \t]+") (replace-match ""))))
2481 (org-back-to-heading)
2484 (defun org-optimize-window-after-visibility-change (state)
2485 "Adjust the window after a change in outline visibility.
2486 This function is the default value of the hook `org-cycle-hook'."
2488 ((eq state 'overview) (org-first-headline-recenter 1))
2489 ((eq state 'content) nil)
2490 ((eq state 'all) nil)
2491 ((eq state 'folded) nil)
2492 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2493 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2495 (defun org-subtree-end-visible-p ()
2496 "Is the end of the current subtree visible?"
2497 (pos-visible-in-window-p
2498 (save-excursion (org-end-of-subtree t) (point))))
2500 (defun org-first-headline-recenter (&optional N)
2501 "Move cursor to the first headline and recenter the headline.
2502 Optional argument N means, put the headline into the Nth line of the window."
2503 (goto-char (point-min))
2504 (when (re-search-forward (concat "^" outline-regexp) nil t)
2506 (recenter (prefix-numeric-value N))))
2508 (defvar org-goto-window-configuration nil)
2509 (defvar org-goto-marker nil)
2510 (defvar org-goto-map (make-sparse-keymap))
2511 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2512 (while (setq cmd (pop cmds))
2513 (substitute-key-definition cmd cmd org-goto-map global-map)))
2514 (define-key org-goto-map "\C-m" 'org-goto-ret)
2515 (define-key org-goto-map [(left)] 'org-goto-left)
2516 (define-key org-goto-map [(right)] 'org-goto-right)
2517 (define-key org-goto-map [(?q)] 'org-goto-quit)
2518 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2519 (define-key org-goto-map "\C-i" 'org-cycle)
2520 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2521 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2522 (define-key org-goto-map "n" 'outline-next-visible-heading)
2523 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2524 (define-key org-goto-map "f" 'outline-forward-same-level)
2525 (define-key org-goto-map "b" 'outline-backward-same-level)
2526 (define-key org-goto-map "u" 'outline-up-heading)
2527 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2528 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2529 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2530 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2531 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2532 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2533 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2535 (defconst org-goto-help
2536 "Select a location to jump to, press RET
2537 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2540 "Go to a different location of the document, keeping current visibility.
2542 When you want to go to a different location in a document, the fastest way
2543 is often to fold the entire buffer and then dive into the tree. This
2544 method has the disadvantage, that the previous location will be folded,
2545 which may not be what you want.
2547 This command works around this by showing a copy of the current buffer in
2548 overview mode. You can dive into the tree in that copy, to find the
2549 location you want to reach. When pressing RET, the command returns to the
2550 original buffer in which the visibility is still unchanged. It then jumps
2551 to the new location, making it and the headline hierarchy above it visible."
2553 (let* ((org-goto-start-pos (point))
2555 (org-get-location (current-buffer) org-goto-help)))
2558 (org-mark-ring-push org-goto-start-pos)
2559 (goto-char selected-point)
2560 (if (or (org-invisible-p) (org-invisible-p2))
2561 (org-show-hierarchy-above)))
2564 (defun org-get-location (buf help)
2565 "Let the user select a location in the Org-mode buffer BUF.
2566 This function uses a recursive edit. It returns the selected position
2568 (let (org-selected-point)
2570 (save-window-excursion
2571 (delete-other-windows)
2572 (switch-to-buffer (get-buffer-create "*org-goto*"))
2573 (with-output-to-temp-buffer "*Help*"
2575 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2576 (setq buffer-read-only nil)
2578 (insert-buffer-substring buf)
2579 (let ((org-startup-truncated t)
2580 (org-startup-folded t)
2581 (org-startup-with-deadline-check nil))
2583 (setq buffer-read-only t)
2584 (if (boundp 'org-goto-start-pos)
2585 (goto-char org-goto-start-pos)
2586 (goto-char (point-min)))
2587 (org-beginning-of-line)
2588 (message "Select location and press RET")
2589 ;; now we make sure that during selection, ony very few keys work
2590 ;; and that it is impossible to switch to another window.
2591 (let ((gm (current-global-map))
2592 (overriding-local-map org-goto-map))
2595 (use-global-map org-goto-map)
2597 (use-global-map gm)))))
2598 (kill-buffer "*org-goto*")
2599 org-selected-point))
2601 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2602 (defun org-goto-ret (&optional arg)
2603 "Finish `org-goto' by going to the new location."
2605 (setq org-selected-point (point)
2606 current-prefix-arg arg)
2609 (defun org-goto-left ()
2610 "Finish `org-goto' by going to the new location."
2612 (if (org-on-heading-p)
2614 (beginning-of-line 1)
2615 (setq org-selected-point (point)
2616 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2618 (error "Not on a heading")))
2620 (defun org-goto-right ()
2621 "Finish `org-goto' by going to the new location."
2623 (if (org-on-heading-p)
2625 (outline-end-of-subtree)
2626 (or (eobp) (forward-char 1))
2627 (setq org-selected-point (point)
2628 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2630 (error "Not on a heading")))
2632 (defun org-goto-quit ()
2633 "Finish `org-goto' without cursor motion."
2635 (setq org-selected-point nil)
2638 ;;; Promotion, Demotion, Inserting new headlines
2640 (defvar org-ignore-region nil
2641 "To temporarily disable the active region.")
2643 (defun org-insert-heading (&optional force-heading)
2644 "Insert a new heading or item with same depth at point."
2646 (when (or force-heading (not (org-insert-item)))
2647 (let* ((head (save-excursion
2649 (org-back-to-heading)
2650 (error (outline-next-heading)))
2651 (prog1 (match-string 0)
2652 (funcall outline-level)))))
2653 (unless (bolp) (newline))
2656 (save-excursion (newline-and-indent)))
2657 (unless (equal (char-before) ?\ )
2659 (run-hooks 'org-insert-heading-hook))))
2661 (defun org-insert-item ()
2662 "Insert a new item at the current level.
2663 Return t when things worked, nil when we are not in an item."
2664 (when (save-excursion
2667 (org-beginning-of-item)
2671 (unless (bolp) (newline))
2672 (insert (match-string 0))
2673 (org-maybe-renumber-ordered-list)
2676 (defun org-insert-todo-heading (arg)
2677 "Insert a new heading with the same level and TODO state as current heading.
2678 If the heading has no TODO state, or if the state is DONE, use the first
2679 state (TODO by default). Also with prefix arg, force first state."
2681 (org-insert-heading)
2683 (org-back-to-heading)
2684 (outline-previous-heading)
2685 (looking-at org-todo-line-regexp))
2687 (not (match-beginning 2))
2688 (equal (match-string 2) org-done-string))
2689 (insert (car org-todo-keywords) " ")
2690 (insert (match-string 2) " ")))
2692 (defun org-promote-subtree ()
2693 "Promote the entire subtree.
2694 See also `org-promote'."
2697 (org-map-tree 'org-promote)))
2699 (defun org-demote-subtree ()
2700 "Demote the entire subtree. See `org-demote'.
2701 See also `org-promote'."
2704 (org-map-tree 'org-demote)))
2706 (defun org-do-promote ()
2707 "Promote the current heading higher up the tree.
2708 If the region is active in `transient-mark-mode', promote all headings
2712 (if (org-region-active-p)
2713 (org-map-region 'org-promote (region-beginning) (region-end))
2715 (org-fix-position-after-promote))
2717 (defun org-do-demote ()
2718 "Demote the current heading lower down the tree.
2719 If the region is active in `transient-mark-mode', demote all headings
2723 (if (org-region-active-p)
2724 (org-map-region 'org-demote (region-beginning) (region-end))
2726 (org-fix-position-after-promote))
2728 (defun org-fix-position-after-promote ()
2729 "Make sure that after pro/demotion cursor position is right."
2730 (and (equal (char-after) ?\ )
2731 (equal (char-before) ?*)
2734 (defun org-promote ()
2735 "Promote the current heading higher up the tree.
2736 If the region is active in `transient-mark-mode', promote all headings
2738 (org-back-to-heading t)
2739 (let* ((level (save-match-data (funcall outline-level)))
2740 (up-head (make-string (1- level) ?*)))
2741 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2742 (replace-match up-head nil t)
2743 ;; Fixup tag positioning
2744 (and org-auto-align-tags (org-set-tags nil t))
2745 (if org-adapt-indentation
2746 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2748 (defun org-demote ()
2749 "Demote the current heading lower down the tree.
2750 If the region is active in `transient-mark-mode', demote all headings
2752 (org-back-to-heading t)
2753 (let* ((level (save-match-data (funcall outline-level)))
2754 (down-head (make-string (1+ level) ?*)))
2755 (replace-match down-head nil t)
2756 ;; Fixup tag positioning
2757 (and org-auto-align-tags (org-set-tags nil t))
2758 (if org-adapt-indentation
2759 (org-fixup-indentation "^ " " " "^\\S-"))))
2761 (defun org-map-tree (fun)
2762 "Call FUN for every heading underneath the current one."
2763 (org-back-to-heading)
2764 (let ((level (outline-level)))
2768 (outline-next-heading)
2769 (> (funcall outline-level) level))
2773 (defun org-map-region (fun beg end)
2774 "Call FUN for every heading between BEG and END."
2775 (let ((org-ignore-region t))
2777 (setq end (copy-marker end))
2779 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2783 (outline-next-heading)
2788 (defun org-fixup-indentation (from to prohibit)
2789 "Change the indentation in the current entry by re-replacing FROM with TO.
2790 However, if the regexp PROHIBIT matches at all, don't do anything.
2791 This is being used to change indentation along with the length of the
2792 heading marker. But if there are any lines which are not indented, nothing
2795 (let ((end (save-excursion (outline-next-heading)
2797 (unless (save-excursion (re-search-forward prohibit end t))
2798 (while (re-search-forward from end t)
2800 (beginning-of-line 2)))
2801 (move-marker end nil))))
2803 ;;; Vertical tree motion, cutting and pasting of subtrees
2805 (defun org-move-subtree-up (&optional arg)
2806 "Move the current subtree up past ARG headlines of the same level."
2808 (org-move-subtree-down (- (prefix-numeric-value arg))))
2810 (defun org-move-subtree-down (&optional arg)
2811 "Move the current subtree down past ARG headlines of the same level."
2813 (setq arg (prefix-numeric-value arg))
2814 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2815 'outline-get-last-sibling))
2816 (ins-point (make-marker))
2820 (org-back-to-heading)
2823 (save-excursion (outline-end-of-heading)
2824 (setq folded (org-invisible-p)))
2825 (outline-end-of-subtree))
2826 (outline-next-heading)
2828 ;; Find insertion point, with error handling
2831 (or (and (funcall movfunc) (looking-at outline-regexp))
2832 (progn (goto-char beg)
2833 (error "Cannot move past superior level or buffer limit")))
2834 (setq cnt (1- cnt)))
2836 ;; Moving forward - still need to move over subtree
2837 (progn (outline-end-of-subtree)
2838 (outline-next-heading)
2839 (if (not (or (looking-at (concat "^" outline-regexp))
2842 (move-marker ins-point (point))
2843 (setq txt (buffer-substring beg end))
2844 (delete-region beg end)
2846 (goto-char ins-point)
2847 (if folded (hide-subtree))
2848 (move-marker ins-point nil)))
2850 (defvar org-subtree-clip ""
2851 "Clipboard for cut and paste of subtrees.
2852 This is actually only a copy of the kill, because we use the normal kill
2853 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2855 (defvar org-subtree-clip-folded nil
2856 "Was the last copied subtree folded?
2857 This is used to fold the tree back after pasting.")
2859 (defun org-cut-subtree ()
2860 "Cut the current subtree into the clipboard.
2861 This is a short-hand for marking the subtree and then cutting it."
2863 (org-copy-subtree 'cut))
2865 (defun org-copy-subtree (&optional cut)
2866 "Cut the current subtree into the clipboard.
2867 This is a short-hand for marking the subtree and then copying it.
2868 If CUT is non nil, actually cut the subtree."
2870 (let (beg end folded)
2871 (org-back-to-heading)
2874 (save-excursion (outline-end-of-heading)
2875 (setq folded (org-invisible-p)))
2876 (outline-end-of-subtree))
2877 (if (equal (char-after) ?\n) (forward-char 1))
2881 (setq org-subtree-clip-folded folded)
2882 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2883 (setq org-subtree-clip (current-kill 0))
2884 (message "%s: Subtree with %d characters"
2885 (if cut "Cut" "Copied")
2886 (length org-subtree-clip)))))
2888 (defun org-paste-subtree (&optional level tree)
2889 "Paste the clipboard as a subtree, with modification of headline level.
2890 The entire subtree is promoted or demoted in order to match a new headline
2891 level. By default, the new level is derived from the visible headings
2892 before and after the insertion point, and taken to be the inferior headline
2893 level of the two. So if the previous visible heading is level 3 and the
2894 next is level 4 (or vice versa), level 4 will be used for insertion.
2895 This makes sure that the subtree remains an independent subtree and does
2896 not swallow low level entries.
2898 You can also force a different level, either by using a numeric prefix
2899 argument, or by inserting the heading marker by hand. For example, if the
2900 cursor is after \"*****\", then the tree will be shifted to level 5.
2902 If you want to insert the tree as is, just use \\[yank].
2904 If optional TREE is given, use this text instead of the kill ring."
2906 (unless (org-kill-is-subtree-p tree)
2908 (substitute-command-keys
2909 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2910 (let* ((txt (or tree (current-kill 0)))
2911 (^re (concat "^\\(" outline-regexp "\\)"))
2912 (re (concat "\\(" outline-regexp "\\)"))
2913 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2915 (old-level (if (string-match ^re txt)
2916 (- (match-end 0) (match-beginning 0))
2918 (force-level (cond (level (prefix-numeric-value level))
2920 ^re_ (buffer-substring (point-at-bol) (point)))
2921 (- (match-end 0) (match-beginning 0)))
2923 (previous-level (save-excursion
2926 (outline-previous-visible-heading 1)
2928 (- (match-end 0) (match-beginning 0))
2931 (next-level (save-excursion
2934 (outline-next-visible-heading 1)
2936 (- (match-end 0) (match-beginning 0))
2939 (new-level (or force-level (max previous-level next-level)))
2940 (shift (if (or (= old-level -1)
2942 (= old-level new-level))
2944 (- new-level old-level)))
2946 (delta (if (> shift 0) -1 1))
2947 (func (if (> shift 0) 'org-demote 'org-promote))
2949 ;; Remove the forces level indicator
2951 (delete-region (point-at-bol) (point)))
2952 ;; Make sure we start at the beginning of an empty line
2953 (if (not (bolp)) (insert "\n"))
2954 (if (not (looking-at "[ \t]*$"))
2955 (progn (insert "\n") (backward-char 1)))
2961 ;; Shift if necessary
2963 (message "Pasted at level %d, without shift" new-level)
2965 (narrow-to-region beg end)
2966 (while (not (= shift 0))
2967 (org-map-region func (point-min) (point-max))
2968 (setq shift (+ delta shift)))
2969 (goto-char (point-min))
2970 (message "Pasted at level %d, with shift by %d levels"
2972 (if (and (eq org-subtree-clip (current-kill 0))
2973 org-subtree-clip-folded)
2974 ;; The tree was folded before it was killed/copied
2977 (defun org-kill-is-subtree-p (&optional txt)
2978 "Check if the current kill is an outline subtree, or a set of trees.
2979 Returns nil if kill does not start with a headline, or if the first
2980 headline level is not the largest headline level in the tree.
2981 So this will actually accept several entries of equal levels as well,
2982 which is OK for `org-paste-subtree'.
2983 If optional TXT is given, check this string instead of the current kill."
2984 (let* ((kill (or txt (current-kill 0) ""))
2985 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2986 (- (match-end 0) (match-beginning 0))))
2987 (re (concat "^" outline-regexp))
2989 (if (not start-level)
2990 nil ;; does not even start with a heading
2992 (while (setq start (string-match re kill (1+ start)))
2993 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2997 ;;; Plain list items
2999 (defun org-at-item-p ()
3000 "Is point in a line starting a hand-formatted item?"
3001 (let ((llt org-plain-list-ordered-item-terminator))
3003 (goto-char (point-at-bol))
3006 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3007 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3008 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3009 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3011 (defun org-get-indentation ()
3012 "Get the indentation of the current line, interpreting tabs."
3014 (beginning-of-line 1)
3015 (skip-chars-forward " \t")
3018 (defun org-beginning-of-item ()
3019 "Go to the beginning of the current hand-formatted item.
3020 If the cursor is not in an item, throw an error."
3022 (limit (save-excursion (org-back-to-heading)
3023 (beginning-of-line 2) (point)))
3026 (beginning-of-line 1)
3027 (beginning-of-line 1)
3028 (skip-chars-forward " \t")
3029 (setq ind (current-column))
3032 (beginning-of-line 0)
3033 (if (< (point) limit) (throw 'exit nil))
3034 (unless (looking-at " \t]*$")
3035 (skip-chars-forward " \t")
3036 (setq ind1 (current-column))
3038 (throw 'exit (org-at-item-p))))))
3041 (error "Not in an item")))))
3043 (defun org-end-of-item ()
3044 "Go to the end of the current hand-formatted item.
3045 If the cursor is not in an item, throw an error."
3047 (limit (save-excursion (outline-next-heading) (point)))
3048 (ind (save-excursion
3049 (org-beginning-of-item)
3050 (skip-chars-forward " \t")
3055 (beginning-of-line 2)
3056 (if (>= (point) limit) (throw 'exit t))
3057 (unless (looking-at "[ \t]*$")
3058 (skip-chars-forward " \t")
3059 (setq ind1 (current-column))
3060 (if (<= ind1 ind) (throw 'exit t)))))
3061 (beginning-of-line 1)
3063 (error "Not in an item"))))
3065 (defun org-move-item-down (arg)
3066 "Move the plain list item at point down, i.e. swap with following item.
3067 Subitems (items with larger indentation) are considered part of the item,
3068 so this really moves item trees."
3070 (let (beg end ind ind1 (pos (point)) txt)
3071 (org-beginning-of-item)
3073 (setq ind (org-get-indentation))
3076 (setq ind1 (org-get-indentation))
3077 (if (and (org-at-item-p) (= ind ind1))
3080 (setq txt (buffer-substring beg end))
3082 (delete-region beg end))
3086 (org-maybe-renumber-ordered-list))
3088 (error "Cannot move this item further down"))))
3090 (defun org-move-item-up (arg)
3091 "Move the plain list item at point up, i.e. swap with previous item.
3092 Subitems (items with larger indentation) are considered part of the item,
3093 so this really moves item trees."
3095 (let (beg end ind ind1 (pos (point)) txt)
3096 (org-beginning-of-item)
3098 (setq ind (org-get-indentation))
3104 (beginning-of-line 0)
3105 (if (looking-at "[ \t]*$")
3107 (if (<= (setq ind1 (org-get-indentation)) ind)
3110 (org-beginning-of-item)
3111 (error (goto-char beg)
3112 (error "Cannot move this item further up")))
3113 (setq ind1 (org-get-indentation))
3114 (if (and (org-at-item-p) (= ind ind1))
3116 (setq txt (buffer-substring beg end))
3118 (delete-region beg end))
3122 (org-maybe-renumber-ordered-list))
3124 (error "Cannot move this item further up"))))
3126 (defun org-maybe-renumber-ordered-list ()
3127 "Renumber the ordered list at point if setup allows it.
3128 This tests the user option `org-auto-renumber-ordered-lists' before
3129 doing the renumbering."
3130 (and org-auto-renumber-ordered-lists
3133 (org-renumber-ordered-list 1)))
3135 (defun org-get-string-indentation (s)
3136 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3137 (let ((n -1) (i 0) (w tab-width) c)
3139 (while (< (setq n (1+ n)) (length s))
3141 (cond ((= c ?\ ) (setq i (1+ i)))
3142 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3143 (t (throw 'exit t)))))
3146 (defun org-renumber-ordered-list (arg)
3147 "Renumber an ordered plain list.
3148 Cursor next to be in the first line of an item, the line that starts
3149 with something like \"1.\" or \"2)\"."
3151 (unless (and (org-at-item-p)
3152 (match-beginning 3))
3153 (error "This is not an ordered list"))
3154 (let ((line (org-current-line))
3155 (col (current-column))
3156 (ind (org-get-string-indentation
3157 (buffer-substring (point-at-bol) (match-beginning 3))))
3158 ;; (term (substring (match-string 3) -1))
3160 ;; find where this list begins
3164 (beginning-of-line 0)
3165 (if (looking-at "[ \t]*$") (throw 'next t))
3166 (skip-chars-forward " \t") (setq ind1 (current-column))
3167 (if (or (< ind1 ind)
3169 (not (org-at-item-p))))
3171 ;; Walk forward and replace these numbers
3175 (beginning-of-line 2)
3176 (if (eobp) (throw 'exit nil))
3177 (if (looking-at "[ \t]*$") (throw 'next nil))
3178 (skip-chars-forward " \t") (setq ind1 (current-column))
3179 (if (> ind1 ind) (throw 'next t))
3180 (if (< ind1 ind) (throw 'exit t))
3181 (if (not (org-at-item-p)) (throw 'exit nil))
3182 (if (not (match-beginning 3))
3183 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3184 (delete-region (match-beginning 3) (1- (match-end 3)))
3185 (goto-char (match-beginning 3))
3186 (insert (format "%d" (setq n (1+ n)))))))
3188 (move-to-column col)))
3190 (defvar org-last-indent-begin-marker (make-marker))
3191 (defvar org-last-indent-end-marker (make-marker))
3194 (defun org-outdent-item (arg)
3195 "Outdent a local list item."
3197 (org-indent-item (- arg)))
3199 (defun org-indent-item (arg)
3200 "Indent a local list item."
3202 (unless (org-at-item-p)
3203 (error "Not on an item"))
3204 (let (beg end ind ind1)
3205 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3206 (setq beg org-last-indent-begin-marker
3207 end org-last-indent-end-marker)
3208 (org-beginning-of-item)
3209 (setq beg (move-marker org-last-indent-begin-marker (point)))
3211 (setq end (move-marker org-last-indent-end-marker (point))))
3213 (skip-chars-forward " \t") (setq ind (current-column))
3214 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3215 (while (< (point) end)
3216 (beginning-of-line 1)
3217 (skip-chars-forward " \t") (setq ind1 (current-column))
3218 (delete-region (point-at-bol) (point))
3219 (indent-to-column (+ ind1 arg))
3220 (beginning-of-line 2))
3225 (defun org-archive-subtree ()
3226 "Move the current subtree to the archive.
3227 The archive can be a certain top-level heading in the current file, or in
3228 a different file. The tree will be moved to that location, the subtree
3229 heading be marked DONE, and the current time will be added."
3231 ;; Save all relevant TODO keyword-relatex variables
3232 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3233 (tr-org-todo-keywords org-todo-keywords)
3234 (tr-org-todo-interpretation org-todo-interpretation)
3235 (tr-org-done-string org-done-string)
3236 (tr-org-todo-regexp org-todo-regexp)
3237 (tr-org-todo-line-regexp org-todo-line-regexp)
3238 (this-buffer (current-buffer))
3239 file heading buffer level newfile-p)
3240 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3242 (setq file (format (match-string 1 org-archive-location)
3243 (file-name-nondirectory (buffer-file-name)))
3244 heading (match-string 2 org-archive-location)))
3245 (error "Invalid `org-archive-location'"))
3246 (if (> (length file) 0)
3247 (setq newfile-p (not (file-exists-p file))
3248 buffer (find-file-noselect file))
3249 (setq buffer (current-buffer)))
3251 (error "Cannot access file \"%s\"" file))
3252 (if (and (> (length heading) 0)
3253 (string-match "^\\*+" heading))
3254 (setq level (match-end 0))
3255 (setq heading nil level 0))
3257 ;; We first only copy, in case something goes wrong
3258 ;; we need to protect this-command, to avoid kill-region sets it,
3259 ;; which would lead to duplication of subtrees
3260 (let (this-command) (org-copy-subtree))
3262 ;; Enforce org-mode for the archive buffer
3263 (if (not (eq major-mode 'org-mode))
3264 ;; Force the mode for future visits.
3265 (let ((org-insert-mode-line-in-empty-file t))
3266 (call-interactively 'org-mode)))
3268 (goto-char (point-max))
3269 (insert (format "\nArchived entries from file %s\n\n"
3270 (buffer-file-name this-buffer))))
3271 ;; Force the TODO keywords of the original buffer
3272 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3273 (org-todo-keywords tr-org-todo-keywords)
3274 (org-todo-interpretation tr-org-todo-interpretation)
3275 (org-done-string tr-org-done-string)
3276 (org-todo-regexp tr-org-todo-regexp)
3277 (org-todo-line-regexp tr-org-todo-line-regexp))
3278 (goto-char (point-min))
3281 (if (re-search-forward
3282 (concat "\\(^\\|\r\\)"
3283 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3285 (goto-char (match-end 0))
3286 ;; Heading not found, just insert it at the end
3287 (goto-char (point-max))
3288 (or (bolp) (insert "\n"))
3289 (insert "\n" heading "\n")
3291 ;; Make the heading visible, and the following as well
3292 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3293 (if (re-search-forward
3294 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3296 (progn (goto-char (match-beginning 0)) (insert "\n")
3297 (beginning-of-line 0))
3298 (goto-char (point-max)) (insert "\n")))
3299 (goto-char (point-max)) (insert "\n"))
3301 (org-paste-subtree (1+ level))
3302 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3303 (if org-archive-mark-done
3304 (org-todo (length org-todo-keywords)))
3305 ;; Move cursor to right after the TODO keyword
3306 (when org-archive-stamp-time
3307 (beginning-of-line 1)
3308 (looking-at org-todo-line-regexp)
3309 (goto-char (or (match-end 2) (match-beginning 3)))
3310 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3313 ;; Save the buffer, if it is not the same buffer.
3314 (if (not (eq this-buffer buffer)) (save-buffer))))
3315 ;; Here we are back in the original buffer. Everything seems to have
3316 ;; worked. So now cut the tree and finish up.
3317 (let (this-command) (org-cut-subtree))
3318 (if (looking-at "[ \t]*$") (kill-line))
3319 (message "Subtree archived %s"
3320 (if (eq this-buffer buffer)
3321 (concat "under heading: " heading)
3322 (concat "in file: " (abbreviate-file-name file))))))
3326 (defun org-complete (&optional arg)
3327 "Perform completion on word at point.
3328 At the beginning of a headline, this completes TODO keywords as given in
3329 `org-todo-keywords'.
3330 If the current word is preceded by a backslash, completes the TeX symbols
3331 that are supported for HTML support.
3332 If the current word is preceded by \"#+\", completes special words for
3333 setting file options.
3334 At all other locations, this simply calls `ispell-complete-word'."
3337 (let* ((end (point))
3338 (beg1 (save-excursion
3339 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3340 (skip-chars-backward "a-zA-Z_@0-9")
3342 (beg (save-excursion
3343 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3344 (skip-chars-backward "a-zA-Z0-9_:$")
3346 (camel (equal (char-before beg) ?*))
3347 (tag (equal (char-before beg1) ?:))
3348 (texp (equal (char-before beg) ?\\))
3349 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3352 (completion-ignore-case opt)
3359 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3360 (cons (match-string 2 x) (match-string 1 x)))
3361 (org-split-string (org-get-current-options) "\n")))
3365 ((string-match "\\`\\*+[ \t]*\\'"
3366 (buffer-substring (point-at-bol) beg))
3368 (mapcar 'list org-todo-keywords))
3372 (goto-char (point-min))
3373 (while (re-search-forward org-todo-line-regexp nil t)
3375 (if org-file-link-context-use-camel-case
3376 (org-make-org-heading-camel (match-string 3) t)
3377 (org-make-org-heading-search-string
3378 (match-string 3) t)))
3381 (tag (setq type :tag beg beg1)
3382 (org-get-buffer-tags))
3383 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3384 (pattern (buffer-substring-no-properties beg end))
3385 (completion (try-completion pattern table)))
3386 (cond ((eq completion t)
3387 (if (equal type :opt)
3388 (insert (substring (cdr (assoc (upcase pattern) table))
3389 (length pattern)))))
3391 (message "Can't find completion for \"%s\"" pattern)
3393 ((not (string= pattern completion))
3394 (delete-region beg end)
3395 (if (string-match " +$" completion)
3396 (setq completion (replace-match "" t t completion)))
3398 (if (get-buffer-window "*Completions*")
3399 (delete-window (get-buffer-window "*Completions*")))
3400 (if (assoc completion table)
3401 (if (eq type :todo) (insert " ")
3402 (if (eq type :tag) (insert ":"))))
3403 (if (and (equal type :opt) (assoc completion table))
3404 (message "%s" (substitute-command-keys
3405 "Press \\[org-complete] again to insert example settings"))))
3407 (message "Making completion list...")
3408 (let ((list (sort (all-completions pattern table) 'string<)))
3409 (with-output-to-temp-buffer "*Completions*"
3410 (display-completion-list list)))
3411 (message "Making completion list...%s" "done"))))))
3413 ;;; Comments, TODO and DEADLINE
3415 (defun org-toggle-comment ()
3416 "Change the COMMENT state of an entry."
3419 (org-back-to-heading)
3420 (if (looking-at (concat outline-regexp
3421 "\\( +\\<" org-comment-string "\\>\\)"))
3422 (replace-match "" t t nil 1)
3423 (if (looking-at outline-regexp)
3425 (goto-char (match-end 0))
3426 (insert " " org-comment-string))))))
3428 (defvar org-last-todo-state-is-todo nil
3429 "This is non-nil when the last TODO state change led to a TODO state.
3430 If the last change removed the TODO tag or switched to DONE, then
3433 (defun org-todo (&optional arg)
3434 "Change the TODO state of an item.
3435 The state of an item is given by a keyword at the start of the heading,
3437 *** TODO Write paper
3440 The different keywords are specified in the variable `org-todo-keywords'.
3441 By default the available states are \"TODO\" and \"DONE\".
3442 So for this example: when the item starts with TODO, it is changed to DONE.
3443 When it starts with DONE, the DONE is removed. And when neither TODO nor
3444 DONE are present, add TODO at the beginning of the heading.
3446 With prefix arg, use completion to determine the new state. With numeric
3447 prefix arg, switch to that state."
3450 (org-back-to-heading)
3451 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3452 (or (looking-at (concat " +" org-todo-regexp " *"))
3454 (let* ((this (match-string 1))
3455 (completion-ignore-case t)
3456 (member (member this org-todo-keywords))
3460 ;; Read a state with completion
3461 (completing-read "State: " (mapcar (lambda(x) (list x))
3466 (if tail (car tail) nil)
3467 (car org-todo-keywords)))
3469 (if (equal member org-todo-keywords)
3472 (nth (- (length org-todo-keywords) (length tail) 2)
3476 ;; user requests a specific state
3477 (nth (1- (prefix-numeric-value arg))
3479 ((null member) (car org-todo-keywords))
3480 ((null tail) nil) ;; -> first entry
3481 ((eq org-todo-interpretation 'sequence)
3483 ((memq org-todo-interpretation '(type priority))
3484 (if (eq this-command last-command)
3486 (if (> (length tail) 0) org-done-string nil)))
3488 (next (if state (concat " " state " ") " ")))
3489 (replace-match next t t)
3490 (setq org-last-todo-state-is-todo
3491 (not (equal state org-done-string)))
3493 (if (equal state org-done-string)
3497 ;; Fixup tag positioning
3498 (and org-auto-align-tags (org-set-tags nil t))
3499 (run-hooks 'org-after-todo-state-change-hook)))
3500 ;; Fixup cursor location if close to the keyword
3501 (if (and (outline-on-heading-p)
3503 (save-excursion (beginning-of-line 1)
3504 (looking-at org-todo-line-regexp))
3505 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3507 (goto-char (or (match-end 2) (match-end 1)))
3510 (defun org-log-done (&optional undone)
3511 "Add a time stamp logging that a TODO entry has been closed.
3512 When UNDONE is non-nil, remove such a time stamp again."
3516 (org-back-to-heading t)
3518 (looking-at (concat outline-regexp " *"))
3519 (goto-char (match-end 0))
3520 (setq col (current-column))
3521 (outline-next-heading)
3524 (when (re-search-forward (concat
3526 (regexp-quote org-closed-string)
3527 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3528 (delete-region (match-beginning 1) (match-end 1)))
3530 (org-back-to-heading t)
3531 (skip-chars-forward "^\n\r")
3532 (goto-char (min (1+ (point)) (point-max)))
3533 (when (not (member (char-before) '(?\r ?\n)))
3536 (insert org-closed-string " "
3538 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3542 (defun org-show-todo-tree (arg)
3543 "Make a compact tree which shows all headlines marked with TODO.
3544 The tree will show the lines where the regexp matches, and all higher
3545 headlines above the match.
3546 With \\[universal-argument] prefix, also show the DONE entries.
3547 With a numeric prefix N, construct a sparse tree for the Nth element
3548 of `org-todo-keywords'."
3550 (let ((case-fold-search nil)
3552 (cond ((null arg) org-not-done-regexp)
3553 ((equal arg '(4)) org-todo-regexp)
3554 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3555 (regexp-quote (nth (1- (prefix-numeric-value arg))
3556 org-todo-keywords)))
3557 (t (error "Invalid prefix argument: %s" arg)))))
3558 (message "%d TODO entries found"
3559 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3561 (defun org-deadline ()
3562 "Insert the DEADLINE: string to make a deadline.
3563 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3564 to modify it to the correct date."
3567 org-deadline-string " "
3568 (format-time-string (car org-time-stamp-formats)
3569 (org-read-date nil 'to-time)))
3570 (message "%s" (substitute-command-keys
3571 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3573 (defun org-schedule ()
3574 "Insert the SCHEDULED: string to schedule a TODO item.
3575 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3576 to modify it to the correct date."
3579 org-scheduled-string " "
3580 (format-time-string (car org-time-stamp-formats)
3581 (org-read-date nil 'to-time)))
3582 (message "%s" (substitute-command-keys
3583 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3586 (defun org-occur (regexp &optional callback)
3587 "Make a compact tree which shows all matches of REGEXP.
3588 The tree will show the lines where the regexp matches, and all higher
3589 headlines above the match. It will also show the heading after the match,
3590 to make sure editing the matching entry is easy.
3591 If CALLBACK is non-nil, it is a function which is called to confirm
3592 that the match should indeed be shown."
3593 (interactive "sRegexp: ")
3594 (org-remove-occur-highlights nil nil t)
3595 (setq regexp (org-check-occur-regexp regexp))
3598 (goto-char (point-min))
3600 (while (re-search-forward regexp nil t)
3601 (when (or (not callback)
3602 (save-match-data (funcall callback)))
3604 (org-highlight-new-match (match-beginning 0) (match-end 0))
3605 (org-show-hierarchy-above))))
3606 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
3608 (run-hooks 'org-occur-hook)
3610 (message "%d match(es) for regexp %s" cnt regexp))
3613 (defun org-show-hierarchy-above ()
3614 "Make sure point and the headings hierarchy above is visible."
3616 (if (org-on-heading-p t)
3617 (org-flag-heading nil) ; only show the heading
3618 (and (or (org-invisible-p) (org-invisible-p2))
3619 (org-show-hidden-entry))) ; show entire entry
3621 (and org-show-following-heading
3622 (outline-next-heading)
3623 (org-flag-heading nil))) ; show the next heading
3624 (when org-show-hierarchy-above
3625 (save-excursion ; show all higher headings
3626 (while (and (condition-case nil
3627 (progn (org-up-heading-all 1) t)
3630 (org-flag-heading nil))))))
3632 ;; Overlay compatibility functions
3633 (defun org-make-overlay (beg end &optional buffer)
3634 (if org-xemacs-p (make-extent beg end buffer) (make-overlay beg end buffer)))
3635 (defun org-delete-overlay (ovl)
3636 (if org-xemacs-p (delete-extent ovl) (delete-overlay ovl)))
3637 (defun org-detatch-overlay (ovl)
3638 (if org-xemacs-p (detach-extent ovl) (delete-overlay ovl)))
3639 (defun org-move-overlay (ovl beg end &optional buffer)
3641 (set-extent-endpoints ovl beg end buffer)
3642 (move-overlay ovl beg end buffer)))
3643 (defun org-overlay-put (ovl prop value)
3645 (set-extent-property ovl prop value)
3646 (overlay-put ovl prop value)))
3648 (defvar org-occur-highlights nil)
3649 (defun org-highlight-new-match (beg end)
3650 "Highlight from BEG to END and mark the highlight is an occur headline."
3651 (let ((ov (org-make-overlay beg end)))
3652 (org-overlay-put ov 'face 'secondary-selection)
3653 (push ov org-occur-highlights)))
3655 (defun org-remove-occur-highlights (&optional beg end noremove)
3656 "Remove the occur highlights from the buffer.
3657 BEG and END are ignored. If NOREMOVE is nil, remove this function
3658 from the `before-change-functions' in the current buffer."
3660 (mapc 'org-delete-overlay org-occur-highlights)
3661 (setq org-occur-highlights nil)
3663 (remove-hook 'before-change-functions
3664 'org-remove-occur-highlights 'local)))
3668 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3669 "Regular expression matching the priority indicator.")
3671 (defvar org-remove-priority-next-time nil)
3673 (defun org-priority-up ()
3674 "Increase the priority of the current item."
3678 (defun org-priority-down ()
3679 "Decrease the priority of the current item."
3681 (org-priority 'down))
3683 (defun org-priority (&optional action)
3684 "Change the priority of an item by ARG.
3685 ACTION can be set, up, or down."
3687 (setq action (or action 'set))
3688 (let (current new news have remove)
3690 (org-back-to-heading)
3691 (if (looking-at org-priority-regexp)
3692 (setq current (string-to-char (match-string 2))
3694 (setq current org-default-priority))
3697 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3698 (setq new (read-char-exclusive))
3699 (cond ((equal new ?\ ) (setq remove t))
3700 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3701 (error "Priority must be between `%c' and `%c'"
3702 ?A org-lowest-priority))))
3704 (setq new (1- current)))
3706 (setq new (1+ current)))
3707 (t (error "Invalid action")))
3708 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3709 (setq news (format "%c" new))
3712 (replace-match "" t t nil 1)
3713 (replace-match news t t nil 2))
3715 (error "No priority cookie found in line")
3716 (looking-at org-todo-line-regexp)
3719 (goto-char (match-end 2))
3720 (insert " [#" news "]"))
3721 (goto-char (match-beginning 3))
3722 (insert "[#" news "] ")))))
3724 (message "Priority removed")
3725 (message "Priority of current item set to %s" news))))
3728 (defun org-get-priority (s)
3729 "Find priority cookie and return priority."
3731 (if (not (string-match org-priority-regexp s))
3732 (* 1000 (- org-lowest-priority org-default-priority))
3733 (* 1000 (- org-lowest-priority
3734 (string-to-char (match-string 2 s)))))))
3738 (defvar org-last-changed-timestamp nil)
3740 (defun org-time-stamp (arg)
3741 "Prompt for a date/time and insert a time stamp.
3742 If the user specifies a time like HH:MM, or if this command is called
3743 with a prefix argument, the time stamp will contain date and time.
3744 Otherwise, only the date will be included. All parts of a date not
3745 specified by the user will be filled in from the current date/time.
3746 So if you press just return without typing anything, the time stamp
3747 will represent the current date/time. If there is already a timestamp
3748 at the cursor, it will be modified."
3750 (let ((fmt (if arg (cdr org-time-stamp-formats)
3751 (car org-time-stamp-formats)))
3752 (org-time-was-given nil)
3755 ((and (org-at-timestamp-p)
3756 (eq last-command 'org-time-stamp)
3757 (eq this-command 'org-time-stamp))
3759 (setq time (let ((this-command this-command))
3760 (org-read-date arg 'totime)))
3761 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3762 (insert (format-time-string fmt time)))
3763 ((org-at-timestamp-p)
3764 (setq time (let ((this-command this-command))
3765 (org-read-date arg 'totime)))
3766 (and (org-at-timestamp-p) (replace-match
3767 (setq org-last-changed-timestamp
3768 (format-time-string fmt time))
3770 (message "Timestamp updated"))
3772 (setq time (let ((this-command this-command))
3773 (org-read-date arg 'totime)))
3774 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3775 (insert (format-time-string fmt time))))))
3777 (defun org-time-stamp-inactive (&optional arg)
3778 "Insert an inactive time stamp.
3779 An inactive time stamp is enclosed in square brackets instead of angle
3780 brackets. It is inactive in the sense that it does not trigger agenda entries,
3781 does not link to the calendar and cannot be changed with the S-cursor keys.
3782 So these are more for recording a certain time/date."
3783 ;; FIXME: Would it be better not to ask for a date/time here?
3785 (let ((fmt (if arg (cdr org-time-stamp-formats)
3786 (car org-time-stamp-formats)))
3787 (org-time-was-given nil)
3789 (setq time (org-read-date arg 'totime))
3790 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3791 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3792 (insert (format-time-string fmt time))))
3794 (defvar org-date-ovl (org-make-overlay 1 1))
3795 (org-overlay-put org-date-ovl 'face 'org-warning)
3796 (org-detatch-overlay org-date-ovl)
3798 ;;; FIXME: Make the function take "Fri" as "next friday"
3799 ;;; because these are mostly being used to record the current time.
3800 (defun org-read-date (&optional with-time to-time)
3801 "Read a date and make things smooth for the user.
3802 The prompt will suggest to enter an ISO date, but you can also enter anything
3803 which will at least partially be understood by `parse-time-string'.
3804 Unrecognized parts of the date will default to the current day, month, year,
3805 hour and minute. For example,
3806 3-2-5 --> 2003-02-05
3807 feb 15 --> currentyear-02-15
3808 sep 12 9 --> 2009-09-12
3809 12:45 --> today 12:45
3810 22 sept 0:34 --> currentyear-09-22 0:34
3811 12 --> currentyear-currentmonth-12
3813 The function understands only English month and weekday abbreviations,
3814 but this can be configured with the variables `parse-time-months' and
3815 `parse-time-weekdays'.
3817 While prompting, a calendar is popped up - you can also select the
3818 date with the mouse (button 1). The calendar shows a period of three
3819 months. To scroll it to other months, use the keys `>' and `<'.
3820 If you don't like the calendar, turn it off with
3821 \(setq org-popup-calendar-for-date-prompt nil)
3823 With optional argument TO-TIME, the date will immediately be converted
3824 to an internal time.
3825 With an optional argument WITH-TIME, the prompt will suggest to also
3826 insert a time. Note that when WITH-TIME is not set, you can still
3827 enter a time, and this function will inform the calling routine about
3828 this change. The calling routine may then choose to change the format
3829 used to insert the time stamp into the buffer to include the time."
3830 (let* ((default-time
3831 ;; Default time is either today, or, when entering a range,
3835 (concat org-ts-regexp "--\\=")
3839 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3840 (parse-time-string (match-string 1))))
3842 (calendar-move-hook nil)
3843 (view-diary-entries-initially nil)
3844 (timestr (format-time-string
3845 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3846 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3848 second minute hour day month year tl)
3850 (if org-popup-calendar-for-date-prompt
3851 ;; Also show a calendar for date selection
3852 ;; Copied (with modifications) from planner.el by John Wiegley
3854 (save-window-excursion
3856 (calendar-forward-day (- (time-to-days default-time)
3857 (calendar-absolute-from-gregorian
3858 (calendar-current-date))))
3859 (org-eval-in-calendar nil)
3860 (let* ((old-map (current-local-map))
3861 (map (copy-keymap calendar-mode-map))
3862 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3863 (define-key map (kbd "RET") 'org-calendar-select)
3864 (define-key map (if org-xemacs-p [button1] [mouse-1])
3865 'org-calendar-select-mouse)
3866 (define-key map (if org-xemacs-p [button2] [mouse-2])
3867 'org-calendar-select-mouse)
3868 (define-key minibuffer-local-map [(meta shift left)]
3869 (lambda () (interactive)
3870 (org-eval-in-calendar '(calendar-backward-month 1))))
3871 (define-key minibuffer-local-map [(meta shift right)]
3872 (lambda () (interactive)
3873 (org-eval-in-calendar '(calendar-forward-month 1))))
3874 (define-key minibuffer-local-map [(shift up)]
3875 (lambda () (interactive)
3876 (org-eval-in-calendar '(calendar-backward-week 1))))
3877 (define-key minibuffer-local-map [(shift down)]
3878 (lambda () (interactive)
3879 (org-eval-in-calendar '(calendar-forward-week 1))))
3880 (define-key minibuffer-local-map [(shift left)]
3881 (lambda () (interactive)
3882 (org-eval-in-calendar '(calendar-backward-day 1))))
3883 (define-key minibuffer-local-map [(shift right)]
3884 (lambda () (interactive)
3885 (org-eval-in-calendar '(calendar-forward-day 1))))
3886 (define-key minibuffer-local-map ">"
3887 (lambda () (interactive)
3888 (org-eval-in-calendar '(scroll-calendar-left 1))))
3889 (define-key minibuffer-local-map "<"
3890 (lambda () (interactive)
3891 (org-eval-in-calendar '(scroll-calendar-right 1))))
3895 (setq ans (read-string prompt "" nil nil))
3896 (if (not (string-match "\\S-" ans)) (setq ans nil))
3897 (setq ans (or ans1 ans ans2)))
3898 (use-local-map old-map)))))
3899 ;; Naked prompt only
3900 (setq ans (read-string prompt "" nil timestr)))
3901 (org-detatch-overlay org-date-ovl)
3904 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3906 (setq year (if (match-end 2)
3907 (string-to-number (match-string 2 ans))
3908 (string-to-number (format-time-string "%Y")))
3909 month (string-to-number (match-string 3 ans))
3910 day (string-to-number (match-string 4 ans)))
3911 (if (< year 100) (setq year (+ 2000 year)))
3912 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3914 (setq tl (parse-time-string ans)
3915 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3916 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3917 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3918 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3919 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3920 second (or (nth 0 tl) 0))
3921 (if (and (boundp 'org-time-was-given)
3923 (setq org-time-was-given t))
3924 (if (< year 100) (setq year (+ 2000 year)))
3926 (encode-time second minute hour day month year)
3927 (if (or (nth 1 tl) (nth 2 tl))
3928 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3929 (format "%04d-%02d-%02d" year month day)))))
3931 (defun org-eval-in-calendar (form)
3932 "Eval FORM in the calendar window and return to current window.
3933 Also, store the cursor date in variable ans2."
3934 (let ((sw (selected-window)))
3935 (select-window (get-buffer-window "*Calendar*"))
3937 (when (calendar-cursor-to-date)
3938 (let* ((date (calendar-cursor-to-date))
3939 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3940 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3941 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
3942 (select-window sw)))
3944 (defun org-calendar-select ()
3945 "Return to `org-read-date' with the date currently selected.
3946 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3948 (when (calendar-cursor-to-date)
3949 (let* ((date (calendar-cursor-to-date))
3950 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3951 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3952 (if (active-minibuffer-window) (exit-minibuffer))))
3954 (defun org-calendar-select-mouse (ev)
3955 "Return to `org-read-date' with the date currently selected.
3956 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3958 (mouse-set-point ev)
3959 (when (calendar-cursor-to-date)
3960 (let* ((date (calendar-cursor-to-date))
3961 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3962 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3963 (if (active-minibuffer-window) (exit-minibuffer))))
3965 (defun org-check-deadlines (ndays)
3966 "Check if there are any deadlines due or past due.
3967 A deadline is considered due if it happens within `org-deadline-warning-days'
3968 days from today's date. If the deadline appears in an entry marked DONE,
3969 it is not shown. The prefix arg NDAYS can be used to test that many
3970 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3972 (let* ((org-warn-days
3974 ((equal ndays '(4)) 100000)
3975 (ndays (prefix-numeric-value ndays))
3976 (t org-deadline-warning-days)))
3977 (case-fold-search nil)
3978 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3981 (and (let ((d1 (time-to-days (current-time)))
3983 (org-time-string-to-time (match-string 1)))))
3984 (< (- d2 d1) org-warn-days))
3985 (not (org-entry-is-done-p))))))
3986 (message "%d deadlines past-due or due within %d days"
3987 (org-occur regexp callback)
3990 (defun org-evaluate-time-range (&optional to-buffer)
3991 "Evaluate a time range by computing the difference between start and end.
3992 Normally the result is just printed in the echo area, but with prefix arg
3993 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3994 If the time range is actually in a table, the result is inserted into the
3996 For time difference computation, a year is assumed to be exactly 365
3997 days in order to avoid rounding problems."
4000 (unless (org-at-date-range-p)
4001 (goto-char (point-at-bol))
4002 (re-search-forward org-tr-regexp (point-at-eol) t))
4003 (if (not (org-at-date-range-p))
4004 (error "Not at a time-stamp range, and none found in current line")))
4005 (let* ((ts1 (match-string 1))
4006 (ts2 (match-string 2))
4007 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4008 (match-end (match-end 0))
4009 (time1 (org-time-string-to-time ts1))
4010 (time2 (org-time-string-to-time ts2))
4011 (t1 (time-to-seconds time1))
4012 (t2 (time-to-seconds time2))
4013 (diff (abs (- t2 t1)))
4014 (negative (< (- t2 t1) 0))
4015 ;; (ys (floor (* 365 24 60 60)))
4018 (fy "%dy %dd %02d:%02d")
4020 (fd "%dd %02d:%02d")
4024 ;; FIXME: Should I re-introduce years, make year refer to same date?
4025 ;; This would be the only useful way to have years, actually.
4027 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4029 d (floor (/ diff ds)) diff (mod diff ds)
4030 h (floor (/ diff hs)) diff (mod diff hs)
4031 m (floor (/ diff 60)))
4032 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4034 d (floor (+ (/ diff ds) 0.5))
4037 (message (org-make-tdiff-string y d h m))
4038 (when (org-at-table-p)
4039 (goto-char match-end)
4041 (and (looking-at " *|") (goto-char (match-end 0))))
4043 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4045 (if negative (insert " -"))
4046 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4047 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4048 (insert " " (format fh h m))))
4049 (if align (org-table-align))
4050 (message "Time difference inserted"))))
4052 (defun org-make-tdiff-string (y d h m)
4055 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4057 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4059 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4061 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4063 (apply 'format fmt (nreverse l))))
4065 (defun org-time-string-to-time (s)
4066 (apply 'encode-time (org-parse-time-string s)))
4068 (defun org-parse-time-string (s &optional nodefault)
4069 "Parse the standard Org-mode time string.
4070 This should be a lot faster than the normal `parse-time-string'.
4071 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4072 hour and minute fields will be nil if not given."
4073 (if (string-match org-ts-regexp1 s)
4075 (if (or (match-beginning 8) (not nodefault))
4076 (string-to-number (or (match-string 8 s) "0")))
4077 (if (or (match-beginning 7) (not nodefault))
4078 (string-to-number (or (match-string 7 s) "0")))
4079 (string-to-number (match-string 4 s))
4080 (string-to-number (match-string 3 s))
4081 (string-to-number (match-string 2 s))
4085 (defun org-timestamp-up (&optional arg)
4086 "Increase the date item at the cursor by one.
4087 If the cursor is on the year, change the year. If it is on the month or
4088 the day, change that.
4089 With prefix ARG, change by that many units."
4091 (org-timestamp-change (prefix-numeric-value arg)))
4093 (defun org-timestamp-down (&optional arg)
4094 "Decrease the date item at the cursor by one.
4095 If the cursor is on the year, change the year. If it is on the month or
4096 the day, change that.
4097 With prefix ARG, change by that many units."
4099 (org-timestamp-change (- (prefix-numeric-value arg))))
4101 (defun org-timestamp-up-day (&optional arg)
4102 "Increase the date in the time stamp by one day.
4103 With prefix ARG, change that many days."
4105 (if (and (not (org-at-timestamp-p))
4108 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4110 (defun org-timestamp-down-day (&optional arg)
4111 "Decrease the date in the time stamp by one day.
4112 With prefix ARG, change that many days."
4114 (if (and (not (org-at-timestamp-p))
4117 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4119 (defsubst org-pos-in-match-range (pos n)
4120 (and (match-beginning n)
4121 (<= (match-beginning n) pos)
4122 (>= (match-end n) pos)))
4124 (defun org-at-timestamp-p ()
4125 "Determine if the cursor is in or at a timestamp."
4127 (let* ((tsr org-ts-regexp2)
4129 (ans (or (looking-at tsr)
4131 (skip-chars-backward "^<\n\r\t")
4132 (if (> (point) 1) (backward-char 1))
4133 (and (looking-at tsr)
4134 (> (- (match-end 0) pos) -1))))))
4135 (and (boundp 'org-ts-what)
4138 ((org-pos-in-match-range pos 2) 'year)
4139 ((org-pos-in-match-range pos 3) 'month)
4140 ((org-pos-in-match-range pos 7) 'hour)
4141 ((org-pos-in-match-range pos 8) 'minute)
4142 ((or (org-pos-in-match-range pos 4)
4143 (org-pos-in-match-range pos 5)) 'day)
4147 (defun org-timestamp-change (n &optional what)
4148 "Change the date in the time stamp at point.
4149 The date will be changed by N times WHAT. WHAT can be `day', `month',
4150 `year', `minute', `second'. If WHAT is not given, the cursor position
4151 in the timestamp determines what will be changed."
4152 (let ((fmt (car org-time-stamp-formats))
4156 (if (not (org-at-timestamp-p))
4157 (error "Not at a timestamp"))
4158 (setq org-ts-what (or what org-ts-what))
4159 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4160 (- (match-end 0) (match-beginning 0))))
4162 (cdr org-time-stamp-formats)
4163 (car org-time-stamp-formats)))
4164 (setq ts (match-string 0))
4166 (setq time0 (org-parse-time-string ts))
4170 (list (or (car time0) 0))
4171 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4172 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4173 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4174 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4175 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4177 (if (eq what 'calendar)
4181 (set-buffer "*Calendar*")
4182 (calendar-cursor-to-date)))))
4183 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4184 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4185 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4186 (setcar time0 (or (car time0) 0))
4187 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4188 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4189 (setq time (apply 'encode-time time0))))
4190 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4192 ;; Try to recenter the calendar window, if any
4193 (if (and org-calendar-follow-timestamp-change
4194 (get-buffer-window "*Calendar*" t)
4195 (memq org-ts-what '(day month year)))
4196 (org-recenter-calendar (time-to-days time)))))
4198 (defun org-recenter-calendar (date)
4199 "If the calendar is visible, recenter it to DATE."
4200 (let* ((win (selected-window))
4201 (cwin (get-buffer-window "*Calendar*" t))
4202 (calendar-move-hook nil))
4204 (select-window cwin)
4205 (calendar-goto-date (if (listp date) date
4206 (calendar-gregorian-from-absolute date)))
4207 (select-window win))))
4209 (defun org-goto-calendar (&optional arg)
4210 "Go to the Emacs calendar at the current date.
4211 If there is a time stamp in the current line, go to that date.
4212 A prefix ARG can be used to force the current date."
4214 (let ((tsr org-ts-regexp) diff
4215 (calendar-move-hook nil)
4216 (view-diary-entries-initially nil))
4217 (if (or (org-at-timestamp-p)
4219 (beginning-of-line 1)
4220 (looking-at (concat ".*" tsr))))
4221 (let ((d1 (time-to-days (current-time)))
4223 (org-time-string-to-time (match-string 1)))))
4224 (setq diff (- d2 d1))))
4226 (calendar-goto-today)
4227 (if (and diff (not arg)) (calendar-forward-day diff))))
4229 (defun org-date-from-calendar ()
4230 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4231 If there is already a time stamp at the cursor position, update it."
4233 (org-timestamp-change 0 'calendar))
4235 ;;; Agenda, and Diary Integration
4239 (defvar org-agenda-mode-map (make-sparse-keymap)
4240 "Keymap for `org-agenda-mode'.")
4242 (defvar org-agenda-menu)
4243 (defvar org-agenda-follow-mode nil)
4244 (defvar org-agenda-show-log nil)
4245 (defvar org-agenda-buffer-name "*Org Agenda*")
4246 (defvar org-agenda-redo-command nil)
4247 (defvar org-agenda-mode-hook nil)
4248 (defvar org-agenda-type nil)
4249 (defvar org-agenda-force-single-file nil)
4252 (defun org-agenda-mode ()
4253 "Mode for time-sorted view on action items in Org-mode files.
4255 The following commands are available:
4257 \\{org-agenda-mode-map}"
4259 (kill-all-local-variables)
4260 (setq major-mode 'org-agenda-mode)
4261 (setq mode-name "Org-Agenda")
4262 (use-local-map org-agenda-mode-map)
4263 (easy-menu-add org-agenda-menu)
4264 (if org-startup-truncated (setq truncate-lines t))
4265 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4266 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4267 (unless org-agenda-keep-modes
4268 (setq org-agenda-follow-mode nil
4269 org-agenda-show-log nil))
4271 '("Agenda") "Agenda Files"
4275 (if (get 'org-agenda-files 'org-restrict)
4276 "Restricted to single file"
4278 '(customize-variable 'org-agenda-files)
4279 (not (get 'org-agenda-files 'org-restrict)))
4281 (mapcar 'org-file-menu-entry (org-agenda-files))))
4282 (org-agenda-set-mode-name)
4284 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4285 (list 'org-agenda-mode-hook)))
4287 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4288 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4289 (define-key org-agenda-mode-map " " 'org-agenda-show)
4290 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4291 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4292 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4293 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4294 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4295 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4296 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4297 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4298 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4299 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4300 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4301 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4303 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4304 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4305 (while l (define-key org-agenda-mode-map
4306 (int-to-string (pop l)) 'digit-argument)))
4308 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4309 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4310 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4311 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4312 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4313 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4314 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4315 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4316 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4317 (define-key org-agenda-mode-map "n" 'next-line)
4318 (define-key org-agenda-mode-map "p" 'previous-line)
4319 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4320 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4321 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4322 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4323 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4324 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4325 (eval-after-load "calendar"
4326 '(define-key calendar-mode-map org-calendar-to-agenda-key
4327 'org-calendar-goto-agenda))
4328 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4329 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4330 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4331 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4332 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4333 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4334 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4335 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4336 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4337 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4338 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4339 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4340 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4341 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4342 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4343 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4344 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4345 "Local keymap for agenda entries from Org-mode.")
4347 (define-key org-agenda-keymap
4348 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4349 (define-key org-agenda-keymap
4350 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4352 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4356 ["Show" org-agenda-show t]
4357 ["Go To (other window)" org-agenda-goto t]
4358 ["Go To (one window)" org-agenda-switch-to t]
4359 ["Follow Mode" org-agenda-follow-mode
4360 :style toggle :selected org-agenda-follow-mode :active t]
4362 ["Cycle TODO" org-agenda-todo t]
4364 ["Show all Tags" org-agenda-show-tags t]
4365 ["Set Tags" org-agenda-set-tags t])
4367 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4368 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4370 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4372 ["Set Priority" org-agenda-priority t]
4373 ["Increase Priority" org-agenda-priority-up t]
4374 ["Decrease Priority" org-agenda-priority-down t]
4375 ["Show Priority" org-agenda-show-priority t])
4377 ;; ["New agenda command" org-agenda t]
4378 ["Rebuild buffer" org-agenda-redo t]
4380 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4381 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4382 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4384 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4385 :style radio :selected (equal org-agenda-ndays 1)]
4386 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4387 :style radio :selected (equal org-agenda-ndays 7)]
4389 ["Show Logbook entries" org-agenda-log-mode
4390 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4391 ["Include Diary" org-agenda-toggle-diary
4392 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4393 ["Use Time Grid" org-agenda-toggle-time-grid
4394 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4396 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4397 ("Calendar Commands"
4398 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4399 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4400 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4401 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4402 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4403 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4405 ["Quit" org-agenda-quit t]
4406 ["Exit and Release Buffers" org-agenda-exit t]
4410 (defun org-agenda (arg)
4411 "Dispatch agenda commands to collect entries to the agenda buffer.
4412 Prompts for a character to select a command. Any prefix arg will be passed
4413 on to the selected command. The default selections are:
4415 a Call `org-agenda' to display the agenda for the current day or week.
4416 t Call `org-todo-list' to display the global todo list.
4417 T Call `org-todo-list' to display the global todo list, select only
4418 entries with a specific TODO keyword (the user gets a prompt).
4419 m Call `org-tags-view' to display headlines with tags matching
4420 a condition (the user is prompted for the condition).
4421 M Like `m', but select only TODO entries, no ordinary headlines.
4423 More commands can be added by configuring the variable
4424 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4425 searches can be pre-defined in this way.
4427 If the current buffer is in Org-mode and visiting a file, you can also
4428 first press `1' to indicate that the agenda should be temporarily (until the
4429 next use of \\[org-agenda]) restricted to the current file."
4432 (let ((restrict-ok (and (buffer-file-name) (eq major-mode 'org-mode)))
4433 (custom org-agenda-custom-commands)
4434 c entry key type string)
4435 (put 'org-agenda-files 'org-restrict nil)
4436 (save-window-excursion
4437 (delete-other-windows)
4438 (switch-to-buffer-other-window " *Agenda Commands*")
4441 "Press key for an agenda command:
4442 --------------------------------
4443 a Agenda for current week or day
4444 t List of all TODO entries T Entries with special TODO kwd
4445 m Match a TAGS query M Like m, but only TODO entries
4446 C Configure your own agenda commands")
4447 (while (setq entry (pop custom))
4448 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4449 (insert (format "\n%-4s%-14s: %s"
4452 ((eq type 'tags) "Tags query")
4453 ((eq type 'todo) "TODO keyword")
4454 ((eq type 'tags-tree) "Tags tree")
4455 ((eq type 'todo-tree) "TODO kwd tree")
4456 ((eq type 'occur-tree) "Occur tree")
4458 (org-string-props string 'face 'org-link))))
4459 (goto-char (point-min))
4460 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4461 (message "Press key for agenda command%s"
4462 (if restrict-ok ", or [1] to restrict to current file" ""))
4463 (setq c (read-char-exclusive))
4467 (put 'org-agenda-files 'org-restrict (list (buffer-file-name)))
4468 (error "Cannot restrict agenda to current buffer"))
4469 (message "Press key for agenda command%s"
4470 (if restrict-ok " (restricted to current file)" ""))
4471 (setq c (read-char-exclusive))
4473 (require 'calendar) ; FIXME: can we avoid this for some commands?
4474 ;; For example the todo list should not need it (but does...)
4476 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4477 ((equal c ?a) (call-interactively 'org-agenda-list))
4478 ((equal c ?t) (call-interactively 'org-todo-list))
4480 (setq current-prefix-arg (or arg '(4)))
4481 (call-interactively 'org-todo-list))
4482 ((equal c ?m) (call-interactively 'org-tags-view))
4484 (setq current-prefix-arg (or arg '(4)))
4485 (call-interactively 'org-tags-view))
4486 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4487 (setq type (nth 1 entry) string (nth 2 entry))
4490 (org-tags-view current-prefix-arg string))
4492 (org-todo-list string))
4493 ((eq type 'tags-tree)
4494 (org-check-for-org-mode)
4495 (org-tags-sparse-tree current-prefix-arg string))
4496 ((eq type 'todo-tree)
4497 (org-check-for-org-mode)
4498 (org-occur (concat "^" outline-regexp "[ \t]*"
4499 (regexp-quote string) "\\>")))
4500 ((eq type 'occur-tree)
4501 (org-check-for-org-mode)
4503 (t (error "Invalid custom agenda command type %s" type))))
4504 (t (error "Invalid key"))))))
4506 (defun org-check-for-org-mode ()
4507 "Make sure current buffer is in org-mode. Error if not."
4508 (or (eq major-mode 'org-mode)
4509 (error "Cannot execute org-mode agenda command on buffer in %s."
4512 (defun org-fit-agenda-window ()
4513 "Fit the window to the buffer size."
4514 (and org-fit-agenda-window
4515 (fboundp 'fit-window-to-buffer)
4516 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4517 (/ (frame-height) 2))))
4519 (defun org-agenda-files ()
4520 "Get the list of agenda files."
4521 (or (get 'org-agenda-files 'org-restrict)
4524 (defvar org-agenda-markers nil
4525 "List of all currently active markers created by `org-agenda'.")
4526 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4527 "Creation time of the last agenda marker.")
4529 (defun org-agenda-new-marker (&optional pos)
4530 "Return a new agenda marker.
4531 Org-mode keeps a list of these markers and resets them when they are
4533 (let ((m (copy-marker (or pos (point)))))
4534 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4535 (push m org-agenda-markers)
4538 (defun org-agenda-maybe-reset-markers (&optional force)
4539 "Reset markers created by `org-agenda'. But only if they are old enough."
4541 (> (- (time-to-seconds (current-time))
4542 org-agenda-last-marker-time)
4544 (while org-agenda-markers
4545 (move-marker (pop org-agenda-markers) nil))))
4547 (defvar org-agenda-new-buffers nil
4548 "Buffers created to visit agenda files.")
4550 (defun org-get-agenda-file-buffer (file)
4551 "Get a buffer visiting FILE. If the buffer needs to be created, add
4552 it to the list of buffers which might be released later."
4553 (let ((buf (find-buffer-visiting file)))
4555 buf ; just return it
4556 ;; Make a new buffer and remember it
4557 (setq buf (find-file-noselect file))
4558 (if buf (push buf org-agenda-new-buffers))
4561 (defun org-release-buffers (blist)
4562 "Release all buffers in list, asking the user for confirmation when needed.
4563 When a buffer is unmodified, it is just killed. When modified, it is saved
4564 \(if the user agrees) and then killed."
4566 (while (setq buf (pop blist))
4567 (setq file (buffer-file-name buf))
4568 (when (and (buffer-modified-p buf)
4570 (y-or-n-p (format "Save file %s? " file)))
4571 (with-current-buffer buf (save-buffer)))
4572 (kill-buffer buf))))
4574 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4576 (defun org-timeline (&optional include-all keep-modes)
4577 "Show a time-sorted view of the entries in the current org file.
4578 Only entries with a time stamp of today or later will be listed. With
4579 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4580 under the current date.
4581 If the buffer contains an active region, only check the region for
4585 (org-agenda-maybe-reset-markers 'force)
4586 (org-compile-prefix-format org-timeline-prefix-format)
4588 (dotodo include-all)
4589 (doclosed org-agenda-show-log)
4590 (org-agenda-keep-modes keep-modes)
4591 (entry (buffer-file-name))
4592 (org-agenda-files (list (buffer-file-name)))
4593 (date (calendar-current-date))
4594 (win (selected-window))
4596 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4597 (end (if (org-region-active-p) (region-end) (point-max)))
4598 (day-numbers (org-get-all-dates beg end 'no-ranges
4599 t doclosed)) ; always include today
4600 (today (time-to-days (current-time)))
4601 (org-respect-restriction t)
4605 (setq org-agenda-redo-command
4607 (list 'switch-to-buffer-other-window (current-buffer))
4608 (list 'org-timeline (list 'quote include-all) t)))
4610 ;; Remove past dates from the list of dates.
4611 (setq day-numbers (delq nil (mapcar (lambda(x)
4612 (if (>= x today) x nil))
4614 (switch-to-buffer-other-window
4615 (get-buffer-create org-agenda-buffer-name))
4616 (setq buffer-read-only nil)
4618 (org-agenda-mode) (setq buffer-read-only nil)
4619 (set (make-local-variable 'org-agenda-type) 'timeline)
4620 (if doclosed (push :closed args))
4621 (push :timestamp args)
4622 (if dotodo (push :todo args))
4623 (while (setq d (pop day-numbers))
4624 (if (and (>= d today)
4629 (insert (make-string 79 ?-) "\n")))
4630 (setq date (calendar-gregorian-from-absolute d))
4632 (setq rtn (apply 'org-agenda-get-day-entries
4634 (if (or rtn (equal d today))
4636 (insert (calendar-day-name date) " "
4637 (number-to-string (extract-calendar-day date)) " "
4638 (calendar-month-name (extract-calendar-month date)) " "
4639 (number-to-string (extract-calendar-year date)) "\n")
4640 (put-text-property s (1- (point)) 'face
4643 (put-text-property s (1- (point)) 'org-today t))
4644 (insert (org-finalize-agenda-entries rtn) "\n")
4645 (put-text-property s (1- (point)) 'day d))))
4646 (goto-char (point-min))
4647 (setq buffer-read-only t)
4648 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4650 (when (not org-select-timeline-window)
4655 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4656 "Produce a weekly view from all files in variable `org-agenda-files'.
4657 The view will be for the current week, but from the overview buffer you
4658 will be able to go to other weeks.
4659 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4660 also be shown, under the current date.
4661 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4662 on the days are also shown. See the variable `org-log-done' for how
4664 START-DAY defaults to TODAY, or to the most recent match for the weekday
4665 given in `org-agenda-start-on-weekday'.
4666 NDAYS defaults to `org-agenda-ndays'."
4668 (org-agenda-maybe-reset-markers 'force)
4669 (org-compile-prefix-format org-agenda-prefix-format)
4671 (let* ((org-agenda-start-on-weekday
4672 (if (or (equal ndays 1)
4673 (and (null ndays) (equal 1 org-agenda-ndays)))
4674 nil org-agenda-start-on-weekday))
4675 (org-agenda-keep-modes keep-modes)
4676 (files (copy-sequence (org-agenda-files)))
4677 (win (selected-window))
4678 (today (time-to-days (current-time)))
4679 (sd (or start-day today))
4680 (start (if (or (null org-agenda-start-on-weekday)
4681 (< org-agenda-ndays 7))
4683 (let* ((nt (calendar-day-of-week
4684 (calendar-gregorian-from-absolute sd)))
4685 (n1 org-agenda-start-on-weekday)
4687 (- sd (+ (if (< d 0) 7 0) d)))))
4688 (day-numbers (list start))
4689 (inhibit-redisplay t)
4690 s e rtn rtnall file date d start-pos end-pos todayp nd)
4691 (setq org-agenda-redo-command
4692 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4693 ;; Make the list of days
4694 (setq ndays (or ndays org-agenda-ndays)
4697 (push (1+ (car day-numbers)) day-numbers)
4698 (setq ndays (1- ndays)))
4699 (setq day-numbers (nreverse day-numbers))
4700 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4702 (delete-other-windows)
4703 (switch-to-buffer-other-window
4704 (get-buffer-create org-agenda-buffer-name))))
4705 (setq buffer-read-only nil)
4707 (org-agenda-mode) (setq buffer-read-only nil)
4708 (set (make-local-variable 'org-agenda-type) 'agenda)
4709 (set (make-local-variable 'starting-day) (car day-numbers))
4710 (set (make-local-variable 'include-all-loc) include-all)
4711 (when (and (or include-all org-agenda-include-all-todo)
4712 (member today day-numbers))
4713 (setq files (org-agenda-files)
4715 (while (setq file (pop files))
4717 (org-check-agenda-file file)
4718 (setq date (calendar-gregorian-from-absolute today)
4719 rtn (org-agenda-get-day-entries
4721 (setq rtnall (append rtnall rtn))))
4723 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4724 (add-text-properties (point-min) (1- (point))
4725 (list 'face 'org-link))
4726 (insert (org-finalize-agenda-entries rtnall) "\n")))
4727 (while (setq d (pop day-numbers))
4728 (setq date (calendar-gregorian-from-absolute d)
4730 (if (or (setq todayp (= d today))
4731 (and (not start-pos) (= d sd)))
4732 (setq start-pos (point))
4733 (if (and start-pos (not end-pos))
4734 (setq end-pos (point))))
4735 (setq files (org-agenda-files)
4737 (while (setq file (pop files))
4739 (org-check-agenda-file file)
4740 (if org-agenda-show-log
4741 (setq rtn (org-agenda-get-day-entries
4743 :deadline :scheduled :timestamp :closed))
4744 (setq rtn (org-agenda-get-day-entries
4746 :deadline :scheduled :timestamp)))
4747 (setq rtnall (append rtnall rtn))))
4748 (if org-agenda-include-diary
4750 (require 'diary-lib)
4751 (setq rtn (org-get-entries-from-diary date))
4752 (setq rtnall (append rtnall rtn))))
4753 (if (or rtnall org-agenda-show-all-dates)
4755 (insert (format "%-9s %2d %s %4d\n"
4756 (calendar-day-name date)
4757 (extract-calendar-day date)
4758 (calendar-month-name (extract-calendar-month date))
4759 (extract-calendar-year date)))
4760 (put-text-property s (1- (point)) 'face
4763 (org-finalize-agenda-entries
4764 (org-agenda-add-time-grid-maybe
4767 (put-text-property s (1- (point)) 'day d))))
4768 (goto-char (point-min))
4769 (setq buffer-read-only t)
4770 (org-fit-agenda-window)
4771 (unless (and (pos-visible-in-window-p (point-min))
4772 (pos-visible-in-window-p (point-max)))
4773 (goto-char (1- (point-max)))
4775 (if (not (pos-visible-in-window-p (or start-pos 1)))
4777 (goto-char (or start-pos 1))
4779 (goto-char (or start-pos 1))
4780 (if (not org-select-agenda-window) (select-window win))
4783 (defvar org-select-this-todo-keyword nil)
4786 (defun org-todo-list (arg &optional keep-modes)
4787 "Show all TODO entries from all agenda file in a single list.
4788 The prefix arg can be used to select a specific TODO keyword and limit
4789 the list to these. When using \\[universal-argument], you will be prompted
4790 for a keyword. A numeric prefix directly selects the Nth keyword in
4791 `org-todo-keywords'."
4793 (org-agenda-maybe-reset-markers 'force)
4794 (org-compile-prefix-format org-agenda-prefix-format)
4795 (let* ((org-agenda-keep-modes keep-modes)
4796 (today (time-to-days (current-time)))
4797 (date (calendar-gregorian-from-absolute today))
4798 (win (selected-window))
4799 (kwds org-todo-keywords)
4800 (completion-ignore-case t)
4801 (org-select-this-todo-keyword
4802 (if (stringp arg) arg
4803 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
4804 rtn rtnall files file pos)
4805 (when (equal arg '(4))
4806 (setq org-select-this-todo-keyword
4807 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4809 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4810 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4812 (delete-other-windows)
4813 (switch-to-buffer-other-window
4814 (get-buffer-create org-agenda-buffer-name))))
4815 (setq buffer-read-only nil)
4817 (org-agenda-mode) (setq buffer-read-only nil)
4818 (set (make-local-variable 'org-agenda-type) 'todo)
4819 (set (make-local-variable 'last-arg) arg)
4820 (set (make-local-variable 'org-todo-keywords) kwds)
4821 (set (make-local-variable 'org-agenda-redo-command)
4822 '(org-todo-list (or current-prefix-arg last-arg) t))
4823 (setq files (org-agenda-files)
4825 (while (setq file (pop files))
4827 (org-check-agenda-file file)
4828 (setq rtn (org-agenda-get-day-entries file date :todo))
4829 (setq rtnall (append rtnall rtn))))
4830 (insert "Global list of TODO items of type: ")
4831 (add-text-properties (point-min) (1- (point))
4832 (list 'face 'org-link))
4834 (insert (or org-select-this-todo-keyword "ALL") "\n")
4835 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4838 "Available with `N r': (0)ALL "
4840 (mapconcat (lambda (x)
4841 (format "(%d)%s" (setq n (1+ n)) x))
4842 org-todo-keywords " "))
4844 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4846 (insert (org-finalize-agenda-entries rtnall) "\n"))
4847 (goto-char (point-min))
4848 (setq buffer-read-only t)
4849 (org-fit-agenda-window)
4850 (if (not org-select-agenda-window) (select-window win))))
4852 (defun org-check-agenda-file (file)
4853 "Make sure FILE exists. If not, ask user what to do."
4854 ;; FIXME: this does not correctly change the menus
4855 ;; Could probably be fixed by explicitly going to the buffer where
4856 ;; the call originated.
4857 (when (not (file-exists-p file))
4858 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4860 (let ((r (downcase (read-char-exclusive))))
4863 (org-remove-file file)
4864 (throw 'nextfile t))
4865 (t (error "Abort"))))))
4867 (defun org-agenda-check-type (error &rest types)
4868 "Check if agenda buffer is of allowed type.
4869 If ERROR is non-nil, throw an error, otherwise just return nil."
4870 (if (memq org-agenda-type types)
4873 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
4876 (defun org-agenda-quit ()
4877 "Exit agenda by removing the window or the buffer."
4879 (let ((buf (current-buffer)))
4880 (if (not (one-window-p)) (delete-window))
4882 (org-agenda-maybe-reset-markers 'force)))
4884 (defun org-agenda-exit ()
4885 "Exit agenda by removing the window or the buffer.
4886 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4887 Org-mode buffers visited directly by the user will not be touched."
4889 (org-release-buffers org-agenda-new-buffers)
4890 (setq org-agenda-new-buffers nil)
4893 (defun org-agenda-redo ()
4895 When this is the global TODO list, a prefix argument will be interpreted."
4897 (message "Rebuilding agenda buffer...")
4898 (eval org-agenda-redo-command)
4899 (message "Rebuilding agenda buffer...done"))
4901 (defun org-agenda-goto-today ()
4904 (org-agenda-check-type t 'timeline 'agenda)
4905 (if (boundp 'starting-day)
4906 (let ((cmd (car org-agenda-redo-command))
4907 (iall (nth 1 org-agenda-redo-command))
4908 (nday (nth 3 org-agenda-redo-command))
4909 (keep (nth 4 org-agenda-redo-command)))
4910 (eval (list cmd iall nil nday keep)))
4911 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4914 (defun org-agenda-later (arg)
4915 "Go forward in time by `org-agenda-ndays' days.
4916 With prefix ARG, go forward that many times `org-agenda-ndays'."
4918 (org-agenda-check-type t 'agenda)
4919 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4920 (+ starting-day (* arg org-agenda-ndays)) nil t))
4922 (defun org-agenda-earlier (arg)
4923 "Go back in time by `org-agenda-ndays' days.
4924 With prefix ARG, go back that many times `org-agenda-ndays'."
4926 (org-agenda-check-type t 'agenda)
4927 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4928 (- starting-day (* arg org-agenda-ndays)) nil t))
4930 (defun org-agenda-week-view ()
4931 "Switch to weekly view for agenda."
4933 (org-agenda-check-type t 'agenda)
4934 (setq org-agenda-ndays 7)
4935 (org-agenda-list include-all-loc
4936 (or (get-text-property (point) 'day)
4939 (org-agenda-set-mode-name)
4940 (message "Switched to week view"))
4942 (defun org-agenda-day-view ()
4943 "Switch to daily view for agenda."
4945 (org-agenda-check-type t 'agenda)
4946 (setq org-agenda-ndays 1)
4947 (org-agenda-list include-all-loc
4948 (or (get-text-property (point) 'day)
4951 (org-agenda-set-mode-name)
4952 (message "Switched to day view"))
4954 (defun org-agenda-next-date-line (&optional arg)
4955 "Jump to the next line indicating a date in agenda buffer."
4957 (org-agenda-check-type t 'agenda 'timeline)
4958 (beginning-of-line 1)
4959 (if (looking-at "^\\S-") (forward-char 1))
4960 (if (not (re-search-forward "^\\S-" nil t arg))
4963 (error "No next date after this line in this buffer")))
4964 (goto-char (match-beginning 0)))
4966 (defun org-agenda-previous-date-line (&optional arg)
4967 "Jump to the previous line indicating a date in agenda buffer."
4969 (org-agenda-check-type t 'agenda 'timeline)
4970 (beginning-of-line 1)
4971 (if (not (re-search-backward "^\\S-" nil t arg))
4972 (error "No previous date before this line in this buffer")))
4974 ;; Initialize the highlight
4975 (defvar org-hl (org-make-overlay 1 1))
4976 (org-overlay-put org-hl 'face 'highlight)
4978 (defun org-highlight (begin end &optional buffer)
4979 "Highlight a region with overlay."
4980 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4981 org-hl begin end (or buffer (current-buffer))))
4983 (defun org-unhighlight ()
4984 "Detach overlay INDEX."
4985 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4988 (defun org-agenda-follow-mode ()
4989 "Toggle follow mode in an agenda buffer."
4991 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4992 (org-agenda-set-mode-name)
4993 (message "Follow mode is %s"
4994 (if org-agenda-follow-mode "on" "off")))
4996 (defun org-agenda-log-mode ()
4997 "Toggle log mode in an agenda buffer."
4999 (org-agenda-check-type t 'agenda 'timeline)
5000 (setq org-agenda-show-log (not org-agenda-show-log))
5001 (org-agenda-set-mode-name)
5003 (message "Log mode is %s"
5004 (if org-agenda-show-log "on" "off")))
5006 (defun org-agenda-toggle-diary ()
5007 "Toggle diary inclusion in an agenda buffer."
5009 (org-agenda-check-type t 'agenda)
5010 (setq org-agenda-include-diary (not org-agenda-include-diary))
5012 (org-agenda-set-mode-name)
5013 (message "Diary inclusion turned %s"
5014 (if org-agenda-include-diary "on" "off")))
5016 (defun org-agenda-toggle-time-grid ()
5017 "Toggle time grid in an agenda buffer."
5019 (org-agenda-check-type t 'agenda)
5020 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5022 (org-agenda-set-mode-name)
5023 (message "Time-grid turned %s"
5024 (if org-agenda-use-time-grid "on" "off")))
5026 (defun org-agenda-set-mode-name ()
5027 "Set the mode name to indicate all the small mode settings."
5029 (concat "Org-Agenda"
5030 (if (equal org-agenda-ndays 1) " Day" "")
5031 (if (equal org-agenda-ndays 7) " Week" "")
5032 (if org-agenda-follow-mode " Follow" "")
5033 (if org-agenda-include-diary " Diary" "")
5034 (if org-agenda-use-time-grid " Grid" "")
5035 (if org-agenda-show-log " Log" "")))
5036 (force-mode-line-update))
5038 (defun org-agenda-post-command-hook ()
5039 (and (eolp) (not (bolp)) (backward-char 1))
5040 (if (and org-agenda-follow-mode
5041 (get-text-property (point) 'org-marker))
5044 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5046 (defun org-get-entries-from-diary (date)
5047 "Get the (Emacs Calendar) diary entries for DATE."
5048 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5049 (diary-display-hook '(fancy-diary-display))
5050 (list-diary-entries-hook
5051 (cons 'org-diary-default-entry list-diary-entries-hook))
5052 (diary-file-name-prefix-function nil) ; turn this feature off
5053 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5055 (org-disable-agenda-to-diary t))
5057 (save-window-excursion
5058 (list-diary-entries date 1)))
5059 (if (not (get-buffer fancy-diary-buffer))
5061 (with-current-buffer fancy-diary-buffer
5062 (setq buffer-read-only nil)
5063 (if (= (point-max) 1)
5066 ;; Omit the date and other unnecessary stuff
5067 (org-agenda-cleanup-fancy-diary)
5068 ;; Add prefix to each line and extend the text properties
5069 (if (= (point-max) 1)
5071 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5072 (set-buffer-modified-p nil)
5073 (kill-buffer fancy-diary-buffer)))
5075 (setq entries (org-split-string entries "\n"))
5079 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5080 ;; Extend the text properties to the beginning of the line
5081 (add-text-properties
5083 (text-properties-at (1- (length x)) x)
5088 (defun org-agenda-cleanup-fancy-diary ()
5089 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5090 This gets rid of the date, the underline under the date, and
5091 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5092 date. It also removes lines that contain only whitespace."
5093 (goto-char (point-min))
5094 (if (looking-at ".*?:[ \t]*")
5097 (re-search-forward "\n=+$" nil t)
5099 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5100 (re-search-forward "\n=+$" nil t)
5101 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5102 (goto-char (point-min))
5103 (while (re-search-forward "^ +\n" nil t)
5105 (goto-char (point-min))
5106 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5107 (replace-match "")))
5109 ;; Make sure entries from the diary have the right text properties.
5110 (eval-after-load "diary-lib"
5111 '(if (boundp 'diary-modify-entry-list-string-function)
5112 ;; We can rely on the hook, nothing to do
5114 ;; Hook not avaiable, must use advice to make this work
5115 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5116 "Make the position visible."
5117 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5120 (setq string (org-modify-diary-entry-string string))))))
5122 (defun org-modify-diary-entry-string (string)
5123 "Add text properties to string, allowing org-mode to act on it."
5124 (add-text-properties
5126 (list 'mouse-face 'highlight
5127 'keymap org-agenda-keymap
5130 "mouse-2 or RET jump to diary file %s"
5131 (abbreviate-file-name (buffer-file-name)))
5132 'org-agenda-diary-link t
5133 'org-marker (org-agenda-new-marker (point-at-bol)))
5137 (defun org-diary-default-entry ()
5138 "Add a dummy entry to the diary.
5139 Needed to avoid empty dates which mess up holiday display."
5140 ;; Catch the error if dealing with the new add-to-diary-alist
5141 (when org-disable-agenda-to-diary
5143 (add-to-diary-list original-date "Org-mode dummy" "")
5145 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5147 (defun org-cycle-agenda-files ()
5148 "Cycle through the files in `org-agenda-files'.
5149 If the current buffer visits an agenda file, find the next one in the list.
5150 If the current buffer does not, find the first agenda file."
5152 (let ((files (append org-agenda-files (list (car org-agenda-files))))
5153 (tcf (if (buffer-file-name) (file-truename (buffer-file-name))))
5155 (unless files (error "No agenda files"))
5157 (while (setq file (pop files))
5158 (if (equal (file-truename file) tcf)
5160 (find-file (car files))
5162 (find-file (car org-agenda-files)))))
5164 (defun org-agenda-file-to-end (&optional file)
5165 "Move/add the current file to the end of the agenda file list.
5166 If the file is not present in the list, it is appended to the list. If it is
5167 present, it is moved there."
5169 (org-agenda-file-to-front 'to-end file))
5171 (defun org-agenda-file-to-front (&optional to-end file)
5172 "Move/add the current file to the top of the agenda file list.
5173 If the file is not present in the list, it is added to the front. If it is
5174 present, it is moved there. With optional argument TO-END, add/move to the
5177 (let ((file-alist (mapcar (lambda (x)
5178 (cons (file-truename x) x))
5180 (ctf (file-truename (buffer-file-name)))
5182 (setq x (assoc ctf file-alist) had x)
5184 (if (not x) (setq x (cons ctf (abbreviate-file-name (buffer-file-name)))))
5186 (setq file-alist (append (delq x file-alist) (list x)))
5187 (setq file-alist (cons x (delq x file-alist))))
5188 (setq org-agenda-files (mapcar 'cdr file-alist))
5189 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5190 (customize-save-variable 'org-agenda-files org-agenda-files))
5191 (org-install-agenda-files-menu)
5192 (message "File %s to %s of agenda file list"
5193 (if had "moved" "added") (if to-end "end" "front"))))
5195 (defun org-remove-file (&optional file)
5196 "Remove current file from the list of files in variable `org-agenda-files'.
5197 These are the files which are being checked for agenda entries.
5198 Optional argument FILE means, use this file instead of the current."
5200 (let* ((file (or file (buffer-file-name)))
5201 (true-file (file-truename file))
5202 (afile (abbreviate-file-name file))
5203 (files (delq nil (mapcar
5205 (if (equal true-file
5208 org-agenda-files))))
5209 (if (not (= (length files) (length org-agenda-files)))
5211 (setq org-agenda-files files)
5212 (customize-save-variable 'org-agenda-files org-agenda-files)
5213 (org-install-agenda-files-menu)
5214 (message "Removed file: %s" afile))
5215 (message "File was not in list: %s" afile))))
5217 (defun org-file-menu-entry (file)
5218 (vector file (list 'find-file file) t))
5219 ;; FIXME: Maybe we removed a buffer visited through the menu from
5220 ;; org-agenda-new-buffers, so that the buffer will not be removed
5221 ;; when exiting the agenda????
5223 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5224 "Return a list of all relevant day numbers from BEG to END buffer positions.
5225 If NO-RANGES is non-nil, include only the start and end dates of a range,
5226 not every single day in the range. If FORCE-TODAY is non-nil, make
5227 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5228 inactive time stamps (those in square brackets) are included."
5229 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5230 dates date day day1 day2 ts1 ts2)
5232 (setq dates (list (time-to-days (current-time)))))
5235 (while (re-search-forward re end t)
5236 (setq day (time-to-days (org-time-string-to-time
5237 (substring (match-string 1) 0 10))))
5238 (or (memq day dates) (push day dates)))
5241 (while (re-search-forward org-tr-regexp end t)
5242 (setq ts1 (substring (match-string 1) 0 10)
5243 ts2 (substring (match-string 2) 0 10)
5244 day1 (time-to-days (org-time-string-to-time ts1))
5245 day2 (time-to-days (org-time-string-to-time ts2)))
5246 (while (< (setq day1 (1+ day1)) day2)
5247 (or (memq day1 dates) (push day1 dates)))))
5251 (defun org-diary (&rest args)
5252 "Return diary information from org-files.
5253 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5254 It accesses org files and extracts information from those files to be
5255 listed in the diary. The function accepts arguments specifying what
5256 items should be listed. The following arguments are allowed:
5258 :timestamp List the headlines of items containing a date stamp or
5259 date range matching the selected date. Deadlines will
5260 also be listed, on the expiration day.
5262 :deadline List any deadlines past due, or due within
5263 `org-deadline-warning-days'. The listing occurs only
5264 in the diary for *today*, not at any other date. If
5265 an entry is marked DONE, it is no longer listed.
5267 :scheduled List all items which are scheduled for the given date.
5268 The diary for *today* also contains items which were
5269 scheduled earlier and are not yet marked DONE.
5271 :todo List all TODO items from the org-file. This may be a
5272 long list - so this is not turned on by default.
5273 Like deadlines, these entries only show up in the
5274 diary for *today*, not at any other date.
5276 The call in the diary file should look like this:
5278 &%%(org-diary) ~/path/to/some/orgfile.org
5280 Use a separate line for each org file to check. Or, if you omit the file name,
5281 all files listed in `org-agenda-files' will be checked automatically:
5285 If you don't give any arguments (as in the example above), the default
5286 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5289 &%%(org-diary :deadline :timestamp :scheduled)
5291 The function expects the lisp variables `entry' and `date' to be provided
5292 by the caller, because this is how the calendar works. Don't use this
5293 function from a program - use `org-agenda-get-day-entries' instead."
5294 (org-agenda-maybe-reset-markers)
5295 (org-compile-prefix-format org-agenda-prefix-format)
5296 (setq args (or args '(:deadline :scheduled :timestamp)))
5297 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5301 ;; If this is called during org-agenda, don't return any entries to
5302 ;; the calendar. Org Agenda will list these entries itself.
5303 (if org-disable-agenda-to-diary (setq files nil))
5304 (while (setq file (pop files))
5305 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5306 (setq results (append results rtn)))
5308 (concat (org-finalize-agenda-entries results) "\n"))))
5309 (defvar org-category-table nil)
5310 (defun org-get-category-table ()
5311 "Get the table of categories and positions in current buffer."
5314 (goto-char (point-min))
5315 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5316 (push (cons (point) (org-trim (match-string 2))) tbl)))
5318 (defun org-get-category (&optional pos)
5319 "Get the category applying to position POS."
5320 (if (not org-category-table)
5322 ((null org-category)
5324 (if (buffer-file-name)
5325 (file-name-sans-extension
5326 (file-name-nondirectory (buffer-file-name)))
5328 ((symbolp org-category) (symbol-name org-category))
5330 (let ((tbl org-category-table)
5331 (pos (or pos (point))))
5332 (while (and tbl (> (caar tbl) pos))
5334 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5335 org-category-table))))))
5337 (defun org-agenda-get-day-entries (file date &rest args)
5338 "Does the work for `org-diary' and `org-agenda'.
5339 FILE is the path to a file to be checked for entries. DATE is date like
5340 the one returned by `calendar-current-date'. ARGS are symbols indicating
5341 which kind of entries should be extracted. For details about these, see
5342 the documentation of `org-diary'."
5343 (setq args (or args '(:deadline :scheduled :timestamp)))
5344 (let* ((org-startup-with-deadline-check nil)
5345 (org-startup-folded nil)
5346 (buffer (if (file-exists-p file)
5347 (org-get-agenda-file-buffer file)
5348 (error "No such file %s" file)))
5351 ;; If file does not exist, make sure an error message ends up in diary
5352 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5353 (with-current-buffer buffer
5354 (unless (eq major-mode 'org-mode)
5355 (error "Agenda file %s is not in `org-mode'" file))
5356 (setq org-category-table (org-get-category-table))
5357 (let ((case-fold-search nil))
5360 (if org-respect-restriction
5361 (if (org-region-active-p)
5362 ;; Respect a region to restrict search
5363 (narrow-to-region (region-beginning) (region-end)))
5364 ;; If we work for the calendar or many files,
5365 ;; get rid of any restriction
5367 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5368 (while (setq arg (pop args))
5370 ((and (eq arg :todo)
5371 (equal date (calendar-current-date)))
5372 (setq rtn (org-agenda-get-todos))
5373 (setq results (append results rtn)))
5374 ((eq arg :timestamp)
5375 (setq rtn (org-agenda-get-blocks))
5376 (setq results (append results rtn))
5377 (setq rtn (org-agenda-get-timestamps))
5378 (setq results (append results rtn)))
5379 ((eq arg :scheduled)
5380 (setq rtn (org-agenda-get-scheduled))
5381 (setq results (append results rtn)))
5383 (setq rtn (org-agenda-get-closed))
5384 (setq results (append results rtn)))
5385 ((and (eq arg :deadline)
5386 (equal date (calendar-current-date)))
5387 (setq rtn (org-agenda-get-deadlines))
5388 (setq results (append results rtn))))))))
5391 (defun org-entry-is-done-p ()
5392 "Is the current entry marked DONE?"
5394 (and (re-search-backward "[\r\n]\\*" nil t)
5395 (looking-at org-nl-done-regexp))))
5397 (defun org-at-date-range-p ()
5398 "Is the cursor inside a date range?"
5402 (let ((pos (point)))
5403 (skip-chars-backward "^<\r\n")
5404 (skip-chars-backward "<")
5405 (and (looking-at org-tr-regexp)
5406 (>= (match-end 0) pos)
5408 (skip-chars-backward "^<\r\n")
5409 (skip-chars-backward "<")
5410 (and (looking-at org-tr-regexp)
5411 (>= (match-end 0) pos)
5415 (defun org-agenda-get-todos ()
5416 "Return the TODO information for agenda display."
5417 (let* ((props (list 'face nil
5418 'done-face 'org-done
5419 'mouse-face 'highlight
5420 'keymap org-agenda-keymap
5422 (format "mouse-2 or RET jump to org file %s"
5423 (abbreviate-file-name (buffer-file-name)))))
5424 (regexp (concat "[\n\r]\\*+ *\\("
5425 (if org-select-this-todo-keyword
5426 (concat "\\<\\(" org-select-this-todo-keyword
5428 org-not-done-regexp)
5430 marker priority category tags
5432 (goto-char (point-min))
5433 (while (re-search-forward regexp nil t)
5434 (goto-char (match-beginning 1))
5435 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5436 category (org-get-category)
5437 tags (org-get-tags-at (point))
5438 txt (org-format-agenda-item "" (match-string 1) category tags)
5440 (+ (org-get-priority txt)
5441 (if org-todo-kwd-priority-p
5442 (- org-todo-kwd-max-priority -2
5444 (member (match-string 2) org-todo-keywords)))
5446 (add-text-properties
5447 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5448 'priority priority 'category category)
5452 (goto-char (match-end 1)))
5455 (defconst org-agenda-no-heading-message
5456 "No heading for this item in buffer or region.")
5458 (defun org-agenda-get-timestamps ()
5459 "Return the date stamp information for agenda display."
5460 (let* ((props (list 'face nil
5461 'mouse-face 'highlight
5462 'keymap org-agenda-keymap
5464 (format "mouse-2 or RET jump to org file %s"
5465 (abbreviate-file-name (buffer-file-name)))))
5466 (regexp (regexp-quote
5469 (car org-time-stamp-formats)
5470 (apply 'encode-time ; DATE bound by calendar
5471 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5473 marker hdmarker deadlinep scheduledp donep tmp priority category
5474 ee txt timestr tags)
5475 (goto-char (point-min))
5476 (while (re-search-forward regexp nil t)
5477 (if (not (save-match-data (org-at-date-range-p)))
5479 (setq marker (org-agenda-new-marker (match-beginning 0))
5480 category (org-get-category (match-beginning 0))
5481 tmp (buffer-substring (max (point-min)
5482 (- (match-beginning 0)
5483 org-ds-keyword-length))
5484 (match-beginning 0))
5485 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5486 deadlinep (string-match org-deadline-regexp tmp)
5487 scheduledp (string-match org-scheduled-regexp tmp)
5488 donep (org-entry-is-done-p))
5489 (if (string-match ">" timestr)
5490 ;; substring should only run to end of time stamp
5491 (setq timestr (substring timestr 0 (match-end 0))))
5493 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5495 (goto-char (match-end 1))
5496 (setq hdmarker (org-agenda-new-marker)
5497 tags (org-get-tags-at))
5498 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5499 (setq txt (org-format-agenda-item
5501 (if deadlinep "Deadline: " "")
5502 (if scheduledp "Scheduled: " ""))
5503 (match-string 1) category tags timestr)))
5504 (setq txt org-agenda-no-heading-message))
5505 (setq priority (org-get-priority txt))
5506 (add-text-properties
5507 0 (length txt) (append (list 'org-marker marker
5508 'org-hd-marker hdmarker) props)
5511 (add-text-properties
5514 (if donep 'org-done 'org-warning)
5515 'undone-face 'org-warning
5516 'done-face 'org-done
5518 'priority (+ 100 priority))
5521 (add-text-properties
5523 (list 'face 'org-scheduled-today
5524 'undone-face 'org-scheduled-today
5525 'done-face 'org-done
5527 priority (+ 99 priority))
5529 (add-text-properties
5531 (list 'priority priority 'category category) txt)))
5533 (outline-next-heading))))
5536 (defun org-agenda-get-closed ()
5537 "Return the logged TODO entries for agenda display."
5538 (let* ((props (list 'mouse-face 'highlight
5539 'keymap org-agenda-keymap
5541 (format "mouse-2 or RET jump to org file %s"
5542 (abbreviate-file-name (buffer-file-name)))))
5544 "\\<" org-closed-string " *\\["
5548 (car org-time-stamp-formats)
5549 (apply 'encode-time ; DATE bound by calendar
5550 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5552 marker hdmarker priority category tags
5554 (goto-char (point-min))
5555 (while (re-search-forward regexp nil t)
5556 (if (not (save-match-data (org-at-date-range-p)))
5558 (setq marker (org-agenda-new-marker (match-beginning 0))
5559 category (org-get-category (match-beginning 0))
5560 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5561 ;; donep (org-entry-is-done-p)
5563 (if (string-match "\\]" timestr)
5564 ;; substring should only run to end of time stamp
5565 (setq timestr (substring timestr 0 (match-end 0))))
5567 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5569 (goto-char (match-end 1))
5570 (setq hdmarker (org-agenda-new-marker)
5571 tags (org-get-tags-at))
5572 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5573 (setq txt (org-format-agenda-item
5575 (match-string 1) category tags timestr)))
5576 (setq txt org-agenda-no-heading-message))
5577 (setq priority 100000)
5578 (add-text-properties
5579 0 (length txt) (append (list 'org-marker marker
5580 'org-hd-marker hdmarker
5584 'undone-face 'org-warning
5585 'done-face 'org-done) props)
5588 (outline-next-heading))))
5591 (defun org-agenda-get-deadlines ()
5592 "Return the deadline information for agenda display."
5593 (let* ((wdays org-deadline-warning-days)
5594 (props (list 'mouse-face 'highlight
5595 'keymap org-agenda-keymap
5597 (format "mouse-2 or RET jump to org file %s"
5598 (abbreviate-file-name (buffer-file-name)))))
5599 (regexp org-deadline-time-regexp)
5600 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5601 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5602 d2 diff pos pos1 category tags
5604 (goto-char (point-min))
5605 (while (re-search-forward regexp nil t)
5606 (setq pos (1- (match-beginning 1))
5608 (org-time-string-to-time (match-string 1)))
5610 ;; When to show a deadline in the calendar:
5611 ;; If the expiration is within wdays warning time.
5612 ;; Past-due deadlines are only shown on the current date
5613 (if (and (< diff wdays) todayp (not (= diff 0)))
5615 (setq category (org-get-category))
5616 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5618 (goto-char (match-end 0))
5619 (setq pos1 (match-end 1))
5620 (setq tags (org-get-tags-at pos1))
5621 (setq head (buffer-substring-no-properties
5623 (progn (skip-chars-forward "^\r\n")
5625 (if (string-match org-looking-at-done-regexp head)
5627 (setq txt (org-format-agenda-item
5628 (format "In %3d d.: " diff) head category tags))))
5629 (setq txt org-agenda-no-heading-message))
5631 (add-text-properties
5634 (list 'org-marker (org-agenda-new-marker pos)
5635 'org-hd-marker (org-agenda-new-marker pos1)
5636 'priority (+ (- 10 diff) (org-get-priority txt))
5638 'face (cond ((<= diff 0) 'org-warning)
5639 ((<= diff 5) 'org-scheduled-previously)
5642 ((<= diff 0) 'org-warning)
5643 ((<= diff 5) 'org-scheduled-previously)
5645 'done-face 'org-done)
5651 (defun org-agenda-get-scheduled ()
5652 "Return the scheduled information for agenda display."
5653 (let* ((props (list 'face 'org-scheduled-previously
5654 'undone-face 'org-scheduled-previously
5655 'done-face 'org-done
5656 'mouse-face 'highlight
5657 'keymap org-agenda-keymap
5659 (format "mouse-2 or RET jump to org file %s"
5660 (abbreviate-file-name (buffer-file-name)))))
5661 (regexp org-scheduled-time-regexp)
5662 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5663 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5664 d2 diff pos pos1 category tags
5666 (goto-char (point-min))
5667 (while (re-search-forward regexp nil t)
5668 (setq pos (1- (match-beginning 1))
5670 (org-time-string-to-time (match-string 1)))
5672 ;; When to show a scheduled item in the calendar:
5673 ;; If it is on or past the date.
5674 (if (and (< diff 0) todayp)
5676 (setq category (org-get-category))
5677 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5679 (goto-char (match-end 0))
5680 (setq pos1 (match-end 1))
5681 (setq tags (org-get-tags-at))
5682 (setq head (buffer-substring-no-properties
5684 (progn (skip-chars-forward "^\r\n") (point))))
5685 (if (string-match org-looking-at-done-regexp head)
5687 (setq txt (org-format-agenda-item
5688 (format "Sched.%2dx: " (- 1 diff)) head
5690 (setq txt org-agenda-no-heading-message))
5692 (add-text-properties
5694 (append (list 'org-marker (org-agenda-new-marker pos)
5695 'org-hd-marker (org-agenda-new-marker pos1)
5696 'priority (+ (- 5 diff) (org-get-priority txt))
5702 (defun org-agenda-get-blocks ()
5703 "Return the date-range information for agenda display."
5704 (let* ((props (list 'face nil
5705 'mouse-face 'highlight
5706 'keymap org-agenda-keymap
5708 (format "mouse-2 or RET jump to org file %s"
5709 (abbreviate-file-name (buffer-file-name)))))
5710 (regexp org-tr-regexp)
5711 (d0 (calendar-absolute-from-gregorian date))
5712 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
5713 (goto-char (point-min))
5714 (while (re-search-forward regexp nil t)
5715 (setq timestr (match-string 0)
5718 d1 (time-to-days (org-time-string-to-time s1))
5719 d2 (time-to-days (org-time-string-to-time s2)))
5720 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5721 ;; Only allow days between the limits, because the normal
5722 ;; date stamps will catch the limits.
5724 (setq marker (org-agenda-new-marker (point)))
5725 (setq category (org-get-category))
5726 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5728 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5729 (goto-char (match-end 1))
5730 (setq tags (org-get-tags-at))
5731 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5732 (setq txt (org-format-agenda-item
5733 (format (if (= d1 d2) "" "(%d/%d): ")
5734 (1+ (- d0 d1)) (1+ (- d2 d1)))
5735 (match-string 1) category tags
5736 (if (= d0 d1) timestr))))
5737 (setq txt org-agenda-no-heading-message))
5738 (add-text-properties
5739 0 (length txt) (append (list 'org-marker marker
5740 'org-hd-marker hdmarker
5741 'priority (org-get-priority txt)
5746 (outline-next-heading))
5747 ;; Sort the entries by expiration date.
5750 (defconst org-plain-time-of-day-regexp
5753 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5756 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5758 "Regular expression to match a plain time or time range.
5759 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5760 groups carry important information:
5762 1 the first time, range or not
5763 8 the second time, if it is a range.")
5765 (defconst org-stamp-time-of-day-regexp
5767 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5768 "\\([012][0-9]:[0-5][0-9]\\)>"
5770 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5771 "Regular expression to match a timestamp time or time range.
5772 After a match, the following groups carry important information:
5774 1 date plus weekday, for backreferencing to make sure both times on same day
5775 2 the first time, range or not
5776 4 the second time, if it is a range.")
5778 (defvar org-prefix-has-time nil
5779 "A flag, set by `org-compile-prefix-format'.
5780 The flag is set if the currently compiled format contains a `%t'.")
5781 (defvar org-prefix-has-tag nil
5782 "A flag, set by `org-compile-prefix-format'.
5783 The flag is set if the currently compiled format contains a `%T'.")
5785 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
5786 "Format TXT to be inserted into the agenda buffer.
5787 In particular, it adds the prefix and corresponding text properties. EXTRA
5788 must be a string and replaces the `%s' specifier in the prefix format.
5789 CATEGORY (string, symbol or nil) may be used to overrule the default
5790 category taken from local variable or file name. It will replace the `%c'
5791 specifier in the format. DOTIME, when non-nil, indicates that a
5792 time-of-day should be extracted from TXT for sorting of this entry, and for
5793 the `%t' specifier in the format. When DOTIME is a string, this string is
5794 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5795 only the correctly processes TXT should be returned - this is used by
5796 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
5798 ;; Diary entries sometimes have extra whitespace at the beginning
5799 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5800 (let* ((category (or category
5802 (if (buffer-file-name)
5803 (file-name-sans-extension
5804 (file-name-nondirectory (buffer-file-name)))
5806 (tag (or (nth (1- (length tags)) tags) ""))
5807 time ;; needed for the eval of the prefix format
5808 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5809 (time-of-day (and dotime (org-get-time-of-day ts)))
5810 stamp plain s0 s1 s2 rtn)
5811 (when (and dotime time-of-day org-prefix-has-time)
5812 ;; Extract starting and ending time and move them to prefix
5813 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5814 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5815 (setq s0 (match-string 0 ts)
5816 s1 (match-string (if plain 1 2) ts)
5817 s2 (match-string (if plain 8 4) ts))
5819 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5820 ;; them, we might want to remove them there to avoid duplication.
5821 ;; The user can turn this off with a variable.
5822 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5823 (string-match (concat (regexp-quote s0) " *") txt)
5824 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5825 (= (match-beginning 0) 0)
5827 (setq txt (replace-match "" nil nil txt))))
5828 ;; Normalize the time(s) to 24 hour
5829 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5830 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5832 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
5833 (and org-agenda-remove-tags-when-in-prefix
5834 org-prefix-has-tag))
5835 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
5836 (setq txt (replace-match "" t t txt)))
5838 ;; Create the final string
5841 ;; Prepare the variables needed in the eval of the compiled format
5842 (setq time (cond (s2 (concat s1 "-" s2))
5843 (s1 (concat s1 "......"))
5846 category (if (symbolp category) (symbol-name category) category))
5847 ;; Evaluate the compiled format
5848 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5850 ;; And finally add the text properties
5851 (add-text-properties
5852 0 (length rtn) (list 'category (downcase category)
5854 'prefix-length (- (length rtn) (length txt))
5855 'time-of-day time-of-day
5860 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5862 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5863 ((and todayp (member 'today (car org-agenda-time-grid))))
5864 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5865 ((member 'weekly (car org-agenda-time-grid)))
5866 (t (throw 'exit list)))
5867 (let* ((have (delq nil (mapcar
5868 (lambda (x) (get-text-property 1 'time-of-day x))
5870 (string (nth 1 org-agenda-time-grid))
5871 (gridtimes (nth 2 org-agenda-time-grid))
5872 (req (car org-agenda-time-grid))
5873 (remove (member 'remove-match req))
5875 (if (and (member 'require-timed req) (not have))
5876 ;; don't show empty grid
5878 (while (setq time (pop gridtimes))
5879 (unless (and remove (member time have))
5880 (setq time (int-to-string time))
5881 (push (org-format-agenda-item
5882 nil string "" nil ;; FIXME: put a category for the grid?
5883 (concat (substring time 0 -2) ":" (substring time -2)))
5886 1 (length (car new)) 'face 'org-time-grid (car new))))
5887 (if (member 'time-up org-agenda-sorting-strategy)
5889 (append list new)))))
5891 (defun org-compile-prefix-format (format)
5892 "Compile the prefix format into a Lisp form that can be evaluated.
5893 The resulting form is returned and stored in the variable
5894 `org-prefix-format-compiled'."
5895 (setq org-prefix-has-time nil org-prefix-has-tag nil)
5896 (let ((start 0) varform vars var (s format)e c f opt)
5897 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5899 (setq var (cdr (assoc (match-string 4 s)
5900 '(("c" . category) ("t" . time) ("s" . extra)
5902 c (or (match-string 3 s) "")
5903 opt (match-beginning 1)
5904 start (1+ (match-beginning 0)))
5905 (if (equal var 'time) (setq org-prefix-has-time t))
5906 (if (equal var 'tag) (setq org-prefix-has-tag t))
5907 (setq f (concat "%" (match-string 2 s) "s"))
5910 `(if (equal "" ,var)
5912 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
5913 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
5914 (setq s (replace-match "%s" t nil s))
5915 (push varform vars))
5916 (setq vars (nreverse vars))
5917 (setq org-prefix-format-compiled `(format ,s ,@vars))))
5919 (defun org-get-time-of-day (s &optional string)
5920 "Check string S for a time of day.
5921 If found, return it as a military time number between 0 and 2400.
5922 If not found, return nil.
5923 The optional STRING argument forces conversion into a 5 character wide string
5929 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
5931 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
5932 (let* ((t0 (+ (* 100
5933 (+ (string-to-number (match-string 1 s))
5934 (if (and (match-beginning 4)
5935 (equal (downcase (match-string 4 s)) "pm"))
5937 (if (match-beginning 3)
5938 (string-to-number (match-string 3 s))
5941 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
5942 (int-to-string t0))))
5943 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
5945 (defun org-finalize-agenda-entries (list)
5946 "Sort and concatenate the agenda items."
5947 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
5949 (defsubst org-cmp-priority (a b)
5950 "Compare the priorities of string A and B."
5951 (let ((pa (or (get-text-property 1 'priority a) 0))
5952 (pb (or (get-text-property 1 'priority b) 0)))
5953 (cond ((> pa pb) +1)
5957 (defsubst org-cmp-category (a b)
5958 "Compare the string values of categories of strings A and B."
5959 (let ((ca (or (get-text-property 1 'category a) ""))
5960 (cb (or (get-text-property 1 'category b) "")))
5961 (cond ((string-lessp ca cb) -1)
5962 ((string-lessp cb ca) +1)
5965 (defsubst org-cmp-time (a b)
5966 "Compare the time-of-day values of strings A and B."
5967 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
5968 (ta (or (get-text-property 1 'time-of-day a) def))
5969 (tb (or (get-text-property 1 'time-of-day b) def)))
5970 (cond ((< ta tb) -1)
5974 (defun org-entries-lessp (a b)
5975 "Predicate for sorting agenda entries."
5976 ;; The following variables will be used when the form is evaluated.
5977 (let* ((time-up (org-cmp-time a b))
5978 (time-down (if time-up (- time-up) nil))
5979 (priority-up (org-cmp-priority a b))
5980 (priority-down (if priority-up (- priority-up) nil))
5981 (category-up (org-cmp-category a b))
5982 (category-down (if category-up (- category-up) nil))
5983 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
5985 (eval (cons 'or org-agenda-sorting-strategy))
5986 '((-1 . t) (1 . nil) (nil . nil))))))
5988 (defun org-agenda-show-priority ()
5989 "Show the priority of the current item.
5990 This priority is composed of the main priority given with the [#A] cookies,
5991 and by additional input from the age of a schedules or deadline entry."
5993 (let* ((pri (get-text-property (point-at-bol) 'priority)))
5994 (message "Priority is %d" (if pri pri -1000))))
5996 (defun org-agenda-show-tags ()
5997 "Show the tags applicable to the current item."
5999 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6001 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6002 (message "No tags associated with this line"))))
6004 (defun org-agenda-goto (&optional highlight)
6005 "Go to the Org-mode file which contains the item at point."
6007 (let* ((marker (or (get-text-property (point) 'org-marker)
6008 (org-agenda-error)))
6009 (buffer (marker-buffer marker))
6010 (pos (marker-position marker)))
6011 (switch-to-buffer-other-window buffer)
6014 (when (eq major-mode 'org-mode)
6015 (org-show-hidden-entry)
6017 (and (outline-next-heading)
6018 (org-flag-heading nil)))) ; show the next heading
6019 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6021 (defun org-agenda-switch-to ()
6022 "Go to the Org-mode file which contains the item at point."
6024 (let* ((marker (or (get-text-property (point) 'org-marker)
6025 (org-agenda-error)))
6026 (buffer (marker-buffer marker))
6027 (pos (marker-position marker)))
6028 (switch-to-buffer buffer)
6029 (delete-other-windows)
6032 (when (eq major-mode 'org-mode)
6033 (org-show-hidden-entry)
6035 (and (outline-next-heading)
6036 (org-flag-heading nil)))))) ; show the next heading
6038 (defun org-agenda-goto-mouse (ev)
6039 "Go to the Org-mode file which contains the item at the mouse click."
6041 (mouse-set-point ev)
6044 (defun org-agenda-show ()
6045 "Display the Org-mode file which contains the item at point."
6047 (let ((win (selected-window)))
6049 (select-window win)))
6051 (defun org-agenda-recenter (arg)
6052 "Display the Org-mode file which contains the item at point and recenter."
6054 (let ((win (selected-window)))
6057 (select-window win)))
6059 (defun org-agenda-show-mouse (ev)
6060 "Display the Org-mode file which contains the item at the mouse click."
6062 (mouse-set-point ev)
6065 (defun org-agenda-check-no-diary ()
6066 "Check if the entry is a diary link and abort if yes."
6067 (if (get-text-property (point) 'org-agenda-diary-link)
6068 (org-agenda-error)))
6070 (defun org-agenda-error ()
6071 (error "Command not allowed in this line"))
6073 (defvar org-last-heading-marker (make-marker)
6074 "Marker pointing to the headline that last changed its TODO state
6075 by a remote command from the agenda.")
6077 (defun org-agenda-todo (&optional arg)
6078 "Cycle TODO state of line at point, also in Org-mode file.
6079 This changes the line at point, all other lines in the agenda referring to
6080 the same tree node, and the headline of the tree node in the Org-mode file."
6082 (org-agenda-check-no-diary)
6083 (let* ((col (current-column))
6084 (marker (or (get-text-property (point) 'org-marker)
6085 (org-agenda-error)))
6086 (buffer (marker-buffer marker))
6087 (pos (marker-position marker))
6088 (hdmarker (get-text-property (point) 'org-hd-marker))
6089 (buffer-read-only nil)
6091 (with-current-buffer buffer
6094 (org-show-hidden-entry)
6096 (and (outline-next-heading)
6097 (org-flag-heading nil))) ; show the next heading
6100 (setq newhead (org-get-heading))
6102 (org-back-to-heading)
6103 (move-marker org-last-heading-marker (point))))
6104 (beginning-of-line 1)
6106 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6107 (move-to-column col)))
6109 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6110 "Change all lines in the agenda buffer which match HDMARKER.
6111 The new content of the line will be NEWHEAD (as modified by
6112 `org-format-agenda-item'). HDMARKER is checked with
6113 `equal' against all `org-hd-marker' text properties in the file.
6114 If FIXFACE is non-nil, the face of each item is modified acording to
6115 the new TODO state."
6116 (let* (props m pl undone-face done-face finish new dotime cat tags)
6117 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6119 (goto-char (point-max))
6120 (beginning-of-line 1)
6122 (setq finish (bobp))
6123 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6125 (setq props (text-properties-at (point))
6126 dotime (get-text-property (point) 'dotime)
6127 cat (get-text-property (point) 'category)
6128 tags (get-text-property (point) 'tags)
6129 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6130 pl (get-text-property (point) 'prefix-length)
6131 undone-face (get-text-property (point) 'undone-face)
6132 done-face (get-text-property (point) 'done-face))
6134 (if (looking-at ".*")
6136 (replace-match new t t)
6137 (beginning-of-line 1)
6138 (add-text-properties (point-at-bol) (point-at-eol) props)
6140 (add-text-properties
6141 (point-at-bol) (point-at-eol)
6143 (if org-last-todo-state-is-todo
6144 undone-face done-face))))
6145 (beginning-of-line 1))
6146 (error "Line update did not work")))
6147 (beginning-of-line 0)))))
6149 (defun org-agenda-priority-up ()
6150 "Increase the priority of line at point, also in Org-mode file."
6152 (org-agenda-priority 'up))
6154 (defun org-agenda-priority-down ()
6155 "Decrease the priority of line at point, also in Org-mode file."
6157 (org-agenda-priority 'down))
6159 (defun org-agenda-priority (&optional force-direction)
6160 "Set the priority of line at point, also in Org-mode file.
6161 This changes the line at point, all other lines in the agenda referring to
6162 the same tree node, and the headline of the tree node in the Org-mode file."
6164 (org-agenda-check-no-diary)
6165 (let* ((marker (or (get-text-property (point) 'org-marker)
6166 (org-agenda-error)))
6167 (buffer (marker-buffer marker))
6168 (pos (marker-position marker))
6169 (hdmarker (get-text-property (point) 'org-hd-marker))
6170 (buffer-read-only nil)
6172 (with-current-buffer buffer
6175 (org-show-hidden-entry)
6177 (and (outline-next-heading)
6178 (org-flag-heading nil))) ; show the next heading
6179 (funcall 'org-priority force-direction)
6181 (setq newhead (org-get-heading)))
6182 (org-agenda-change-all-lines newhead hdmarker)
6183 (beginning-of-line 1)))
6185 (defun org-get-tags-at (&optional pos)
6186 "Get a list of all headline targs applicable at POS.
6187 POS defaults to point. If tags are inherited, the list contains
6188 the targets in the same sequence as the headlines appear, i.e.
6189 the tags of the current headline come last."
6193 (goto-char (or pos (point)))
6195 (org-back-to-heading t)
6198 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6199 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6200 (or org-use-tag-inheritance (error ""))
6201 (org-up-heading-all 1))
6206 (defun org-agenda-set-tags ()
6207 "Set tags for the current headline."
6209 (org-agenda-check-no-diary)
6210 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6211 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6212 (org-agenda-error)))
6213 (buffer (marker-buffer hdmarker))
6214 (pos (marker-position hdmarker))
6215 (buffer-read-only nil)
6217 (with-current-buffer buffer
6220 (org-show-hidden-entry)
6222 (and (outline-next-heading)
6223 (org-flag-heading nil))) ; show the next heading
6224 (call-interactively 'org-set-tags)
6226 (setq newhead (org-get-heading)))
6227 (org-agenda-change-all-lines newhead hdmarker)
6228 (beginning-of-line 1)))
6230 (defun org-agenda-date-later (arg &optional what)
6231 "Change the date of this item to one day later."
6233 (org-agenda-check-type t 'agenda 'timeline)
6234 (org-agenda-check-no-diary)
6235 (let* ((marker (or (get-text-property (point) 'org-marker)
6236 (org-agenda-error)))
6237 (buffer (marker-buffer marker))
6238 (pos (marker-position marker)))
6239 (with-current-buffer buffer
6242 (if (not (org-at-timestamp-p))
6243 (error "Cannot find time stamp"))
6244 (org-timestamp-change arg (or what 'day))
6245 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6247 (defun org-agenda-date-earlier (arg &optional what)
6248 "Change the date of this item to one day earlier."
6250 (org-agenda-date-later (- arg) what))
6252 (defun org-agenda-date-prompt (arg)
6253 "Change the date of this item. Date is prompted for, with default today.
6254 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6255 be used to request time specification in the time stamp."
6257 (org-agenda-check-type t 'agenda 'timeline)
6258 (org-agenda-check-no-diary)
6259 (let* ((marker (or (get-text-property (point) 'org-marker)
6260 (org-agenda-error)))
6261 (buffer (marker-buffer marker))
6262 (pos (marker-position marker)))
6263 (with-current-buffer buffer
6266 (if (not (org-at-timestamp-p))
6267 (error "Cannot find time stamp"))
6268 (org-time-stamp arg)
6269 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6271 (defun org-get-heading ()
6272 "Return the heading of the current entry, without the stars."
6274 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6275 ;;FIXME???????? (and (bolp) (end-of-line 1))
6276 (if (and (re-search-backward "[\r\n]\\*" nil t)
6277 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6281 (defun org-agenda-diary-entry ()
6282 "Make a diary entry, like the `i' command from the calendar.
6283 All the standard commands work: block, weekly etc."
6285 (org-agenda-check-type t 'agenda 'timeline)
6286 (require 'diary-lib)
6288 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6289 (read-char-exclusive)))
6290 (cmd (cdr (assoc char
6291 '((?d . insert-diary-entry)
6292 (?w . insert-weekly-diary-entry)
6293 (?m . insert-monthly-diary-entry)
6294 (?y . insert-yearly-diary-entry)
6295 (?a . insert-anniversary-diary-entry)
6296 (?b . insert-block-diary-entry)
6297 (?c . insert-cyclic-diary-entry)))))
6298 (oldf (symbol-function 'calendar-cursor-to-date))
6300 (mark (or (mark t) (point))))
6302 (error "No command associated with <%c>" char))
6303 (unless (and (get-text-property point 'day)
6304 (or (not (equal ?b char))
6305 (get-text-property mark 'day)))
6306 (error "Don't know which date to use for diary entry"))
6307 ;; We implement this by hacking the `calendar-cursor-to-date' function
6308 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6309 (let ((calendar-mark-ring
6310 (list (calendar-gregorian-from-absolute
6311 (or (get-text-property mark 'day)
6312 (get-text-property point 'day))))))
6315 (fset 'calendar-cursor-to-date
6316 (lambda (&optional error)
6317 (calendar-gregorian-from-absolute
6318 (get-text-property point 'day))))
6319 (call-interactively cmd))
6320 (fset 'calendar-cursor-to-date oldf)))))
6323 (defun org-agenda-execute-calendar-command (cmd)
6324 "Execute a calendar command from the agenda, with the date associated to
6325 the cursor position."
6326 (org-agenda-check-type t 'agenda 'timeline)
6327 (require 'diary-lib)
6328 (unless (get-text-property (point) 'day)
6329 (error "Don't know which date to use for calendar command"))
6330 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6332 (date (calendar-gregorian-from-absolute
6333 (get-text-property point 'day)))
6334 (displayed-day (extract-calendar-day date))
6335 (displayed-month (extract-calendar-month date))
6336 (displayed-year (extract-calendar-year date)))
6339 (fset 'calendar-cursor-to-date
6340 (lambda (&optional error)
6341 (calendar-gregorian-from-absolute
6342 (get-text-property point 'day))))
6343 (call-interactively cmd))
6344 (fset 'calendar-cursor-to-date oldf))))
6346 (defun org-agenda-phases-of-moon ()
6347 "Display the phases of the moon for the 3 months around the cursor date."
6349 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6351 (defun org-agenda-holidays ()
6352 "Display the holidays for the 3 months around the cursor date."
6354 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6356 (defun org-agenda-sunrise-sunset (arg)
6357 "Display sunrise and sunset for the cursor date.
6358 Latitude and longitude can be specified with the variables
6359 `calendar-latitude' and `calendar-longitude'. When called with prefix
6360 argument, latitude and longitude will be prompted for."
6362 (let ((calendar-longitude (if arg nil calendar-longitude))
6363 (calendar-latitude (if arg nil calendar-latitude))
6364 (calendar-location-name
6365 (if arg "the given coordinates" calendar-location-name)))
6366 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6368 (defun org-agenda-goto-calendar ()
6369 "Open the Emacs calendar with the date at the cursor."
6371 (org-agenda-check-type t 'agenda 'timeline)
6372 (let* ((day (or (get-text-property (point) 'day)
6373 (error "Don't know which date to open in calendar")))
6374 (date (calendar-gregorian-from-absolute day))
6375 (calendar-move-hook nil)
6376 (view-diary-entries-initially nil))
6378 (calendar-goto-date date)))
6380 (defun org-calendar-goto-agenda ()
6381 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6382 This is a command that has to be installed in `calendar-mode-map'."
6384 (org-agenda-list nil (calendar-absolute-from-gregorian
6385 (calendar-cursor-to-date))
6388 (defun org-agenda-convert-date ()
6390 (org-agenda-check-type t 'agenda 'timeline)
6391 (let ((day (get-text-property (point) 'day))
6394 (error "Don't know which date to convert"))
6395 (setq date (calendar-gregorian-from-absolute day))
6397 "Gregorian: " (calendar-date-string date) "\n"
6398 "ISO: " (calendar-iso-date-string date) "\n"
6399 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6400 "Julian: " (calendar-julian-date-string date) "\n"
6401 "Astron. JD: " (calendar-astro-date-string date)
6402 " (Julian date number at noon UTC)\n"
6403 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6404 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6405 "French: " (calendar-french-date-string date) "\n"
6406 "Mayan: " (calendar-mayan-date-string date) "\n"
6407 "Coptic: " (calendar-coptic-date-string date) "\n"
6408 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6409 "Persian: " (calendar-persian-date-string date) "\n"
6410 "Chinese: " (calendar-chinese-date-string date) "\n"))
6411 (with-output-to-temp-buffer "*Dates*"
6413 (if (fboundp 'fit-window-to-buffer)
6414 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6418 (defun org-scan-tags (action matcher &optional todo-only)
6419 "Scan headline tags with inheritance and produce output ACTION.
6420 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6421 evaluated, testing if a given set of tags qualifies a headline for
6422 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
6423 are included in the output."
6424 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6425 (mapconcat 'regexp-quote
6426 (nreverse (cdr (reverse org-todo-keywords)))
6428 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
6429 (props (list 'face nil
6430 'done-face 'org-done
6432 'mouse-face 'highlight
6433 'keymap org-agenda-keymap
6435 (format "mouse-2 or RET jump to org file %s"
6436 (abbreviate-file-name (buffer-file-name)))))
6438 tags tags-list tags-alist (llast 0) rtn level category i txt
6442 (goto-char (point-min))
6443 (when (eq action 'sparse-tree) (hide-sublevels 1))
6444 (while (re-search-forward re nil t)
6445 (setq todo (if (match-end 1) (match-string 2))
6446 tags (if (match-end 4) (match-string 4)))
6447 (goto-char (setq lspos (1+ (match-beginning 0))))
6448 (setq level (outline-level)
6449 category (org-get-category))
6450 (setq i llast llast level)
6451 ;; remove tag lists from same and sublevels
6453 (when (setq entry (assoc i tags-alist))
6454 (setq tags-alist (delete entry tags-alist)))
6458 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6460 (cons (cons level tags) tags-alist)))
6461 ;; compile tags for current headline
6463 (if org-use-tag-inheritance
6464 (apply 'append (mapcar 'cdr tags-alist))
6466 (when (and (or (not todo-only) todo)
6468 ;; list this headline
6469 (if (eq action 'sparse-tree)
6471 (org-show-hierarchy-above))
6472 (setq txt (org-format-agenda-item
6475 (if org-tags-match-list-sublevels
6476 (make-string (1- level) ?.) "")
6478 category tags-list))
6480 (setq marker (org-agenda-new-marker))
6481 (add-text-properties
6483 (append (list 'org-marker marker 'org-hd-marker marker
6488 ;; if we are to skip sublevels, jump to end of subtree
6490 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6493 (defun org-tags-sparse-tree (&optional arg match)
6494 "Create a sparse tree according to tags search string MATCH.
6495 MATCH can contain positive and negative selection of tags, like
6496 \"+WORK+URGENT-WITHBOSS\"."
6498 (let ((org-show-following-heading nil)
6499 (org-show-hierarchy-above nil))
6500 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6502 (defun org-make-tags-matcher (match)
6503 "Create the TAGS matcher form for the tags-selecting string MATCH."
6505 ;; Get a new match request, with completion
6506 (setq org-last-tags-completion-table
6507 (or (org-get-buffer-tags)
6508 org-last-tags-completion-table))
6509 (setq match (completing-read
6510 "Tags: " 'org-tags-completion-function nil nil nil
6511 'org-tags-history)))
6512 ;; parse the string and create a lisp form
6513 (let ((match0 match) minus tag mm matcher orterms term orlist)
6514 (setq orterms (org-split-string match "|"))
6515 (while (setq term (pop orterms))
6516 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
6517 (setq minus (and (match-end 1)
6518 (equal (match-string 1 term) "-"))
6519 tag (match-string 2 term)
6520 term (substring term (match-end 0))
6521 mm (list 'member (downcase tag) 'tags-list)
6522 mm (if minus (list 'not mm) mm))
6524 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6527 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6528 ;; Return the string and lisp forms of the matcher
6529 (cons match0 matcher)))
6532 (defun org-tags-view (&optional todo-only match keep-modes)
6533 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
6534 The prefix arg TODO-ONLY limits the search to TODO entries."
6536 (org-agenda-maybe-reset-markers 'force)
6537 (org-compile-prefix-format org-agenda-prefix-format)
6538 (let* ((org-agenda-keep-modes keep-modes)
6539 (org-tags-match-list-sublevels
6540 (if todo-only t org-tags-match-list-sublevels))
6541 (win (selected-window))
6542 (completion-ignore-case t)
6543 rtn rtnall files file pos matcher
6545 (setq matcher (org-make-tags-matcher match)
6546 match (car matcher) matcher (cdr matcher))
6547 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6549 (delete-other-windows)
6550 (switch-to-buffer-other-window
6551 (get-buffer-create org-agenda-buffer-name))))
6552 (setq buffer-read-only nil)
6554 (org-agenda-mode) (setq buffer-read-only nil)
6555 (set (make-local-variable 'org-agenda-type) 'tags)
6556 (set (make-local-variable 'org-agenda-redo-command)
6557 (list 'org-tags-view (list 'quote todo-only)
6558 (list 'if 'current-prefix-arg nil match) t))
6559 (setq files (org-agenda-files)
6561 (while (setq file (pop files))
6563 (org-check-agenda-file file)
6564 (setq buffer (if (file-exists-p file)
6565 (org-get-agenda-file-buffer file)
6566 (error "No such file %s" file)))
6568 ;; If file does not exist, merror message to agenda
6570 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6571 rtnall (append rtnall rtn))
6572 (with-current-buffer buffer
6573 (unless (eq major-mode 'org-mode)
6574 (error "Agenda file %s is not in `org-mode'" file))
6577 (if org-respect-restriction
6578 (if (org-region-active-p)
6579 ;; Respect a region to restrict search
6580 (narrow-to-region (region-beginning) (region-end)))
6581 ;; If we work for the calendar or many files,
6582 ;; get rid of any restriction
6584 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6585 (setq rtnall (append rtnall rtn))))))))
6586 (insert "Headlines with TAGS match: ")
6587 (add-text-properties (point-min) (1- (point))
6588 (list 'face 'org-link))
6591 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6593 (insert "Press `C-u r' to search again with new search string\n")
6594 (add-text-properties pos (1- (point)) (list 'face 'org-link))
6596 (insert (mapconcat 'identity rtnall "\n")))
6597 (goto-char (point-min))
6598 (setq buffer-read-only t)
6599 (org-fit-agenda-window)
6600 (if (not org-select-agenda-window) (select-window win))))
6602 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
6603 (defun org-set-tags (&optional arg just-align)
6604 "Set the tags for the current headline.
6605 With prefix ARG, realign all tags in headings in the current buffer."
6607 (let* (;(inherit (org-get-inherited-tags))
6608 (re (concat "^" outline-regexp))
6609 (col (current-column))
6610 (current (org-get-tags))
6611 tags hd empty invis)
6614 (goto-char (point-min))
6615 (while (re-search-forward re nil t)
6616 (org-set-tags nil t))
6617 (message "All tags realigned to column %d" org-tags-column))
6620 (setq org-last-tags-completion-table
6621 (or (org-get-buffer-tags)
6622 org-last-tags-completion-table))
6624 (let ((org-add-colon-after-tag-completion t))
6625 (completing-read "Tags: " 'org-tags-completion-function
6626 nil nil current 'org-tags-history)))
6627 (while (string-match "[-+&]+" tags)
6628 (setq tags (replace-match ":" t t tags)))
6629 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
6630 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
6631 (unless (string-match "^:" tags) (setq tags (concat ":" tags)))))
6632 (if (equal current "")
6635 (or empty (insert-before-markers " ")))
6636 (beginning-of-line 1)
6637 (setq invis (org-invisible-p))
6638 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
6639 (setq hd (match-string 1))
6640 (delete-region (match-beginning 0) (match-end 0))
6641 (insert-before-markers (org-trim hd) (if empty "" " ")))
6642 ;; FIXME: What happens when adding a new tag??? Seems OK!!!
6643 (unless (equal tags "")
6644 (move-to-column (max (current-column)
6645 (if (> org-tags-column 0)
6647 (- (- org-tags-column) (length tags))))
6649 (insert-before-markers tags)
6650 (if (and (not invis) (org-invisible-p))
6651 (outline-flag-region (point-at-bol) (point) nil)))
6652 (move-to-column col))))
6654 (defun org-tags-completion-function (string predicate &optional flag)
6655 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
6656 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
6657 (setq s1 (match-string 1 string)
6658 s2 (match-string 2 string))
6659 (setq s1 "" s2 string))
6663 (setq rtn (try-completion s2 ctable))
6665 (concat s1 s2 (substring rtn (length s2))
6666 (if (and org-add-colon-after-tag-completion
6672 (all-completions s2 ctable)
6679 (defun org-get-tags ()
6680 "Get the TAGS string in the current headline."
6681 (unless (org-on-heading-p)
6682 (error "Not on a heading"))
6684 (beginning-of-line 1)
6685 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
6689 (defun org-get-buffer-tags ()
6690 "Get a table of all tags used in the buffer, for completion."
6693 (goto-char (point-min))
6694 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
6695 (mapc (lambda (x) (add-to-list 'tags x))
6696 (org-split-string (match-string 1) ":"))))
6697 (mapcar 'list tags)))
6701 (defun org-find-file-at-mouse (ev)
6702 "Open file link or URL at mouse."
6704 (mouse-set-point ev)
6705 (org-open-at-point 'in-emacs))
6707 (defun org-open-at-mouse (ev)
6708 "Open file link or URL at mouse."
6710 (mouse-set-point ev)
6711 (org-open-at-point))
6713 (defun org-open-at-point (&optional in-emacs)
6714 "Open link at or after point.
6715 If there is no link at point, this function will search forward up to
6716 the end of the current subtree.
6717 Normally, files will be opened by an appropriate application. If the
6718 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6720 (org-remove-occur-highlights nil nil t)
6721 (if (org-at-timestamp-p)
6722 (org-agenda-list nil (time-to-days (org-time-string-to-time
6723 (substring (match-string 1) 0 10)))
6725 (let (type path link line search (pos (point)))
6728 (skip-chars-forward "^]\n\r")
6729 (when (and (re-search-backward "\\[\\[" nil t)
6730 (looking-at org-bracket-link-regexp)
6731 (<= (match-beginning 0) pos)
6732 (>= (match-end 0) pos))
6733 (setq link (match-string 1))
6734 (while (string-match " *\n *" link)
6735 (setq link (replace-match " " t t link)))
6736 (if (string-match org-link-regexp link)
6737 (setq type (match-string 1)
6738 path (match-string 2))
6739 (setq type "thisfile"
6743 (when (get-text-property (point) 'org-linked-text)
6744 (setq type "thisfile"
6745 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6746 (1+ (point)) (point))
6747 path (buffer-substring
6748 (previous-single-property-change pos 'org-linked-text)
6749 (next-single-property-change pos 'org-linked-text)))
6753 (skip-chars-backward
6754 (concat (if org-allow-space-in-links "^" "^ ")
6755 org-non-link-chars))
6756 (when (or (looking-at org-link-regexp)
6757 (and (re-search-forward org-link-regexp (point-at-eol) t)
6758 (<= (match-beginning 0) pos)
6759 (>= (match-end 0) pos)))
6760 (setq type (match-string 1)
6761 path (match-string 2))
6764 (skip-chars-backward "^ \t\n\r")
6765 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
6767 path (match-string 1))
6768 (while (string-match ":" path)
6769 (setq path (replace-match "+" t t path)))
6772 (skip-chars-backward "a-zA-Z_")
6773 (when (and org-activate-camels
6774 (looking-at org-camel-regexp))
6775 (setq type "camel" path (match-string 0))
6776 (if (equal (char-before) ?*)
6777 (setq path (concat "*" path))))
6780 (when (re-search-forward
6784 (progn (outline-end-of-subtree) (max pos (point)))
6785 (error (end-of-line 1) (point))))
6787 (setq type (match-string 1)
6788 path (match-string 2)))))
6790 (error "No link found"))
6791 ;; Remove any trailing spaces in path
6792 (if (string-match " +\\'" path)
6793 (setq path (replace-match "" t t path)))
6797 ((string= type "tags")
6798 (org-tags-view in-emacs path))
6799 ((or (string= type "camel")
6800 (string= type "thisfile"))
6801 (org-mark-ring-push)
6804 (cond ((equal in-emacs '(4)) 'occur)
6805 ((equal in-emacs '(16)) 'org-occur)
6808 ((string= type "file")
6809 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
6810 (setq line (string-to-number (match-string 1 path))
6811 path (substring path 0 (match-beginning 0)))
6812 (if (string-match "::\\(.+\\)\\'" path)
6813 (setq search (match-string 1 path)
6814 path (substring path 0 (match-beginning 0)))))
6815 (org-open-file path in-emacs line search))
6817 ((string= type "news")
6818 (org-follow-gnus-link path))
6820 ((string= type "bbdb")
6821 (org-follow-bbdb-link path))
6823 ((string= type "gnus")
6824 (let (group article)
6825 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6826 (error "Error in Gnus link"))
6827 (setq group (match-string 1 path)
6828 article (match-string 3 path))
6829 (org-follow-gnus-link group article)))
6831 ((string= type "vm")
6832 (let (folder article)
6833 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6834 (error "Error in VM link"))
6835 (setq folder (match-string 1 path)
6836 article (match-string 3 path))
6837 ;; in-emacs is the prefix arg, will be interpreted as read-only
6838 (org-follow-vm-link folder article in-emacs)))
6840 ((string= type "wl")
6841 (let (folder article)
6842 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6843 (error "Error in Wanderlust link"))
6844 (setq folder (match-string 1 path)
6845 article (match-string 3 path))
6846 (org-follow-wl-link folder article)))
6848 ((string= type "mhe")
6849 (let (folder article)
6850 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6851 (error "Error in MHE link"))
6852 (setq folder (match-string 1 path)
6853 article (match-string 3 path))
6854 (org-follow-mhe-link folder article)))
6856 ((string= type "rmail")
6857 (let (folder article)
6858 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6859 (error "Error in RMAIL link"))
6860 (setq folder (match-string 1 path)
6861 article (match-string 3 path))
6862 (org-follow-rmail-link folder article)))
6864 ((string= type "shell")
6866 (while (string-match "@{" cmd)
6867 (setq cmd (replace-match "<" t t cmd)))
6868 (while (string-match "@}" cmd)
6869 (setq cmd (replace-match ">" t t cmd)))
6870 (if (or (not org-confirm-shell-links)
6871 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
6876 (browse-url-at-point))))))
6878 (defun org-link-search (s &optional type)
6879 "Search for a link search option.
6880 When S is a CamelCaseWord, search for a target, or for a sentence containing
6881 the words. If S is surrounded by forward slashes, it is interpreted as a
6882 regular expression. In org-mode files, this will create an `org-occur'
6883 sparse tree. In ordinary files, `occur' will be used to list matches.
6884 If the current buffer is in `dired-mode', grep will be used to search
6886 (let ((case-fold-search t)
6887 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6890 words re0 re1 re2 re3 re4 re5 reall camel)
6891 (cond ((save-excursion
6892 (goto-char (point-min))
6895 (concat "<<" (regexp-quote s0) ">>") nil t)
6896 (setq pos (match-beginning 0))))
6897 ;; There is an exact target for this
6899 ((string-match "^/\\(.*\\)/$" s)
6900 ;; A regular expression
6902 ((eq major-mode 'org-mode)
6903 (org-occur (match-string 1 s)))
6904 ;;((eq major-mode 'dired-mode)
6905 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6906 (t (org-do-occur (match-string 1 s)))))
6907 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
6909 ;; A camel or a normal search string
6910 (when (equal (string-to-char s) ?*)
6911 ;; Anchor on headlines, post may include tags.
6912 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
6913 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
6915 (remove-text-properties
6917 '(face nil mouse-face nil keymap nil fontified nil) s)
6918 ;; Make a series of regular expressions to find a match
6921 (org-camel-to-words s)
6922 (org-split-string s "[ \n\r\t]+"))
6923 re0 (concat "<<" (regexp-quote s0) ">>")
6924 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
6925 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
6926 re1 (concat pre re2 post)
6927 re3 (concat pre re4 post)
6928 re5 (concat pre ".*" re4)
6929 re2 (concat pre re2)
6930 re4 (concat pre re4)
6931 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6932 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6936 ((eq type 'org-occur) (org-occur reall))
6937 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6938 (t (goto-char (point-min))
6939 (if (or (re-search-forward re0 nil t)
6940 (re-search-forward re1 nil t)
6941 (re-search-forward re2 nil t)
6942 (re-search-forward re3 nil t)
6943 (re-search-forward re4 nil t)
6944 (re-search-forward re5 nil t))
6945 (goto-char (match-beginning 0))
6947 (error "No match")))))
6949 ;; Normal string-search
6950 (goto-char (point-min))
6951 (if (search-forward s nil t)
6952 (goto-char (match-beginning 0))
6953 (error "No match"))))
6954 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
6956 (defun org-do-occur (regexp &optional cleanup)
6957 "Call the Emacs command `occur'.
6958 If CLEANUP is non-nil, remove the printout of the regular expression
6959 in the *Occur* buffer. This is useful if the regex is long and not useful
6963 (let ((cwin (selected-window)) win beg end)
6964 (when (setq win (get-buffer-window "*Occur*"))
6965 (select-window win))
6966 (goto-char (point-min))
6967 (when (re-search-forward "match[a-z]+" nil t)
6968 (setq beg (match-end 0))
6969 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6970 (setq end (1- (match-beginning 0)))))
6971 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
6972 (goto-char (point-min))
6973 (select-window cwin))))
6975 (defvar org-mark-ring nil
6976 "Mark ring for positions before jumps in Org-mode.")
6977 (defvar org-mark-ring-last-goto nil
6978 "Last position in the mark ring used to go back.")
6979 ;; Fill and close the ring
6980 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
6981 (loop for i from 1 to org-mark-ring-length do
6982 (push (make-marker) org-mark-ring))
6983 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
6986 (defun org-mark-ring-push (&optional pos buffer)
6987 "Put the current position or POS into the mark ring and rotate it."
6989 (setq pos (or pos (point)))
6990 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
6991 (move-marker (car org-mark-ring)
6993 (or buffer (current-buffer)))
6995 (substitute-command-keys
6996 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
6998 (defun org-mark-ring-goto (&optional n)
6999 "Jump to the previous position in the mark ring.
7000 With prefix arg N, jump back that many stored positions. When
7001 called several times in succession, walk through the entire ring.
7002 Org-mode commands jumping to a different position in the current file,
7003 or to another Org-mode file, automatically push the old position
7007 (if (eq last-command this-command)
7008 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7009 (setq p org-mark-ring))
7010 (setq org-mark-ring-last-goto p)
7012 (switch-to-buffer (marker-buffer m))
7014 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7016 (defun org-camel-to-words (s)
7017 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7018 (let ((case-fold-search nil)
7020 (while (string-match "[a-z][A-Z]" s)
7021 (push (substring s 0 (1+ (match-beginning 0))) words)
7022 (setq s (substring s (1+ (match-beginning 0)))))
7023 (nreverse (cons s words))))
7025 (defun org-remove-angle-brackets (s)
7026 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7027 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7029 (defun org-add-angle-brackets (s)
7030 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7031 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7034 (defun org-follow-bbdb-link (name)
7035 "Follow a BBDB link to NAME."
7037 (let ((inhibit-redisplay t)
7038 (bbdb-electric-p nil))
7040 ;; Exact match on name
7041 (bbdb-name (concat "\\`" name "\\'") nil)
7042 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7043 ;; Exact match on name
7044 (bbdb-company (concat "\\`" name "\\'") nil)
7045 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7046 ;; Partial match on name
7047 (bbdb-name name nil)
7048 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7049 ;; Partial match on company
7050 (bbdb-company name nil)
7051 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7052 ;; General match including network address and notes
7054 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7055 (delete-window (get-buffer-window "*BBDB*"))
7056 (error "No matching BBDB record")))))
7058 (defun org-follow-gnus-link (&optional group article)
7059 "Follow a Gnus link to GROUP and ARTICLE."
7061 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7062 (if group (gnus-fetch-group group))
7064 (or (gnus-summary-goto-article article nil 'force)
7065 (if (fboundp 'gnus-summary-insert-cached-articles)
7067 (gnus-summary-insert-cached-articles)
7068 (gnus-summary-goto-article article nil 'force))
7069 (message "Message could not be found.")))))
7071 (defun org-follow-vm-link (&optional folder article readonly)
7072 "Follow a VM link to FOLDER and ARTICLE."
7074 (setq article (org-add-angle-brackets article))
7075 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7076 ;; ange-ftp or efs or tramp access
7077 (let ((user (or (match-string 1 folder) (user-login-name)))
7078 (host (match-string 2 folder))
7079 (file (match-string 3 folder)))
7082 ;; use tramp to access the file
7084 (setq folder (format "[%s@%s]%s" user host file))
7085 (setq folder (format "/%s@%s:%s" user host file))))
7087 ;; use ange-ftp or efs
7088 (require (if org-xemacs-p 'efs 'ange-ftp))
7089 (setq folder (format "/%s@%s:%s" user host file))))))
7091 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7094 (vm-select-folder-buffer)
7096 (let ((case-fold-search t))
7097 (goto-char (point-min))
7098 (if (not (re-search-forward
7099 (concat "^" "message-id: *" (regexp-quote article))))
7100 (error "Could not find the specified message in this folder"))
7103 (vm-beginning-of-message)
7106 (defun org-follow-wl-link (folder article)
7107 "Follow a Wanderlust link to FOLDER and ARTICLE."
7108 (setq article (org-add-angle-brackets article))
7109 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7110 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7111 (wl-summary-redisplay))
7113 (defun org-follow-rmail-link (folder article)
7114 "Follow an RMAIL link to FOLDER and ARTICLE."
7115 (setq article (org-add-angle-brackets article))
7116 (let (message-number)
7118 (save-window-excursion
7119 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7120 (setq message-number
7123 (goto-char (point-max))
7124 (if (re-search-backward
7125 (concat "^Message-ID:\\s-+" (regexp-quote
7128 (rmail-what-message))))))
7131 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7132 (rmail-show-message message-number)
7134 (error "Message not found"))))
7136 ;; mh-e integration based on planner-mode
7137 (defun org-mhe-get-message-real-folder ()
7138 "Return the name of the current message real folder, so if you use
7139 sequences, it will now work."
7142 (if (equal major-mode 'mh-folder-mode)
7144 ;; Refer to the show buffer
7145 mh-show-folder-buffer))
7147 (if (boundp 'mh-index-folder)
7148 (min (length mh-index-folder) (length folder))))
7150 ;; a simple test on mh-index-data does not work, because
7151 ;; mh-index-data is always nil in a show buffer.
7152 (if (and (boundp 'mh-index-folder)
7153 (string= mh-index-folder (substring folder 0 end-index)))
7154 (if (equal major-mode 'mh-show-mode)
7155 (save-window-excursion
7156 (when (buffer-live-p (get-buffer folder))
7158 (pop-to-buffer folder)
7159 (org-mhe-get-message-folder-from-index)
7162 (org-mhe-get-message-folder-from-index)
7168 (defun org-mhe-get-message-folder-from-index ()
7169 "Returns the name of the message folder in a index folder buffer."
7171 (mh-index-previous-folder)
7172 (if (not (re-search-forward "^\\(+.*\\)$" nil t))
7173 (message "Problem getting folder from index.")
7174 (message (match-string 1)))))
7176 (defun org-mhe-get-message-folder ()
7177 "Return the name of the current message folder. Be careful if you
7180 (if (equal major-mode 'mh-folder-mode)
7182 ;; Refer to the show buffer
7183 mh-show-folder-buffer)))
7185 (defun org-mhe-get-message-num ()
7186 "Return the number of the current message. Be careful if you
7189 (if (equal major-mode 'mh-folder-mode)
7190 (mh-get-msg-num nil)
7191 ;; Refer to the show buffer
7192 (mh-show-buffer-message-number))))
7194 (defun org-mhe-get-header (header)
7195 "Return a header of the message in folder mode. This will create a
7196 show buffer for the corresponding message. If you have a more clever
7198 (let* ((folder (org-mhe-get-message-folder))
7199 (num (org-mhe-get-message-num))
7200 (buffer (get-buffer-create (concat "show-" folder)))
7202 (with-current-buffer buffer
7203 (mh-display-msg num folder)
7204 (if (equal major-mode 'mh-folder-mode)
7206 (mh-show-header-display))
7208 (setq header-field (mh-get-header-field header))
7209 (if (equal major-mode 'mh-folder-mode)
7214 (defun org-follow-mhe-link (folder article)
7215 "Follow an MHE link to FOLDER and ARTICLE."
7216 (setq article (org-add-angle-brackets article))
7219 (let* ((show-buf (concat "show-" folder)))
7220 (mh-visit-folder folder)
7221 (get-buffer-create show-buf)
7227 (expand-file-name "pick" mh-progs)
7234 (pop-to-buffer show-buf)))
7236 (defun org-open-file (path &optional in-emacs line search)
7237 "Open the file at PATH.
7238 First, this expands any special file name abbreviations. Then the
7239 configuration variable `org-file-apps' is checked if it contains an
7240 entry for this file type, and if yes, the corresponding command is launched.
7241 If no application is found, Emacs simply visits the file.
7242 With optional argument IN-EMACS, Emacs will visit the file.
7243 Optional LINE specifies a line to go to, optional SEARCH a string to
7244 search for. If LINE or SEARCH is given, the file will always be
7246 If the file does not exist, an error is thrown."
7247 (setq in-emacs (or in-emacs line search))
7248 (let* ((file (if (equal path "")
7250 (convert-standard-filename (org-expand-file-name path))))
7251 (dirp (file-directory-p file))
7252 (dfile (downcase file))
7253 (old-buffer (current-buffer))
7255 (old-mode major-mode)
7257 (if (and (not (file-exists-p file))
7258 (not org-open-non-existing-files))
7259 (error "No such file: %s" file))
7260 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7261 (setq ext (match-string 1 dfile))
7262 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7263 (setq ext (match-string 1 dfile))))
7264 (setq apps (append org-file-apps (org-default-apps)))
7267 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7268 (cdr (assoc ext apps))
7269 (cdr (assoc t apps)))))
7270 (when (eq cmd 'mailcap)
7272 (mailcap-parse-mailcaps)
7273 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7274 (command (mailcap-mime-info mime-type)))
7275 (if (stringp command)
7277 (setq cmd 'emacs))))
7279 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7280 (setq cmd (format cmd (concat "\"" file "\"")))
7281 (save-window-excursion
7282 (shell-command (concat cmd " &"))))
7285 (unless (equal (file-truename file) (file-truename (buffer-file-name)))
7286 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7287 (if line (goto-line line)
7288 (if search (org-link-search search))))
7291 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7292 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7293 (or (not (equal old-buffer (current-buffer)))
7294 (not (equal old-pos (point))))
7295 (org-mark-ring-push old-pos old-buffer))))
7297 (defun org-default-apps ()
7298 "Return the default applications for this operating system."
7300 ((eq system-type 'darwin)
7301 org-file-apps-defaults-macosx)
7302 ((eq system-type 'windows-nt)
7303 org-file-apps-defaults-windowsnt)
7304 (t org-file-apps-defaults-gnu)))
7306 (defun org-expand-file-name (path)
7307 "Replace special path abbreviations and expand the file name."
7308 (expand-file-name path))
7311 (defvar org-insert-link-history nil
7312 "Minibuffer history for links inserted with `org-insert-link'.")
7314 (defvar org-stored-links nil
7315 "Contains the links stored with `org-store-link'.")
7318 (defun org-store-link (arg)
7319 "\\<org-mode-map>Store an org-link to the current location.
7320 This link can later be inserted into an org-buffer with
7321 \\[org-insert-link].
7322 For some link types, a prefix arg is interpreted:
7323 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7324 For file links, arg negates `org-context-in-file-links'."
7326 (let (link cpltxt txt (pos (point)))
7329 ((eq major-mode 'bbdb-mode)
7330 (setq cpltxt (concat
7332 (or (bbdb-record-name (bbdb-current-record))
7333 (bbdb-record-company (bbdb-current-record))))
7334 link (org-make-link cpltxt)))
7336 ((eq major-mode 'calendar-mode)
7337 (let ((cd (calendar-cursor-to-date)))
7340 (car org-time-stamp-formats)
7342 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7345 ((or (eq major-mode 'vm-summary-mode)
7346 (eq major-mode 'vm-presentation-mode))
7347 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7348 (vm-follow-summary-cursor)
7350 (vm-select-folder-buffer)
7351 (let* ((message (car vm-message-pointer))
7352 (folder (buffer-file-name))
7353 (subject (vm-su-subject message))
7354 (author (vm-su-full-name message))
7355 (message-id (vm-su-message-id message)))
7356 (setq message-id (org-remove-angle-brackets message-id))
7357 (setq folder (abbreviate-file-name folder))
7358 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7360 (setq folder (replace-match "" t t folder)))
7361 (setq cpltxt (concat author " on: " subject))
7362 (setq link (concat cpltxt "\n "
7364 "vm:" folder "#" message-id))))))
7366 ((eq major-mode 'wl-summary-mode)
7367 (let* ((msgnum (wl-summary-message-number))
7368 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7369 msgnum 'message-id))
7370 (wl-message-entity (elmo-msgdb-overview-get-entity
7371 msgnum (wl-summary-buffer-msgdb)))
7372 (author (wl-summary-line-from)) ; FIXME: how to get author name?
7373 (subject "???")) ; FIXME: How to get subject of email?
7374 (setq message-id (org-remove-angle-brackets message-id))
7375 (setq cpltxt (concat author " on: " subject))
7376 (setq link (concat cpltxt "\n "
7378 "wl:" wl-summary-buffer-folder-name
7381 ((or (equal major-mode 'mh-folder-mode)
7382 (equal major-mode 'mh-show-mode))
7383 (let ((from-header (org-mhe-get-header "From:"))
7384 (to-header (org-mhe-get-header "To:"))
7385 (subject (org-mhe-get-header "Subject:")))
7386 (setq cpltxt (concat from-header " on: " subject))
7387 (setq link (concat cpltxt "\n "
7389 "mhe:" (org-mhe-get-message-real-folder) "#"
7390 (org-remove-angle-brackets
7391 (org-mhe-get-header "Message-Id:")))))))
7393 ((eq major-mode 'rmail-mode)
7396 (rmail-narrow-to-non-pruned-header)
7397 (let ((folder (buffer-file-name))
7398 (message-id (mail-fetch-field "message-id"))
7399 (author (mail-fetch-field "from"))
7400 (subject (mail-fetch-field "subject")))
7401 (setq message-id (org-remove-angle-brackets message-id))
7402 (setq cpltxt (concat author " on: " subject))
7403 (setq link (concat cpltxt "\n "
7405 "rmail:" folder "#" message-id)))))))
7407 ((eq major-mode 'gnus-group-mode)
7408 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7409 (gnus-group-group-name)) ; version
7410 ((fboundp 'gnus-group-name)
7413 (setq cpltxt (concat
7414 (if (org-xor arg org-usenet-links-prefer-google)
7415 "http://groups.google.com/groups?group="
7418 link (org-make-link cpltxt))))
7420 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7421 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7422 (gnus-summary-beginning-of-article)
7423 (let* ((group (car gnus-article-current))
7424 (article (cdr gnus-article-current))
7425 (header (gnus-summary-article-header article))
7426 (author (mail-header-from header))
7427 (message-id (mail-header-id header))
7428 (date (mail-header-date header))
7429 (subject (gnus-summary-subject-string)))
7430 (setq cpltxt (concat author " on: " subject))
7431 (if (org-xor arg org-usenet-links-prefer-google)
7435 (format "http://groups.google.com/groups?as_umsgid=%s"
7436 (org-fixup-message-id-for-http message-id))))
7437 (setq link (concat cpltxt "\n"
7440 "#" (number-to-string article)))))))
7442 ((eq major-mode 'w3-mode)
7443 (setq cpltxt (url-view-url t)
7444 link (org-make-link cpltxt)))
7445 ((eq major-mode 'w3m-mode)
7446 (setq cpltxt w3m-current-url
7447 link (org-make-link cpltxt)))
7449 ((eq major-mode 'org-mode)
7450 ;; Just link to current headline
7451 (setq cpltxt (concat "file:"
7452 (abbreviate-file-name (buffer-file-name))))
7453 ;; Add a context search string
7454 (when (org-xor org-context-in-file-links arg)
7455 ;; Check if we are on a target
7457 (skip-chars-forward "^>\n\r")
7458 (and (re-search-backward "<<" nil t)
7459 (looking-at "<<\\(.*?\\)>>")
7460 (<= (match-beginning 0) pos)
7461 (>= (match-end 0) pos)))
7462 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7464 ((org-on-heading-p) nil)
7465 ((org-region-active-p)
7466 (buffer-substring (region-beginning) (region-end)))
7467 (t (buffer-substring (point-at-bol) (point-at-eol)))))
7470 (if org-file-link-context-use-camel-case
7471 (org-make-org-heading-camel txt)
7472 (org-make-org-heading-search-string txt))))))
7473 (if (string-match "::\\'" cpltxt)
7474 (setq cpltxt (substring cpltxt 0 -2)))
7475 (setq link (org-make-link cpltxt)))
7478 ;; Just link to this file here.
7479 (setq cpltxt (concat "file:"
7480 (abbreviate-file-name (buffer-file-name))))
7481 ;; Add a context string
7482 (when (org-xor org-context-in-file-links arg)
7483 (setq txt (if (org-region-active-p)
7484 (buffer-substring (region-beginning) (region-end))
7485 (buffer-substring (point-at-bol) (point-at-eol))))
7488 (if org-file-link-context-use-camel-case
7489 (org-make-org-heading-camel txt)
7490 (org-make-org-heading-search-string txt)))))
7491 (setq link (org-make-link cpltxt)))
7494 (error "Cannot link to a buffer which is not visiting a file"))
7496 (t (setq link nil)))
7498 (if (and (interactive-p) link)
7500 (setq org-stored-links
7501 (cons (cons (or cpltxt link) link) org-stored-links))
7502 (message "Stored: %s" (or cpltxt link)))
7505 (defun org-make-org-heading-search-string (&optional string heading)
7506 "Make search string for STRING or current headline."
7508 (let ((s (or string (org-get-heading))))
7509 (unless (and string (not heading))
7510 ;; We are using a headline, clean up garbage in there.
7511 (if (string-match org-todo-regexp s)
7512 (setq s (replace-match "" t t s)))
7513 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7514 (setq s (replace-match "" t t s)))
7515 (setq s (org-trim s))
7516 (if (string-match (concat "^\\(" org-quote-string "\\|"
7517 org-comment-string "\\)") s)
7518 (setq s (replace-match "" t t s)))
7519 (while (string-match org-ts-regexp s)
7520 (setq s (replace-match "" t t s))))
7521 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7522 (setq s (replace-match " " t t s)))
7523 (or string (setq s (concat "*" s))) ; Add * for headlines
7524 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7526 (defun org-make-org-heading-camel (&optional string heading)
7527 "Make a CamelCase string for STRING or the current headline."
7529 (let ((s (or string (org-get-heading))))
7530 (unless (and string (not heading))
7531 ;; We are using a headline, clean up garbage in there.
7532 (if (string-match org-todo-regexp s)
7533 (setq s (replace-match "" t t s)))
7534 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7535 (setq s (replace-match "" t t s)))
7536 (setq s (org-trim s))
7537 (if (string-match (concat "^\\(" org-quote-string "\\|"
7538 org-comment-string "\\)") s)
7539 (setq s (replace-match "" t t s)))
7540 (while (string-match org-ts-regexp s)
7541 (setq s (replace-match "" t t s))))
7542 (while (string-match "[^a-zA-Z_ \t]+" s)
7543 (setq s (replace-match " " t t s)))
7544 (or string (setq s (concat "*" s))) ; Add * for headlines
7545 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7547 (defun org-make-link (&rest strings)
7548 "Concatenate STRINGS, format resulting string with `org-link-format'."
7549 (format org-link-format (apply 'concat strings)))
7551 (defun org-make-link2 (link &optional description)
7552 "Make a link with brackets."
7553 (concat "[[" link "]"
7554 (if description (concat "[" description "]") "")
7557 (defun org-xor (a b)
7561 (defun org-get-header (header)
7562 "Find a header field in the current buffer."
7564 (goto-char (point-min))
7565 (let ((case-fold-search t) s)
7568 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7569 (setq s (match-string 1)))
7570 (while (string-match "\"" s)
7571 (setq s (replace-match "" t t s)))
7572 (if (string-match "[<(].*" s)
7573 (setq s (replace-match "" t t s))))
7574 ((eq header 'message-id)
7575 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7576 (setq s (match-string 1))))
7577 ((eq header 'subject)
7578 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7579 (setq s (match-string 1)))))
7580 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7581 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7585 (defun org-fixup-message-id-for-http (s)
7586 "Replace special characters in a message id, so it can be used in an http query."
7587 (while (string-match "<" s)
7588 (setq s (replace-match "%3C" t t s)))
7589 (while (string-match ">" s)
7590 (setq s (replace-match "%3E" t t s)))
7591 (while (string-match "@" s)
7592 (setq s (replace-match "%40" t t s)))
7595 (defun org-insert-link (&optional complete-file)
7596 "Insert a link. At the prompt, enter the link.
7598 Completion can be used to select a link previously stored with
7599 `org-store-link'. When the empty string is entered (i.e. if you just
7600 press RET at the prompt), the link defaults to the most recently
7601 stored link. As SPC triggers completion in the minibuffer, you need to
7602 use M-SPC or C-q SPC to force the insertion of a space character.
7604 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7605 selected using completion. The path to the file will be relative to
7606 the current directory if the file is in the current directory or a
7607 subdirectory. Otherwise, the link will be the absolute path as
7608 completed in the minibuffer (i.e. normally ~/path/to/file).
7610 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7611 is in the current directory or below."
7613 (let ((link (if complete-file
7614 (read-file-name "File: ")
7616 "Link: " org-stored-links nil nil nil
7617 org-insert-link-history
7618 (or (car (car org-stored-links))))))
7620 (if (or (not link) (equal link ""))
7621 (error "No links available"))
7623 (let ((pwd (file-name-as-directory (expand-file-name "."))))
7625 ((equal complete-file '(16))
7628 "file:" (abbreviate-file-name (expand-file-name link)))))
7629 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7630 (expand-file-name link))
7633 "file:" (match-string 1 (expand-file-name link)))))
7634 (t (insert (org-make-link "file:" link)))))
7635 (setq linktxt (cdr (assoc link org-stored-links)))
7636 (if (not org-keep-stored-link-after-insertion)
7637 (setq org-stored-links (delq (assoc link org-stored-links)
7639 (if (not linktxt) (setq link (org-make-link link)))
7640 (setq link (or linktxt link))
7641 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
7642 (let* ((path (match-string 1 link))
7643 (case-fold-search nil)
7644 (search (match-string 2 link)))
7645 (when (save-match-data
7646 (equal (file-truename (buffer-file-name))
7647 (file-truename path)))
7648 ;; We are linking to this same file
7649 (if (and org-file-link-context-use-camel-case
7651 (string-match (concat "^" org-camel-regexp "$") search)))
7652 (setq link (replace-match search t t link)
7654 (setq link (replace-match (concat "[[" search "]]")
7657 (let ((lines (org-split-string link "\n")))
7658 (insert (car lines))
7659 (setq matched (or matched (string-match org-link-regexp (car lines))))
7660 (setq lines (cdr lines))
7664 (beginning-of-line 0)
7665 (looking-at "[ \t]+\\S-"))
7667 (setq matched (or matched
7668 (string-match org-link-regexp (car lines))))
7669 (insert (car lines))
7670 (setq lines (cdr lines))))
7672 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
7674 ;;; Hooks for remember.el
7676 (defun org-remember-annotation ()
7677 "Return a link to the current location as an annotation for remember.el.
7678 If you are using Org-mode files as target for data storage with
7679 remember.el, then the annotations should include a link compatible with the
7680 conventions in Org-mode. This function returns such a link."
7681 (org-store-link nil))
7683 (defconst org-remember-help
7684 "Select a destination location for the note.
7685 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
7686 RET at beg-of-buf -> Append to file as level 2 headline
7687 RET on headline -> Store as sublevel entry to current headline
7688 <left>/<right> -> before/after current headline, same headings level")
7691 (defun org-remember-handler ()
7692 "Store stuff from remember.el into an org file.
7693 First prompts for an org file. If the user just presses return, the value
7694 of `org-default-notes-file' is used.
7695 Then the command offers the headings tree of the selected file in order to
7696 file the text at a specific location.
7697 You can either immediately press RET to get the note appended to the
7698 file, or you can use vertical cursor motion and visibility cycling (TAB) to
7699 find a better place. Then press RET or <left> or <right> in insert the note.
7701 Key Cursor position Note gets inserted
7702 -----------------------------------------------------------------------------
7703 RET buffer-start as level 2 heading at end of file
7704 RET on headline as sublevel of the heading at cursor
7705 RET no heading at cursor position, level taken from context.
7706 Or use prefix arg to specify level manually.
7707 <left> on headline as same level, before current heading
7708 <right> on headline as same level, after current heading
7710 So the fastest way to store the note is to press RET RET to append it to
7711 the default file. This way your current train of thought is not
7712 interrupted, in accordance with the principles of remember.el. But with
7713 little extra effort, you can push it directly to the correct location.
7715 Before being stored away, the function ensures that the text has a
7716 headline, i.e. a first line that starts with a \"*\". If not, a headline
7717 is constructed from the current date and some additional data.
7719 If the variable `org-adapt-indentation' is non-nil, the entire text is
7720 also indented so that it starts in the same column as the headline
7721 \(i.e. after the stars).
7723 See also the variable `org-reverse-note-order'."
7725 (let* ((txt (buffer-substring (point-min) (point-max)))
7726 (fastp current-prefix-arg)
7727 (file (if fastp org-default-notes-file (org-get-org-file)))
7728 (visiting (find-buffer-visiting file))
7729 (org-startup-with-deadline-check nil)
7730 (org-startup-folded nil)
7731 spos level indent reversed)
7732 ;; Modify text so that it becomes a nice subtree which can be inserted
7733 ;; into an org tree.
7734 (let* ((lines (split-string txt "\n"))
7736 (lines (cdr lines)))
7737 (if (string-match "^\\*+" first)
7738 ;; Is already a headline
7739 (setq indent (make-string (- (match-end 0) (match-beginning 0)
7741 ;; We need to add a headline: Use time and first buffer line
7742 (setq lines (cons first lines)
7743 first (concat "* " (current-time-string)
7744 " (" (remember-buffer-desc) ")")
7746 (if org-adapt-indentation
7747 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
7748 (setq txt (concat first "\n"
7749 (mapconcat 'identity lines "\n"))))
7752 (find-file-noselect file))
7753 (with-current-buffer (get-file-buffer file)
7754 (setq reversed (org-notes-order-reversed-p))
7758 ;; Ask the User for a location
7759 (setq spos (if fastp 1 (org-get-location
7761 org-remember-help)))
7762 (if (not spos) (throw 'quit nil)) ; return nil to show we did
7763 ; not handle this note
7766 ;; Put it at the start or end, as level 2
7769 (goto-char (if reversed (point-min) (point-max)))
7770 (if (not (bolp)) (newline))
7771 (org-paste-subtree (or current-prefix-arg 2) txt)))
7772 ((and (org-on-heading-p nil) (not current-prefix-arg))
7773 ;; Put it below this entry, at the beg/end of the subtree
7774 (org-back-to-heading)
7775 (setq level (outline-level))
7777 (outline-end-of-heading)
7778 (outline-end-of-subtree))
7779 (if (not (bolp)) (newline))
7780 (beginning-of-line 1)
7781 (org-paste-subtree (1+ level) txt))
7783 ;; Put it right there, with automatic level determined by
7784 ;; org-paste-subtree or from prefix arg
7785 (org-paste-subtree current-prefix-arg txt)))
7786 (when remember-save-after-remembering
7788 (if (not visiting) (kill-buffer (current-buffer)))))))))
7789 t) ;; return t to indicate that we took care of this note.
7791 (defun org-get-org-file ()
7792 "Read a filename, with default directory `org-directory'."
7793 (let ((default (or org-default-notes-file remember-data-file)))
7794 (read-file-name (format "File name [%s]: " default)
7795 (file-name-as-directory org-directory)
7798 (defun org-notes-order-reversed-p ()
7799 "Check if the current file should receive notes in reversed order."
7801 ((not org-reverse-note-order) nil)
7802 ((eq t org-reverse-note-order) t)
7803 ((not (listp org-reverse-note-order)) nil)
7805 (let ((all org-reverse-note-order)
7807 (while (setq entry (pop all))
7808 (if (string-match (car entry) (buffer-file-name))
7809 (throw 'exit (cdr entry))))
7814 ;; Watch out: Here we are talking about two different kind of tables.
7815 ;; Most of the code is for the tables created with the Org-mode table editor.
7816 ;; Sometimes, we talk about tables created and edited with the table.el
7817 ;; Emacs package. We call the former org-type tables, and the latter
7818 ;; table.el-type tables.
7821 (defun org-before-change-function (beg end)
7822 "Every change indicates that a table might need an update."
7823 (setq org-table-may-need-update t))
7825 (defconst org-table-line-regexp "^[ \t]*|"
7826 "Detects an org-type table line.")
7827 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7828 "Detects an org-type table line.")
7829 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7830 "Detects a table line marked for automatic recalculation.")
7831 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7832 "Detects a table line marked for automatic recalculation.")
7833 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7834 "Detects a table line marked for automatic recalculation.")
7835 (defconst org-table-hline-regexp "^[ \t]*|-"
7836 "Detects an org-type table hline.")
7837 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7838 "Detects a table-type table hline.")
7839 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7840 "Detects an org-type or table-type table.")
7841 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7842 "Searching from within a table (any type) this finds the first line
7843 outside the table.")
7844 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7845 "Searching from within a table (any type) this finds the first line
7846 outside the table.")
7848 (defun org-table-create-with-table.el ()
7849 "Use the table.el package to insert a new table.
7850 If there is already a table at point, convert between Org-mode tables
7851 and table.el tables."
7855 ((org-at-table.el-p)
7856 (if (y-or-n-p "Convert table to Org-mode table? ")
7857 (org-table-convert)))
7859 (if (y-or-n-p "Convert table to table.el table? ")
7860 (org-table-convert)))
7861 (t (call-interactively 'table-insert))))
7863 (defun org-table-create (&optional size)
7864 "Query for a size and insert a table skeleton.
7865 SIZE is a string Columns x Rows like for example \"3x2\"."
7868 (setq size (read-string
7869 (concat "Table size Columns x Rows [e.g. "
7870 org-table-default-size "]: ")
7871 "" nil org-table-default-size)))
7873 (let* ((pos (point))
7874 (indent (make-string (current-column) ?\ ))
7875 (split (org-split-string size " *x *"))
7876 (rows (string-to-number (nth 1 split)))
7877 (columns (string-to-number (car split)))
7878 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7880 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7881 (point-at-bol) (point)))
7882 (beginning-of-line 1)
7884 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7885 (dotimes (i rows) (insert line))
7888 ;; Insert a hline after the first row.
7895 (defun org-table-convert-region (beg0 end0 nspace)
7896 "Convert region to a table.
7897 The region goes from BEG0 to END0, but these borders will be moved
7898 slightly, to make sure a beginning of line in the first line is included.
7899 When NSPACE is non-nil, it indicates the minimum number of spaces that
7900 separate columns (default: just one space)."
7901 (let* ((beg (min beg0 end0))
7902 (end (max beg0 end0))
7906 (beginning-of-line 1)
7907 (setq beg (move-marker (make-marker) (point)))
7909 (if (bolp) (backward-char 1) (end-of-line 1))
7910 (setq end (move-marker (make-marker) (point)))
7911 ;; Lets see if this is tab-separated material. If every nonempty line
7912 ;; contains a tab, we will assume that it is tab-separated material
7916 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
7917 (if nspace (setq tabsep nil))
7920 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
7921 (max 1 (prefix-numeric-value nspace)))))
7923 (while (re-search-forward re end t)
7924 (replace-match "|" t t))
7929 (defun org-table-import (file arg)
7930 "Import FILE as a table.
7931 The file is assumed to be tab-separated. Such files can be produced by most
7932 spreadsheet and database applications. If no tabs (at least one per line)
7933 are found, lines will be split on whitespace into fields."
7934 (interactive "f\nP")
7935 (or (bolp) (newline))
7938 (insert-file-contents file)
7939 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7941 (defun org-table-export ()
7942 "Export table as a tab-separated file.
7943 Such a file can be imported into a spreadsheet program like Excel."
7945 (let* ((beg (org-table-begin))
7946 (end (org-table-end))
7947 (table (buffer-substring beg end))
7948 (file (read-file-name "Export table to: "))
7950 (unless (or (not (file-exists-p file))
7951 (y-or-n-p (format "Overwrite file %s? " file)))
7953 (with-current-buffer (find-file-noselect file)
7954 (setq buf (current-buffer))
7958 (goto-char (point-min))
7959 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7960 (replace-match "" t t)
7962 (goto-char (point-min))
7963 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7964 (replace-match "" t t)
7965 (goto-char (min (1+ (point)) (point-max))))
7966 (goto-char (point-min))
7967 (while (re-search-forward "^-[-+]*$" nil t)
7969 (if (looking-at "\n")
7971 (goto-char (point-min))
7972 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7973 (replace-match "\t" t t))
7977 (defvar org-table-aligned-begin-marker (make-marker)
7978 "Marker at the beginning of the table last aligned.
7979 Used to check if cursor still is in that table, to minimize realignment.")
7980 (defvar org-table-aligned-end-marker (make-marker)
7981 "Marker at the end of the table last aligned.
7982 Used to check if cursor still is in that table, to minimize realignment.")
7983 (defvar org-table-last-alignment nil
7984 "List of flags for flushright alignment, from the last re-alignment.
7985 This is being used to correctly align a single field after TAB or RET.")
7986 ;; FIXME: The following is currently not used.
7987 (defvar org-table-last-column-widths nil
7988 "List of max width of fields in each column.
7989 This is being used to correctly align a single field after TAB or RET.")
7991 (defvar org-last-recalc-line nil)
7993 (defun org-table-align ()
7994 "Align the table at point by aligning all vertical bars."
7996 ;; (message "align") (sit-for 2)
7999 (beg (org-table-begin))
8000 (end (org-table-end))
8001 ;; Current cursor position
8002 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8003 (colpos (org-table-current-column))
8004 (winstart (window-start))
8005 text lines (new "") lengths l typenums ty fields maxfields i
8007 (indent "") cnt frac
8009 (spaces (if (org-in-invisibility-spec-p '(org-table))
8010 org-table-spaces-around-invisible-separators
8011 org-table-spaces-around-separators))
8015 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8017 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8020 ;; (message "Aligning table...")
8022 (setq lines (org-split-string
8023 (buffer-substring-no-properties beg end) "\n"))
8024 ;; Store the indentation of the first line
8025 (if (string-match "^ *" (car lines))
8026 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8028 (setq lines (mapcar (lambda (l)
8029 (if (string-match "^ *|-" l)
8031 (if (string-match "[ \t]+$" l)
8032 (substring l 0 (match-beginning 0))
8035 ;; Get the data fields
8036 (setq fields (mapcar
8038 (org-split-string l " *| *"))
8039 (delq nil (copy-sequence lines))))
8040 ;; How many fields in the longest line?
8042 (setq maxfields (apply 'max (mapcar 'length fields)))
8044 (kill-region beg end)
8045 (org-table-create org-table-default-size)
8046 (error "Empty table - created default table")))
8047 ;; A list of empty string to fill any short rows on output
8048 (setq emptystrings (make-list maxfields ""))
8049 ;; Get the maximum length of a field and the most common datatype
8052 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8053 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8055 (push (apply 'max 1 (mapcar 'string-width column)) lengths)
8056 ;; compute the fraction stepwise, ignoring empty fields
8057 (setq cnt 0 frac 0.0)
8062 (setq frac ( / (+ (* frac cnt)
8063 (if (string-match org-table-number-regexp x) 1 0))
8064 (setq cnt (1+ cnt))))))
8066 (push (>= frac org-table-number-fraction) typenums))
8067 (setq lengths (nreverse lengths)
8068 typenums (nreverse typenums))
8069 (setq org-table-last-alignment typenums
8070 org-table-last-column-widths lengths)
8071 ;; Compute the formats needed for output of the table
8072 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8073 (while (setq l (pop lengths))
8074 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8075 (setq rfmt (concat rfmt (format rfmt1 ty l))
8076 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8077 (setq rfmt (concat rfmt "\n")
8078 hfmt (concat (substring hfmt 0 -1) "|\n"))
8079 ;; Produce the new table
8081 ;; (setq l (pop lines))
8083 ;; (setq new (concat new (apply 'format rfmt
8084 ;; (append (pop fields) emptystrings))))
8085 ;; (setq new (concat new hfmt))))
8086 (setq new (mapconcat
8088 (if l (apply 'format rfmt
8089 (append (pop fields) emptystrings))
8092 ;; Replace the old one
8093 (delete-region beg end)
8094 (move-marker end nil)
8095 (move-marker org-table-aligned-begin-marker (point))
8097 (move-marker org-table-aligned-end-marker (point))
8098 ;; Try to move to the old location (approximately)
8100 (set-window-start (selected-window) winstart 'noforce)
8101 (org-table-goto-column colpos)
8102 (setq org-table-may-need-update nil)
8103 (if (org-in-invisibility-spec-p '(org-table))
8104 (org-table-add-invisible-to-vertical-lines))
8107 (defun org-table-begin (&optional table-type)
8108 "Find the beginning of the table and return its position.
8109 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8111 (if (not (re-search-backward
8112 (if table-type org-table-any-border-regexp
8113 org-table-border-regexp)
8115 (error "Can't find beginning of table")
8116 (goto-char (match-beginning 0))
8117 (beginning-of-line 2)
8120 (defun org-table-end (&optional table-type)
8121 "Find the end of the table and return its position.
8122 With argument TABLE-TYPE, go to the end of a table.el-type table."
8124 (if (not (re-search-forward
8125 (if table-type org-table-any-border-regexp
8126 org-table-border-regexp)
8128 (goto-char (point-max))
8129 (goto-char (match-beginning 0)))
8132 (defun org-table-justify-field-maybe (&optional new)
8133 "Justify the current field, text to left, number to right.
8134 Optional argument NEW may specify text to replace the current field content."
8136 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8137 ((org-at-table-hline-p)
8138 ;; FIXME: I used to enforce realign here, but I think this is not needed.
8139 ;; (setq org-table-may-need-update t)
8142 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8144 (< (point) org-table-aligned-begin-marker)
8145 (>= (point) org-table-aligned-end-marker)))
8146 ;; This is not the same table, force a full re-align
8147 (setq org-table-may-need-update t))
8148 (t ;; realign the current field, based on previous full realign
8149 (let* ((pos (point)) s
8150 (col (org-table-current-column))
8151 (num (nth (1- col) org-table-last-alignment))
8154 (skip-chars-backward "^|\n")
8155 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8157 (setq s (match-string 1)
8159 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8160 e (not (= (match-beginning 2) (match-end 2))))
8161 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8162 l (if e "|" (setq org-table-may-need-update t) ""))
8165 (if (<= (length new) l)
8166 (setq n (format f new t t)) ;; FIXME: why t t?????
8167 (setq n (concat new "|") org-table-may-need-update t)))
8169 (let (org-table-may-need-update)
8170 (replace-match n))))
8171 (setq org-table-may-need-update t))
8172 (goto-char pos))))))
8174 (defun org-table-next-field ()
8175 "Go to the next field in the current table, creating new lines as needed.
8176 Before doing so, re-align the table if necessary."
8178 (org-table-maybe-eval-formula)
8179 (org-table-maybe-recalculate-line)
8180 (if (and org-table-automatic-realign
8181 org-table-may-need-update)
8183 (let ((end (org-table-end)))
8184 (if (org-at-table-hline-p)
8188 (re-search-forward "|" end)
8189 (if (looking-at "[ \t]*$")
8190 (re-search-forward "|" end))
8191 (if (and (looking-at "-")
8192 org-table-tab-jumps-over-hlines
8193 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8194 (goto-char (match-beginning 1)))
8195 (if (looking-at "-")
8197 (beginning-of-line 0)
8198 (org-table-insert-row 'below))
8199 (if (looking-at " ") (forward-char 1))))
8201 (org-table-insert-row 'below)))))
8203 (defun org-table-previous-field ()
8204 "Go to the previous field in the table.
8205 Before doing so, re-align the table if necessary."
8207 (org-table-justify-field-maybe)
8208 (org-table-maybe-recalculate-line)
8209 (if (and org-table-automatic-realign
8210 org-table-may-need-update)
8212 (if (org-at-table-hline-p)
8214 (re-search-backward "|" (org-table-begin))
8215 (re-search-backward "|" (org-table-begin))
8216 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8217 (re-search-backward "|" (org-table-begin)))
8218 (if (looking-at "| ?")
8219 (goto-char (match-end 0))))
8221 (defun org-table-next-row ()
8222 "Go to the next row (same column) in the current table.
8223 Before doing so, re-align the table if necessary."
8225 (org-table-maybe-eval-formula)
8226 (org-table-maybe-recalculate-line)
8227 (if (or (looking-at "[ \t]*$")
8228 (save-excursion (skip-chars-backward " \t") (bolp)))
8230 (if (and org-table-automatic-realign
8231 org-table-may-need-update)
8233 (let ((col (org-table-current-column)))
8234 (beginning-of-line 2)
8235 (if (or (not (org-at-table-p))
8236 (org-at-table-hline-p))
8238 (beginning-of-line 0)
8239 (org-table-insert-row 'below)))
8240 (org-table-goto-column col)
8241 (skip-chars-backward "^|\n\r")
8242 (if (looking-at " ") (forward-char 1)))))
8244 (defun org-table-copy-down (n)
8245 "Copy a field down in the current column.
8246 If the field at the cursor is empty, copy into it the content of the nearest
8247 non-empty field above. With argument N, use the Nth non-empty field.
8248 If the current field is not empty, it is copied down to the next row, and
8249 the cursor is moved with it. Therefore, repeating this command causes the
8250 column to be filled row-by-row.
8251 If the variable `org-table-copy-increment' is non-nil and the field is an
8252 integer, it will be incremented while copying."
8254 (let* ((colpos (org-table-current-column))
8255 (field (org-table-get-field))
8256 (non-empty (string-match "[^ \t]" field))
8257 (beg (org-table-begin))
8259 (org-table-check-inside-data-field)
8262 (setq txt (org-trim field))
8263 (org-table-next-row)
8264 (org-table-blank-field))
8268 (while (progn (beginning-of-line 1)
8269 (re-search-backward org-table-dataline-regexp
8271 (org-table-goto-column colpos t)
8272 (if (and (looking-at
8273 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8274 (= (setq n (1- n)) 0))
8275 (throw 'exit (match-string 1))))))))
8278 (if (and org-table-copy-increment
8279 (string-match "^[0-9]+$" txt))
8280 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8282 (org-table-maybe-recalculate-line)
8284 (error "No non-empty field found"))))
8286 (defun org-table-check-inside-data-field ()
8287 "Is point inside a table data field?
8288 I.e. not on a hline or before the first or after the last column?
8289 This actually throws an error, so it aborts the current command."
8290 (if (or (not (org-at-table-p))
8291 (= (org-table-current-column) 0)
8292 (org-at-table-hline-p)
8293 (looking-at "[ \t]*$"))
8294 (error "Not in table data field")))
8296 (defvar org-table-clip nil
8297 "Clipboard for table regions.")
8299 (defun org-table-blank-field ()
8300 "Blank the current table field or active region."
8302 (org-table-check-inside-data-field)
8303 (if (and (interactive-p) (org-region-active-p))
8304 (let (org-table-clip)
8305 (org-table-cut-region (region-beginning) (region-end)))
8306 (skip-chars-backward "^|")
8308 (if (looking-at "|[^|\n]+")
8309 (let* ((pos (match-beginning 0))
8310 (match (match-string 0))
8311 (len (string-width match)))
8312 (replace-match (concat "|" (make-string (1- len) ?\ )))
8313 (goto-char (+ 2 pos))
8314 (substring match 1)))))
8316 (defun org-table-get-field (&optional n replace)
8317 "Return the value of the field in column N of current row.
8318 N defaults to current field.
8319 If REPLACE is a string, replace field with this value. The return value
8320 is always the old value."
8321 (and n (org-table-goto-column n))
8322 (skip-chars-backward "^|\n")
8324 (if (looking-at "|[^|\r\n]*")
8325 (let* ((pos (match-beginning 0))
8326 (val (buffer-substring (1+ pos) (match-end 0))))
8328 (replace-match (concat "|" replace)))
8329 (goto-char (min (point-at-eol) (+ 2 pos)))
8331 (forward-char 1) ""))
8333 (defun org-table-current-column ()
8334 "Find out which column we are in.
8335 When called interactively, column is also displayed in echo area."
8337 (if (interactive-p) (org-table-check-inside-data-field))
8339 (let ((cnt 0) (pos (point)))
8340 (beginning-of-line 1)
8341 (while (search-forward "|" pos t)
8342 (setq cnt (1+ cnt)))
8343 (if (interactive-p) (message "This is table column %d" cnt))
8346 (defun org-table-goto-column (n &optional on-delim force)
8347 "Move the cursor to the Nth column in the current table line.
8348 With optional argument ON-DELIM, stop with point before the left delimiter
8350 If there are less than N fields, just go to after the last delimiter.
8351 However, when FORCE is non-nil, create new columns if necessary."
8353 (let ((pos (point-at-eol)))
8354 (beginning-of-line 1)
8356 (while (and (> (setq n (1- n)) -1)
8357 (or (search-forward "|" pos t)
8359 (progn (end-of-line 1)
8360 (skip-chars-backward "^|")
8362 ; (backward-char 2) t)))))
8363 (when (and force (not (looking-at ".*|")))
8364 (save-excursion (end-of-line 1) (insert " | ")))
8367 (if (looking-at " ") (forward-char 1))))))
8369 (defun org-at-table-p (&optional table-type)
8370 "Return t if the cursor is inside an org-type table.
8371 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8372 (if org-enable-table-editor
8374 (beginning-of-line 1)
8375 (looking-at (if table-type org-table-any-line-regexp
8376 org-table-line-regexp)))
8379 (defun org-at-table.el-p ()
8380 "Return t if and only if we are at a table.el table."
8381 (and (org-at-table-p 'any)
8383 (goto-char (org-table-begin 'any))
8384 (looking-at org-table1-hline-regexp))))
8386 (defun org-table-recognize-table.el ()
8387 "If there is a table.el table nearby, recognize it and move into it."
8388 (if org-table-tab-recognizes-table.el
8389 (if (org-at-table.el-p)
8391 (beginning-of-line 1)
8392 (if (looking-at org-table-dataline-regexp)
8394 (if (looking-at org-table1-hline-regexp)
8396 (beginning-of-line 2)
8397 (if (looking-at org-table-any-border-regexp)
8398 (beginning-of-line -1)))))
8399 (if (re-search-forward "|" (org-table-end t) t)
8402 (if (table--at-cell-p (point))
8404 (message "recognizing table.el table...")
8405 (table-recognize-table)
8406 (message "recognizing table.el table...done")))
8407 (error "This should not happen..."))
8412 (defun org-at-table-hline-p ()
8413 "Return t if the cursor is inside a hline in a table."
8414 (if org-enable-table-editor
8416 (beginning-of-line 1)
8417 (looking-at org-table-hline-regexp))
8420 (defun org-table-insert-column ()
8421 "Insert a new column into the table."
8423 (if (not (org-at-table-p))
8424 (error "Not at a table"))
8425 (org-table-find-dataline)
8426 (let* ((col (max 1 (org-table-current-column)))
8427 (beg (org-table-begin))
8428 (end (org-table-end))
8429 ;; Current cursor position
8430 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8433 (while (< (point) end)
8434 (if (org-at-table-hline-p)
8436 (org-table-goto-column col t)
8438 (beginning-of-line 2))
8439 (move-marker end nil)
8441 (org-table-goto-column colpos)
8443 (org-table-modify-formulas 'insert col)))
8445 (defun org-table-find-dataline ()
8446 "Find a dataline in the current table, which is needed for column commands."
8447 (if (and (org-at-table-p)
8448 (not (org-at-table-hline-p)))
8450 (let ((col (current-column))
8451 (end (org-table-end)))
8452 (move-to-column col)
8453 (while (and (< (point) end)
8454 (or (not (= (current-column) col))
8455 (org-at-table-hline-p)))
8456 (beginning-of-line 2)
8457 (move-to-column col))
8458 (if (and (org-at-table-p)
8459 (not (org-at-table-hline-p)))
8462 "Please position cursor in a data line for column operations")))))
8464 (defun org-table-delete-column ()
8465 "Delete a column into the table."
8467 (if (not (org-at-table-p))
8468 (error "Not at a table"))
8469 (org-table-find-dataline)
8470 (org-table-check-inside-data-field)
8471 (let* ((col (org-table-current-column))
8472 (beg (org-table-begin))
8473 (end (org-table-end))
8474 ;; Current cursor position
8475 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8478 (while (< (point) end)
8479 (if (org-at-table-hline-p)
8481 (org-table-goto-column col t)
8482 (and (looking-at "|[^|\n]+|")
8483 (replace-match "|")))
8484 (beginning-of-line 2))
8485 (move-marker end nil)
8487 (org-table-goto-column colpos)
8489 (org-table-modify-formulas 'remove col)))
8491 (defun org-table-move-column-right ()
8492 "Move column to the right."
8494 (org-table-move-column nil))
8495 (defun org-table-move-column-left ()
8496 "Move column to the left."
8498 (org-table-move-column 'left))
8500 (defun org-table-move-column (&optional left)
8501 "Move the current column to the right. With arg LEFT, move to the left."
8503 (if (not (org-at-table-p))
8504 (error "Not at a table"))
8505 (org-table-find-dataline)
8506 (org-table-check-inside-data-field)
8507 (let* ((col (org-table-current-column))
8508 (col1 (if left (1- col) col))
8509 (beg (org-table-begin))
8510 (end (org-table-end))
8511 ;; Current cursor position
8512 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8513 (colpos (if left (1- col) (1+ col))))
8514 (if (and left (= col 1))
8515 (error "Cannot move column further left"))
8516 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8517 (error "Cannot move column further right"))
8519 (while (< (point) end)
8520 (if (org-at-table-hline-p)
8522 (org-table-goto-column col1 t)
8523 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8524 (replace-match "|\\2|\\1|")))
8525 (beginning-of-line 2))
8526 (move-marker end nil)
8528 (org-table-goto-column colpos)
8530 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
8532 (defun org-table-move-row-down ()
8533 "Move table row down."
8535 (org-table-move-row nil))
8536 (defun org-table-move-row-up ()
8537 "Move table row up."
8539 (org-table-move-row 'up))
8541 (defun org-table-move-row (&optional up)
8542 "Move the current table line down. With arg UP, move it up."
8544 (let ((col (current-column))
8548 (beginning-of-line tonew)
8549 (if (not (org-at-table-p))
8552 (error "Cannot move row further")))
8554 (beginning-of-line 1)
8556 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8557 (delete-region (point) (1+ (point-at-eol)))
8558 (beginning-of-line tonew)
8560 (beginning-of-line 0)
8561 (move-to-column col)))
8563 (defun org-table-insert-row (&optional arg)
8564 "Insert a new row above the current line into the table.
8565 With prefix ARG, insert below the current line."
8567 (if (not (org-at-table-p))
8568 (error "Not at a table"))
8570 (org-expand-wide-chars
8571 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8573 (if (string-match "^[ \t]*|-" line)
8574 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
8575 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
8576 ;; Fix the first field if necessary
8577 (setq new (concat new))
8578 (if (string-match "^[ \t]*| *[#$] *|" line)
8579 (setq new (replace-match (match-string 0 line) t t new)))
8580 (beginning-of-line (if arg 2 1))
8581 (let (org-table-may-need-update)
8582 (insert-before-markers new)
8583 (insert-before-markers "\n"))
8584 (beginning-of-line 0)
8585 (re-search-forward "| ?" (point-at-eol) t)
8586 (and org-table-may-need-update (org-table-align))))
8588 (defun org-table-insert-hline (&optional arg)
8589 "Insert a horizontal-line below the current line into the table.
8590 With prefix ARG, insert above the current line."
8592 (if (not (org-at-table-p))
8593 (error "Not at a table"))
8595 (org-expand-wide-chars
8596 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8597 (col (current-column))
8599 (if (string-match "^[ \t]*|-" line)
8601 (mapcar (lambda (x) (if (member x '(?| ?+))
8602 (prog1 (if start ?+ ?|) (setq start t))
8606 (mapcar (lambda (x) (if (equal x ?|)
8607 (prog1 (if start ?+ ?|) (setq start t))
8610 (beginning-of-line (if arg 1 2))
8611 (apply 'insert line)
8612 (if (equal (char-before (point)) ?+)
8613 (progn (backward-delete-char 1) (insert "|")))
8615 (beginning-of-line (if arg 1 -1))
8616 (move-to-column col)))
8618 (defun org-expand-wide-chars (s)
8619 "Expand wide characters to spaces."
8623 (if (> (setq w (string-width (setq a (char-to-string x)))) 1)
8628 (defun org-table-kill-row ()
8629 "Delete the current row or horizontal line from the table."
8631 (if (not (org-at-table-p))
8632 (error "Not at a table"))
8633 (let ((col (current-column)))
8634 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8635 (if (not (org-at-table-p)) (beginning-of-line 0))
8636 (move-to-column col)))
8638 (defun org-table-sort-lines (beg end numericp)
8639 "Sort table lines in region.
8640 Point and mark define the first and last line to include. Both point and
8641 mark should be in the column that is used for sorting. For example, to
8642 sort according to column 3, put the mark in the first line to sort, in
8643 table column 3. Put point into the last line to be included in the sorting,
8644 also in table column 3. The command will prompt for the sorting method
8645 \(n for numerical, a for alphanumeric)."
8646 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
8647 (setq numericp (string-match "[nN]" numericp))
8648 (org-table-align) ;; Just to be safe
8649 (let* (bcol ecol cmp column lns)
8651 (org-table-check-inside-data-field)
8652 (setq column (org-table-current-column)
8653 beg (move-marker (make-marker) (point-at-bol)))
8655 (org-table-check-inside-data-field)
8656 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
8659 (org-table-goto-column column)
8660 (skip-chars-backward "^|")
8661 (setq bcol (current-column))
8662 (org-table-goto-column (1+ column))
8663 (skip-chars-backward "^|")
8664 (setq ecol (1- (current-column)))
8665 (setq cmp (if numericp
8666 (lambda (a b) (< (car a) (car b)))
8667 (lambda (a b) (string< (car a) (car b)))))
8668 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8669 (split-string (buffer-substring beg end) "\n")))
8671 (setq lns (mapcar (lambda(x)
8672 (cons (string-to-number (car x)) (cdr x)))
8674 (delete-region beg end)
8675 (move-marker beg nil)
8676 (move-marker end nil)
8677 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
8678 (message "%d lines sorted %s based on column %d"
8680 (if numericp "numerically" "alphabetically") column)))
8682 (defun org-table-cut-region (beg end)
8683 "Copy region in table to the clipboard and blank all relevant fields."
8685 (org-table-copy-region beg end 'cut))
8687 (defun org-table-copy-region (beg end &optional cut)
8688 "Copy rectangular region in table to clipboard.
8689 A special clipboard is used which can only be accessed
8690 with `org-table-paste-rectangle'."
8692 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8694 (rpl (if cut " " nil)))
8696 (org-table-check-inside-data-field)
8697 (setq l01 (count-lines (point-min) (point))
8698 c01 (org-table-current-column))
8700 (org-table-check-inside-data-field)
8701 (setq l02 (count-lines (point-min) (point))
8702 c02 (org-table-current-column))
8703 (setq l1 (min l01 l02) l2 (max l01 l02)
8704 c1 (min c01 c02) c2 (max c01 c02))
8708 (if (> l1 l2) (throw 'exit t))
8710 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8711 (setq cols nil ic1 c1 ic2 c2)
8712 (while (< ic1 (1+ ic2))
8713 (push (org-table-get-field ic1 rpl) cols)
8714 (setq ic1 (1+ ic1)))
8715 (push (nreverse cols) region)
8716 (setq l1 (1+ l1)))))
8717 (setq org-table-clip (nreverse region))
8718 (if cut (org-table-align))
8721 (defun org-table-paste-rectangle ()
8722 "Paste a rectangular region into a table.
8723 The upper right corner ends up in the current field. All involved fields
8724 will be overwritten. If the rectangle does not fit into the present table,
8725 the table is enlarged as needed. The process ignores horizontal separator
8728 (unless (and org-table-clip (listp org-table-clip))
8729 (error "First cut/copy a region to paste!"))
8730 (org-table-check-inside-data-field)
8731 (let* ((clip org-table-clip)
8732 (line (count-lines (point-min) (point)))
8733 (col (org-table-current-column))
8734 (org-enable-table-editor t)
8735 (org-table-automatic-realign nil)
8737 (while (setq cols (pop clip))
8738 (while (org-at-table-hline-p) (beginning-of-line 2))
8739 (if (not (org-at-table-p))
8740 (progn (end-of-line 0) (org-table-next-field)))
8742 (while (setq field (pop cols))
8743 (org-table-goto-column c nil 'force)
8744 (org-table-get-field nil field)
8746 (beginning-of-line 2))
8748 (org-table-goto-column col)
8751 (defun org-table-convert ()
8752 "Convert from `org-mode' table to table.el and back.
8753 Obviously, this only works within limits. When an Org-mode table is
8754 converted to table.el, all horizontal separator lines get lost, because
8755 table.el uses these as cell boundaries and has no notion of horizontal lines.
8756 A table.el table can be converted to an Org-mode table only if it does not
8757 do row or column spanning. Multiline cells will become multiple cells.
8758 Beware, Org-mode does not test if the table can be successfully converted - it
8759 blindly applies a recipe that works for simple tables."
8762 (if (org-at-table.el-p)
8763 ;; convert to Org-mode table
8764 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8765 (end (move-marker (make-marker) (org-table-end t))))
8766 (table-unrecognize-region beg end)
8768 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8771 (if (org-at-table-p)
8772 ;; convert to table.el table
8773 (let ((beg (move-marker (make-marker) (org-table-begin)))
8774 (end (move-marker (make-marker) (org-table-end))))
8775 ;; first, get rid of all horizontal lines
8777 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8779 ;; insert a hline before first
8781 (org-table-insert-hline 'above)
8782 (beginning-of-line -1)
8783 ;; insert a hline after each line
8784 (while (progn (beginning-of-line 3) (< (point) end))
8785 (org-table-insert-hline))
8787 (setq end (move-marker end (org-table-end)))
8788 ;; replace "+" at beginning and ending of hlines
8789 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8790 (replace-match "\\1+-"))
8792 (while (re-search-forward "-|[ \t]*$" end t)
8793 (replace-match "-+"))
8796 (defun org-table-wrap-region (arg)
8797 "Wrap several fields in a column like a paragraph.
8798 This is useful if you'd like to spread the contents of a field over several
8799 lines, in order to keep the table compact.
8801 If there is an active region, and both point and mark are in the same column,
8802 the text in the column is wrapped to minimum width for the given number of
8803 lines. Generally, this makes the table more compact. A prefix ARG may be
8804 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8805 formats the selected text to two lines. If the region was longer than two
8806 lines, the remaining lines remain empty. A negative prefix argument reduces
8807 the current number of lines by that amount. The wrapped text is pasted back
8808 into the table. If you formatted it to more lines than it was before, fields
8809 further down in the table get overwritten - so you might need to make space in
8812 If there is no region, the current field is split at the cursor position and
8813 the text fragment to the right of the cursor is prepended to the field one
8816 If there is no region, but you specify a prefix ARG, the current field gets
8817 blank, and the content is appended to the field above."
8819 (org-table-check-inside-data-field)
8820 (if (org-region-active-p)
8821 ;; There is a region: fill as a paragraph
8822 (let ((beg (region-beginning))
8824 (org-table-cut-region (region-beginning) (region-end))
8825 (if (> (length (car org-table-clip)) 1)
8826 (error "Region must be limited to single column"))
8827 (setq nlines (if arg
8829 (+ (length org-table-clip) arg)
8831 (length org-table-clip)))
8832 (setq org-table-clip
8833 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8836 (org-table-paste-rectangle))
8837 ;; No region, split the current field at point
8839 ;; combine with field above
8840 (let ((s (org-table-blank-field))
8841 (col (org-table-current-column)))
8842 (beginning-of-line 0)
8843 (while (org-at-table-hline-p) (beginning-of-line 0))
8844 (org-table-goto-column col)
8845 (skip-chars-forward "^|")
8846 (skip-chars-backward " ")
8847 (insert " " (org-trim s))
8850 (when (looking-at "\\([^|]+\\)+|")
8851 (let ((s (match-string 1)))
8852 (replace-match " |")
8853 (goto-char (match-beginning 0))
8854 (org-table-next-row)
8855 (insert (org-trim s) " ")
8856 (org-table-align))))))
8859 "Remove whitespace at beginning and end of string."
8860 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
8861 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
8864 (defun org-wrap (string &optional width lines)
8865 "Wrap string to either a number of lines, or a width in characters.
8866 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8867 that costs. If there is a word longer than WIDTH, the text is actually
8868 wrapped to the length of that word.
8869 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8870 many lines, whatever width that takes.
8871 The return value is a list of lines, without newlines at the end."
8872 (let* ((words (org-split-string string "[ \t\n]+"))
8873 (maxword (apply 'max (mapcar 'string-width words)))
8876 (org-do-wrap words (max maxword width)))
8879 (setq ll (org-do-wrap words maxword))
8880 (if (<= (length ll) lines)
8883 (while (> (length ll) lines)
8885 (setq ll (org-do-wrap words w)))
8887 (t (error "Cannot wrap this")))))
8890 (defun org-do-wrap (words width)
8891 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8894 (setq line (pop words))
8895 (while (and words (< (+ (length line) (length (car words))) width))
8896 (setq line (concat line " " (pop words))))
8897 (setq lines (push line lines)))
8900 ;; FIXME: I think I can make this more efficient
8901 (defun org-split-string (string &optional separators)
8902 "Splits STRING into substrings at SEPARATORS.
8903 No empty strings are returned if there are matches at the beginning
8905 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8909 (while (and (string-match rexp string
8911 (= start (match-beginning 0))
8912 (< start (length string)))
8914 (< (match-beginning 0) (length string)))
8916 (or (eq (match-beginning 0) 0)
8917 (and (eq (match-beginning 0) (match-end 0))
8918 (eq (match-beginning 0) start))
8920 (cons (substring string start (match-beginning 0))
8922 (setq start (match-end 0)))
8923 (or (eq start (length string))
8925 (cons (substring string start)
8929 (defun org-table-add-invisible-to-vertical-lines ()
8930 "Add an `invisible' property to vertical lines of current table."
8932 (let* ((beg (org-table-begin))
8933 (end (org-table-end))
8937 (while (< (point) end)
8938 (setq end1 (point-at-eol))
8939 (if (looking-at org-table-dataline-regexp)
8940 (while (re-search-forward "|" end1 t)
8941 (add-text-properties (1- (point)) (point)
8942 '(invisible org-table)))
8943 (while (re-search-forward "[+|]" end1 t)
8944 (add-text-properties (1- (point)) (point)
8945 '(invisible org-table))))
8946 (beginning-of-line 2)))))
8948 (defun org-table-toggle-vline-visibility (&optional arg)
8949 "Toggle the visibility of table vertical lines.
8950 The effect is immediate and on all tables in the file.
8951 With prefix ARG, make lines invisible when ARG is positive, make lines
8952 visible when ARG is not positive."
8955 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
8956 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
8957 (t (if (org-in-invisibility-spec-p '(org-table))
8960 (if (eq action 'off)
8962 (org-remove-from-invisibility-spec '(org-table))
8963 (org-table-map-tables 'org-table-align)
8964 (message "Vertical table lines visible")
8965 (if (org-at-table-p)
8967 (org-add-to-invisibility-spec '(org-table))
8968 (org-table-map-tables 'org-table-align)
8969 (message "Vertical table lines invisible"))
8970 (redraw-frame (selected-frame))))
8972 (defun org-table-map-tables (function)
8973 "Apply FUNCTION to the start of all tables in the buffer."
8977 (goto-char (point-min))
8978 (while (re-search-forward org-table-any-line-regexp nil t)
8979 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8980 (beginning-of-line 1)
8981 (if (looking-at org-table-line-regexp)
8982 (save-excursion (funcall function)))
8983 (re-search-forward org-table-any-border-regexp nil 1)))))
8985 (defun org-table-sum (&optional beg end nlast)
8986 "Sum numbers in region of current table column.
8987 The result will be displayed in the echo area, and will be available
8988 as kill to be inserted with \\[yank].
8990 If there is an active region, it is interpreted as a rectangle and all
8991 numbers in that rectangle will be summed. If there is no active
8992 region and point is located in a table column, sum all numbers in that
8995 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8996 numbers are assumed to be times as well (in decimal hours) and the
8997 numbers are added as such.
8999 If NLAST is a number, only the NLAST fields will actually be summed."
9002 (let (col (timecnt 0) diff h m s org-table-clip)
9004 ((and beg end)) ; beg and end given explicitly
9005 ((org-region-active-p)
9006 (setq beg (region-beginning) end (region-end)))
9008 (setq col (org-table-current-column))
9009 (goto-char (org-table-begin))
9010 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9011 (error "No table data"))
9012 (org-table-goto-column col)
9013 ;not needed? (skip-chars-backward "^|")
9015 (goto-char (org-table-end))
9016 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9017 (error "No table data"))
9018 (org-table-goto-column col)
9019 ;not needed? (skip-chars-forward "^|")
9020 (setq end (point))))
9021 (let* ((items (apply 'append (org-table-copy-region beg end)))
9022 (items1 (cond ((not nlast) items)
9023 ((>= nlast (length items)) items)
9024 (t (setq items (reverse items))
9025 (setcdr (nthcdr (1- nlast) items) nil)
9027 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9029 (res (apply '+ numbers))
9030 (sres (if (= timecnt 0)
9032 (setq diff (* 3600 res)
9033 h (floor (/ diff 3600)) diff (mod diff 3600)
9034 m (floor (/ diff 60)) diff (mod diff 60)
9036 (format "%d:%02d:%02d" h m s))))
9040 (substitute-command-keys
9041 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9042 (length numbers) sres))))
9045 (defun org-table-get-number-for-summing (s)
9047 (if (string-match "^ *|? *" s)
9048 (setq s (replace-match "" nil nil s)))
9049 (if (string-match " *|? *$" s)
9050 (setq s (replace-match "" nil nil s)))
9051 (setq n (string-to-number s))
9053 ((and (string-match "0" s)
9054 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9055 ((string-match "\\`[ \t]+\\'" s) nil)
9056 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9057 (let ((h (string-to-number (or (match-string 1 s) "0")))
9058 (m (string-to-number (or (match-string 2 s) "0")))
9059 (s (string-to-number (or (match-string 4 s) "0"))))
9060 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9061 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9065 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9066 "Get a calc vector from a column, accorting to descriptor DESC.
9067 Optional arguments TBEG and COL can give the beginning of the table and
9068 the current column, to avoid unnecessary parsing."
9070 (or tbeg (setq tbeg (org-table-begin)))
9071 (or col (setq col (org-table-current-column)))
9072 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9074 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9075 (setq n1 (- (match-end 1) (match-beginning 1)))
9076 (if (match-beginning 3)
9077 (setq n2 (- (match-end 2) (match-beginning 3))))
9078 (setq n (if n2 (max n1 n2) n1))
9079 (setq n1 (if n2 (min n1 n2)))
9081 (while (and (> nn 0)
9082 (re-search-backward org-table-hline-regexp tbeg t))
9083 (push (org-current-line) hline-list)
9085 (setq hline-list (nreverse hline-list))
9086 (goto-line (nth (1- n) hline-list))
9087 (when (re-search-forward org-table-dataline-regexp)
9088 (org-table-goto-column col)
9090 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9091 (when (re-search-backward org-table-dataline-regexp)
9092 (org-table-goto-column col)
9094 (setq l (apply 'append (org-table-copy-region beg end)))
9095 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9096 (if (equal x "") "0" x))
9098 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9099 (setq n1 (string-to-number (match-string 1 desc))
9100 n2 (string-to-number (match-string 2 desc)))
9101 (beginning-of-line 1)
9103 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9104 (org-table-goto-column col)
9105 (setq beg (point))))
9106 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9107 (org-table-goto-column col)
9109 (setq l (apply 'append (org-table-copy-region beg end)))
9110 (concat "[" (mapconcat
9111 (lambda (x) (setq x (org-trim x))
9112 (if (equal x "") "0" x))
9114 ((string-match "\\([0-9]+\\)" desc)
9115 (beginning-of-line 1)
9116 (when (re-search-backward org-table-dataline-regexp tbeg t
9117 (string-to-number (match-string 0 desc)))
9118 (org-table-goto-column col)
9119 (org-trim (org-table-get-field))))))))
9121 (defvar org-table-formula-history nil)
9123 (defvar org-table-column-names nil
9124 "Alist with column names, derived from the `!' line.")
9125 (defvar org-table-column-name-regexp nil
9126 "Regular expression matching the current column names.")
9127 (defvar org-table-local-parameters nil
9128 "Alist with parameter names, derived from the `$' line.")
9129 (defvar org-table-named-field-locations nil
9130 "Alist with locations of named fields.")
9132 (defun org-table-get-formula (&optional equation named)
9133 "Read a formula from the minibuffer, offer stored formula as default."
9134 (let* ((name (car (rassoc (list (org-current-line)
9135 (org-table-current-column))
9136 org-table-named-field-locations)))
9139 (error "Not in a named field"))
9140 (int-to-string (org-table-current-column))))
9141 (dummy (and name (not named)
9142 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9144 (org-table-may-need-update nil)
9145 (stored-list (org-table-get-stored-formulas))
9146 (stored (cdr (assoc scol stored-list)))
9148 ((and stored equation (string-match "^ *=? *$" equation))
9153 (format "%s formula $%s=" (if named "Field" "Column") scol)
9154 (or stored "") 'org-table-formula-history
9158 (when (not (string-match "\\S-" eq))
9160 (setq stored-list (delq (assoc scol stored-list) stored-list))
9161 (org-table-store-formulas stored-list)
9162 (error "Formula removed"))
9163 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9164 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9165 (if (and name (not named))
9166 ;; We set the column equation, delete the named one.
9167 (setq stored-list (delq (assoc name stored-list) stored-list)
9170 (setcdr (assoc scol stored-list) eq)
9171 (setq stored-list (cons (cons scol eq) stored-list)))
9172 (if (or mustsave (not (equal stored eq)))
9173 (org-table-store-formulas stored-list))
9176 (defun org-table-store-formulas (alist)
9177 "Store the list of formulas below the current table."
9178 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9180 (goto-char (org-table-end))
9181 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9182 (delete-region (point) (match-end 0)))
9184 (mapconcat (lambda (x)
9185 (concat "$" (car x) "=" (cdr x)))
9189 (defun org-table-get-stored-formulas ()
9190 "Return an alist with the t=stored formulas directly after current table."
9192 (let (scol eq eq-alist strings string seen)
9194 (goto-char (org-table-end))
9195 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9196 (setq strings (org-split-string (match-string 2) " *:: *"))
9197 (while (setq string (pop strings))
9198 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9199 (setq scol (match-string 1 string)
9200 eq (match-string 2 string)
9201 eq-alist (cons (cons scol eq) eq-alist))
9202 (if (member scol seen)
9203 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9204 (push scol seen))))))
9205 (nreverse eq-alist)))
9207 (defun org-table-modify-formulas (action &rest columns)
9208 "Modify the formulas stored below the current table.
9209 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
9210 expected, for the other actions only a single column number is needed."
9211 (let ((list (org-table-get-stored-formulas))
9212 (nmax (length (org-split-string
9213 (buffer-substring (point-at-bol) (point-at-eol))
9215 col col1 col2 scol si sc1 sc2)
9217 ((null list)) ; No action needed if there are no stored formulas
9218 ((eq action 'remove)
9219 (setq col (car columns)
9220 scol (int-to-string col))
9221 (org-table-replace-in-formulas list scol "INVALID")
9222 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
9223 (loop for i from (1+ col) upto nmax by 1 do
9224 (setq si (int-to-string i))
9225 (org-table-replace-in-formulas list si (int-to-string (1- i)))
9226 (if (assoc si list) (setcar (assoc si list)
9227 (int-to-string (1- i))))))
9228 ((eq action 'insert)
9229 (setq col (car columns))
9230 (loop for i from nmax downto col by 1 do
9231 (setq si (int-to-string i))
9232 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
9233 (if (assoc si list) (setcar (assoc si list)
9234 (int-to-string (1+ i))))))
9236 (setq col1 (car columns) col2 (nth 1 columns)
9237 sc1 (int-to-string col1) sc2 (int-to-string col2))
9238 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
9239 (org-table-replace-in-formulas list sc1 "ZqZ")
9240 (org-table-replace-in-formulas list sc2 sc1)
9241 (org-table-replace-in-formulas list "ZqZ" sc2)
9242 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
9243 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
9244 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
9245 (t (error "Invalid action in `org-table-modify-formulas'")))
9246 (if list (org-table-store-formulas list))))
9248 (defun org-table-replace-in-formulas (list s1 s2)
9250 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
9251 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
9252 re (concat (regexp-quote s1) "\\>"))
9253 (while (setq elt (pop list))
9255 (while (string-match re s)
9256 (setq s (replace-match s2 t t s)))
9259 (defun org-table-get-specials ()
9260 "Get the column names and local parameters for this table."
9262 (let ((beg (org-table-begin)) (end (org-table-end))
9263 names name fields fields1 field cnt c v line col)
9264 (setq org-table-column-names nil
9265 org-table-local-parameters nil
9266 org-table-named-field-locations nil)
9268 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9269 (setq names (org-split-string (match-string 1) " *| *")
9271 (while (setq name (pop names))
9273 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9274 (push (cons name (int-to-string cnt)) org-table-column-names))))
9275 (setq org-table-column-names (nreverse org-table-column-names))
9276 (setq org-table-column-name-regexp
9277 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9279 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9280 (setq fields (org-split-string (match-string 1) " *| *"))
9281 (while (setq field (pop fields))
9282 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9283 (push (cons (match-string 1 field) (match-string 2 field))
9284 org-table-local-parameters))))
9286 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9287 (setq c (match-string 1)
9288 fields (org-split-string (match-string 2) " *| *"))
9290 (beginning-of-line (if (equal c "_") 2 0))
9291 (setq line (org-current-line) col 1)
9292 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9293 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9294 (while (and fields1 (setq field (pop fields)))
9295 (setq v (pop fields1) col (1+ col))
9296 (when (and (stringp field) (stringp v)
9297 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9298 (push (cons field v) org-table-local-parameters)
9299 (push (list field line col) org-table-named-field-locations)))))))
9301 (defun org-this-word ()
9302 ;; Get the current word
9304 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
9305 (end (progn (skip-chars-forward "^ \t\n") (point))))
9306 (buffer-substring-no-properties beg end))))
9308 (defun org-table-maybe-eval-formula ()
9309 "Check if the current field starts with \"=\" or \":=\".
9310 If yes, store the formula and apply it."
9311 ;; We already know we are in a table. Get field will only return a formula
9312 ;; when appropriate. It might return a separator line, but no problem.
9313 (when org-table-formula-evaluate-inline
9314 (let* ((field (org-trim (or (org-table-get-field) "")))
9316 (when (string-match "^:?=\\(.*\\)" field)
9317 (setq named (equal (string-to-char field) ?:)
9318 eq (match-string 1 field))
9319 (if (fboundp 'calc-eval)
9320 (org-table-eval-formula (if named '(4) nil) eq))))))
9322 (defvar org-recalc-commands nil
9323 "List of commands triggering the recalculation of a line.
9324 Will be filled automatically during use.")
9326 (defvar org-recalc-marks
9327 '((" " . "Unmarked: no special line, no automatic recalculation")
9328 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9329 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9330 ("!" . "Column name definition line. Reference in formula as $name.")
9331 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9332 ("_" . "Names for values in row below this one.")
9333 ("^" . "Names for values in row above this one.")))
9335 (defun org-table-rotate-recalc-marks (&optional newchar)
9336 "Rotate the recalculation mark in the first column.
9337 If in any row, the first field is not consistent with a mark,
9338 insert a new column for the markers.
9339 When there is an active region, change all the lines in the region,
9340 after prompting for the marking character.
9341 After each change, a message will be displayed indicating the meaning
9344 (unless (org-at-table-p) (error "Not at a table"))
9345 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9346 (beg (org-table-begin))
9347 (end (org-table-end))
9348 (l (org-current-line))
9349 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9350 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9354 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9355 (col (org-table-current-column))
9356 (forcenew (car (assoc newchar org-recalc-marks)))
9359 (message "Change region to what mark? Type # * ! $ or SPC: ")
9360 (setq newchar (char-to-string (read-char-exclusive))
9361 forcenew (car (assoc newchar org-recalc-marks))))
9362 (if (and newchar (not forcenew))
9363 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9365 (if l1 (goto-line l1))
9367 (beginning-of-line 1)
9368 (unless (looking-at org-table-dataline-regexp)
9369 (error "Not at a table data line")))
9371 (org-table-goto-column 1)
9372 (org-table-insert-column)
9373 (org-table-goto-column (1+ col)))
9374 (setq epos (point-at-eol))
9376 (beginning-of-line 1)
9377 (org-table-get-field
9378 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9380 (setq new (or forcenew
9381 (cadr (member (match-string 1) marks))))
9387 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9388 (and (looking-at org-table-dataline-regexp)
9389 (org-table-get-field 1 (concat " " new " "))))
9391 (if (not (= epos (point-at-eol))) (org-table-align))
9393 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9395 (defun org-table-maybe-recalculate-line ()
9396 "Recompute the current line if marked for it, and if we haven't just done it."
9398 (and org-table-allow-automatic-line-recalculation
9399 (not (and (memq last-command org-recalc-commands)
9400 (equal org-last-recalc-line (org-current-line))))
9401 (save-excursion (beginning-of-line 1)
9402 (looking-at org-table-auto-recalculate-regexp))
9403 (fboundp 'calc-eval)
9404 (org-table-recalculate) t))
9406 (defvar org-table-formula-debug nil
9407 "Non-nil means, debug table formulas.
9408 When nil, simply write \"#ERROR\" in corrupted fields.")
9411 (defsubst org-set-calc-mode (var &optional value)
9413 (setq var (assoc var '(("D" calc-angle-mode deg)
9414 ("R" calc-angle-mode rad)
9415 ("F" calc-prefer-frac t)
9416 ("S" calc-symbolic-mode t)))
9417 value (nth 2 var) var (nth 1 var)))
9418 (if (memq var modes)
9419 (setcar (cdr (memq var modes)) value)
9420 (cons var (cons value modes)))
9423 (defun org-table-eval-formula (&optional arg equation
9424 suppress-align suppress-const
9426 "Replace the table field value at the cursor by the result of a calculation.
9428 This function makes use of Dave Gillespie's Calc package, in my view the
9429 most exciting program ever written for GNU Emacs. So you need to have Calc
9430 installed in order to use this function.
9432 In a table, this command replaces the value in the current field with the
9433 result of a formula. It also installs the formula as the \"current\" column
9434 formula, by storing it in a special line below the table. When called
9435 with a `C-u' prefix, the current field must ba a named field, and the
9436 formula is installed as valid in only this specific field.
9438 When called, the command first prompts for a formula, which is read in
9439 the minibuffer. Previously entered formulas are available through the
9440 history list, and the last used formula is offered as a default.
9441 These stored formulas are adapted correctly when moving, inserting, or
9442 deleting columns with the corresponding commands.
9444 The formula can be any algebraic expression understood by the Calc package.
9445 For details, see the Org-mode manual.
9447 This function can also be called from Lisp programs and offers
9448 additional arguments: EQUATION can be the formula to apply. If this
9449 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9450 used to speed-up recursive calls by by-passing unnecessary aligns.
9451 SUPPRESS-CONST suppresses the interpretation of constants in the
9452 formula, assuming that this has been done already outside the function.
9453 SUPPRESS-STORE means the formula should not be stored, either because
9454 it is already stored, or because it is a modified equation that should
9455 not overwrite the stored one."
9458 (org-table-check-inside-data-field)
9459 (org-table-get-specials)
9461 (ndown (if (integerp arg) arg 1))
9462 (org-table-automatic-realign nil)
9463 (case-fold-search nil)
9465 (formula (if (and equation suppress-store)
9467 (org-table-get-formula equation (equal arg '(4)))))
9468 (n0 (org-table-current-column))
9469 (modes (copy-sequence org-calc-default-modes))
9470 n form fmt x ev orig c)
9471 ;; Parse the format string. Since we have a lot of modes, this is
9472 ;; a lot of work. However, I think calc still uses most of the time.
9473 (if (string-match ";" formula)
9474 (let ((tmp (org-split-string formula ";")))
9475 (setq formula (car tmp)
9476 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9478 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
9479 (setq c (string-to-char (match-string 1 fmt))
9480 n (string-to-number (or (match-string 1 fmt) "")))
9481 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
9482 (setq modes (org-set-calc-mode
9484 (list (cdr (assoc c '((?n . float) (?f . fix)
9485 (?s . sci) (?e . eng))))
9487 (setq fmt (replace-match "" t t fmt)))
9488 (while (string-match "[DRFS]" fmt)
9489 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9490 (setq fmt (replace-match "" t t fmt)))
9491 (unless (string-match "\\S-" fmt)
9493 (if (and (not suppress-const) org-table-formula-use-constants)
9494 (setq formula (org-table-formula-substitute-names formula)))
9495 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9497 (setq fields (org-split-string
9499 (point-at-bol) (point-at-eol)) " *| *"))
9500 (if org-table-formula-numbers-only
9501 (setq fields (mapcar
9502 (lambda (x) (number-to-string (string-to-number x)))
9504 (setq ndown (1- ndown))
9505 (setq form (copy-sequence formula))
9506 ;; Insert the references to fields in same row
9507 (while (string-match "\\$\\([0-9]+\\)?" form)
9508 (setq n (if (match-beginning 1)
9509 (string-to-number (match-string 1 form))
9511 x (nth (1- n) fields))
9512 (unless x (error "Invalid field specifier \"%s\""
9513 (match-string 0 form)))
9514 (if (equal x "") (setq x "0"))
9515 (setq form (replace-match (concat "(" x ")") t t form)))
9516 ;; Insert ranges in current column
9517 (while (string-match "\\&[-I0-9]+" form)
9518 (setq form (replace-match
9520 (org-table-get-vertical-vector (match-string 0 form)
9523 (setq ev (calc-eval (cons form modes)
9524 (if org-table-formula-numbers-only 'num)))
9526 (when org-table-formula-debug
9527 (with-output-to-temp-buffer "*Help*"
9528 (princ (format "Substitution history of formula
9531 $1-> %s\n" orig formula form))
9533 (princ (format " %s^\nError: %s"
9534 (make-string (car ev) ?\-) (nth 1 ev)))
9535 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9537 (if fmt (format fmt (string-to-number ev)) ev)))))
9538 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
9539 (unless (and (interactive-p) (not ndown))
9540 (unless (let (inhibit-redisplay)
9541 (y-or-n-p "Debugging Formula. Continue to next? "))
9544 (delete-window (get-buffer-window "*Help*"))
9546 (if (listp ev) (setq fmt nil ev "#ERROR"))
9547 (org-table-justify-field-maybe
9548 (if fmt (format fmt (string-to-number ev)) ev))
9549 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9550 (call-interactively 'org-return)
9552 (and down (org-table-maybe-recalculate-line))
9553 (or suppress-align (and org-table-may-need-update
9554 (org-table-align)))))
9556 (defun org-table-recalculate (&optional all noalign)
9557 "Recalculate the current table line by applying all stored formulas."
9559 (or (memq this-command org-recalc-commands)
9560 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9561 (unless (org-at-table-p) (error "Not at a table"))
9562 (org-table-get-specials)
9563 (let* ((eqlist (sort (org-table-get-stored-formulas)
9564 (lambda (a b) (string< (car a) (car b)))))
9565 (inhibit-redisplay t)
9566 (line-re org-table-dataline-regexp)
9567 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9568 (thiscol (org-table-current-column))
9569 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
9570 ;; Insert constants in all formulas
9573 (setcdr x (org-table-formula-substitute-names (cdr x)))
9576 ;; Split the equation list
9577 (while (setq eq (pop eqlist))
9578 (if (<= (string-to-char (car eq)) ?9)
9581 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9584 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9585 (goto-char (setq beg (org-table-begin)))
9586 (if (re-search-forward org-table-calculate-mark-regexp end t)
9587 ;; This is a table with marked lines, only compute selected lines
9588 (setq line-re org-table-recalculate-regexp)
9589 ;; Move forward to the first non-header line
9590 (if (and (re-search-forward org-table-dataline-regexp end t)
9591 (re-search-forward org-table-hline-regexp end t)
9592 (re-search-forward org-table-dataline-regexp end t))
9593 (setq beg (match-beginning 0))
9594 nil))) ;; just leave beg where it is
9595 (setq beg (point-at-bol)
9596 end (move-marker (make-marker) (1+ (point-at-eol)))))
9598 (and all (message "Re-applying formulas to full table..."))
9599 (while (re-search-forward line-re end t)
9600 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
9601 ;; Unprotected line, recalculate
9602 (and all (message "Re-applying formulas to full table...(line %d)"
9603 (setq cnt (1+ cnt))))
9604 (setq org-last-recalc-line (org-current-line))
9606 (while (setq entry (pop eql))
9607 (goto-line org-last-recalc-line)
9608 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9609 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
9610 (goto-line thisline)
9611 (org-table-goto-column thiscol)
9612 (or noalign (and org-table-may-need-update (org-table-align))
9613 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9614 ;; Now do the names fields
9615 (while (setq eq (pop eqlname))
9617 a (assoc name org-table-named-field-locations))
9619 (message "Re-applying formula to named field: %s" name)
9620 (goto-line (nth 1 a))
9621 (org-table-goto-column (nth 2 a))
9622 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
9623 ;; back to initial position
9624 (goto-line thisline)
9625 (org-table-goto-column thiscol)
9626 (or noalign (and org-table-may-need-update (org-table-align))
9627 (and all (message "Re-applying formulas...done")))))
9629 (defun org-table-formula-substitute-names (f)
9630 "Replace $const with values in string F."
9631 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
9632 ;; First, check for column names
9633 (while (setq start (string-match org-table-column-name-regexp f start))
9634 (setq start (1+ start))
9635 (setq a (assoc (match-string 1 f) org-table-column-names))
9636 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9637 ;; Expand ranges to vectors
9638 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
9639 (setq n1 (string-to-number (match-string 1 f))
9640 n2 (string-to-number (match-string 2 f))
9641 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
9642 s (concat "[($" (number-to-string (1- nn1)) ")"))
9643 (loop for i from nn1 upto nn2 do
9644 (setq s (concat s ",($" (int-to-string i) ")")))
9645 (setq s (concat s "]"))
9646 (if (< n2 n1) (setq s (concat "rev(" s ")")))
9647 (setq f (replace-match s t t f)))
9648 ;; Parameters and constants
9650 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
9651 (setq start (1+ start))
9652 (if (setq a (save-match-data
9653 (org-table-get-constant (match-string 1 f))))
9654 (setq f (replace-match (concat "(" a ")") t t f))))
9655 (if org-table-formula-debug
9656 (put-text-property 0 (length f) :orig-formula f1 f))
9659 (defun org-table-get-constant (const)
9660 "Find the value for a parameter or constant in a formula.
9661 Parameters get priority."
9662 (or (cdr (assoc const org-table-local-parameters))
9663 (cdr (assoc const org-table-formula-constants))
9664 (and (fboundp 'constants-get) (constants-get const))
9667 (defvar org-edit-formulas-map (make-sparse-keymap))
9668 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
9669 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
9670 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
9673 (defvar org-window-configuration)
9675 (defun org-table-edit-formulas ()
9676 "Edit the formulas of the current table in a separate buffer."
9678 (unless (org-at-table-p)
9679 (error "Not at a table"))
9680 (org-table-get-specials)
9681 (let ((eql (org-table-get-stored-formulas))
9682 (pos (move-marker (make-marker) (point)))
9683 (wc (current-window-configuration))
9685 (switch-to-buffer-other-window "*Edit Formulas*")
9688 (set (make-local-variable 'org-pos) pos)
9689 (set (make-local-variable 'org-window-configuration) wc)
9690 (use-local-map org-edit-formulas-map)
9691 (setq s "# Edit formulas and finish with `C-c C-c'.
9692 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
9693 # Use `C-c ?' to get information about $name at point.
9694 # To cancel editing, press `C-c C-q'.\n")
9695 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9697 (while (setq entry (pop eql))
9698 (when (setq loc (assoc (car entry) org-table-named-field-locations))
9699 (setq s (format "# Named formula, referring to column %d in line %d\n"
9700 (nth 2 loc) (nth 1 loc)))
9701 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9703 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
9704 (remove-text-properties 0 (length s) '(face nil) s)
9706 (goto-char (point-min))
9707 (message "Edit formulas and finish with `C-c C-c'.")))
9709 (defun org-show-variable ()
9710 "Show the location/value of the $ expression at point."
9712 (let (var (pos org-pos) (win (selected-window)) e)
9714 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
9715 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
9716 (setq var (match-string 1))
9717 (error "No variable at point")))
9719 ((setq e (assoc var org-table-named-field-locations))
9720 (switch-to-buffer-other-window (marker-buffer pos))
9721 (goto-line (nth 1 e))
9722 (org-table-goto-column (nth 2 e))
9724 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9725 ((setq e (assoc var org-table-column-names))
9726 (switch-to-buffer-other-window (marker-buffer pos))
9728 (goto-char (org-table-begin))
9729 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9732 (goto-char (match-beginning 1))
9733 (message "Named column (column %s)" (cdr e)))
9734 (error "Column name not found"))
9735 (select-window win))
9736 ((string-match "^[0-9]$" var)
9738 (switch-to-buffer-other-window (marker-buffer pos))
9740 (goto-char (org-table-begin))
9742 (if (re-search-forward org-table-dataline-regexp
9745 (goto-char (match-beginning 0))
9746 (org-table-goto-column (string-to-number var))
9747 (message "Column %s" var))
9748 (error "Column name not found"))
9749 (select-window win))
9750 ((setq e (assoc var org-table-local-parameters))
9751 (switch-to-buffer-other-window (marker-buffer pos))
9753 (goto-char (org-table-begin))
9754 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9756 (goto-char (match-beginning 1))
9757 (message "Local parameter."))
9758 (error "Parameter not found"))
9759 (select-window win))
9762 ((setq e (assoc var org-table-formula-constants))
9763 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
9764 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9765 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
9766 (t (error "Undefined name $%s" var)))))))
9768 (defun org-finish-edit-formulas (&optional arg)
9769 "Parse the buffer for formula definitions and install them.
9770 With prefix ARG, apply the new formulas to the table."
9772 (let ((pos org-pos) eql)
9773 (goto-char (point-min))
9774 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
9775 (push (cons (match-string 1) (match-string 2)) eql))
9776 (set-window-configuration org-window-configuration)
9777 (select-window (get-buffer-window (marker-buffer pos)))
9779 (unless (org-at-table-p)
9780 (error "Lost table position - cannot install formulae"))
9781 (org-table-store-formulas eql)
9782 (move-marker pos nil)
9783 (kill-buffer "*Edit Formulas*")
9785 (org-table-recalculate 'all)
9786 (message "New formulas installed - press C-u C-c C-c to apply."))))
9788 (defun org-abort-edit-formulas ()
9789 "Abort editing formulas, without installing the changes."
9791 (let ((pos org-pos))
9792 (set-window-configuration org-window-configuration)
9793 (select-window (get-buffer-window (marker-buffer pos)))
9795 (message "Formula editing aborted without installing changes")))
9797 ;;; The orgtbl minor mode
9799 ;; Define a minor mode which can be used in other modes in order to
9800 ;; integrate the org-mode table editor.
9802 ;; This is really a hack, because the org-mode table editor uses several
9803 ;; keys which normally belong to the major mode, for example the TAB and
9804 ;; RET keys. Here is how it works: The minor mode defines all the keys
9805 ;; necessary to operate the table editor, but wraps the commands into a
9806 ;; function which tests if the cursor is currently inside a table. If that
9807 ;; is the case, the table editor command is executed. However, when any of
9808 ;; those keys is used outside a table, the function uses `key-binding' to
9809 ;; look up if the key has an associated command in another currently active
9810 ;; keymap (minor modes, major mode, global), and executes that command.
9811 ;; There might be problems if any of the keys used by the table editor is
9812 ;; otherwise used as a prefix key.
9814 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9815 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9816 ;; addresses this by checking explicitly for both bindings.
9818 ;; The optimized version (see variable `orgtbl-optimized') takes over
9819 ;; all keys which are bound to `self-insert-command' in the *global map*.
9820 ;; Some modes bind other commands to simple characters, for example
9821 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9822 ;; active, this binding is ignored inside tables and replaced with a
9823 ;; modified self-insert.
9825 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
9826 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
9827 In the optimized version, the table editor takes over all simple keys that
9828 normally just insert a character. In tables, the characters are inserted
9829 in a way to minimize disturbing the table structure (i.e. in overwrite mode
9830 for empty fields). Outside tables, the correct binding of the keys is
9833 The default for this option is t if the optimized version is also used in
9834 Org-mode. See the variable `org-enable-table-editor' for details. Changing
9835 this variable requires a restart of Emacs to become effective."
9839 (defvar orgtbl-mode nil
9840 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9841 table editor in arbitrary modes.")
9842 (make-variable-buffer-local 'orgtbl-mode)
9844 (defvar orgtbl-mode-map (make-keymap)
9845 "Keymap for `orgtbl-mode'.")
9848 (defun turn-on-orgtbl ()
9849 "Unconditionally turn on `orgtbl-mode'."
9853 (defun orgtbl-mode (&optional arg)
9854 "The `org-mode' table editor as a minor mode for use in other modes."
9856 (if (eq major-mode 'org-mode)
9857 ;; Exit without error, in case some hook functions calls this
9858 ;; by accident in org-mode.
9859 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9861 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9864 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9865 ;; Make sure we are first in minor-mode-map-alist
9866 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9867 (and c (setq minor-mode-map-alist
9868 (cons c (delq c minor-mode-map-alist)))))
9869 (set (make-local-variable (quote org-table-may-need-update)) t)
9870 (org-add-hook 'before-change-functions 'org-before-change-function
9872 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
9873 auto-fill-inhibit-regexp)
9874 (set (make-local-variable 'auto-fill-inhibit-regexp)
9875 (if auto-fill-inhibit-regexp
9876 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
9878 (easy-menu-add orgtbl-mode-menu)
9879 (run-hooks 'orgtbl-mode-hook))
9880 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9881 (remove-hook 'before-change-functions 'org-before-change-function t)
9882 (easy-menu-remove orgtbl-mode-menu)
9883 (force-mode-line-update 'all))))
9885 ;; Install it as a minor mode.
9886 (put 'orgtbl-mode :included t)
9887 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9888 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9890 (defun orgtbl-make-binding (fun n &rest keys)
9891 "Create a function for binding in the table minor mode.
9892 FUN is the command to call inside a table. N is used to create a unique
9893 command name. KEYS are keys that should be checked in for a command
9894 to execute outside of tables."
9897 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9899 (concat "In tables, run `" (symbol-name fun) "'.\n"
9900 "Outside of tables, run the binding of `"
9901 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9906 (list 'call-interactively (list 'quote fun))
9907 (list 'let '(orgtbl-mode)
9908 (list 'call-interactively
9911 (list 'key-binding k))
9913 '('orgtbl-error))))))))
9915 (defun orgtbl-error ()
9916 "Error when there is no default binding for a table key."
9918 (error "This key is has no function outside tables"))
9920 (defun orgtbl-setup ()
9921 "Setup orgtbl keymaps."
9925 '([(meta shift left)] org-table-delete-column)
9926 '([(meta left)] org-table-move-column-left)
9927 '([(meta right)] org-table-move-column-right)
9928 '([(meta shift right)] org-table-insert-column)
9929 '([(meta shift up)] org-table-kill-row)
9930 '([(meta shift down)] org-table-insert-row)
9931 '([(meta up)] org-table-move-row-up)
9932 '([(meta down)] org-table-move-row-down)
9933 '("\C-c\C-w" org-table-cut-region)
9934 '("\C-c\M-w" org-table-copy-region)
9935 '("\C-c\C-y" org-table-paste-rectangle)
9936 '("\C-c-" org-table-insert-hline)
9937 ; '([(shift tab)] org-table-previous-field)
9938 '("\C-m" org-table-next-row)
9939 (list (org-key 'S-return) 'org-table-copy-down)
9940 '([(meta return)] org-table-wrap-region)
9941 '("\C-c\C-q" org-table-wrap-region)
9942 '("\C-c?" org-table-current-column)
9943 '("\C-c " org-table-blank-field)
9944 '("\C-c+" org-table-sum)
9945 '("\C-c|" org-table-toggle-vline-visibility)
9946 '("\C-c=" org-table-eval-formula)
9947 '("\C-c'" org-table-edit-formulas)
9948 '("\C-c*" org-table-recalculate)
9949 '("\C-c^" org-table-sort-lines)
9950 '([(control ?#)] org-table-rotate-recalc-marks)))
9952 (while (setq elt (pop bindings))
9953 (setq nfunc (1+ nfunc))
9956 cmd (orgtbl-make-binding fun nfunc key))
9957 (define-key orgtbl-mode-map key cmd))
9958 ;; Special treatment needed for TAB and RET
9959 (define-key orgtbl-mode-map [(return)]
9960 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
9961 (define-key orgtbl-mode-map "\C-m"
9962 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
9963 (define-key orgtbl-mode-map [(tab)]
9964 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
9965 (define-key orgtbl-mode-map "\C-i"
9966 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
9967 (define-key orgtbl-mode-map "\C-i"
9968 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
9969 (define-key orgtbl-mode-map "\C-c\C-c"
9970 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
9971 (when orgtbl-optimized
9972 ;; If the user wants maximum table support, we need to hijack
9973 ;; some standard editing functions
9974 (org-remap orgtbl-mode-map
9975 'self-insert-command 'orgtbl-self-insert-command
9976 'delete-char 'orgtbl-delete-char
9977 'delete-backward-char 'orgtbl-delete-backward-char)
9978 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
9979 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
9981 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
9982 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
9983 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
9984 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
9986 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
9987 ["Copy Field from Above"
9988 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
9991 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
9992 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
9993 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
9994 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
9996 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
9997 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
9998 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
9999 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10000 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10002 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10004 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10005 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10006 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10007 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10009 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10010 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10011 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10012 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10013 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10014 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10015 ["Sum Column/Rectangle" org-table-sum
10016 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10017 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10019 (setq org-table-formula-debug (not org-table-formula-debug))
10020 :style toggle :selected org-table-formula-debug]
10024 (defun orgtbl-tab ()
10025 "Justification and field motion for `orgtbl-mode'."
10027 (org-table-justify-field-maybe)
10028 (org-table-next-field))
10030 (defun orgtbl-ret ()
10031 "Justification and field motion for `orgtbl-mode'."
10033 (org-table-justify-field-maybe)
10034 (org-table-next-row))
10036 (defun orgtbl-self-insert-command (N)
10037 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10038 If the cursor is in a table looking at whitespace, the whitespace is
10039 overwritten, and the table is not marked as requiring realignment."
10041 (if (and (org-at-table-p)
10043 (and org-table-auto-blank-field
10044 (member last-command
10045 '(orgtbl-hijacker-command-100
10046 orgtbl-hijacker-command-101
10047 orgtbl-hijacker-command-102
10048 orgtbl-hijacker-command-103
10049 orgtbl-hijacker-command-104
10050 orgtbl-hijacker-command-105))
10051 (org-table-blank-field))
10054 (looking-at "[^|\n]* +|"))
10055 (let (org-table-may-need-update)
10056 (goto-char (1- (match-end 0)))
10057 (delete-backward-char 1)
10058 (goto-char (match-beginning 0))
10059 (self-insert-command N))
10060 (setq org-table-may-need-update t)
10062 (call-interactively (key-binding (vector last-input-event))))))
10064 (defun org-force-self-insert (N)
10065 "Needed to enforce self-insert under remapping."
10067 (self-insert-command N))
10069 (defun orgtbl-delete-backward-char (N)
10070 "Like `delete-backward-char', insert whitespace at field end in tables.
10071 When deleting backwards, in tables this function will insert whitespace in
10072 front of the next \"|\" separator, to keep the table aligned. The table will
10073 still be marked for re-alignment, because a narrow field may lead to a
10074 reduced column width."
10076 (if (and (org-at-table-p)
10078 (string-match "|" (buffer-substring (point-at-bol) (point)))
10079 (looking-at ".*?|"))
10080 (let ((pos (point)))
10081 (backward-delete-char N)
10082 (skip-chars-forward "^|")
10084 (goto-char (1- pos)))
10085 (delete-backward-char N)))
10087 (defun orgtbl-delete-char (N)
10088 "Like `delete-char', but insert whitespace at field end in tables.
10089 When deleting characters, in tables this function will insert whitespace in
10090 front of the next \"|\" separator, to keep the table aligned. The table
10091 will still be marked for re-alignment, because a narrow field may lead to
10092 a reduced column width."
10094 (if (and (org-at-table-p)
10096 (not (= (char-after) ?|))
10098 (if (looking-at ".*?|")
10099 (let ((pos (point)))
10100 (replace-match (concat
10101 (substring (match-string 0) 1 -1)
10108 (defconst org-level-max 20)
10110 (defun org-export-find-first-heading-line (list)
10111 "Remove all lines from LIST which are before the first headline."
10112 (let ((orig-list list)
10113 (re (concat "^" outline-regexp)))
10115 (not (string-match re (car list))))
10117 (or list orig-list)))
10119 (defun org-skip-comments (lines)
10120 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10121 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10122 (re2 "^\\(\\*+\\)[ \t\n\r]")
10124 (while (setq line (pop lines))
10126 ((and (string-match re1 line)
10127 (setq level (- (match-end 1) (match-beginning 1))))
10128 ;; Beginning of a COMMENT subtree. Skip it.
10129 (while (and (setq line (pop lines))
10130 (or (not (string-match re2 line))
10131 (> (- (match-end 1) (match-beginning 1)) level))))
10132 (setq lines (cons line lines)))
10133 ((string-match "^#" line)
10134 ;; an ordinary comment line
10136 ((and org-export-table-remove-special-lines
10137 (string-match "^[ \t]*| *[!_^] *|" line))
10138 ;; a special table line that should be removed
10140 (t (setq rtn (cons line rtn)))))
10145 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10146 "Characters for underlining headings in ASCII export.")
10148 (defconst org-html-entities
10188 ("Aring") ("AA"."Å")
10277 ("varepsilon"."ε")
10290 ("sigmaf") ("varsigma"."ς")
10298 ("thetasym") ("vartheta"."ϑ")
10301 ("bull") ("bullet"."•")
10302 ("hellip") ("dots"."…")
10312 ("larr") ("leftarrow"."←") ("gets"."←")
10313 ("uarr") ("uparrow"."↑")
10314 ("rarr") ("to"."→") ("rightarrow"."→")
10315 ("darr")("downarrow"."↓")
10316 ("harr") ("leftrightarrow"."↔")
10317 ("crarr") ("hookleftarrow"."↵") ; has round hook, not quite CR
10318 ("lArr") ("Leftarrow"."⇐")
10319 ("uArr") ("Uparrow"."⇑")
10320 ("rArr") ("Rightarrow"."⇒")
10321 ("dArr") ("Downarrow"."⇓")
10322 ("hArr") ("Leftrightarrow"."⇔")
10324 ("part") ("partial"."∂")
10325 ("exist") ("exists"."∃")
10326 ("empty") ("emptyset"."∅")
10328 ("isin") ("in"."∈")
10334 ("lowast") ("ast"."∗")
10336 ("prop") ("proptp"."∝")
10337 ("infin") ("infty"."∞")
10338 ("ang") ("angle"."∠")
10339 ("and") ("vee"."∧")
10340 ("or") ("wedge"."∨")
10346 ("cong") ("simeq"."≅")
10347 ("asymp")("approx"."≈")
10348 ("ne") ("neq"."≠")
10352 ("sub") ("subset"."⊂")
10353 ("sup") ("supset"."⊃")
10360 ("sdot") ("cdot"."⋅")
10367 ("loz") ("Diamond"."◊")
10368 ("spades") ("spadesuit"."♠")
10369 ("clubs") ("clubsuit"."♣")
10370 ("hearts") ("diamondsuit"."♥")
10371 ("diams") ("diamondsuit"."♦")
10405 ("arccos"."arccos")
10406 ("arcsin"."arcsin")
10407 ("arctan"."arctan")
10424 ("liminf"."liminf")
10425 ("limsup"."limsup")
10438 "Entities for TeX->HTML translation.
10439 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
10440 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
10441 In that case, \"\\ent\" will be translated to \"&other;\".
10442 The list contains HTML entities for Latin-1, Greek and other symbols.
10443 It is supplemented by a number of commonly used TeX macros with appropriate
10444 translations. There is currently no way for users to extend this.")
10446 (defun org-cleaned-string-for-export (string)
10447 "Cleanup a buffer substring so that links can be created safely."
10449 (let* ((cb (current-buffer))
10450 (re-radio (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)"))
10453 (set-buffer (get-buffer-create " org-mode-tmp"))
10457 ;; Find targets in comments and move them out of comments
10458 (goto-char (point-min))
10459 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
10460 (replace-match "\\1"))
10461 ;; Find matches for radio targets and turn them into links
10462 (goto-char (point-min))
10463 (while (re-search-forward re-radio nil t)
10464 (replace-match "\\1[[\\2]]"))
10465 ;; Find all links that contain a newline and put them into a single line
10466 (goto-char (point-min))
10467 (while (re-search-forward "\\(\\[\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\]\\)" nil t)
10468 (replace-match "\\1 \\2")
10469 (goto-char (match-beginning 0)))
10471 (goto-char (point-min))
10472 (while (re-search-forward "^#.*\n?" nil t)
10473 (replace-match ""))
10474 (setq rtn (buffer-string)))
10475 (kill-buffer " org-mode-tmp")
10478 (defun org-solidify-link-text (s)
10479 "Take link text and make a safe target out of it."
10483 (org-split-string s "[ \t\r\n]+") "--")))
10485 (defvar org-last-level nil) ; dynamically scoped variable
10487 (defun org-export-as-ascii (arg)
10488 "Export the outline as a pretty ASCII file.
10489 If there is an active region, export only the region.
10490 The prefix ARG specifies how many levels of the outline should become
10491 underlined headlines. The default is 3."
10493 (setq-default org-todo-line-regexp org-todo-line-regexp)
10496 (if (org-region-active-p) (region-beginning) (point-min))
10497 (if (org-region-active-p) (region-end) (point-max))))
10498 (lines (org-export-find-first-heading-line
10501 (org-cleaned-string-for-export region)
10503 (org-startup-with-deadline-check nil)
10506 (case-fold-search nil)
10507 (filename (concat (file-name-sans-extension (buffer-file-name))
10509 (buffer (find-file-noselect filename))
10510 (levels-open (make-vector org-level-max nil))
10511 (date (format-time-string "%Y/%m/%d" (current-time)))
10512 (time (format-time-string "%X" (current-time)))
10513 (author user-full-name)
10514 (title (buffer-name))
10516 (email user-mail-address)
10517 (language org-export-default-language)
10522 (setq org-last-level 1)
10523 (org-init-section-numbers)
10525 (find-file-noselect filename)
10527 ;; Search for the export key lines
10528 (org-parse-key-lines)
10530 (setq lang-words (or (assoc language org-export-language-setup)
10531 (assoc "en" org-export-language-setup)))
10532 (if org-export-ascii-show-new-buffer
10533 (switch-to-buffer-other-window buffer)
10534 (set-buffer buffer))
10537 (if options (org-parse-export-options options))
10538 (setq umax (if arg (prefix-numeric-value arg)
10539 org-export-headline-levels))
10542 (if title (org-insert-centered title ?=))
10544 (if (or author email)
10545 (insert (concat (nth 1 lang-words) ": " (or author "")
10546 (if email (concat " <" email ">") "")
10548 (if (and date time)
10549 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
10550 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
10554 (if org-export-with-toc
10556 (insert (nth 3 lang-words) "\n"
10557 (make-string (length (nth 3 lang-words)) ?=) "\n")
10558 (mapcar '(lambda (line)
10559 (if (string-match org-todo-line-regexp
10561 ;; This is a headline
10563 (setq level (- (match-end 1) (match-beginning 1))
10564 txt (match-string 3 line)
10566 (or (and (match-beginning 2)
10567 (not (equal (match-string 2 line)
10570 (and (= level umax)
10571 (org-search-todo-below
10572 line lines level))))
10573 (setq txt (org-html-expand-for-ascii txt))
10575 (if org-export-with-section-numbers
10576 (setq txt (concat (org-section-number level)
10578 (if (<= level umax)
10581 (make-string (* (1- level) 4) ?\ )
10582 (format (if todo "%s (*)\n" "%s\n") txt))
10583 (setq org-last-level level))
10587 (org-init-section-numbers)
10588 (while (setq line (pop lines))
10589 ;; Remove the quoted HTML tags.
10590 (setq line (org-html-expand-for-ascii line))
10592 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
10593 (setq line (replace-match "" t t line)))
10594 ;; Replace internal links
10595 (while (string-match org-bracket-link-regexp line)
10596 (setq line (replace-match
10597 (if (match-end 3) "[\\3]" "[\\1]")
10600 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10602 (setq level (- (match-end 1) (match-beginning 1))
10603 txt (match-string 2 line))
10604 (org-ascii-level-start level txt umax))
10605 (t (insert line "\n"))))
10608 (goto-char (point-min))))
10610 (defun org-search-todo-below (line lines level)
10611 "Search the subtree below LINE for any TODO entries."
10612 (let ((rest (cdr (memq line lines)))
10613 (re org-todo-line-regexp)
10616 (while (setq line (pop rest))
10617 (if (string-match re line)
10619 (setq lv (- (match-end 1) (match-beginning 1))
10620 todo (and (match-beginning 2)
10621 (not (equal (match-string 2 line)
10622 org-done-string))))
10624 (if (<= lv level) (throw 'exit nil))
10625 (if todo (throw 'exit t))))))))
10627 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
10628 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
10629 (defun org-html-expand-for-ascii (line)
10630 "Handle quoted HTML for ASCII export."
10631 (if org-export-html-expand
10632 (while (string-match "@<[^<>\n]*>" line)
10633 ;; We just remove the tags for now.
10634 (setq line (replace-match "" nil nil line))))
10637 (defun org-insert-centered (s &optional underline)
10638 "Insert the string S centered and underline it with character UNDERLINE."
10639 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
10640 (insert (make-string ind ?\ ) s "\n")
10642 (insert (make-string ind ?\ )
10643 (make-string (length s) underline)
10646 (defun org-ascii-level-start (level title umax)
10647 "Insert a new level in ASCII export."
10650 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
10651 (if (or (not (equal (char-before) ?\n))
10652 (not (equal (char-before (1- (point))) ?\n)))
10654 (setq char (nth (- umax level) (reverse org-ascii-underline)))
10655 (if org-export-with-section-numbers
10656 (setq title (concat (org-section-number level) " " title)))
10657 (insert title "\n" (make-string (string-width title) char) "\n"))))
10659 (defun org-export-copy-visible ()
10660 "Copy the visible part of the buffer to another buffer, for printing.
10661 Also removes the first line of the buffer if it specifies a mode,
10662 and all options lines."
10664 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
10666 (buffer (find-file-noselect filename))
10668 (org-make-options-regexp
10669 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
10670 "STARTUP" "ARCHIVE"
10671 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
10672 (if org-noutline-p "\\(\n\\|$\\)" "")))
10674 (with-current-buffer buffer
10678 (setq s (goto-char (point-min)))
10679 (while (not (= (point) (point-max)))
10680 (goto-char (org-find-invisible))
10681 (append-to-buffer buffer s (point))
10682 (setq s (goto-char (org-find-visible)))))
10683 (switch-to-buffer-other-window buffer)
10685 (goto-char (point-min))
10686 (if (looking-at ".*-\\*- mode:.*\n")
10687 (replace-match ""))
10688 (while (re-search-forward ore nil t)
10689 (replace-match ""))
10690 (goto-char (point-min))))
10692 (defun org-find-visible ()
10693 (if (featurep 'noutline)
10695 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10696 (get-char-property s 'invisible)))
10698 (skip-chars-forward "^\n")
10700 (defun org-find-invisible ()
10701 (if (featurep 'noutline)
10703 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10704 (not (get-char-property s 'invisible))))
10706 (skip-chars-forward "^\r")
10711 (defun org-get-current-options ()
10712 "Return a string with current options as keyword options.
10713 Does include HTML export options as well as TODO and CATEGORY stuff."
10719 #+TEXT: Some descriptive text to be emitted. Several lines OK.
10720 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
10727 (buffer-name) (user-full-name) user-mail-address org-export-default-language
10728 org-export-headline-levels
10729 org-export-with-section-numbers
10730 org-export-with-toc
10731 org-export-preserve-breaks
10732 org-export-html-expand
10733 org-export-with-fixed-width
10734 org-export-with-tables
10735 org-export-with-sub-superscripts
10736 org-export-with-emphasize
10737 org-export-with-TeX-macros
10738 (file-name-nondirectory (buffer-file-name))
10739 (if (equal org-todo-interpretation 'sequence)
10740 (mapconcat 'identity org-todo-keywords " ")
10741 "TODO FEEDBACK VERIFY DONE")
10742 (if (equal org-todo-interpretation 'type)
10743 (mapconcat 'identity org-todo-keywords " ")
10744 "Me Jason Marie DONE")
10745 (cdr (assoc org-startup-folded
10746 '((nil . "nofold")(t . "fold")(content . "content"))))
10747 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
10748 org-archive-location
10751 (defun org-insert-export-options-template ()
10752 "Insert into the buffer a template with information for exporting."
10754 (if (not (bolp)) (newline))
10755 (let ((s (org-get-current-options)))
10756 (and (string-match "#\\+CATEGORY" s)
10757 (setq s (substring s 0 (match-beginning 0))))
10760 (defun org-toggle-fixed-width-section (arg)
10761 "Toggle the fixed-width export.
10762 If there is no active region, the QUOTE keyword at the current headline is
10763 inserted or removed. When present, it causes the text between this headline
10764 and the next to be exported as fixed-width text, and unmodified.
10765 If there is an active region, this command adds or removes a colon as the
10766 first character of this line. If the first character of a line is a colon,
10767 this line is also exported in fixed-width font."
10770 (regionp (org-region-active-p))
10771 (beg (if regionp (region-beginning) (point)))
10772 (end (if regionp (region-end)))
10773 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
10774 (re "[ \t]*\\(:\\)")
10779 (setq cc (current-column))
10780 (beginning-of-line 1)
10781 (setq off (looking-at re))
10782 (while (> nlines 0)
10783 (setq nlines (1- nlines))
10784 (beginning-of-line 1)
10787 (move-to-column cc t)
10790 ((and off (looking-at re))
10791 (replace-match "" t t nil 1))
10792 ((not off) (move-to-column cc t) (insert ":")))
10795 (org-back-to-heading)
10796 (if (looking-at (concat outline-regexp
10797 "\\( +\\<" org-quote-string "\\>\\)"))
10798 (replace-match "" t t nil 1)
10799 (if (looking-at outline-regexp)
10801 (goto-char (match-end 0))
10802 (insert " " org-quote-string))))))))
10804 (defun org-export-as-html-and-open (arg)
10805 "Export the outline as HTML and immediately open it with a browser.
10806 If there is an active region, export only the region.
10807 The prefix ARG specifies how many levels of the outline should become
10808 headlines. The default is 3. Lower levels will become bulleted lists."
10810 (org-export-as-html arg 'hidden)
10811 (org-open-file (buffer-file-name)))
10813 (defun org-export-as-html-batch ()
10814 "Call `org-export-as-html', may be used in batch processing as
10816 --load=$HOME/lib/emacs/org.el
10817 --eval \"(setq org-export-headline-levels 2)\"
10818 --visit=MyFile --funcall org-export-as-html-batch"
10819 (org-export-as-html org-export-headline-levels 'hidden))
10821 (defun org-export-as-html (arg &optional hidden)
10822 "Export the outline as a pretty HTML file.
10823 If there is an active region, export only the region.
10824 The prefix ARG specifies how many levels of the outline should become
10825 headlines. The default is 3. Lower levels will become bulleted lists."
10827 (setq-default org-todo-line-regexp org-todo-line-regexp)
10828 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
10829 (setq-default org-done-string org-done-string)
10830 (let* ((style org-export-html-style)
10831 (region-p (org-region-active-p))
10834 (if region-p (region-beginning) (point-min))
10835 (if region-p (region-end) (point-max))))
10837 (org-skip-comments (org-split-string
10838 (org-cleaned-string-for-export region)
10840 (lines (org-export-find-first-heading-line all_lines))
10841 (level 0) (line "") (origline "") txt todo
10843 (filename (concat (file-name-sans-extension (buffer-file-name))
10845 (buffer (find-file-noselect filename))
10846 (levels-open (make-vector org-level-max nil))
10847 (date (format-time-string "%Y/%m/%d" (current-time)))
10848 (time (format-time-string "%X" (current-time)))
10849 (author user-full-name)
10850 (title (buffer-name))
10852 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
10855 (in-local-list nil)
10856 (local-list-num nil)
10857 (local-list-indent nil)
10858 (llt org-plain-list-ordered-item-terminator)
10859 (email user-mail-address)
10860 (language org-export-default-language)
10865 ;; FIXME: The following returns always nil under XEmacs
10866 (coding-system (and (fboundp 'coding-system-get)
10867 (boundp 'buffer-file-coding-system)
10868 buffer-file-coding-system))
10869 (coding-system-for-write (or coding-system coding-system-for-write))
10870 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
10871 (charset (and coding-system
10872 (coding-system-get coding-system 'mime-charset)))
10874 table-buffer table-orig-buffer
10875 ind start-is-num starter
10877 (message "Exporting...")
10879 (setq org-last-level 1)
10880 (org-init-section-numbers)
10882 ;; Search for the export key lines
10883 (org-parse-key-lines)
10884 (setq lang-words (or (assoc language org-export-language-setup)
10885 (assoc "en" org-export-language-setup)))
10887 ;; Switch to the output buffer
10888 (if (or hidden (not org-export-html-show-new-buffer))
10889 (set-buffer buffer)
10890 (switch-to-buffer-other-window buffer))
10893 (let ((case-fold-search nil))
10894 (if options (org-parse-export-options options))
10895 (setq umax (if arg (prefix-numeric-value arg)
10896 org-export-headline-levels))
10900 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
10901 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
10902 <html lang=\"%s\"><head>
10904 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
10905 <meta name=generator content=\"Org-mode\">
10906 <meta name=generated content=\"%s %s\">
10907 <meta name=author content=\"%s\">
10911 language (org-html-expand title) (or charset "iso-8859-1")
10912 date time author style))
10913 (if title (insert (concat "<H1 class=\"title\">"
10914 (org-html-expand title) "</H1>\n")))
10915 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
10916 (if email (insert (concat "<a href=\"mailto:" email "\"><"
10917 email "></a>\n")))
10918 (if (or author email) (insert "<br>\n"))
10919 (if (and date time) (insert (concat (nth 2 lang-words) ": "
10920 date " " time "<br>\n")))
10921 (if text (insert (concat "<p>\n" (org-html-expand text))))
10922 (if org-export-with-toc
10924 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
10926 (mapcar '(lambda (line)
10927 (if (string-match org-todo-line-regexp line)
10928 ;; This is a headline
10930 (setq level (- (match-end 1) (match-beginning 1))
10931 txt (save-match-data
10933 (match-string 3 line)))
10935 (or (and (match-beginning 2)
10936 (not (equal (match-string 2 line)
10939 (and (= level umax)
10940 (org-search-todo-below
10941 line lines level))))
10942 (if org-export-with-section-numbers
10943 (setq txt (concat (org-section-number level)
10945 (if (<= level umax)
10947 (setq head-count (+ head-count 1))
10948 (if (> level org-last-level)
10950 (setq cnt (- level org-last-level))
10951 (while (>= (setq cnt (1- cnt)) 0)
10954 (if (< level org-last-level)
10956 (setq cnt (- org-last-level level))
10957 (while (>= (setq cnt (1- cnt)) 0)
10963 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
10964 "<li><a href=\"#sec-%d\">%s</a>\n")
10966 (setq org-last-level level))
10969 (while (> org-last-level 0)
10970 (setq org-last-level (1- org-last-level))
10971 (insert "</ul>\n"))
10973 (setq head-count 0)
10974 (org-init-section-numbers)
10976 (while (setq line (pop lines) origline line)
10979 ;; end of quote section?
10980 (when (and inquote (string-match "^\\*+" line))
10981 (insert "</pre>\n")
10982 (setq inquote nil))
10983 ;; inside a quote section?
10985 (insert (org-html-protect line) "\n")
10986 (throw 'nextline nil))
10989 (when (and org-export-with-fixed-width
10990 (string-match "^[ \t]*:\\(.*\\)" line))
10991 (when (not infixed)
10993 (insert "<pre>\n"))
10994 (insert (org-html-protect (match-string 1 line)) "\n")
10996 (not (string-match "^[ \t]*\\(:.*\\)"
10999 (insert "</pre>\n"))
11000 (throw 'nextline nil))
11003 ;; make targets to anchors
11004 (while (string-match "<<<?\\([^<>]*\\)>>>?[ \t]*\n?" line)
11005 (setq line (replace-match
11006 (concat "@<a name=\""
11007 (org-solidify-link-text (match-string 1 line))
11010 ;; Replace internal links
11011 (while (string-match org-bracket-link-regexp line)
11012 (setq line (replace-match
11015 (org-solidify-link-text (match-string 1 line))
11017 (match-string (if (match-end 3) 3 1) line)
11021 ;; Protect the external links
11023 (while (string-match org-link-maybe-angles-regexp line start)
11024 (setq start (match-end 0))
11025 (setq line (replace-match
11026 (concat "\000" (match-string 1 line) "\000")
11029 ;; replace "&" by "&", "<" and ">" by "<" and ">"
11030 ;; handle @<..> HTML tags (replace "@>..<" by "<..>")
11031 (setq line (org-html-expand line))
11033 ;; Format the links
11035 (while (string-match org-protected-link-regexp line start)
11036 (setq start (- (match-end 0) 2))
11037 (setq type (match-string 1 line))
11039 ((member type '("http" "https" "ftp" "mailto" "news"))
11041 (setq line (replace-match
11042 ; "<a href=\"\\1:\\2\"><\\1:\\2></a>"
11043 "<a href=\"\\1:\\2\">\\1:\\2</a>"
11045 ((string= type "file")
11047 (let* ((filename (match-string 2 line))
11048 (abs-p (file-name-absolute-p filename))
11049 (thefile (if abs-p (expand-file-name filename) filename))
11050 (thefile (save-match-data
11051 (if (string-match ":[0-9]+$" thefile)
11052 (replace-match "" t t thefile)
11056 (string-match (org-image-file-name-regexp) thefile))))
11057 (setq line (replace-match
11058 (if (and org-export-html-inline-images
11060 (concat "<img src=\"" thefile "\"/>")
11061 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
11064 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11065 (setq line (replace-match
11066 "<i><\\1:\\2></i>" nil nil line)))))
11069 (if (and (string-match org-todo-line-regexp line)
11070 (match-beginning 2))
11071 (if (equal (match-string 2 line) org-done-string)
11072 (setq line (replace-match
11073 "<span class=\"done\">\\2</span>"
11075 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11079 (if (string-match org-deadline-line-regexp line)
11081 (if (save-match-data
11082 (string-match "<a href"
11083 (substring line 0 (match-beginning 0))))
11084 nil ; Don't do the replacement - it is inside a link
11085 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11086 nil nil line 1)))))
11088 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11089 ;; This is a headline
11090 (setq level (- (match-end 1) (match-beginning 1))
11091 txt (match-string 2 line))
11092 (if (<= level umax) (setq head-count (+ head-count 1)))
11093 (when in-local-list
11094 ;; Close any local lists before inserting a new header line
11095 (while local-list-num
11096 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11097 (pop local-list-num))
11098 (setq local-list-indent nil
11099 in-local-list nil))
11100 (org-html-level-start level txt umax
11101 (and org-export-with-toc (<= level umax))
11104 (when (string-match quote-re line)
11108 ((and org-export-with-tables
11109 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11110 (if (not table-open)
11111 ;; New table starts
11112 (setq table-open t table-buffer nil table-orig-buffer nil))
11113 ;; Accumulate lines
11114 (setq table-buffer (cons line table-buffer)
11115 table-orig-buffer (cons origline table-orig-buffer))
11116 (when (or (not lines)
11117 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11119 (setq table-open nil
11120 table-buffer (nreverse table-buffer)
11121 table-orig-buffer (nreverse table-orig-buffer))
11122 (insert (org-format-table-html table-buffer table-orig-buffer))))
11125 (when (and (> org-export-plain-list-max-depth 0)
11128 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11129 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11130 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11131 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
11133 (setq ind (org-get-string-indentation line)
11134 start-is-num (match-beginning 4)
11135 starter (if (match-beginning 2) (match-string 2 line))
11136 line (substring line (match-beginning 5)))
11137 (unless (string-match "[^ \t]" line)
11138 ;; empty line. Pretend indentation is large.
11139 (setq ind (1+ (or (car local-list-indent) 1))))
11140 (while (and in-local-list
11141 (or (and (= ind (car local-list-indent))
11143 (< ind (car local-list-indent))))
11144 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11145 (pop local-list-num) (pop local-list-indent)
11146 (setq in-local-list local-list-indent))
11149 (or (not in-local-list)
11150 (> ind (car local-list-indent)))
11151 (< (length local-list-indent)
11152 org-export-plain-list-max-depth))
11153 ;; Start new (level of ) list
11154 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
11155 (push start-is-num local-list-num)
11156 (push ind local-list-indent)
11157 (setq in-local-list t))
11159 ;; continue current list
11160 (insert "<li>\n"))))
11161 ;; Empty lines start a new paragraph. If hand-formatted lists
11162 ;; are not fully interpreted, lines starting with "-", "+", "*"
11163 ;; also start a new paragraph.
11164 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
11165 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
11167 (if org-export-html-with-timestamp
11168 (insert org-export-html-html-helper-timestamp))
11169 (insert "</body>\n</html>\n")
11172 (goto-char (point-min)))))
11174 (defun org-format-table-html (lines olines)
11175 "Find out which HTML converter to use and return the HTML code."
11176 (if (string-match "^[ \t]*|" (car lines))
11177 ;; A normal org table
11178 (org-format-org-table-html lines)
11179 ;; Table made by table.el - test for spanning
11180 (let* ((hlines (delq nil (mapcar
11182 (if (string-match "^[ \t]*\\+-" x) x
11185 (first (car hlines))
11186 (ll (and (string-match "\\S-+" first)
11187 (match-string 0 first)))
11188 (re (concat "^[ \t]*" (regexp-quote ll)))
11189 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
11191 (if (and (not spanning)
11192 (not org-export-prefer-native-exporter-for-tables))
11193 ;; We can use my own converter with HTML conversions
11194 (org-format-table-table-html lines)
11195 ;; Need to use the code generator in table.el, with the original text.
11196 (org-format-table-table-html-using-table-generate-source olines)))))
11198 (defun org-format-org-table-html (lines)
11199 "Format a table into HTML."
11200 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11201 (setq lines (nreverse lines))
11202 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11203 (setq lines (nreverse lines))
11204 (when org-export-table-remove-special-lines
11205 ;; Check if the table has a marking column. If yes remove the
11206 ;; column and the special lines
11212 (or (string-match "^[ \t]*|-" x)
11213 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
11220 (if (string-match "^[ \t]*| *[!_^] *|" x)
11221 nil ; ignore this line
11222 (and (or (string-match "^[ \t]*|-+\\+" x)
11223 (string-match "^[ \t]*|[^|]*|" x))
11224 (replace-match "|" t t x))))
11227 (let ((head (and org-export-highlight-first-table-line
11229 (lambda (x) (string-match "^[ \t]*|-" x))
11232 (setq html (concat org-export-html-table-tag "\n"))
11233 (while (setq line (pop lines))
11235 (if (string-match "^[ \t]*|-" line)
11237 (setq head nil) ;; head ends here, first time around
11238 ;; ignore this line
11239 (throw 'next-line t)))
11240 ;; Break the line into fields
11241 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11245 (mapconcat (lambda (x)
11247 (concat "<th>" x "</th>")
11248 (concat "<td>" x "</td>")))
11251 (setq html (concat html "</table>\n"))
11254 (defun org-fake-empty-table-line (line)
11255 "Replace everything except \"|\" with spaces."
11256 (let ((i (length line))
11257 (newstr (copy-sequence line)))
11260 (if (not (eq (aref newstr i) ?|))
11261 (aset newstr i ?\ )))
11264 (defun org-format-table-table-html (lines)
11265 "Format a table generated by table.el into HTML.
11266 This conversion does *not* use `table-generate-source' from table.el.
11267 This has the advantage that Org-mode's HTML conversions can be used.
11268 But it has the disadvantage, that no cell- or row-spanning is allowed."
11269 (let (line field-buffer
11270 (head org-export-highlight-first-table-line)
11272 (setq html (concat org-export-html-table-tag "\n"))
11273 (while (setq line (pop lines))
11274 (setq empty " ")
11276 (if (string-match "^[ \t]*\\+-" line)
11285 (if (equal x "") (setq x empty))
11287 (concat "<th>" x "</th>\n")
11288 (concat "<td>" x "</td>\n")))
11292 (setq field-buffer nil)))
11293 ;; Ignore this line
11294 (throw 'next-line t)))
11295 ;; Break the line into fields and store the fields
11296 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11298 (setq field-buffer (mapcar
11300 (concat x "<br>" (pop fields)))
11302 (setq field-buffer fields))))
11303 (setq html (concat html "</table>\n"))
11306 (defun org-format-table-table-html-using-table-generate-source (lines)
11307 "Format a table into html, using `table-generate-source' from table.el.
11308 This has the advantage that cell- or row-spanning is allowed.
11309 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
11311 (with-current-buffer (get-buffer-create " org-tmp1 ")
11313 (insert (mapconcat 'identity lines "\n"))
11314 (goto-char (point-min))
11315 (if (not (re-search-forward "|[^+]" nil t))
11316 (error "Error processing table"))
11317 (table-recognize-table)
11318 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
11319 (table-generate-source 'html " org-tmp2 ")
11320 (set-buffer " org-tmp2 ")
11321 (buffer-substring (point-min) (point-max))))
11323 (defun org-html-protect (s)
11324 ;; convert & to &, < to < and > to >
11326 (while (string-match "&" s start)
11327 (setq s (replace-match "&" t t s)
11328 start (1+ (match-beginning 0))))
11329 (while (string-match "<" s)
11330 (setq s (replace-match "<" t t s)))
11331 (while (string-match ">" s)
11332 (setq s (replace-match ">" t t s))))
11335 (defun org-html-expand (string)
11336 "Prepare STRING for HTML export. Applies all active conversions."
11337 ;; First check if there is a link in the line - if yes, apply conversions
11338 ;; only before the start of the link.
11339 ;; FIXME: This is no longer correct, because links now have an end.
11340 (let* ((m (string-match org-link-regexp string))
11341 (s (if m (substring string 0 m) string))
11342 (r (if m (substring string m) "")))
11343 ;; convert & to &, < to < and > to >
11344 (setq s (org-html-protect s))
11345 (if org-export-html-expand
11346 (while (string-match "@<\\([^&]*\\)>" s)
11347 (setq s (replace-match "<\\1>" nil nil s))))
11348 (if org-export-with-emphasize
11349 (setq s (org-export-html-convert-emphasize s)))
11350 (if org-export-with-sub-superscripts
11351 (setq s (org-export-html-convert-sub-super s)))
11352 (if org-export-with-TeX-macros
11353 (let ((start 0) wd ass)
11354 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
11355 (setq wd (match-string 1 s))
11356 (if (setq ass (assoc wd org-html-entities))
11357 (setq s (replace-match (or (cdr ass)
11358 (concat "&" (car ass) ";"))
11360 (setq start (+ start (length wd)))))))
11363 (defun org-create-multibrace-regexp (left right n)
11364 "Create a regular expression which will match a balanced sexp.
11365 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
11366 as single character strings.
11367 The regexp returned will match the entire expression including the
11368 delimiters. It will also define a single group which contains the
11369 match except for the outermost delimiters. The maximum depth of
11370 stacked delimiters is N. Escaping delimiters is not possible."
11371 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
11374 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
11377 re (concat re or next)
11378 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
11379 (concat left "\\(" re "\\)" right)))
11381 (defvar org-match-substring-regexp
11383 "\\([^\\]\\)\\([_^]\\)\\("
11384 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
11386 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
11388 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
11389 "The regular expression matching a sub- or superscript.")
11391 (defun org-export-html-convert-sub-super (string)
11392 "Convert sub- and superscripts in STRING to HTML."
11394 (while (string-match org-match-substring-regexp string)
11395 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
11396 (setq c (or (match-string 8 string)
11397 (match-string 6 string)
11398 (match-string 5 string)))
11399 (setq string (replace-match
11400 (concat (match-string 1 string)
11401 "<" key ">" c "</" key ">")
11403 (while (string-match "\\\\\\([_^]\\)" string)
11404 (setq string (replace-match (match-string 1 string) t t string))))
11407 (defun org-export-html-convert-emphasize (string)
11408 (while (string-match
11409 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
11411 (setq string (replace-match
11412 (concat "<b>" (match-string 3 string) "</b>")
11414 (while (string-match
11415 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
11417 (setq string (replace-match
11418 (concat "<i>" (match-string 3 string) "</i>")
11420 (while (string-match
11421 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
11423 (setq string (replace-match
11424 (concat "<u>" (match-string 3 string) "</u>")
11428 (defun org-parse-key-lines ()
11429 "Find the special key lines with the information for exporters."
11432 (let ((re (org-make-options-regexp
11433 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
11435 (while (re-search-forward re nil t)
11436 (setq key (match-string 1))
11437 (cond ((string-equal key "TITLE")
11438 (setq title (match-string 2)))
11439 ((string-equal key "AUTHOR")
11440 (setq author (match-string 2)))
11441 ((string-equal key "EMAIL")
11442 (setq email (match-string 2)))
11443 ((string-equal key "LANGUAGE")
11444 (setq language (match-string 2)))
11445 ((string-equal key "TEXT")
11446 (setq text (concat text "\n" (match-string 2))))
11447 ((string-equal key "OPTIONS")
11448 (setq options (match-string 2))))))))
11450 (defun org-parse-export-options (s)
11451 "Parse the export options line."
11452 (let ((op '(("H" . org-export-headline-levels)
11453 ("num" . org-export-with-section-numbers)
11454 ("toc" . org-export-with-toc)
11455 ("\\n" . org-export-preserve-breaks)
11456 ("@" . org-export-html-expand)
11457 (":" . org-export-with-fixed-width)
11458 ("|" . org-export-with-tables)
11459 ("^" . org-export-with-sub-superscripts)
11460 ("*" . org-export-with-emphasize)
11461 ("TeX" . org-export-with-TeX-macros)))
11463 (while (setq o (pop op))
11464 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
11466 (set (make-local-variable (cdr o))
11467 (car (read-from-string (match-string 1 s))))))))
11469 (defun org-html-level-start (level title umax with-toc head-count)
11470 "Insert a new level in HTML export."
11471 (let ((l (1+ (max level umax))))
11472 (while (<= l org-level-max)
11473 (if (aref levels-open (1- l))
11475 (org-html-level-close l)
11476 (aset levels-open (1- l) nil)))
11480 (if (aref levels-open (1- level))
11481 (insert "<li>" title "<p>\n")
11482 (aset levels-open (1- level) t)
11483 (insert "<ul><li>" title "<p>\n")))
11484 (if org-export-with-section-numbers
11485 (setq title (concat (org-section-number level) " " title)))
11486 (setq level (+ level 1))
11488 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
11489 level head-count title level))
11490 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
11492 (defun org-html-level-close (&rest args)
11493 "Terminate one level in HTML export."
11496 ;; Variable holding the vector with section numbers
11497 (defvar org-section-numbers (make-vector org-level-max 0))
11499 (defun org-init-section-numbers ()
11500 "Initialize the vector for the section numbers."
11502 (numbers (nreverse (org-split-string "" "\\.")))
11503 (depth (1- (length org-section-numbers)))
11504 (i depth) number-string)
11507 (aset org-section-numbers i 0)
11508 (setq number-string (or (car numbers) "0"))
11509 (if (string-match "\\`[A-Z]\\'" number-string)
11510 (aset org-section-numbers i
11511 (- (string-to-char number-string) ?A -1))
11512 (aset org-section-numbers i (string-to-number number-string)))
11516 (defun org-section-number (&optional level)
11517 "Return a string with the current section number.
11518 When LEVEL is non-nil, increase section numbers on that level."
11519 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
11522 (aset org-section-numbers
11523 level (1+ (aref org-section-numbers level))))
11524 (setq idx (1+ level))
11525 (while (<= idx depth)
11526 (if (not (= idx 1))
11527 (aset org-section-numbers idx 0))
11528 (setq idx (1+ idx))))
11530 (while (<= idx depth)
11531 (setq n (aref org-section-numbers idx))
11532 (setq string (concat string (if (not (string= string "")) "." "")
11533 (int-to-string n)))
11534 (setq idx (1+ idx)))
11536 (if (string-match "\\`\\([@0]\\.\\)+" string)
11537 (setq string (replace-match "" nil nil string)))
11538 (if (string-match "\\(\\.0\\)+\\'" string)
11539 (setq string (replace-match "" nil nil string))))
11543 (defun org-export-icalendar-this-file ()
11544 "Export current file as an iCalendar file.
11545 The iCalendar file will be located in the same directory as the Org-mode
11546 file, but with extension `.ics'."
11548 (org-export-icalendar nil (buffer-file-name)))
11551 (defun org-export-icalendar-all-agenda-files ()
11552 "Export all files in `org-agenda-files' to iCalendar .ics files.
11553 Each iCalendar file will be located in the same directory as the Org-mode
11554 file, but with extension `.ics'."
11556 (apply 'org-export-icalendar nil org-agenda-files))
11559 (defun org-export-icalendar-combine-agenda-files ()
11560 "Export all files in `org-agenda-files' to a single combined iCalendar file.
11561 The file is stored under the name `org-combined-agenda-icalendar-file'."
11563 (apply 'org-export-icalendar t org-agenda-files))
11565 (defun org-export-icalendar (combine &rest files)
11566 "Create iCalendar files for all elements of FILES.
11567 If COMBINE is non-nil, combine all calendar entries into a single large
11568 file and store it under the name `org-combined-agenda-icalendar-file'."
11570 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
11572 (setq ical-file org-combined-agenda-icalendar-file
11573 ical-buffer (org-get-agenda-file-buffer ical-file))
11574 (set-buffer ical-buffer) (erase-buffer))
11575 (while (setq file (pop files))
11577 (org-check-agenda-file file)
11579 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
11580 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
11581 (set-buffer ical-buffer) (erase-buffer))
11582 (set-buffer (org-get-agenda-file-buffer file))
11583 (setq category (or org-category
11584 (file-name-sans-extension
11585 (file-name-nondirectory (buffer-file-name)))))
11586 (if (symbolp category) (setq category (symbol-name category)))
11587 (let ((standard-output ical-buffer))
11589 (and (not started) (setq started t)
11590 (org-start-icalendar-file org-icalendar-combined-name))
11591 (org-start-icalendar-file category))
11592 (org-print-icalendar-entries combine category)
11593 (when (or (and combine (not files)) (not combine))
11594 (org-finish-icalendar-file)
11595 (set-buffer ical-buffer)
11597 (run-hooks 'org-after-save-iCalendar-file-hook)))))
11598 (org-release-buffers org-agenda-new-buffers))))
11600 (defvar org-after-save-iCalendar-file-hook nil
11601 "Hook run after an iCalendar file has been saved.
11602 The iCalendar buffer is still current when this hook is run.
11603 A good way to use this is to tell a desktop calenndar application to re-read
11604 the iCalendar file.")
11606 (defun org-print-icalendar-entries (&optional combine category)
11607 "Print iCalendar entries for the current Org-mode file to `standard-output'.
11608 When COMBINE is non nil, add the category to each line."
11609 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
11610 (dts (org-ical-ts-to-string
11611 (format-time-string (cdr org-time-stamp-formats) (current-time))
11613 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
11615 (goto-char (point-min))
11616 (while (re-search-forward org-ts-regexp nil t)
11617 (setq pos (match-beginning 0)
11618 ts (match-string 0)
11620 hd (org-get-heading))
11621 (if (looking-at re2)
11623 (goto-char (match-end 0))
11624 (setq ts2 (match-string 1) inc nil))
11626 tmp (buffer-substring (max (point-min)
11627 (- pos org-ds-keyword-length))
11629 deadlinep (string-match org-deadline-regexp tmp)
11630 scheduledp (string-match org-scheduled-regexp tmp)
11631 ;; donep (org-entry-is-done-p)
11633 (if (or (string-match org-tr-regexp hd)
11634 (string-match org-ts-regexp hd))
11635 (setq hd (replace-match "" t t hd)))
11637 (setq hd (concat hd " (category " category ")")))
11638 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
11639 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
11640 (princ (format "BEGIN:VEVENT
11645 (org-ical-ts-to-string ts "DTSTART")
11646 (org-ical-ts-to-string ts2 "DTEND" inc)
11648 (when org-icalendar-include-todo
11649 (goto-char (point-min))
11650 (while (re-search-forward org-todo-line-regexp nil t)
11651 (setq state (match-string 1))
11652 (unless (equal state org-done-string)
11653 (setq hd (match-string 3))
11654 (if (string-match org-priority-regexp hd)
11655 (setq pri (string-to-char (match-string 2 hd))
11656 hd (concat (substring hd 0 (match-beginning 1))
11657 (substring hd (- (match-end 1)))))
11658 (setq pri org-default-priority))
11659 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
11660 (- org-lowest-priority ?A))))))
11662 (princ (format "BEGIN:VTODO
11670 (defun org-start-icalendar-file (name)
11671 "Start an iCalendar file by inserting the header."
11672 (let ((user user-full-name)
11673 (name (or name "unknown"))
11674 (timezone (cadr (current-time-zone))))
11676 (format "BEGIN:VCALENDAR
11679 PRODID:-//%s//Emacs with Org-mode//EN
11681 CALSCALE:GREGORIAN\n" name user timezone))))
11683 (defun org-finish-icalendar-file ()
11684 "Finish an iCalendar file by inserting the END statement."
11685 (princ "END:VCALENDAR\n"))
11687 (defun org-ical-ts-to-string (s keyword &optional inc)
11688 "Take a time string S and convert it to iCalendar format.
11689 KEYWORD is added in front, to make a complete line like DTSTART....
11690 When INC is non-nil, increase the hour by two (if time string contains
11691 a time), or the day by one (if it does not contain a time)."
11692 (let ((t1 (org-parse-time-string s 'nodefault))
11693 t2 fmt have-time time)
11694 (if (and (car t1) (nth 1 t1) (nth 2 t1))
11695 (setq t2 t1 have-time t)
11696 (setq t2 (org-parse-time-string s)))
11697 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
11698 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
11700 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
11701 (setq time (encode-time s mi h d m y)))
11702 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
11703 (concat keyword (format-time-string fmt time))))
11708 ;; - Bindings in Org-mode map are currently
11709 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
11710 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
11711 ;; e (?) useful from outline-mode
11712 ;; i k @ expendable from outline-mode
11713 ;; 0123456789 % & ()_{} " ` free
11715 ;; Make `C-c C-x' a prefix key
11716 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
11718 ;; TAB key with modifiers
11719 (define-key org-mode-map "\C-i" 'org-cycle)
11720 (define-key org-mode-map [(meta tab)] 'org-complete)
11721 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
11722 ;; The following line is necessary under Suse GNU/Linux
11723 (unless org-xemacs-p
11724 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
11725 (define-key org-mode-map [(shift tab)] 'org-shifttab)
11727 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
11728 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
11729 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11730 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
11731 (define-key org-mode-map [(meta return)] 'org-meta-return)
11732 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
11733 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
11735 ;; Cursor keys with modifiers
11736 (define-key org-mode-map [(meta left)] 'org-metaleft)
11737 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
11738 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
11739 (define-key org-mode-map [(meta right)] 'org-metaright)
11740 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
11741 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
11742 (define-key org-mode-map [(meta up)] 'org-metaup)
11743 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
11744 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
11745 (define-key org-mode-map [(meta down)] 'org-metadown)
11746 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
11747 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
11749 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11750 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
11751 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
11752 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
11753 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
11754 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
11755 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
11756 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
11757 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
11758 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
11759 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
11760 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
11761 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
11762 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
11763 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
11764 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
11766 ;; All the other keys
11767 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
11768 (define-key org-mode-map "\C-c\C-j" 'org-goto)
11769 (define-key org-mode-map "\C-c\C-t" 'org-todo)
11770 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
11771 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
11772 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
11773 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11774 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
11775 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
11776 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11777 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
11778 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
11779 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
11780 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
11781 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
11782 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
11783 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
11784 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11785 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11786 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11787 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11788 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
11789 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
11790 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11791 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
11792 (define-key org-mode-map "\C-c]" 'org-remove-file)
11793 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
11794 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
11795 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
11796 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11797 (define-key org-mode-map "\C-m" 'org-return)
11798 (define-key org-mode-map "\C-c?" 'org-table-current-column)
11799 (define-key org-mode-map "\C-c " 'org-table-blank-field)
11800 (define-key org-mode-map "\C-c+" 'org-table-sum)
11801 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
11802 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
11803 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
11804 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
11805 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11806 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
11807 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11808 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
11809 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
11810 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
11811 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
11812 ;; OPML support is only an option for the future
11813 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
11814 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
11815 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
11816 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
11817 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
11818 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
11819 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
11820 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11821 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
11822 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
11823 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
11825 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11826 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11827 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11829 (defsubst org-table-p () (org-at-table-p))
11831 (defun org-self-insert-command (N)
11832 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11833 If the cursor is in a table looking at whitespace, the whitespace is
11834 overwritten, and the table is not marked as requiring realignment."
11836 (if (and (org-table-p)
11838 (and org-table-auto-blank-field
11839 (member last-command
11840 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11841 (org-table-blank-field))
11844 (looking-at "[^|\n]* +|"))
11845 (let (org-table-may-need-update)
11846 (goto-char (1- (match-end 0)))
11847 (delete-backward-char 1)
11848 (goto-char (match-beginning 0))
11849 (self-insert-command N))
11850 (setq org-table-may-need-update t)
11851 (self-insert-command N)))
11854 ;; The following two functions might still be optimized to trigger
11855 ;; re-alignment less frequently.
11857 (defun org-delete-backward-char (N)
11858 "Like `delete-backward-char', insert whitespace at field end in tables.
11859 When deleting backwards, in tables this function will insert whitespace in
11860 front of the next \"|\" separator, to keep the table aligned. The table will
11861 still be marked for re-alignment, because a narrow field may lead to a
11862 reduced column width."
11864 (if (and (org-table-p)
11866 (string-match "|" (buffer-substring (point-at-bol) (point)))
11867 (looking-at ".*?|"))
11868 (let ((pos (point)))
11869 (backward-delete-char N)
11870 (skip-chars-forward "^|")
11872 (goto-char (1- pos)))
11873 (backward-delete-char N)))
11875 (defun org-delete-char (N)
11876 "Like `delete-char', but insert whitespace at field end in tables.
11877 When deleting characters, in tables this function will insert whitespace in
11878 front of the next \"|\" separator, to keep the table aligned. The table
11879 will still be marked for re-alignment, because a narrow field may lead to
11880 a reduced column width."
11882 (if (and (org-table-p)
11884 (not (= (char-after) ?|))
11886 (if (looking-at ".*?|")
11887 (let ((pos (point)))
11888 (replace-match (concat
11889 (substring (match-string 0) 1 -1)
11894 ;; How to do this: Measure non-white length of current string
11895 ;; If equal to column width, we should realign.
11897 (defun org-remap (map &rest commands)
11898 "In MAP, remap the functions given in COMMANDS.
11899 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11902 (setq old (pop commands) new (pop commands))
11903 (if (fboundp 'command-remapping)
11904 (define-key map (vector 'remap old) new)
11905 (substitute-key-definition old new map global-map)))))
11907 (when (eq org-enable-table-editor 'optimized)
11908 ;; If the user wants maximum table support, we need to hijack
11909 ;; some standard editing functions
11910 (org-remap org-mode-map
11911 'self-insert-command 'org-self-insert-command
11912 'delete-char 'org-delete-char
11913 'delete-backward-char 'org-delete-backward-char)
11914 (define-key org-mode-map "|" 'org-force-self-insert))
11916 (defun org-shiftcursor-error ()
11917 "Throw an error because Shift-Cursor command was applied in wrong context."
11918 (error "This command is active in special context like tables, headlines or timestamps"))
11920 (defun org-shifttab ()
11921 "Global visibility cycling or move to previous table field.
11922 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
11923 See the individual commands for more information."
11926 ((org-at-table-p) (org-table-previous-field))
11927 (t (org-cycle '(4)))))
11929 (defun org-shiftmetaleft ()
11930 "Promote subtree or delete table column.
11931 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
11932 See the individual commands for more information."
11935 ((org-at-table-p) (org-table-delete-column))
11936 ((org-on-heading-p) (org-promote-subtree))
11937 ((org-at-item-p) (call-interactively 'org-outdent-item))
11938 (t (org-shiftcursor-error))))
11940 (defun org-shiftmetaright ()
11941 "Demote subtree or insert table column.
11942 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
11943 See the individual commands for more information."
11946 ((org-at-table-p) (org-table-insert-column))
11947 ((org-on-heading-p) (org-demote-subtree))
11948 ((org-at-item-p) (call-interactively 'org-indent-item))
11949 (t (org-shiftcursor-error))))
11951 (defun org-shiftmetaup (&optional arg)
11952 "Move subtree up or kill table row.
11953 Calls `org-move-subtree-up' or `org-table-kill-row' or
11954 `org-move-item-up' depending on context. See the individual commands
11955 for more information."
11958 ((org-at-table-p) (org-table-kill-row))
11959 ((org-on-heading-p) (org-move-subtree-up arg))
11960 ((org-at-item-p) (org-move-item-up arg))
11961 (t (org-shiftcursor-error))))
11962 (defun org-shiftmetadown (&optional arg)
11963 "Move subtree down or insert table row.
11964 Calls `org-move-subtree-down' or `org-table-insert-row' or
11965 `org-move-item-down', depending on context. See the individual
11966 commands for more information."
11969 ((org-at-table-p) (org-table-insert-row arg))
11970 ((org-on-heading-p) (org-move-subtree-down arg))
11971 ((org-at-item-p) (org-move-item-down arg))
11972 (t (org-shiftcursor-error))))
11974 (defun org-metaleft (&optional arg)
11975 "Promote heading or move table column to left.
11976 Calls `org-do-promote' or `org-table-move-column', depending on context.
11977 With no specific context, calls the Emacs default `backward-word'.
11978 See the individual commands for more information."
11981 ((org-at-table-p) (org-table-move-column 'left))
11982 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
11983 (t (backward-word (prefix-numeric-value arg)))))
11985 (defun org-metaright (&optional arg)
11986 "Demote subtree or move table column to right.
11987 Calls `org-do-demote' or `org-table-move-column', depending on context.
11988 With no specific context, calls the Emacs default `forward-word'.
11989 See the individual commands for more information."
11992 ((org-at-table-p) (org-table-move-column nil))
11993 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
11994 (t (forward-word (prefix-numeric-value arg)))))
11996 (defun org-metaup (&optional arg)
11997 "Move subtree up or move table row up.
11998 Calls `org-move-subtree-up' or `org-table-move-row' or
11999 `org-move-item-up', depending on context. See the individual commands
12000 for more information."
12003 ((org-at-table-p) (org-table-move-row 'up))
12004 ((org-on-heading-p) (org-move-subtree-up arg))
12005 ((org-at-item-p) (org-move-item-up arg))
12006 (t (org-shiftcursor-error))))
12008 (defun org-metadown (&optional arg)
12009 "Move subtree down or move table row down.
12010 Calls `org-move-subtree-down' or `org-table-move-row' or
12011 `org-move-item-down', depending on context. See the individual
12012 commands for more information."
12015 ((org-at-table-p) (org-table-move-row nil))
12016 ((org-on-heading-p) (org-move-subtree-down arg))
12017 ((org-at-item-p) (org-move-item-down arg))
12018 (t (org-shiftcursor-error))))
12020 (defun org-shiftup (&optional arg)
12021 "Increase item in timestamp or increase priority of current item.
12022 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12023 See the individual commands for more information."
12026 ((org-at-timestamp-p) (org-timestamp-up arg))
12027 (t (org-priority-up))))
12029 (defun org-shiftdown (&optional arg)
12030 "Decrease item in timestamp or decrease priority of current item.
12031 Calls `org-timestamp-down' or `org-priority-down', depending on context.
12032 See the individual commands for more information."
12035 ((org-at-timestamp-p) (org-timestamp-down arg))
12036 (t (org-priority-down))))
12038 (defun org-shiftright ()
12039 "Next TODO keyword or timestamp one day later, depending on context."
12042 ((org-at-timestamp-p) (org-timestamp-up-day))
12043 ((org-on-heading-p) (org-todo 'right))
12044 (t (org-shiftcursor-error))))
12046 (defun org-shiftleft ()
12047 "Previous TODO keyword or timestamp one day earlier, depending on context."
12050 ((org-at-timestamp-p) (org-timestamp-down-day))
12051 ((org-on-heading-p) (org-todo 'left))
12052 (t (org-shiftcursor-error))))
12054 (defun org-copy-special ()
12055 "Copy region in table or copy current subtree.
12056 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12057 See the individual commands for more information."
12059 (call-interactively
12060 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12062 (defun org-cut-special ()
12063 "Cut region in table or cut current subtree.
12064 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12065 See the individual commands for more information."
12067 (call-interactively
12068 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12070 (defun org-paste-special (arg)
12071 "Paste rectangular region into table, or past subtree relative to level.
12072 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12073 See the individual commands for more information."
12075 (if (org-at-table-p)
12076 (org-table-paste-rectangle)
12077 (org-paste-subtree arg)))
12079 (defun org-ctrl-c-ctrl-c (&optional arg)
12080 "Call realign table, or recognize a table.el table, or update keywords.
12081 When the cursor is inside a table created by the table.el package,
12082 activate that table. Otherwise, if the cursor is at a normal table
12083 created with org.el, re-align that table. This command works even if
12084 the automatic table editor has been turned off.
12086 If the cursor is in a headline, prompt for tags and insert them into
12087 the current line, aligned to `org-tags-column'. When in a headline and
12088 called with prefix arg, realign all tags in the current buffer.
12090 If the cursor is in one of the special #+KEYWORD lines, this triggers
12091 scanning the buffer for these lines and updating the information.
12092 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
12094 (let ((org-enable-table-editor t))
12096 ((org-on-target-p) (org-update-radio-target-regexp))
12097 ((org-on-heading-p) (org-set-tags arg))
12098 ((org-at-table.el-p)
12100 (beginning-of-line 1)
12101 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12102 (table-recognize-table))
12104 (org-table-maybe-eval-formula)
12106 (org-table-recalculate t)
12107 (org-table-maybe-recalculate-line))
12110 (org-renumber-ordered-list (prefix-numeric-value arg)))
12111 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12113 ((equal (match-string 1) "TBLFM")
12114 ;; Recalculate the table before this line
12116 (beginning-of-line 1)
12117 (skip-chars-backward " \r\n\t")
12118 (if (org-at-table-p) (org-table-recalculate t))))
12120 (org-mode-restart))))
12121 ((org-region-active-p)
12122 (org-table-convert-region (region-beginning) (region-end) arg))
12123 ((condition-case nil
12124 (and (region-beginning) (region-end))
12126 (if (y-or-n-p "Convert inactive region to table? ")
12127 (org-table-convert-region (region-beginning) (region-end) arg)
12129 (t (error "C-c C-c can do nothing useful at this location.")))))
12131 (defun org-mode-restart ()
12132 "Restart Org-mode, to scan again for special lines.
12133 Also updates the keyword regular expressions."
12135 (let ((org-inhibit-startup t)) (org-mode))
12136 (message "Org-mode restarted to refresh keyword and special line setup"))
12138 (defun org-return ()
12139 "Goto next table row or insert a newline.
12140 Calls `org-table-next-row' or `newline', depending on context.
12141 See the individual commands for more information."
12145 (org-table-justify-field-maybe)
12146 (org-table-next-row))
12149 (defun org-meta-return (&optional arg)
12150 "Insert a new heading or wrap a region in a table.
12151 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12152 See the individual commands for more information."
12156 (org-table-wrap-region arg))
12157 (t (org-insert-heading arg))))
12161 ;; Define the Org-mode menus
12162 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12164 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
12165 ["Next Field" org-cycle (org-at-table-p)]
12166 ["Previous Field" org-shifttab (org-at-table-p)]
12167 ["Next Row" org-return (org-at-table-p)]
12169 ["Blank Field" org-table-blank-field (org-at-table-p)]
12170 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12173 ["Move Column Left" org-metaleft (org-at-table-p)]
12174 ["Move Column Right" org-metaright (org-at-table-p)]
12175 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12176 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12178 ["Move Row Up" org-metaup (org-at-table-p)]
12179 ["Move Row Down" org-metadown (org-at-table-p)]
12180 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12181 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12182 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12184 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
12186 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12187 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12188 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12189 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12192 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12193 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12194 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12196 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12197 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12198 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12200 ["Sum Column/Rectangle" org-table-sum
12201 (or (org-at-table-p) (org-region-active-p))]
12202 ["Which Column?" org-table-current-column (org-at-table-p)])
12204 (setq org-table-formula-debug (not org-table-formula-debug))
12205 :style toggle :selected org-table-formula-debug]
12207 ["Invisible Vlines" org-table-toggle-vline-visibility
12208 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
12210 ["Create" org-table-create (and (not (org-at-table-p))
12211 org-enable-table-editor)]
12212 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
12213 ["Import from File" org-table-import (not (org-at-table-p))]
12214 ["Export to File" org-table-export (org-at-table-p)]
12216 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12218 (easy-menu-define org-org-menu org-mode-map "Org menu"
12220 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
12221 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
12222 ["Sparse Tree" org-occur t]
12223 ["Show All" show-all t]
12225 ["New Heading" org-insert-heading t]
12226 ("Navigate Headings"
12227 ["Up" outline-up-heading t]
12228 ["Next" outline-next-visible-heading t]
12229 ["Previous" outline-previous-visible-heading t]
12230 ["Next Same Level" outline-forward-same-level t]
12231 ["Previous Same Level" outline-backward-same-level t]
12233 ["Jump" org-goto t])
12235 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12236 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12238 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12239 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12240 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12242 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12243 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12244 ["Demote Heading" org-metaright (not (org-at-table-p))]
12245 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12247 ["Archive Subtree" org-archive-subtree t])
12250 ["TODO/DONE/-" org-todo t]
12251 ["Show TODO Tree" org-show-todo-tree t]
12252 ["Global TODO list" org-todo-list t]
12254 ["Set Priority" org-priority t]
12255 ["Priority Up" org-shiftup t]
12256 ["Priority Down" org-shiftdown t])
12257 ("Dates and Scheduling"
12258 ["Timestamp" org-time-stamp t]
12259 ["Timestamp (inactive)" org-time-stamp-inactive t]
12261 ["1 Day Later" org-timestamp-up-day t]
12262 ["1 Day Earlier" org-timestamp-down-day t]
12263 ["1 ... Later" org-shiftup t]
12264 ["1 ... Earlier" org-shiftdown t])
12265 ["Compute Time Range" org-evaluate-time-range t]
12266 ["Schedule Item" org-schedule t]
12267 ["Deadline" org-deadline t]
12269 ["Goto Calendar" org-goto-calendar t]
12270 ["Date from Calendar" org-date-from-calendar t])
12272 ["Agenda Command" org-agenda t]
12273 ("File List for Agenda")
12274 ("Special views current file"
12275 ["TODO Tree" org-show-todo-tree t]
12276 ["Check Deadlines" org-check-deadlines t]
12277 ["Timeline" org-timeline t]
12278 ["Tags Tree" org-tags-sparse-tree t])
12281 ["Store Link (Global)" org-store-link t]
12282 ["Insert Link" org-insert-link t]
12283 ["Follow Link" org-open-at-point t])
12286 ["ASCII" org-export-as-ascii t]
12287 ["Extract Visible Text" org-export-copy-visible t]
12288 ["HTML" org-export-as-html t]
12289 ["HTML and Open" org-export-as-html-and-open t]
12290 ; ["OPML" org-export-as-opml nil]
12292 ["iCalendar this file" org-export-icalendar-this-file t]
12293 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
12294 :active t :keys "C-c C-x C-i"]
12295 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
12297 ["Option Template" org-insert-export-options-template t]
12298 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
12301 ["Show Version" org-version t]
12302 ["Info Documentation" org-info t])
12304 ["Browse Org Group" org-customize t]
12306 ["Build Full Customize Menu" org-create-customize-menu
12307 (fboundp 'customize-menu-create)])
12309 ["Refresh setup" org-mode-restart t]
12312 (defun org-info (&optional node)
12313 "Read documentation for Org-mode in the info system.
12314 With optional NODE, go directly to that node."
12317 (Info-goto-node (format "(org)%s" (or node ""))))
12319 (defun org-install-agenda-files-menu ()
12321 '("Org") "File List for Agenda"
12324 ["Edit File List" (customize-variable 'org-agenda-files) t]
12325 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12326 ["Remove Current File from List" org-remove-file t]
12327 ["Cycle through agenda files" org-cycle-agenda-files t]
12329 (mapcar 'org-file-menu-entry org-agenda-files))))
12333 (defun org-customize ()
12334 "Call the customize function with org as argument."
12336 (customize-browse 'org))
12338 (defun org-create-customize-menu ()
12339 "Create a full customization menu for Org-mode, insert it into the menu."
12341 (if (fboundp 'customize-menu-create)
12344 '("Org") "Customize"
12345 `(["Browse Org group" org-customize t]
12347 ,(customize-menu-create 'org)
12348 ["Set" Custom-set t]
12349 ["Save" Custom-save t]
12350 ["Reset to Current" Custom-reset-current t]
12351 ["Reset to Saved" Custom-reset-saved t]
12352 ["Reset to Standard Settings" Custom-reset-standard t]))
12353 (message "\"Org\"-menu now contains full customization menu"))
12354 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12356 ;;; Miscellaneous stuff
12358 (defun org-move-line-down (arg)
12359 "Move the current line down. With prefix argument, move it past ARG lines."
12361 (let ((col (current-column))
12363 (beginning-of-line 1) (setq beg (point))
12364 (beginning-of-line 2) (setq end (point))
12365 (beginning-of-line (+ 1 arg))
12366 (setq pos (move-marker (make-marker) (point)))
12367 (insert (delete-and-extract-region beg end))
12369 (move-to-column col)))
12371 (defun org-move-line-up (arg)
12372 "Move the current line up. With prefix argument, move it past ARG lines."
12374 (let ((col (current-column))
12376 (beginning-of-line 1) (setq beg (point))
12377 (beginning-of-line 2) (setq end (point))
12378 (beginning-of-line (- arg))
12379 (setq pos (move-marker (make-marker) (point)))
12380 (insert (delete-and-extract-region beg end))
12382 (move-to-column col)))
12384 ;; Paragraph filling stuff.
12385 ;; We want this to be just right, so use the full arsenal.
12386 ;; FIXME: This very likely does not work correctly for XEmacs, because the
12387 ;; filladapt package works slightly differently.
12389 (defun org-set-autofill-regexps ()
12391 ;; In the paragraph separator we include headlines, because filling
12392 ;; text in a line directly attached to a headline would otherwise
12393 ;; fill the headline as well.
12394 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
12395 ;; The paragraph starter includes hand-formatted lists.
12396 (set (make-local-variable 'paragraph-start)
12397 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
12398 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
12399 ;; But only if the user has not turned off tables or fixed-width regions
12400 (set (make-local-variable 'auto-fill-inhibit-regexp)
12402 (if (or org-enable-table-editor org-enable-fixed-width-editor)
12405 (if org-enable-table-editor "|" "")
12406 (if org-enable-fixed-width-editor ":" "")
12408 ;; We use our own fill-paragraph function, to make sure that tables
12409 ;; and fixed-width regions are not wrapped. That function will pass
12410 ;; through to `fill-paragraph' when appropriate.
12411 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
12412 ;; Adaptive filling: To get full control, first make sure that
12413 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
12414 (setq adaptive-fill-regexp "\000")
12415 (setq adaptive-fill-function 'org-adaptive-fill-function))
12417 (defun org-fill-paragraph (&optional justify)
12418 "Re-align a table, pass through to fill-paragraph if no table."
12419 (let ((table-p (org-at-table-p))
12420 (table.el-p (org-at-table.el-p)))
12421 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
12422 (table.el-p t) ; skip table.el tables
12423 (table-p (org-table-align) t) ; align org-mode tables
12424 (t nil)))) ; call paragraph-fill
12426 ;; For reference, this is the default value of adaptive-fill-regexp
12427 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
12429 (defun org-adaptive-fill-function ()
12430 "Return a fill prefix for org-mode files.
12431 In particular, this makes sure hanging paragraphs for hand-formatted lists
12433 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
12434 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
12436 ;; Functions needed for Emacs/XEmacs region compatibility
12438 (defun org-add-hook (hook function &optional append local)
12439 "Add-hook, compatible with both Emacsen."
12440 (if (and local org-xemacs-p)
12441 (add-local-hook hook function append)
12442 (add-hook hook function append local)))
12444 (defun org-region-active-p ()
12445 "Is `transient-mark-mode' on and the region active?
12446 Works on both Emacs and XEmacs."
12447 (if org-ignore-region
12450 (and zmacs-regions (region-active-p))
12451 (and transient-mark-mode mark-active))))
12453 (defun org-add-to-invisibility-spec (arg)
12454 "Add elements to `buffer-invisibility-spec'.
12455 See documentation for `buffer-invisibility-spec' for the kind of elements
12456 that can be added."
12458 ((fboundp 'add-to-invisibility-spec)
12459 (add-to-invisibility-spec arg))
12460 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
12461 (setq buffer-invisibility-spec (list arg)))
12463 (setq buffer-invisibility-spec
12464 (cons arg buffer-invisibility-spec)))))
12466 (defun org-remove-from-invisibility-spec (arg)
12467 "Remove elements from `buffer-invisibility-spec'."
12468 (if (fboundp 'remove-from-invisibility-spec)
12469 (remove-from-invisibility-spec arg)
12470 (if (consp buffer-invisibility-spec)
12471 (setq buffer-invisibility-spec
12472 (delete arg buffer-invisibility-spec)))))
12474 (defun org-in-invisibility-spec-p (arg)
12475 "Is ARG a member of `buffer-invisibility-spec'?"
12476 (if (consp buffer-invisibility-spec)
12477 (member arg buffer-invisibility-spec)
12480 (defun org-image-file-name-regexp ()
12481 "Return regexp matching the file names of images."
12482 (if (fboundp 'image-file-name-regexp)
12483 (image-file-name-regexp)
12484 (let ((image-file-name-extensions
12485 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
12486 "xbm" "xpm" "pbm" "pgm" "ppm")))
12488 (regexp-opt (nconc (mapcar 'upcase
12489 image-file-name-extensions)
12490 image-file-name-extensions)
12494 ;; Functions needed for compatibility with old outline.el.
12496 ;; Programming for the old outline.el (that uses selective display
12497 ;; instead of `invisible' text properties) is a nightmare, mostly
12498 ;; because regular expressions can no longer be anchored at
12499 ;; beginning/end of line. Therefore a number of function need special
12500 ;; treatment when the old outline.el is being used.
12502 ;; The following functions capture almost the entire compatibility code
12503 ;; between the different versions of outline-mode. The only other
12504 ;; places where this is important are the font-lock-keywords, and in
12505 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
12507 ;; C-a should go to the beginning of a *visible* line, also in the
12508 ;; new outline.el. I guess this should be patched into Emacs?
12509 (defun org-beginning-of-line ()
12510 "Go to the beginning of the current line. If that is invisible, continue
12511 to a visible line beginning. This makes the function of C-a more intuitive."
12513 (beginning-of-line 1)
12517 (if (org-invisible-p)
12518 (while (and (not (bobp)) (org-invisible-p))
12520 (beginning-of-line 1))
12521 (forward-char 1))))
12523 (when org-noutline-p
12524 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
12525 ;; FIXME: should I use substitute-key-definition to reach other bindings
12526 ;; of beginning-of-line?
12528 (defun org-invisible-p ()
12529 "Check if point is at a character currently not visible."
12531 ;; Early versions of noutline don't have `outline-invisible-p'.
12532 (if (fboundp 'outline-invisible-p)
12533 (outline-invisible-p)
12534 (get-char-property (point) 'invisible))
12536 (skip-chars-backward "^\r\n")
12537 (equal (char-before) ?\r))))
12539 (defun org-invisible-p2 ()
12540 "Check if point is at a character currently not visible."
12544 (if (and (eolp) (not (bobp))) (backward-char 1))
12545 ;; Early versions of noutline don't have `outline-invisible-p'.
12546 (if (fboundp 'outline-invisible-p)
12547 (outline-invisible-p)
12548 (get-char-property (point) 'invisible)))
12549 (skip-chars-backward "^\r\n")
12550 (equal (char-before) ?\r))))
12552 (defun org-back-to-heading (&optional invisible-ok)
12553 "Move to previous heading line, or beg of this line if it's a heading.
12554 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
12556 (outline-back-to-heading invisible-ok)
12557 (if (and (memq (char-before) '(?\n ?\r))
12558 (looking-at outline-regexp))
12560 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
12564 (progn (goto-char (match-end 1))
12565 (looking-at outline-regexp)))
12566 (error "Before first heading")))))
12568 (defun org-on-heading-p (&optional invisible-ok)
12569 "Return t if point is on a (visible) heading line.
12570 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
12572 (outline-on-heading-p 'invisible-ok)
12574 (skip-chars-backward "^\n\r")
12575 (and (looking-at outline-regexp)
12578 (equal (char-before) ?\n))))))
12580 (defun org-on-target-p ()
12581 (let ((pos (point)))
12583 (skip-chars-forward "<")
12584 (and (re-search-backward "<<" nil t)
12585 (or (looking-at org-target-regexp)
12586 (looking-at org-radio-target-regexp))
12587 (<= (match-beginning 0) pos)
12588 (>= (match-end 0) pos)))))
12590 (defun org-up-heading-all (arg)
12591 "Move to the heading line of which the present line is a subheading.
12592 This function considers both visible and invisible heading lines.
12593 With argument, move up ARG levels."
12595 (if (fboundp 'outline-up-heading-all)
12596 (outline-up-heading-all arg) ; emacs 21 version of outline.el
12597 (outline-up-heading arg t)) ; emacs 22 version of outline.el
12598 (org-back-to-heading t)
12599 (looking-at outline-regexp)
12600 (if (<= (- (match-end 0) (match-beginning 0)) arg)
12601 (error "Cannot move up %d levels" arg)
12602 (re-search-backward
12603 (concat "[\n\r]" (regexp-quote
12604 (make-string (- (match-end 0) (match-beginning 0) arg)
12607 (forward-char 1))))
12609 (defun org-show-hidden-entry ()
12610 "Show an entry where even the heading is hidden."
12612 (if (not org-noutline-p)
12614 (org-back-to-heading t)
12615 (org-flag-heading nil)))
12618 (defun org-check-occur-regexp (regexp)
12619 "If REGEXP starts with \"^\", modify it to check for \\r as well.
12620 Of course, only for the old outline mode."
12623 (if (string-match "^\\^" regexp)
12624 (concat "[\n\r]" (substring regexp 1))
12627 (defun org-flag-heading (flag &optional entry)
12628 "Flag the current heading. FLAG non-nil means make invisible.
12629 When ENTRY is non-nil, show the entire entry."
12631 (org-back-to-heading t)
12632 (if (not org-noutline-p)
12633 ;; Make the current headline visible
12634 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
12635 ;; Check if we should show the entire entry
12639 (save-excursion ;; FIXME: Is this the fix for points in the -|
12640 ;; middle of text? |
12641 (and (outline-next-heading) ;; |
12642 (org-flag-heading nil)))) ; show the next heading _|
12643 (outline-flag-region (max 1 (1- (point)))
12644 (save-excursion (outline-end-of-heading) (point))
12647 (if flag ?\r ?\n))))))
12649 (defun org-end-of-subtree (&optional invisible-OK)
12650 ;; This is an exact copy of the original function, but it uses
12651 ;; `org-back-to-heading', to make it work also in invisible
12652 ;; trees. And is uses an invisible-OK argument.
12653 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
12654 (org-back-to-heading invisible-OK)
12656 (level (funcall outline-level)))
12657 (while (and (not (eobp))
12658 (or first (> (funcall outline-level) level)))
12660 (outline-next-heading))
12661 (if (memq (preceding-char) '(?\n ?\^M))
12663 ;; Go to end of line before heading
12665 (if (memq (preceding-char) '(?\n ?\^M))
12666 ;; leave blank line before heading
12667 (forward-char -1))))))
12669 (defun org-show-subtree ()
12670 "Show everything after this heading at deeper levels."
12671 (outline-flag-region
12674 (outline-end-of-subtree) (outline-next-heading) (point))
12675 (if org-noutline-p nil ?\n)))
12677 (defun org-show-entry ()
12678 "Show the body directly following this heading.
12679 Show the heading too, if it is currently invisible."
12682 (org-back-to-heading t)
12683 (outline-flag-region
12686 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
12687 (or (match-beginning 1) (point-max)))
12688 (if org-noutline-p nil ?\n))))
12691 (defun org-make-options-regexp (kwds)
12692 "Make a regular expression for keyword lines."
12694 (if org-noutline-p "^" "[\n\r]")
12696 (mapconcat 'regexp-quote kwds "\\|")
12698 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
12700 ;; Make `bookmark-jump' show the jump location if it was hidden.
12701 (eval-after-load "bookmark"
12702 '(if (boundp 'bookmark-after-jump-hook)
12703 ;; We can use the hook
12704 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
12705 ;; Hook not available, use advice
12706 (defadvice bookmark-jump (after org-make-visible activate)
12707 "Make the position visible."
12708 (org-bookmark-jump-unhide))))
12710 (defun org-bookmark-jump-unhide ()
12711 "Unhide the current position, to show the bookmark location."
12712 (and (eq major-mode 'org-mode)
12713 (or (org-invisible-p)
12714 (save-excursion (goto-char (max (point-min) (1- (point))))
12715 (org-invisible-p)))
12716 (org-show-hierarchy-above)))
12722 (run-hooks 'org-load-hook)
12724 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
12725 ;;; org.el ends here