1 ;;; org.el --- Outline-based notes management and organize
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (c) 2004, 2005, 2006 Free Software Foundation
5 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around a NOTES file that contains
34 ;; information about projects as plain text. Org-mode is implemented on top
35 ;; of outline-mode - ideal to keep the content of large files well structured.
36 ;; It supports ToDo items, deadlines and time stamps, which can be extracted
37 ;; to create a daily/weekly agenda that also integrates the diary of the Emacs
38 ;; calendar. Tables are easily created with a built-in table editor. Plain
39 ;; text URL-like links connect to websites, emails (VM, RMAIL, WANDERLUST),
40 ;; Usenet messages (Gnus), BBDB entries, and any files related to the
41 ;; projects. For printing and sharing of notes, an Org-mode file (or a part
42 ;; of it) can be exported as a structured ASCII file, or as HTML.
46 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
47 ;; only need to copy the following lines to your .emacs file. The last two
48 ;; lines define *global* keys for the commands `org-store-link' and
49 ;; `org-agenda' - please choose suitable keys yourself.
51 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
52 ;; (define-key global-map "\C-cl" 'org-store-link)
53 ;; (define-key global-map "\C-ca" 'org-agenda)
55 ;; If you have downloaded Org-mode from the Web, you must byte-compile
56 ;; org.el and put it on your load path. In addition to the Emacs Lisp
57 ;; lines above, you also need to add the following lines to .emacs:
59 ;; (autoload 'org-mode "org" "Org mode" t)
60 ;; (autoload 'org-diary "org" "Diary entries from Org mode")
61 ;; (autoload 'org-agenda "org" "Multi-file agenda from Org mode" t)
62 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
63 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
64 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
66 ;; This setup will put all files with extension ".org" into Org-mode. As
67 ;; an alternative, make the first line of a file look like this:
69 ;; MY PROJECTS -*- mode: org; -*-
71 ;; which will select Org-mode for this buffer no matter what the file's
76 ;; The documentation of Org-mode can be found in the TeXInfo file. The
77 ;; distribution also contains a PDF version of it. At the homepage of
78 ;; Org-mode, you can read the same text online as HTML. There is also an
79 ;; excellent reference card made by Philip Rooke. This card can be found
80 ;; in the etc/ directory of Emacs 22.
82 ;; Changes since version 4.00:
83 ;; ---------------------------
85 ;; - Minor bug fixes and improvements around tag searches.
86 ;; - XEmacs compatibility fixes.
89 ;; - Tags can also be set remotely from agenda buffer.
90 ;; - Boolean logic for tag searches.
91 ;; - Additional agenda commands can be configured through the variable
92 ;; `org-agenda-custom-commands'.
97 (eval-when-compile (require 'cl) (require 'calendar))
102 (defvar calc-embedded-close-formula)
103 (defvar calc-embedded-open-formula)
104 (defvar font-lock-unfontify-region-function)
106 ;;; Customization variables
108 (defvar org-version "4.01"
109 "The version number of the file org.el.")
110 (defun org-version ()
112 (message "Org-mode version %s" org-version))
114 ;; The following two constants are for compatibility with different Emacs
115 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
116 ;; The compatibility code in org.el is based on these two constants.
117 (defconst org-xemacs-p (featurep 'xemacs)
118 "Are we running xemacs?")
119 (defconst org-noutline-p (featurep 'noutline)
120 "Are we using the new outline mode?")
123 "Outline-based notes management and organizer "
129 (defgroup org-startup nil
130 "Options concerning startup of Org-mode."
134 (defcustom org-CUA-compatible nil
135 "Non-nil means use alternative key bindings for S-<cursor movement>.
136 Org-mode used S-<cursor movement> for changing timestamps and priorities.
137 S-<cursor movement> is also used for example by `CUA-mode' to select text.
138 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
139 alternative bindings. Setting this variable to t will replace the following
140 keys both in Org-mode and in the Org-agenda buffer.
148 If you do not like the alternative keys, take a look at the variable
151 This option is only relevant at load-time of Org-mode. Changing it requires
152 a restart of Emacs to become effective."
156 (defvar org-disputed-keys
157 '((S-up [(shift up)] [(meta ?p)])
158 (S-down [(shift down)] [(meta ?n)])
159 (S-left [(shift left)] [(meta ?-)])
160 (S-right [(shift right)] [(meta ?+)])
161 (S-return [(shift return)] [(control shift return)]))
162 "Keys for which Org-mode and other modes compete.
163 This is an alist, cars are symbols for lookup, 1st element is the default key,
164 second element will be used when `org-CUA-compatible' is t.")
167 "Select a key according to `org-CUA-compatible'."
168 (nth (if org-CUA-compatible 2 1)
169 (or (assq key org-disputed-keys)
170 (error "Invalid Key %s in `org-key'" key))))
172 (defcustom org-startup-folded t
173 "Non-nil means, entering Org-mode will switch to OVERVIEW.
174 This can also be configured on a per-file basis by adding one of
175 the following lines anywhere in the buffer:
182 (const :tag "nofold: show all" nil)
183 (const :tag "fold: overview" t)
184 (const :tag "content: all headlines" content)))
186 (defcustom org-startup-truncated t
187 "Non-nil means, entering Org-mode will set `truncate-lines'.
188 This is useful since some lines containing links can be very long and
189 uninteresting. Also tables look terrible when wrapped."
193 (defcustom org-startup-with-deadline-check nil
194 "Non-nil means, entering Org-mode will run the deadline check.
195 This means, if you start editing an org file, you will get an
196 immediate reminder of any due deadlines.
197 This can also be configured on a per-file basis by adding one of
198 the following lines anywhere in the buffer:
201 #+STARTUP: nodlcheck"
205 (defcustom org-insert-mode-line-in-empty-file nil
206 "Non-nil means insert the first line setting Org-mode in empty files.
207 When the function `org-mode' is called interactively in an empty file, this
208 normally means that the file name does not automatically trigger Org-mode.
209 To ensure that the file will always be in Org-mode in the future, a
210 line enforcing Org-mode will be inserted into the buffer, if this option
215 (defgroup org-keywords nil
216 "Options concerning TODO items in Org-mode."
220 (defcustom org-todo-keywords '("TODO" "DONE")
221 "List of TODO entry keywords.
222 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
223 considered to mean that the entry is \"done\". All the other mean that
224 action is required, and will make the entry show up in todo lists, diaries
226 The command \\[org-todo] cycles an entry through these states, and an
227 additional state where no keyword is present. For details about this
228 cycling, see also the variable `org-todo-interpretation'
229 Changes become only effective after restarting Emacs."
231 :type '(repeat (string :tag "Keyword")))
233 (defcustom org-todo-interpretation 'sequence
234 "Controls how TODO keywords are interpreted.
235 \\<org-mode-map>Possible values are `sequence' and `type'.
236 This variable is only relevant if `org-todo-keywords' contains more than two
237 states. There are two ways how these keywords can be used:
239 - As a sequence in the process of working on a TODO item, for example
240 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
241 org-todo-interpretation 'sequence)
243 - As different types of TODO items, for example
244 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
245 org-todo-interpretation 'type)
247 When the states are interpreted as a sequence, \\[org-todo] always cycles
248 to the next state, in order to walk through all different states. So with
249 \\[org-todo], you turn an empty entry into the state TODO. When you started
250 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
251 later to VERIFY and finally to DONE.
253 When the states are interpreted as types, \\[org-todo] still cycles through
254 when it is called several times in direct succession, in order to initially
255 select the type. However, if not called immediately after a previous
256 \\[org-todo], it switches from each type directly to DONE. So with the
257 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
258 RELAXED. If you later return to this entry and press \\[org-todo] again,
259 RELAXED will not be changed REMIND, but directly to DONE.
261 You can create a large number of types. To initially select a
262 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
263 type with completion. Of course, you can also type the keyword
264 directly into the buffer. M-TAB completes TODO keywords at the
265 beginning of a headline."
267 :type '(choice (const sequence)
270 (defcustom org-default-priority ?B
271 "The default priority of TODO items.
272 This is the priority an item get if no explicit priority is given."
276 (defcustom org-lowest-priority ?C
277 "The lowest priority of TODO items. A character like ?A, ?B etc."
281 (defcustom org-deadline-string "DEADLINE:"
282 "String to mark deadline entries.
283 A deadline is this string, followed by a time stamp. Should be a word,
284 terminated by a colon. You can insert a schedule keyword and
285 a timestamp with \\[org-deadline].
286 Changes become only effective after restarting Emacs."
290 (defcustom org-scheduled-string "SCHEDULED:"
291 "String to mark scheduled TODO entries.
292 A schedule is this string, followed by a time stamp. Should be a word,
293 terminated by a colon. You can insert a schedule keyword and
294 a timestamp with \\[org-schedule].
295 Changes become only effective after restarting Emacs."
299 (defcustom org-closed-string "CLOSED:"
300 "String ued as the prefix for timestamps logging closing a TODO entry."
304 (defcustom org-comment-string "COMMENT"
305 "Entries starting with this keyword will never be exported.
306 An entry can be toggled between COMMENT and normal with
307 \\[org-toggle-comment].
308 Changes become only effective after restarting Emacs."
312 (defcustom org-quote-string "QUOTE"
313 "Entries starting with this keyword will be exported in fixed-width font.
314 Quoting applies only to the text in the entry following the headline, and does
315 not extend beyond the next headline, even if that is lower level.
316 An entry can be toggled between QUOTE and normal with
317 \\[org-toggle-fixed-width-section]"
321 (defcustom org-after-todo-state-change-hook nil
322 "Hook which is run after the state of a TODO item was changed.
323 The new state (a string with a todo keyword, or nil) is available in the
324 Lisp variable `state'."
328 ;; Variables for pre-computed regular expressions, all buffer local
329 (defvar org-todo-kwd-priority-p nil
330 "Do TODO items have priorities?")
331 (make-variable-buffer-local 'org-todo-kwd-priority-p)
332 (defvar org-todo-kwd-max-priority nil
333 "Maximum priority of TODO items.")
334 (make-variable-buffer-local 'org-todo-kwd-max-priority)
335 (defvar org-ds-keyword-length 12
336 "Maximum length of the Deadline and SCHEDULED keywords.")
337 (make-variable-buffer-local 'org-ds-keyword-length)
338 (defvar org-done-string nil
339 "The last string in `org-todo-keywords', indicating an item is DONE.")
340 (make-variable-buffer-local 'org-done-string)
341 (defvar org-todo-regexp nil
342 "Matches any of the TODO state keywords.")
343 (make-variable-buffer-local 'org-todo-regexp)
344 (defvar org-not-done-regexp nil
345 "Matches any of the TODO state keywords except the last one.")
346 (make-variable-buffer-local 'org-not-done-regexp)
347 (defvar org-todo-line-regexp nil
348 "Matches a headline and puts TODO state into group 2 if present.")
349 (make-variable-buffer-local 'org-todo-line-regexp)
350 (defvar org-nl-done-regexp nil
351 "Matches newline followed by a headline with the DONE keyword.")
352 (make-variable-buffer-local 'org-nl-done-regexp)
353 (defvar org-looking-at-done-regexp nil
354 "Matches the DONE keyword a point.")
355 (make-variable-buffer-local 'org-looking-at-done-regexp)
356 (defvar org-deadline-regexp nil
357 "Matches the DEADLINE keyword.")
358 (make-variable-buffer-local 'org-deadline-regexp)
359 (defvar org-deadline-time-regexp nil
360 "Matches the DEADLINE keyword together with a time stamp.")
361 (make-variable-buffer-local 'org-deadline-time-regexp)
362 (defvar org-deadline-line-regexp nil
363 "Matches the DEADLINE keyword and the rest of the line.")
364 (make-variable-buffer-local 'org-deadline-line-regexp)
365 (defvar org-scheduled-regexp nil
366 "Matches the SCHEDULED keyword.")
367 (make-variable-buffer-local 'org-scheduled-regexp)
368 (defvar org-scheduled-time-regexp nil
369 "Matches the SCHEDULED keyword together with a time stamp.")
370 (make-variable-buffer-local 'org-scheduled-time-regexp)
372 (defvar org-category nil
373 "Variable used by org files to set a category for agenda display.
374 Such files should use a file variable to set it, for example
376 -*- mode: org; org-category: \"ELisp\"
378 or contain a special line
382 If the file does not specify a category, then file's base name
384 (make-variable-buffer-local 'org-category)
386 (defgroup org-time nil
387 "Options concerning time stamps and deadlines in Org-mode."
391 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
392 "Formats for `format-time-string' which are used for time stamps.
393 It is not recommended to change this constant.")
396 (defcustom org-deadline-warning-days 30
397 "No. of days before expiration during which a deadline becomes active.
398 This variable governs the display in the org file."
402 (defcustom org-popup-calendar-for-date-prompt t
403 "Non-nil means, pop up a calendar when prompting for a date.
404 In the calendar, the date can be selected with mouse-1. However, the
405 minibuffer will also be active, and you can simply enter the date as well.
406 When nil, only the minibuffer will be available."
410 (defcustom org-calendar-follow-timestamp-change t
411 "Non-nil means, make the calendar window follow timestamp changes.
412 When a timestamp is modified and the calendar window is visible, it will be
413 moved to the new date."
417 (defcustom org-log-done nil
418 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
419 When the state of an entry is changed from nothing to TODO, remove a previous
424 (defgroup org-agenda nil
425 "Options concerning agenda display Org-mode."
429 (defcustom org-agenda-files nil
430 "A list of org files for agenda/diary display.
431 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
432 \\[org-remove-file]. You can also use customize to edit the list."
434 :type '(repeat file))
436 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
437 "Custom commands for the agenda.
438 These commands will be offered on the splash screen displayed by the
439 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
441 key The key (a single char as a string) to be associated with the command.
442 type The command type, any of the following symbols:
443 todo Entries with a specific TODO keyword, in all agenda files.
444 tags Tags match in all agenda files.
445 todo-tree Sparse tree of specific TODO keyword in *current* file.
446 tags-tree Sparse tree with all tags matches in *current* file.
447 occur-tree Occur sparse tree for current file.
448 match What to search for:
449 - a single keyword for TODO keyword searches
450 - a tags match expression for tags searches
451 - a regular expression for occur searches"
454 (list (string :tag "Key")
456 (const :tag "Tags search in all agenda files" tags)
457 (const :tag "TODO keyword search in all agenda files" todo)
458 (const :tag "Tags sparse tree in current buffer" tags-tree)
459 (const :tag "TODO keyword tree in current buffer" todo-tree)
460 (const :tag "Occur tree in current buffer" occur-tree))
461 (string :tag "Match"))))
463 (defcustom org-select-timeline-window t
464 "Non-nil means, after creating a timeline, move cursor into Timeline window.
465 When nil, cursor will remain in the current window."
469 (defcustom org-select-agenda-window t
470 "Non-nil means, after creating an agenda, move cursor into Agenda window.
471 When nil, cursor will remain in the current window."
475 (defcustom org-fit-agenda-window t
476 "Non-nil means, change window size of agenda to fit content."
480 (defcustom org-agenda-show-all-dates t
481 "Non-nil means, `org-agenda' shows every day in the selected range.
482 When nil, only the days which actually have entries are shown."
486 ;; FIXME: First day of month works only for current month because it would
487 ;; require a variable ndays treatment.
488 (defcustom org-agenda-start-on-weekday 1
489 "Non-nil means, start the overview always on the specified weekday.
490 0 Denotes Sunday, 1 denotes Monday etc.
491 When nil, always start on the current day."
493 :type '(choice (const :tag "Today" nil)
494 (const :tag "First day of month" t)
495 (number :tag "Weekday No.")))
497 (defcustom org-agenda-ndays 7
498 "Number of days to include in overview display."
502 (defcustom org-agenda-include-all-todo t
503 "Non-nil means, the agenda will always contain all TODO entries.
504 When nil, date-less entries will only be shown if `org-agenda' is called
505 with a prefix argument.
506 When non-nil, the TODO entries will be listed at the top of the agenda, before
507 the entries for specific days."
511 (defcustom org-agenda-include-diary nil
512 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
516 (defcustom org-calendar-to-agenda-key [?c]
517 "The key to be installed in `calendar-mode-map' for switching to the agenda.
518 The command `org-calendar-goto-agenda' will be bound to this key. The
519 default is the character `c' because then`c' can be used to switch back and
520 force between agenda and calendar."
524 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
525 "Sorting structure for the agenda items of a single day.
526 This is a list of symbols which will be used in sequence to determine
527 if an entry should be listed before another entry. The following
528 symbols are recognized.
530 time-up Put entries with time-of-day indications first, early first
531 time-down Put entries with time-of-day indications first, late first
532 category-keep Keep the default order of categories, corresponding to the
533 sequence in `org-agenda-files'.
534 category-up Sort alphabetically by category, A-Z.
535 category-down Sort alphabetically by category, Z-A.
536 priority-up Sort numerically by priority, high priority last.
537 priority-down Sort numerically by priority, high priority first.
539 The different possibilities will be tried in sequence, and testing stops
540 if one comparison returns a \"not-equal\". For example, the default
541 '(time-up category-keep priority-down)
542 means: Pull out all entries having a specified time of day and sort them,
543 in order to make a time schedule for the current day the first thing in the
544 agenda listing for the day. Of the entries without a time indication, keep
545 the grouped in categories, don't sort the categories, but keep them in
546 the sequence given in `org-agenda-files'. Within each category sort by
549 Leaving out `category-keep' would mean that items will be sorted across
550 categories by priority."
556 (const category-keep)
558 (const category-down)
560 (const priority-down))))
562 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
563 "Format specification for the prefix of items in the agenda buffer.
564 This format works similar to a printf format, with the following meaning:
566 %c the category of the item, \"Diary\" for entries from the diary, or
567 as given by the CATEGORY keyword or derived from the file name.
568 %t the time-of-day specification if one applies to the entry, in the
570 %s Scheduling/Deadline information, a short string
572 All specifiers work basically like the standard `%s' of printf, but may
573 contain two additional characters: A question mark just after the `%' and
574 a whitespace/punctuation character just before the final letter.
576 If the first character after `%' is a question mark, the entire field
577 will only be included if the corresponding value applies to the
578 current entry. This is useful for fields which should have fixed
579 width when present, but zero width when absent. For example,
580 \"%?-12t\" will result in a 12 character time field if a time of the
581 day is specified, but will completely disappear in entries which do
584 If there is punctuation or whitespace character just before the final
585 format letter, this character will be appended to the field value if
586 the value is not empty. For example, the format \"%-12:c\" leads to
587 \"Diary: \" if the category is \"Diary\". If the category were be
588 empty, no additional colon would be interted.
590 The default value of this option is \" %-12:c%?-12t% s\", meaning:
591 - Indent the line with two space characters
592 - Give the category in a 12 chars wide field, padded with whitespace on
593 the right (because of `-'). Append a colon if there is a category
595 - If there is a time-of-day, put it into a 12 chars wide field. If no
596 time, don't put in an empty field, just skip it (because of '?').
597 - Finally, put the scheduling information and append a whitespace.
599 As another example, if you don't want the time-of-day of entries in
600 the prefix, you could use:
602 (setq org-agenda-prefix-format \" %-11:c% s\")
604 See also the variable `org-agenda-remove-times-when-in-prefix'."
608 (defcustom org-timeline-prefix-format " % s"
609 "Like `org-agenda-prefix-format', but for the timeline of a single file."
613 (defvar org-prefix-format-compiled nil
614 "The compiled version of the most recently used prefix format.
615 Depending on which command was used last, this may be the compiled version
616 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
618 (defcustom org-agenda-use-time-grid t
619 "Non-nil means, show a time grid in the agenda schedule.
620 A time grid is a set of lines for specific times (like every two hours between
621 8:00 and 20:00. The items scheduled for a day at specific times are
622 sorted in between these lines.
623 For deails about when the grid will be shown, and what it will look like, see
624 the variable `org-agenda-time-grid'."
628 (defcustom org-agenda-time-grid
629 '((daily today require-timed)
631 (800 1000 1200 1400 1600 1800 2000))
633 "The settings for time grid for agenda display.
634 This is a list of three items. The first item is again a list. It contains
635 symbols specifying conditions when the grid should be displayed:
637 daily if the agenda shows a single day
638 weekly if the agenda shows an entire week
639 today show grid on current date, independent of daily/weekly display
640 require-timed show grid only if at least on item has a time specification
642 The second item is a string which will be places behing the grid time.
644 The third item is a list of integers, indicating the times that should have
649 (set :greedy t :tag "Grid Display Options"
650 (const :tag "Show grid in single day agenda display" daily)
651 (const :tag "Show grid in weekly agenda display" weekly)
652 (const :tag "Always show grid for today" today)
653 (const :tag "Show grid only if any timed entries are present"
655 (const :tag "Skip grid times already present in an entry"
657 (string :tag "Grid String")
658 (repeat :tag "Grid Times" (integer :tag "Time"))))
660 (defcustom org-agenda-remove-times-when-in-prefix t
661 "Non-nil means, remove duplicate time specifications in agenda items.
662 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
663 time-of-day specification in a headline or diary entry is extracted and
664 placed into the prefix. If this option is non-nil, the original specification
665 \(a timestamp or -range, or just a plain time(range) specification like
666 11:30-4pm) will be removed for agenda display. This makes the agenda less
668 The option can be t or nil. It may also be the symbol `beg', indicating
669 that the time should only be removed what it is located at the beginning of
670 the headline/diary entry."
673 (const :tag "Always" t)
674 (const :tag "Never" nil)
675 (const :tag "When at beginning of entry" beg)))
677 (defcustom org-sort-agenda-notime-is-late t
678 "Non-nil means, items without time are considered late.
679 This is only relevant for sorting. When t, items which have no explicit
680 time like 15:30 will be considered as 24:01, i.e. later than any items which
681 do have a time. When nil, the default time is before 0:00. You can use this
682 option to decide if the schedule for today should come before or after timeless
687 (defgroup org-structure nil
688 "Options concerning structure editing in Org-mode."
692 (defcustom org-cycle-include-plain-lists nil
693 "Non-nil means, include plain lists into visibility cycling.
694 This means that during cycling, plain list items will *temporarily* be
695 interpreted as outline headlines with a level given by 1000+i where i is the
696 indentation of the bullet. In all other operations, plain list items are
697 not seen as headlines. For example, you cannot assign a TODO keyword to
699 :group 'org-structure
702 (defcustom org-cycle-emulate-tab t
703 "Where should `org-cycle' emulate TAB.
705 white Only in completely white lines
706 t Everywhere except in headlines"
707 :group 'org-structure
708 :type '(choice (const :tag "Never" nil)
709 (const :tag "Only in completely white lines" white)
710 (const :tag "Everywhere except in headlines" t)
713 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
714 "Hook that is run after `org-cycle' has changed the buffer visibility.
715 The function(s) in this hook must accept a single argument which indicates
716 the new state that was set by the most recent `org-cycle' command. The
717 argument is a symbol. After a global state change, it can have the values
718 `overview', `content', or `all'. After a local state change, it can have
719 the values `folded', `children', or `subtree'."
720 :group 'org-structure
723 (defcustom org-highlight-sparse-tree-matches t
724 "Non-nil means, highlight all matches that define a sparse tree.
725 The highlights will automatically disappear the next time the buffer is
726 changed by an edit command."
727 :group 'org-structure
730 (defcustom org-show-hierarchy-above t
731 "Non-nil means, show full hierarchy when showing a spot in the tree.
732 Turning this off makes sparse trees more compact, but also less clear."
733 :group 'org-structure
736 (defcustom org-show-following-heading t
737 "Non-nil means, show heading following match in `org-occur'.
738 When doing an `org-occur' it is useful to show the headline which
739 follows the match, even if they do not match the regexp. This makes it
740 easier to edit directly inside the sparse tree. However, if you use
741 org-occur mainly as an overview, the following headlines are
742 unnecessary clutter."
743 :group 'org-structure
746 (defcustom org-occur-hook '(org-first-headline-recenter)
747 "Hook that is run after `org-occur' has constructed a sparse tree.
748 This can be used to recenter the window to show as much of the structure
750 :group 'org-structure
753 (defcustom org-level-color-stars-only nil
754 "Non-nil means fontify only the stars in each headline.
755 When nil, the entire headline is fontified.
756 After changin this, requires restart of Emacs to become effective."
757 :group 'org-structure
760 (defcustom org-adapt-indentation t
761 "Non-nil means, adapt indentation when promoting and demoting.
762 When this is set and the *entire* text in an entry is indented, the
763 indentation is increased by one space in a demotion command, and
764 decreased by one in a promotion command. If any line in the entry
765 body starts at column 0, indentation is not changed at all."
766 :group 'org-structure
769 (defcustom org-plain-list-ordered-item-terminator t
770 "The character that makes a line with leading number an ordered list item.
771 Valid values are ?. and ?\). To get both terminators, use t. While
772 ?. may look nicer, it creates the danger that a line with leading
773 number may be incorrectly interpreted as an item. ?\) therefore is
775 :group 'org-structure
776 :type '(choice (const :tag "dot like in \"2.\"" ?.)
777 (const :tag "paren like in \"2)\"" ?\))
778 (const :tab "both" t)))
780 (defcustom org-auto-renumber-ordered-lists t
781 "Non-nil means, automatically renumber ordered plain lists.
782 Renumbering happens when the sequence have been changed with
783 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
784 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
785 :group 'org-structure
788 (defcustom org-enable-fixed-width-editor t
789 "Non-nil means, lines starting with \":\" are treated as fixed-width.
790 This currently only means, they are never auto-wrapped.
791 When nil, such lines will be treated like ordinary lines.
792 See also the QUOTE keyword."
793 :group 'org-structure
796 (defcustom org-archive-location "%s_archive::"
797 "The location where subtrees should be archived.
798 This string consists of two parts, separated by a double-colon.
800 The first part is a file name - when omitted, archiving happens in the same
801 file. %s will be replaced by the current file name (without directory part).
802 Archiving to a different file is useful to keep archived entries from
803 contributing to the Org-mode Agenda.
805 The part after the double colon is a headline. The archived entries will be
806 filed under that headline. When omitted, the subtrees are simply filed away
807 at the end of the file, as top-level entries.
809 Here are a few examples:
811 If the current file is Projects.org, archive in file
812 Projects.org_archive, as top-level trees. This is the default.
814 \"::* Archived Tasks\"
815 Archive in the current file, under the top-level headline
816 \"* Archived Tasks\".
818 \"~/org/archive.org::\"
819 Archive in file ~/org/archive.org (absolute path), as top-level trees.
821 \"basement::** Finished Tasks\"
822 Archive in file ./basement (relative path), as level 3 trees
823 below the level 2 heading \"** Finished Tasks\".
825 You may set this option on a per-file basis by adding to the buffer a
828 #+ARCHIVE: basement::** Finished Tasks"
829 :group 'org-structure
832 (defcustom org-archive-mark-done t
833 "Non-nil means, mark archived entries as DONE."
834 :group 'org-structure
837 (defcustom org-archive-stamp-time t
838 "Non-nil means, add a time stamp to archived entries.
839 The time stamp will be added directly after the TODO state keyword in the
840 first line, so it is probably best to use this in combinations with
841 `org-archive-mark-done'."
842 :group 'org-structure
845 (defgroup org-tags nil
846 "Options concerning startup of Org-mode."
850 (defcustom org-tags-column 48
851 "The column to which tags should be indented in a headline.
852 If this number is positive, it specified the column. If it is negative,
853 it means that the tags should be flushright to that column. For example,
854 -79 works well for a normal 80 character screen."
858 (defcustom org-auto-align-tags t
859 "Non-nil means, realign tags after pro/demotion of TODO state change.
860 These operations change the length of a headline and therefore shift
861 the tags around. With this options turned on, after each such operation
862 the tags are again aligned to `org-tags-column'."
866 (defcustom org-use-tag-inheritance t
867 "Non-nil means, tags in levels apply also for sublevels.
868 When nil, only the tags directly give in a specific line apply there.
869 If you turn off this option, you very likely want to turn on the
870 companion option `org-tags-match-list-sublevels'."
874 (defcustom org-tags-match-list-sublevels nil
875 "Non-nil means list also sublevels of headlines matching tag search.
876 Because of tag inheritance (see variable `org-use-tag-inheritance'),
877 the sublevels of a headline matching a tag search often also match
878 the same search. Listing all of them can create very long lists.
879 Setting this variable to nil causes subtrees to be skipped.
880 This option is off by default, because inheritance in on. If you turn
881 inheritance off, you very likely want to turn this option on.
883 As a special case, if the tag search is restricted to TODO items, the
884 value of this variable is ignored and sublevels are always checked, to
885 make sure all corresponding TODO items find their way into the list."
889 (defvar org-tags-history nil
890 "History of minibuffer reads for tags.")
891 (defvar org-last-tags-completion-table nil
892 "The last used completion table for tags.")
894 (defgroup org-link nil
895 "Options concerning links in Org-mode."
899 (defcustom org-tab-follows-link nil
900 "Non-nil means, on links TAB will follow the link.
901 Needs to be set before org.el is loaded."
905 (defcustom org-return-follows-link nil
906 "Non-nil means, on links RET will follow the link.
907 Needs to be set before org.el is loaded."
911 (defcustom org-link-format "<%s>"
912 "Default format for linkes in the buffer.
913 This is a format string for printf, %s will be replaced by the link text.
914 If you want to make sure that your link is always properly terminated,
915 include angle brackets into this format, like \"<%s>\". Some people also
916 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
919 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
920 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
921 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
922 (string :tag "Other" :value "<%s>")))
924 (defcustom org-allow-space-in-links t
925 "Non-nil means, file names in links may contain space characters.
926 When nil, it becomes possible to put several links into a line.
927 Note that in tables, a link never extends accross fields, so in a table
928 it is always possible to put several links into a line.
929 Changing this varable requires a re-launch of Emacs of become effective."
933 (defcustom org-context-in-file-links t
934 "Non-nil means, file links from `org-store-link' contain context.
935 The line number will be added to the file name with :: as separator and
936 used to find the context when the link is activated by the command
938 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
939 negates this setting for the duration of the command."
943 (defcustom org-keep-stored-link-after-insertion nil
944 "Non-nil means, keep link in list for entire session.
946 The command `org-store-link' adds a link pointing to the current
947 location to an internal list. These links accumulate during a session.
948 The command `org-insert-link' can be used to insert links into any
949 Org-mode file (offering completion for all stored links). When this
950 option is nil, every link which has been inserted once using \\[org-insert-link]
951 will be removed from the list, to make completing the unused links
956 (defcustom org-link-frame-setup
957 '((vm . vm-visit-folder-other-frame)
958 (gnus . gnus-other-frame)
959 (file . find-file-other-window))
960 "Setup the frame configuration for following links.
961 When following a link with Emacs, it may often be useful to display
962 this link in another window or frame. This variable can be used to
963 set this up for the different types of links.
966 `vm-visit-folder-other-frame'
972 `find-file-other-window'
973 `find-file-other-frame'
974 For the calendar, use the variable `calendar-setup'.
975 For BBDB, it is currently only possible to display the matches in
981 (const vm-visit-folder)
982 (const vm-visit-folder-other-window)
983 (const vm-visit-folder-other-frame)))
987 (const gnus-other-frame)))
991 (const find-file-other-window)
992 (const find-file-other-frame)))))
994 (defcustom org-usenet-links-prefer-google nil
995 "Non-nil means, `org-store-link' will create web links to google groups.
996 When nil, Gnus will be used for such links.
997 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
998 negates this setting for the duration of the command."
1002 (defcustom org-open-non-existing-files nil
1003 "Non-nil means, `org-open-file' will open non-existing file.
1004 When nil, an error will be generated."
1008 (defcustom org-confirm-shell-links t
1009 "Non-nil means, ask for confirmation before executing shell links.
1010 The default is true, to keep new users from shooting into their own foot."
1014 (defconst org-file-apps-defaults-gnu
1026 ("eps.gz" . "gv %s")
1028 ("mpeg" . "plaympeg %s")
1029 ("mp3" . "plaympeg %s")
1031 ("pdf" . "acroread %s")
1032 ("doc" . "soffice %s")
1033 ("ppt" . "soffice %s")
1034 ("pps" . "soffice %s")
1035 ("html" . "netscape -remote openURL(%s,new-window)")
1036 ("htm" . "netscape -remote openURL(%s,new-window)")
1037 ("xs" . "soffice %s"))
1038 "Default file applications on a UNIX/LINUX system.
1039 See `org-file-apps'.")
1041 (defconst org-file-apps-defaults-macosx
1046 ("eps.gz" . "gv %s")
1048 ("fig" . "xfig %s"))
1049 "Default file applications on a MacOS X system.
1050 The system \"open\" is known as a default, but we use X11 applications
1051 for some files for which the OS does not have a good default.
1052 See `org-file-apps'.")
1054 (defconst org-file-apps-defaults-windowsnt
1055 '((t . (w32-shell-execute "open" file)))
1056 "Default file applications on a Windows NT system.
1057 The system \"open\" is used for most files.
1058 See `org-file-apps'.")
1060 (defcustom org-file-apps
1068 "External applications for opening `file:path' items in a document.
1069 Org-mode uses system defaults for different file types, but
1070 you can use this variable to set the application for a given file
1071 extension. The entries in this list are cons cells with a file extension
1072 and the corresponding command. Possible values for the command are:
1073 `emacs' The file will be visited by the current Emacs process.
1074 `default' Use the default application for this file type.
1075 string A command to be executed by a shell; %s will be replaced
1076 by the path to the file.
1077 sexp A Lisp form which will be evaluated. The file path will
1078 be available in the Lisp variable `file'.
1079 For more examples, see the system specific constants
1080 `org-file-apps-defaults-macosx'
1081 `org-file-apps-defaults-windowsnt'
1082 `org-file-apps-defaults-gnu'."
1085 (cons (string :tag "Extension")
1087 (const :tag "Visit with Emacs" 'emacs)
1088 (const :tag "Use system default" 'default)
1089 (string :tag "Command")
1090 (sexp :tag "Lisp form")))))
1093 (defgroup org-remember nil
1094 "Options concerning interaction with remember.el."
1098 (defcustom org-directory "~/org"
1099 "Directory with org files.
1100 This directory will be used as default to prompt for org files.
1101 Used by the hooks for remember.el."
1102 :group 'org-remember
1105 (defcustom org-default-notes-file "~/.notes"
1106 "Default target for storing notes.
1107 Used by the hooks for remember.el. This can be a string, or nil to mean
1108 the value of `remember-data-file'."
1109 :group 'org-remember
1111 (const :tag "Default from remember-data-file" nil)
1114 (defcustom org-reverse-note-order nil
1115 "Non-nil means, store new notes at the beginning of a file or entry.
1116 When nil, new notes will be filed to the end of a file or entry."
1117 :group 'org-remember
1119 (const :tag "Reverse always" t)
1120 (const :tag "Reverse never" nil)
1121 (repeat :tag "By file name regexp"
1122 (cons regexp boolean))))
1124 (defgroup org-table nil
1125 "Options concerning tables in Org-mode."
1129 (defcustom org-enable-table-editor 'optimized
1130 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1131 When nil, such lines will be treated like ordinary lines.
1133 When equal to the symbol `optimized', the table editor will be optimized to
1135 - Use automatic overwrite mode in front of whitespace in table fields.
1136 This make the structure of the table stay in tact as long as the edited
1137 field does not exceed the column width.
1138 - Minimize the number of realigns. Normally, the table is aligned each time
1139 TAB or RET are pressed to move to another field. With optimization this
1140 happens only if changes to a field might have changed the column width.
1141 Optimization requires replacing the functions `self-insert-command',
1142 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1143 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1144 very good at guessing when a re-align will be necessary, but you can always
1145 force one with \\[org-ctrl-c-ctrl-c].
1147 If you would like to use the optimized version in Org-mode, but the
1148 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1150 This variable can be used to turn on and off the table editor during a session,
1151 but in order to toggle optimization, a restart is required.
1153 See also the variable `org-table-auto-blank-field'."
1156 (const :tag "off" nil)
1158 (const :tag "on, optimized" optimized)))
1160 ;; FIXME: We could have a third option which makes it jump only over the first
1161 ;; hline in a table.
1162 (defcustom org-table-tab-jumps-over-hlines t
1163 "Non-nil means, tab in the last column of a table with jump over a hline.
1164 If a horizontal separator line is following the current line,
1165 `org-table-next-field' can either create a new row before that line, or jump
1166 over the line. When this option is nil, a new line will be created before
1171 (defcustom org-table-auto-blank-field t
1172 "Non-nil means, automatically blank table field when starting to type into it.
1173 This only happens when typing immediately after a field motion
1174 command (TAB, S-TAB or RET).
1175 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1179 (defcustom org-table-default-size "5x2"
1180 "The default size for newly created tables, Columns x Rows."
1184 (defcustom org-table-automatic-realign t
1185 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1186 When nil, aligning is only done with \\[org-table-align], or after column
1191 (defcustom org-table-spaces-around-separators '(1 . 1)
1192 "The number of spaces to be placed before and after separators."
1194 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1196 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1197 "The number of spaces to be placed before and after separators.
1198 This option applies when the column separators have been made invisible."
1200 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1202 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1203 "Regular expression for recognizing numbers in table columns.
1204 If a table column contains mostly numbers, it will be aligned to the
1205 right. If not, it will be aligned to the left.
1207 The default value of this option is a regular expression which allows
1208 anything which looks remotely like a number as used in scientific
1209 context. For example, all of the following will be considered a
1211 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1213 Other options offered by the customize interface are more restrictive."
1216 (const :tag "Positive Integers"
1218 (const :tag "Integers"
1220 (const :tag "Floating Point Numbers"
1221 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1222 (const :tag "Floating Point Number or Integer"
1223 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1224 (const :tag "Exponential, Floating point, Integer"
1225 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1226 (const :tag "Very General Number-Like"
1227 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1228 (string :tag "Regexp:")))
1230 (defcustom org-table-number-fraction 0.5
1231 "Fraction of numbers in a column required to make the column align right.
1232 In a column all non-white fields are considered. If at least this
1233 fraction of fields is matched by `org-table-number-fraction',
1234 alignment to the right border applies."
1238 (defcustom org-export-highlight-first-table-line t
1239 "Non-nil means, highlight the first table line.
1240 In HTML export, this means use <th> instead of <td>.
1241 In tables created with table.el, this applies to the first table line.
1242 In Org-mode tables, all lines before the first horizontal separator
1243 line will be formatted with <th> tags."
1247 (defcustom org-table-tab-recognizes-table.el t
1248 "Non-nil means, TAB will automatically notice a table.el table.
1249 When it sees such a table, it moves point into it and - if necessary -
1250 calls `table-recognize-table'."
1254 (defgroup org-table-calculation nil
1255 "Options concerning tables in Org-mode."
1256 :tag "Org Table Calculation"
1259 (defcustom org-table-copy-increment t
1260 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1261 :group 'org-table-calculation
1264 (defcustom org-calc-default-modes
1265 '(calc-internal-prec 12
1266 calc-float-format (float 5)
1268 calc-prefer-frac nil
1269 calc-symbolic-mode nil
1270 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1271 calc-display-working-message t
1273 "List with Calc mode settings for use in calc-eval for table formulas.
1274 The list must contain alternating symbols (calc modes variables and values.
1275 Don't remove any of the default settings, just change the values. Org-mode
1276 relies on the variables to be present in the list."
1277 :group 'org-table-calculation
1280 (defcustom org-table-formula-evaluate-inline t
1281 "Non-nil means, TAB and RET evaluate a formula in current table field.
1282 If the current field starts with an equal sign, it is assumed to be a formula
1283 which should be evaluated as described in the manual and in the documentation
1284 string of the command `org-table-eval-formula'. This feature requires the
1286 When this variable is nil, formula calculation is only available through
1287 the command \\[org-table-eval-formula]."
1288 :group 'org-table-calculation
1292 (defcustom org-table-formula-use-constants t
1293 "Non-nil means, interpret constants in formulas in tables.
1294 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1295 by the value given in `org-table-formula-constants', or by a value obtained
1296 from the `constants.el' package."
1297 :group 'org-table-calculation
1300 (defcustom org-table-formula-constants nil
1301 "Alist with constant names and values, for use in table formulas.
1302 The car of each element is a name of a constant, without the `$' before it.
1303 The cdr is the value as a string. For example, if you'd like to use the
1304 speed of light in a formula, you would configure
1306 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1308 and then use it in an equation like `$1*$c'."
1309 :group 'org-table-calculation
1311 (cons (string :tag "name")
1312 (string :tag "value"))))
1314 (defcustom org-table-formula-numbers-only nil
1315 "Non-nil means, calculate only with numbers in table formulas.
1316 Then all input fields will be converted to a number, and the result
1317 must also be a number. When nil, calc's full potential is available
1318 in table calculations, including symbolics etc."
1319 :group 'org-table-calculation
1322 (defcustom org-table-allow-automatic-line-recalculation t
1323 "Non-nil means, lines makred with |#| or |*| will be recomputed automatically.
1324 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1325 :group 'org-table-calculation
1328 (defgroup org-export nil
1329 "Options for exporting org-listings."
1333 (defcustom org-export-language-setup
1334 '(("en" "Author" "Date" "Table of Contents")
1335 ("da" "Ophavsmand" "Dato" "Indhold")
1336 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1337 ("es" "Autor" "Fecha" "\xccndice")
1338 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1339 ("it" "Autore" "Data" "Indice")
1340 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1341 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1342 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1343 "Terms used in export text, translated to different languages.
1344 Use the variable `org-export-default-language' to set the language,
1345 or use the +OPTION lines for a per-file setting."
1349 (string :tag "HTML language tag")
1350 (string :tag "Author")
1351 (string :tag "Date")
1352 (string :tag "Table of Contents"))))
1354 (defcustom org-export-default-language "en"
1355 "The default language of HTML export, as a string.
1356 This should have an association in `org-export-language-setup'."
1360 (defcustom org-export-html-style
1361 "<style type=\"text/css\">
1363 font-family: Times, serif;
1366 .title { text-align: center; }
1367 .todo, .deadline { color: red; }
1368 .done { color: green; }
1370 border: 1pt solid #AEBDCC;
1371 background-color: #F3F5F7;
1373 font-family: courier, monospace;
1375 table { border-collapse: collapse; }
1377 vertical-align: top;
1378 border: 1pt solid #ADB9CC;
1381 "The default style specification for exported HTML files.
1382 Since there are different ways of setting style information, this variable
1383 needs to contain the full HTML structure to provide a style, including the
1384 surrounding HTML tags. The style specifications should include definiitons
1385 for new classes todo, done, title, and deadline. For example, legal values
1388 <style type=\"text/css\">
1389 p {font-weight: normal; color: gray; }
1391 .title { text-align: center; }
1392 .todo, .deadline { color: red; }
1393 .done { color: green; }
1396 or, if you want to keep the style in a file,
1398 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1400 As the value of this option simply gets inserted into the HTML <head> header,
1401 you can \"misuse\" it to add arbitrary text to the header."
1405 (defcustom org-export-headline-levels 3
1406 "The last level which is still exported as a headline.
1407 Inferior levels will produce itemize lists when exported.
1408 Note that a numeric prefix argument to an exporter function overrides
1411 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1415 (defcustom org-export-with-section-numbers t
1416 "Non-nil means, add section numbers to headlines when exporting.
1418 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1422 (defcustom org-export-with-toc t
1423 "Non-nil means, create a table of contents in exported files.
1424 The TOC contains headlines with levels up to`org-export-headline-levels'.
1426 Headlines which contain any TODO items will be marked with \"(*)\" in
1427 ASCII export, and with red color in HTML output.
1429 In HTML output, the TOC will be clickable.
1431 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1435 (defcustom org-export-plain-list-max-depth 20
1436 "Maximum depth of hand-formatted lists in HTML export.
1438 Org-mode parses hand-formatted enumeration and bullet lists and
1439 transforms them to HTML open export. Different indentation of the
1440 bullet or number indicates different list nesting levels. To avoid
1441 confusion, only a single level is allowed by default. When this is
1442 larger than 1, deeper indentation leads to deeper list nesting. For
1443 example, the default value of 3 allows the following list to be
1444 formatted correctly in HTML:
1450 2. from South America
1457 (defcustom org-export-preserve-breaks nil
1458 "Non-nil means, preserve all line breaks when exporting.
1459 Normally, in HTML output paragraphs will be reformatted. In ASCII
1460 export, line breaks will always be preserved, regardless of this variable.
1462 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1466 (defcustom org-export-html-inline-images t
1467 "Non-nil means, inline images into exported HTML pages.
1468 The link will still be to the original location of the image file.
1469 So if you are moving the page, lets say to your public HTML site,
1470 you will have to move the image and maybe change the link."
1474 (defcustom org-export-html-expand t
1475 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1476 When nil, these tags will be exported as plain text and therefore
1477 not be interpreted by a browser.
1479 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1483 (defcustom org-export-with-fixed-width t
1484 "Non-nil means, lines starting with \":\" will be in fixed width font.
1485 This can be used to have pre-formatted text, fragments of code etc. For
1487 : ;; Some Lisp examples
1490 will be looking just like this in also HTML. In ASCII export, this option
1493 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1497 (defcustom org-export-with-tables t
1498 "If non-nil, lines starting with \"|\" define a table.
1501 | Name | Address | Birthday |
1502 |-------------+----------+-----------|
1503 | Arthur Dent | England | 29.2.2100 |
1505 In ASCII export, this option has no effect.
1507 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1511 (defcustom org-export-prefer-native-exporter-for-tables nil
1512 "Non-nil means, always export tables created with table.el natively.
1513 Natively means, use the HTML code generator in table.el.
1514 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1515 the table does not use row- or column-spanning). This has the
1516 advantage, that the automatic HTML conversions for math symbols and
1517 sub/superscripts can be applied. Org-mode's HTML generator is also
1522 (defcustom org-export-html-table-tag
1523 "<table border=1 cellspacing=0 cellpadding=6>"
1524 "The HTML tag used to start a table.
1525 This must be a <table> tag, but you may change the options like
1526 borders and spacing."
1530 (defcustom org-export-with-emphasize t
1531 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1532 If the export target supports emphasizing text, the word will be
1533 typeset in bold, italic, or underlined, respectively. Works only for
1534 single words, but you can say: I *really* *mean* *this*.
1535 In ASCII export, this option has no effect.
1537 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1541 (defcustom org-match-sexp-depth 3
1542 "Number of stacked braces for sub/superscript matching.
1543 This has to be set before loading org.el to be effective."
1547 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1548 (defcustom org-export-with-sub-superscripts t
1549 "Non-nil means, interpret \"_\" and \"^\" for export.
1550 When this option is turned on, you can use TeX-like syntax for sub- and
1551 superscripts. Several characters after \"_\" or \"^\" will be
1552 considered as a single item - so grouping with {} is normally not
1553 needed. For example, the following things will be parsed as single
1554 sub- or superscripts.
1556 10^24 or 10^tau several digits will be considered 1 item
1557 10^-12 or 10^-tau a leading sign with digits or a word
1558 x^2-y^3 will be read as x^2 - y^3, because items are
1559 terminated by almost any nonword/nondigit char.
1560 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1562 Still, ambiguity is possible - so when in doubt use {} to enclose the
1564 In ASCII export, this option has no effect.
1566 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1570 (defcustom org-export-with-TeX-macros t
1571 "Non-nil means, interpret simple TeX-like macros when exporting.
1572 For example, HTML export converts \\alpha to α and \\AA to Å.
1573 No only real TeX macros will work here, but the standard HTML entities
1574 for math can be used as macro names as well. For a list of supported
1575 names in HTML export, see the constant `org-html-entities'.
1576 In ASCII export, this option has no effect.
1578 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1582 (defcustom org-export-html-with-timestamp nil
1583 "If non-nil, write `org-export-html-html-helper-timestamp'
1584 into the exported html text. Otherwise, the buffer will just be saved
1589 (defcustom org-export-html-html-helper-timestamp
1590 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1591 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1595 (defcustom org-export-ascii-show-new-buffer t
1596 "Non-nil means, popup buffer containing the exported ASCII text.
1597 Otherwise the buffer will just be saved to a file and stay hidden."
1601 (defcustom org-export-html-show-new-buffer nil
1602 "Non-nil means, popup buffer containing the exported html text.
1603 Otherwise, the buffer will just be saved to a file and stay hidden."
1607 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1608 "The file name for the iCalendar file covering all agenda files.
1609 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1613 (defcustom org-icalendar-include-todo nil
1614 "Non-nil means, export to iCalendar files should also cover TODO items."
1618 (defcustom org-icalendar-combined-name "OrgMode"
1619 "Calendar name for the combined iCalendar representing all agenda files."
1623 (defgroup org-faces nil
1624 "Faces for highlighting in Org-mode."
1628 (defface org-level-1 ;; font-lock-function-name-face
1629 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1630 (((class color) (background light)) (:foreground "Blue"))
1631 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1632 (t (:inverse-video t :bold t)))
1633 "Face used for level 1 headlines."
1636 (defface org-level-2 ;; font-lock-variable-name-face
1637 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1638 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1639 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1640 (t (:bold t :italic t)))
1641 "Face used for level 2 headlines."
1644 (defface org-level-3 ;; font-lock-keyword-face
1645 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1646 (((class color) (background light)) (:foreground "Purple"))
1647 (((class color) (background dark)) (:foreground "Cyan"))
1649 "Face used for level 3 headlines."
1652 (defface org-level-4 ;; font-lock-comment-face
1653 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1654 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1655 (((class color) (background light)) (:foreground "Firebrick"))
1656 (((class color) (background dark)) (:foreground "chocolate1"))
1657 (t (:bold t :italic t)))
1658 "Face used for level 4 headlines."
1661 (defface org-level-5 ;; font-lock-type-face
1662 '((((type tty) (class color)) (:foreground "green"))
1663 (((class color) (background light)) (:foreground "ForestGreen"))
1664 (((class color) (background dark)) (:foreground "PaleGreen"))
1665 (t (:bold t :underline t)))
1666 "Face used for level 5 headlines."
1669 (defface org-level-6 ;; font-lock-constant-face
1670 '((((type tty) (class color)) (:foreground "magenta"))
1671 (((class color) (background light)) (:foreground "CadetBlue"))
1672 (((class color) (background dark)) (:foreground "Aquamarine"))
1673 (t (:bold t :underline t)))
1674 "Face used for level 6 headlines."
1677 (defface org-level-7 ;; font-lock-builtin-face
1678 '((((type tty) (class color)) (:foreground "blue" :weight light))
1679 (((class color) (background light)) (:foreground "Orchid"))
1680 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1682 "Face used for level 7 headlines."
1685 (defface org-level-8 ;; font-lock-string-face
1686 '((((type tty) (class color)) (:foreground "green"))
1687 (((class color) (background light)) (:foreground "RosyBrown"))
1688 (((class color) (background dark)) (:foreground "LightSalmon"))
1690 "Face used for level 8 headlines."
1693 (defface org-special-keyword ;; font-lock-string-face
1694 '((((type tty) (class color)) (:foreground "green"))
1695 (((class color) (background light)) (:foreground "RosyBrown"))
1696 (((class color) (background dark)) (:foreground "LightSalmon"))
1698 "Face used for level 8 headlines."
1701 (defface org-warning ;; font-lock-warning-face
1702 '((((type tty) (class color)) (:foreground "red"))
1703 (((class color) (background light)) (:foreground "Red" :bold t))
1704 (((class color) (background dark)) (:foreground "Red1" :bold t))
1705 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1706 (t (:inverse-video t :bold t)))
1707 "Face for deadlines and TODO keywords."
1710 (defcustom org-fontify-done-headline nil
1711 "Non-nil means, change the face of a headline if it is marked DONE.
1712 Normally, only the TODO/DONE keyword indicates the state of a headline.
1713 When this is non-nil, the headline after the keyword is set to the
1714 `org-headline-done' as an additional indication."
1718 (defface org-headline-done ;; font-lock-string-face
1719 '((((type tty) (class color)) (:foreground "green"))
1720 (((class color) (background light)) (:foreground "RosyBrown"))
1721 (((class color) (background dark)) (:foreground "LightSalmon"))
1723 "Face used to indicate that a headline is DONE. See also the variable
1724 `org-fontify-done-headline'."
1727 ;; Inheritance does not yet work for xemacs. So we just copy...
1729 (defface org-deadline-announce
1730 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1731 (((class color) (background light)) (:foreground "Blue"))
1732 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1733 (t (:inverse-video t :bold t)))
1734 "Face for upcoming deadlines."
1737 (defface org-scheduled-today
1738 '((((type tty) (class color)) (:foreground "green"))
1739 (((class color) (background light)) (:foreground "DarkGreen"))
1740 (((class color) (background dark)) (:foreground "PaleGreen"))
1741 (t (:bold t :underline t)))
1742 "Face for items scheduled for a certain day."
1745 (defface org-scheduled-previously
1746 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1747 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1748 (((class color) (background light)) (:foreground "Firebrick"))
1749 (((class color) (background dark)) (:foreground "chocolate1"))
1750 (t (:bold t :italic t)))
1751 "Face for items scheduled previously, and not yet done."
1754 (defface org-formula
1755 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1756 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1757 (((class color) (background light)) (:foreground "Firebrick"))
1758 (((class color) (background dark)) (:foreground "chocolate1"))
1759 (t (:bold t :italic t)))
1760 "Face for items scheduled previously, and not yet done."
1764 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1765 (((class color) (background light)) (:foreground "Purple"))
1766 (((class color) (background dark)) (:foreground "Cyan"))
1771 (defface org-done ;; font-lock-type-face
1772 '((((type tty) (class color)) (:foreground "green"))
1773 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1774 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1775 (t (:bold t :underline t)))
1776 "Face used for DONE."
1779 (defface org-table ;; font-lock-function-name-face
1780 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1781 (((class color) (background light)) (:foreground "Blue"))
1782 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1783 (t (:inverse-video t :bold t)))
1784 "Face used for tables."
1787 (defface org-time-grid ;; font-lock-variable-name-face
1788 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1789 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1790 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1791 (t (:bold t :italic t)))
1792 "Face used for level 2 headlines."
1795 (defvar org-level-faces
1806 (defvar org-n-levels (length org-level-faces))
1808 (defun org-set-regexps-and-options ()
1809 "Precompute regular expressions for current buffer."
1810 (when (eq major-mode 'org-mode)
1811 (let ((re (org-make-options-regexp
1812 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1813 "STARTUP" "ARCHIVE")))
1815 kwds int key value cat arch)
1819 (goto-char (point-min))
1820 (while (re-search-forward re nil t)
1821 (setq key (match-string 1) value (match-string 2))
1823 ((equal key "CATEGORY")
1824 (if (string-match "[ \t]+$" value)
1825 (setq value (replace-match "" t t value)))
1826 (setq cat (intern value)))
1827 ((equal key "SEQ_TODO")
1829 kwds (append kwds (org-split-string value splitre))))
1830 ((equal key "PRI_TODO")
1832 kwds (append kwds (org-split-string value splitre))))
1833 ((equal key "TYP_TODO")
1835 kwds (append kwds (org-split-string value splitre))))
1836 ((equal key "STARTUP")
1837 (let ((opts (org-split-string value splitre))
1838 (set '(("fold" org-startup-folded t)
1839 ("nofold" org-startup-folded nil)
1840 ("content" org-startup-folded content)
1841 ("dlcheck" org-startup-with-deadline-check t)
1842 ("nodlcheck" org-startup-with-deadline-check nil)))
1844 (while (setq l (assoc (pop opts) set))
1845 (setq var (nth 1 l) val (nth 2 l))
1846 (set (make-local-variable var) val))))
1847 ((equal key "ARCHIVE")
1848 (string-match " *$" value)
1849 (setq arch (replace-match "" t t value))
1850 (remove-text-properties 0 (length arch)
1851 '(face t fontified t) arch)))
1853 (and cat (set (make-local-variable 'org-category) cat))
1854 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
1855 (and arch (set (make-local-variable 'org-archive-location) arch))
1856 (and int (set (make-local-variable 'org-todo-interpretation) int)))
1857 ;; Compute the regular expressions and other local variables
1858 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
1859 org-todo-kwd-max-priority (1- (length org-todo-keywords))
1860 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
1861 (length org-scheduled-string)))
1863 (nth (1- (length org-todo-keywords)) org-todo-keywords)
1865 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
1869 (mapconcat 'regexp-quote
1870 (nreverse (cdr (reverse org-todo-keywords)))
1873 org-todo-line-regexp
1874 (concat "^\\(\\*+\\)[ \t]*\\("
1875 (mapconcat 'regexp-quote org-todo-keywords "\\|")
1878 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
1879 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
1880 org-deadline-regexp (concat "\\<" org-deadline-string)
1881 org-deadline-time-regexp
1882 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
1883 org-deadline-line-regexp
1884 (concat "\\<\\(" org-deadline-string "\\).*")
1885 org-scheduled-regexp
1886 (concat "\\<" org-scheduled-string)
1887 org-scheduled-time-regexp
1888 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
1889 (org-set-font-lock-defaults)))
1891 ;; Tell the compiler about dynamically scoped variables,
1892 ;; and variables from other packages
1894 (defvar zmacs-regions)
1895 (defvar original-date)
1896 (defvar org-transient-mark-mode)
1897 (defvar org-old-auto-fill-inhibit-regexp)
1898 (defvar orgtbl-mode-menu)
1899 (defvar org-html-entities)
1900 (defvar org-goto-start-pos)
1901 (defvar org-cursor-color)
1902 (defvar org-time-was-given)
1903 (defvar org-ts-what)
1904 (defvar mark-active)
1906 (defvar levels-open)
1917 (defvar starting-day)
1918 (defvar include-all-loc)
1919 (defvar vm-message-pointer)
1920 (defvar vm-folder-directory)
1921 (defvar wl-summary-buffer-elmo-folder)
1922 (defvar wl-summary-buffer-folder-name)
1923 (defvar gnus-group-name)
1924 (defvar gnus-article-current)
1925 (defvar w3m-current-url)
1926 (defvar org-selected-point)
1927 (defvar calendar-mode-map)
1928 (defvar remember-save-after-remembering)
1929 (defvar remember-data-file))
1934 (defvar org-mode-map (copy-keymap outline-mode-map)
1935 "Keymap for Org-mode.")
1937 (defvar org-struct-menu)
1938 (defvar org-org-menu)
1939 (defvar org-tbl-menu)
1941 ;; We use a before-change function to check if a table might need
1943 (defvar org-table-may-need-update t
1944 "Indicates of a table might need an update.
1945 This variable is set by `org-before-change-function'. `org-table-align'
1946 sets it back to nil.")
1947 (defvar org-mode-hook nil)
1948 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
1949 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
1953 (define-derived-mode org-mode outline-mode "Org"
1954 "Outline-based notes management and organizer, alias
1955 \"Carstens outline-mode for keeping track of everything.\"
1957 Org-mode develops organizational tasks around a NOTES file which
1958 contains information about projects as plain text. Org-mode is
1959 implemented on top of outline-mode, which is ideal to keep the content
1960 of large files well structured. It supports ToDo items, deadlines and
1961 time stamps, which magically appear in the diary listing of the Emacs
1962 calendar. Tables are easily created with a built-in table editor.
1963 Plain text URL-like links connect to websites, emails (VM), Usenet
1964 messages (Gnus), BBDB entries, and any files related to the project.
1965 For printing and sharing of notes, an Org-mode file (or a part of it)
1966 can be exported as a structured ASCII or HTML file.
1968 The following commands are available:
1971 (easy-menu-add org-org-menu)
1972 (easy-menu-add org-tbl-menu)
1973 (org-install-agenda-files-menu)
1974 (setq outline-regexp "\\*+")
1975 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
1976 (setq outline-level 'org-outline-level)
1977 (if org-startup-truncated (setq truncate-lines t))
1978 (org-set-regexps-and-options)
1979 (set (make-local-variable 'font-lock-unfontify-region-function)
1980 'org-unfontify-region)
1981 ;; Activate before-change-function
1982 (set (make-local-variable 'org-table-may-need-update) t)
1983 (make-local-hook 'before-change-functions) ;; needed for XEmacs
1984 (add-hook 'before-change-functions 'org-before-change-function nil
1986 ;; FIXME: The following does not work because isearch-mode-end-hook
1987 ;; is called *before* the visibility overlays as removed.
1988 ;; There should be another hook then for me to be used.
1989 ;; (make-local-hook 'isearch-mode-end-hook) ;; needed for XEmacs
1990 ;; (add-hook 'isearch-mode-end-hook 'org-show-hierarchy-above nil
1992 ;; Paragraphs and auto-filling
1993 (org-set-autofill-regexps)
1994 ;; Settings for Calc embedded mode
1995 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
1996 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
1997 (if (and org-insert-mode-line-in-empty-file
1999 (= (point-min) (point-max)))
2000 (insert " -*- mode: org -*-\n\n"))
2002 ;; Get rid of Outline menus, they are not needed
2003 ;; Need to do this here because define-derived-mode sets up
2004 ;; the keymap so late.
2007 (delete-menu-item '("Headings"))
2008 (delete-menu-item '("Show"))
2009 (delete-menu-item '("Hide"))
2010 (set-menubar-dirty-flag))
2011 (define-key org-mode-map [menu-bar headings] 'undefined)
2012 (define-key org-mode-map [menu-bar hide] 'undefined)
2013 (define-key org-mode-map [menu-bar show] 'undefined))
2015 (unless org-inhibit-startup
2016 (if org-startup-with-deadline-check
2017 (call-interactively 'org-check-deadlines)
2019 ((eq org-startup-folded t)
2021 ((eq org-startup-folded 'content)
2022 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2023 (org-cycle '(4)) (org-cycle '(4))))))))
2025 (defsubst org-current-line (&optional pos)
2026 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2029 ;; FIXME: Do we need to copy?
2030 (defun org-string-props (string &rest properties)
2031 "Add PROPERTIES to string."
2032 (add-text-properties 0 (length string) properties string)
2037 (defvar org-mouse-map (make-sparse-keymap))
2038 (define-key org-mouse-map
2039 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2040 (define-key org-mouse-map
2041 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2042 (when org-tab-follows-link
2043 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2044 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2045 (when org-return-follows-link
2046 (define-key org-mouse-map [(return)] 'org-open-at-point)
2047 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2049 (require 'font-lock)
2051 (defconst org-non-link-chars "\t\n\r|<>\000")
2052 (defconst org-link-regexp
2053 (if org-allow-space-in-links
2055 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2057 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2059 "Regular expression for matching links.")
2060 (defconst org-link-maybe-angles-regexp
2061 (concat "<?\\(" org-link-regexp "\\)>?")
2062 "Matches a link and optionally surrounding angle brackets.")
2063 (defconst org-protected-link-regexp
2064 (concat "\000" org-link-regexp "\000")
2065 "Matches a link and optionally surrounding angle brackets.")
2067 (defconst org-ts-lengths
2068 (cons (length (format-time-string (car org-time-stamp-formats)))
2069 (length (format-time-string (cdr org-time-stamp-formats))))
2070 "This holds the lengths of the two different time formats.")
2071 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2072 "Regular expression for fast time stamp matching.")
2073 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2074 "Regular expression for fast time stamp matching.")
2075 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2076 "Regular expression matching time strings for analysis.")
2077 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2078 "Regular expression matching time stamps, with groups.")
2079 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2080 "Regular expression matching a time stamp range.")
2081 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2082 org-ts-regexp "\\)?")
2083 "Regular expression matching a time stamp or time stamp range.")
2085 (defun org-activate-links (limit)
2086 "Run through the buffer and add overlays to links."
2087 (if (re-search-forward org-link-regexp limit t)
2089 (add-text-properties (match-beginning 0) (match-end 0)
2090 (list 'mouse-face 'highlight
2091 'keymap org-mouse-map))
2094 (defun org-activate-dates (limit)
2095 "Run through the buffer and add overlays to dates."
2096 (if (re-search-forward org-tsr-regexp limit t)
2098 (add-text-properties (match-beginning 0) (match-end 0)
2099 (list 'mouse-face 'highlight
2100 'keymap org-mouse-map))
2103 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2104 "Matches CamelCase words, possibly with a star before it.")
2105 (defun org-activate-camels (limit)
2106 "Run through the buffer and add overlays to dates."
2107 (if (re-search-forward org-camel-regexp limit t)
2109 (add-text-properties (match-beginning 0) (match-end 0)
2110 (list 'mouse-face 'highlight
2111 'keymap org-mouse-map))
2114 (defun org-activate-tags (limit)
2115 (if (re-search-forward "[ \t]\\(:[A-Za-z_:]+:\\)[ \r\n]" limit t)
2117 (add-text-properties (match-beginning 1) (match-end 1)
2118 (list 'mouse-face 'highlight
2119 'keymap org-mouse-map))
2122 (defun org-font-lock-level ()
2124 (org-back-to-heading t)
2125 (- (match-end 0) (match-beginning 0))))
2127 (defun org-outline-level ()
2129 (looking-at outline-regexp)
2130 (if (match-beginning 1)
2131 (+ (org-get-string-indentation (match-string 1)) 1000)
2132 (- (match-end 0) (match-beginning 0)))))
2134 (defvar org-font-lock-keywords nil)
2136 (defun org-set-font-lock-defaults ()
2137 (let ((org-font-lock-extra-keywords
2139 '(org-activate-links (0 'org-link t))
2140 '(org-activate-dates (0 'org-link t))
2141 '(org-activate-camels (0 'org-link t))
2142 '(org-activate-tags (1 'org-link t))
2143 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2144 '(1 'org-warning t))
2145 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2146 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2147 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2148 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2149 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
2151 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
2153 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
2155 ; (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
2156 ; '(1 'org-warning t))
2157 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2158 "\\|" org-quote-string "\\)\\>")
2159 '(1 'org-special-keyword t))
2160 '("^#.*" (0 'font-lock-comment-face t))
2161 (if org-fontify-done-headline
2162 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2163 '(1 'org-done t) '(2 'org-headline-done t))
2164 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2166 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2168 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2169 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2170 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2172 (set (make-local-variable 'org-font-lock-keywords)
2174 (if org-noutline-p ; FIXME: I am not sure if eval will work
2175 ; on XEmacs if noutline is ever ported
2176 `((eval . (list "^\\(\\*+\\).*"
2177 ,(if org-level-color-stars-only 1 0)
2179 (% (- (match-end 1) (match-beginning 1) 1)
2183 `(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
2184 (,(if org-level-color-stars-only 2 0)
2185 (nth (% (- (match-end 2) (match-beginning 2) 1)
2189 org-font-lock-extra-keywords))
2190 (set (make-local-variable 'font-lock-defaults)
2191 '(org-font-lock-keywords t nil nil backward-paragraph))
2192 (kill-local-variable 'font-lock-keywords) nil))
2194 (defun org-unfontify-region (beg end &optional maybe_loudly)
2195 "Remove fontification and activation overlays from links."
2196 (font-lock-default-unfontify-region beg end)
2197 (let* ((buffer-undo-list t)
2198 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2199 (inhibit-modification-hooks t)
2200 deactivate-mark buffer-file-name buffer-file-truename)
2201 (remove-text-properties beg end '(mouse-face nil keymap nil))))
2203 ;;; Visibility cycling
2205 (defvar org-cycle-global-status nil)
2206 (defvar org-cycle-subtree-status nil)
2207 (defun org-cycle (&optional arg)
2208 "Visibility cycling for Org-mode.
2210 - When this function is called with a prefix argument, rotate the entire
2211 buffer through 3 states (global cycling)
2212 1. OVERVIEW: Show only top-level headlines.
2213 2. CONTENTS: Show all headlines of all levels, but no body text.
2214 3. SHOW ALL: Show everything.
2216 - When point is at the beginning of a headline, rotate the subtree started
2217 by this line through 3 different states (local cycling)
2218 1. FOLDED: Only the main headline is shown.
2219 2. CHILDREN: The main headline and the direct children are shown. From
2220 this state, you can move to one of the children and
2222 3. SUBTREE: Show the entire subtree, including body text.
2224 - When there is a numeric prefix, go up to a heading with level ARG, do
2225 a `show-subtree' and return to the previous cursor position. If ARG
2226 is negative, go up that many levels.
2228 - When point is not at the beginning of a headline, execute
2229 `indent-relative', like TAB normally does. See the option
2230 `org-cycle-emulate-tab' for details.
2232 - Special case: if point is the the beginning of the buffer and there is
2233 no headline in line 1, this function will act as if called with prefix arg."
2236 (if (or (and (bobp) (not (looking-at outline-regexp)))
2238 ;; special case: use global cycling
2241 (let ((outline-regexp
2242 (if org-cycle-include-plain-lists
2243 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2248 ((org-at-table-p 'any)
2249 ;; Enter the table or move to the next field in the table
2250 (or (org-table-recognize-table.el)
2252 (org-table-justify-field-maybe)
2253 (org-table-next-field))))
2255 ((eq arg t) ;; Global cycling
2258 ((and (eq last-command this-command)
2259 (eq org-cycle-global-status 'overview))
2260 ;; We just created the overview - now do table of contents
2261 ;; This can be slow in very large buffers, so indicate action
2262 (message "CONTENTS...")
2264 ;; Visit all headings and show their offspring
2265 (goto-char (point-max))
2267 (while (and (progn (condition-case nil
2268 (outline-previous-visible-heading 1)
2269 (error (goto-char (point-min))))
2271 (looking-at outline-regexp))
2273 (if (bobp) (throw 'exit nil))))
2274 (message "CONTENTS...done"))
2275 (setq org-cycle-global-status 'contents)
2276 (run-hook-with-args 'org-cycle-hook 'contents))
2278 ((and (eq last-command this-command)
2279 (eq org-cycle-global-status 'contents))
2280 ;; We just showed the table of contents - now show everything
2282 (message "SHOW ALL")
2283 (setq org-cycle-global-status 'all)
2284 (run-hook-with-args 'org-cycle-hook 'all))
2287 ;; Default action: go to overview
2289 (message "OVERVIEW")
2290 (setq org-cycle-global-status 'overview)
2291 (run-hook-with-args 'org-cycle-hook 'overview))))
2294 ;; Show-subtree, ARG levels up from here.
2296 (org-back-to-heading)
2297 (outline-up-heading (if (< arg 0) (- arg)
2298 (- (outline-level) arg)))
2299 (org-show-subtree)))
2301 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2302 ;; At a heading: rotate between three different views
2303 (org-back-to-heading)
2304 (let ((goal-column 0) eoh eol eos)
2305 ;; First, some boundaries
2307 (org-back-to-heading)
2309 (beginning-of-line 2)
2310 (while (and (not (eobp)) ;; this is like `next-line'
2311 (get-char-property (1- (point)) 'invisible))
2312 (beginning-of-line 2)) (setq eol (point)))
2313 (outline-end-of-heading) (setq eoh (point))
2314 (org-end-of-subtree t) (setq eos (point))
2315 (outline-next-heading))
2316 ;; Find out what to do next and set `this-command'
2319 ;; Nothing is hidden behind this heading
2320 (message "EMPTY ENTRY")
2321 (setq org-cycle-subtree-status nil))
2323 ;; Entire subtree is hidden in one line: open it
2326 (message "CHILDREN")
2327 (setq org-cycle-subtree-status 'children)
2328 (run-hook-with-args 'org-cycle-hook 'children))
2329 ((and (eq last-command this-command)
2330 (eq org-cycle-subtree-status 'children))
2331 ;; We just showed the children, now show everything.
2334 (setq org-cycle-subtree-status 'subtree)
2335 (run-hook-with-args 'org-cycle-hook 'subtree))
2337 ;; Default action: hide the subtree.
2340 (setq org-cycle-subtree-status 'folded)
2341 (run-hook-with-args 'org-cycle-hook 'folded)))))
2344 (buffer-read-only (org-back-to-heading))
2345 ((if (and (eq org-cycle-emulate-tab 'white)
2346 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2348 (eq org-cycle-emulate-tab t))
2349 (if (and (looking-at "[ \n\r\t]")
2350 (string-match "^[ \t]*$" (buffer-substring
2351 (point-at-bol) (point))))
2353 (beginning-of-line 1)
2354 (and (looking-at "[ \t]+") (replace-match ""))))
2358 (org-back-to-heading)
2361 (defun org-optimize-window-after-visibility-change (state)
2362 "Adjust the window after a change in outline visibility.
2363 This function is the default value of the hook `org-cycle-hook'."
2365 ((eq state 'overview) (org-first-headline-recenter 1))
2366 ((eq state 'content) nil)
2367 ((eq state 'all) nil)
2368 ((eq state 'folded) nil)
2369 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2370 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2372 (defun org-subtree-end-visible-p ()
2373 "Is the end of the current subtree visible?"
2374 (pos-visible-in-window-p
2375 (save-excursion (org-end-of-subtree t) (point))))
2377 (defun org-first-headline-recenter (&optional N)
2378 "Move cursor to the first headline and recenter the headline.
2379 Optional argument N means, put the headline into the Nth line of the window."
2380 (goto-char (point-min))
2381 (when (re-search-forward (concat "^" outline-regexp) nil t)
2383 (recenter (prefix-numeric-value N))))
2385 (defvar org-goto-window-configuration nil)
2386 (defvar org-goto-marker nil)
2387 (defvar org-goto-map (make-sparse-keymap))
2388 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2389 (while (setq cmd (pop cmds))
2390 (substitute-key-definition cmd cmd org-goto-map global-map)))
2391 (define-key org-goto-map "\C-m" 'org-goto-ret)
2392 (define-key org-goto-map [(left)] 'org-goto-left)
2393 (define-key org-goto-map [(right)] 'org-goto-right)
2394 (define-key org-goto-map [(?q)] 'org-goto-quit)
2395 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2396 (define-key org-goto-map "\C-i" 'org-cycle)
2397 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2398 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2399 (define-key org-goto-map "n" 'outline-next-visible-heading)
2400 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2401 (define-key org-goto-map "f" 'outline-forward-same-level)
2402 (define-key org-goto-map "b" 'outline-backward-same-level)
2403 (define-key org-goto-map "u" 'outline-up-heading)
2404 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2405 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2406 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2407 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2408 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2409 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2410 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2412 (defconst org-goto-help
2413 "Select a location to jump to, press RET
2414 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2417 "Go to a different location of the document, keeping current visibility.
2419 When you want to go to a different location in a document, the fastest way
2420 is often to fold the entire buffer and then dive into the tree. This
2421 method has the disadvantage, that the previous location will be folded,
2422 which may not be what you want.
2424 This command works around this by showing a copy of the current buffer in
2425 overview mode. You can dive into the tree in that copy, to find the
2426 location you want to reach. When pressing RET, the command returns to the
2427 original buffer in which the visibility is still unchanged. It then jumps
2428 to the new location, making it and the headline hierarchy above it visible."
2430 (let* ((org-goto-start-pos (point))
2432 (org-get-location (current-buffer) org-goto-help)))
2435 (goto-char selected-point)
2436 (if (org-invisible-p) (org-show-hierarchy-above)))
2439 (defun org-get-location (buf help)
2440 "Let the user select a location in the Org-mode buffer BUF.
2441 This function uses a recursive edit. It returns the selected position
2443 (let (org-selected-point)
2445 (save-window-excursion
2446 (delete-other-windows)
2447 (switch-to-buffer (get-buffer-create "*org-goto*"))
2448 (with-output-to-temp-buffer "*Help*"
2450 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2451 (setq buffer-read-only nil)
2453 (insert-buffer-substring buf)
2454 (let ((org-startup-truncated t)
2455 (org-startup-folded t)
2456 (org-startup-with-deadline-check nil))
2458 (setq buffer-read-only t)
2459 (if (boundp 'org-goto-start-pos)
2460 (goto-char org-goto-start-pos)
2461 (goto-char (point-min)))
2462 (org-beginning-of-line)
2463 (message "Select location and press RET")
2464 ;; now we make sure that during selection, ony very few keys work
2465 ;; and that it is impossible to switch to another window.
2466 (let ((gm (current-global-map))
2467 (overriding-local-map org-goto-map))
2470 (use-global-map org-goto-map)
2472 (use-global-map gm)))))
2473 (kill-buffer "*org-goto*")
2474 org-selected-point))
2476 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2477 (defun org-goto-ret (&optional arg)
2478 "Finish org-goto by going to the new location."
2480 (setq org-selected-point (point)
2481 current-prefix-arg arg)
2484 (defun org-goto-left ()
2485 "Finish org-goto by going to the new location."
2487 (if (org-on-heading-p)
2489 (beginning-of-line 1)
2490 (setq org-selected-point (point)
2491 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2493 (error "Not on a heading")))
2495 (defun org-goto-right ()
2496 "Finish org-goto by going to the new location."
2498 (if (org-on-heading-p)
2500 (outline-end-of-subtree)
2501 (or (eobp) (forward-char 1))
2502 (setq org-selected-point (point)
2503 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2505 (error "Not on a heading")))
2507 (defun org-goto-quit ()
2508 "Finish org-goto without cursor motion."
2510 (setq org-selected-point nil)
2513 ;;; Promotion, Demotion, Inserting new headlines
2515 (defvar org-ignore-region nil
2516 "To temporarily disable the active region.")
2518 (defun org-insert-heading (&optional force-heading)
2519 "Insert a new heading or item with same depth at point.
2522 (when (or force-heading (not (org-insert-item)))
2523 (let* ((head (save-excursion
2525 (org-back-to-heading)
2526 (error (outline-next-heading)))
2527 (prog1 (match-string 0)
2528 (funcall outline-level)))))
2529 (unless (bolp) (newline))
2532 (save-excursion (newline-and-indent)))
2533 (unless (equal (char-before) ?\ )
2535 (run-hooks 'org-insert-heading-hook))))
2537 (defun org-insert-item ()
2538 "Insert a new item at the current level.
2539 Return t when tings worked, nil when we are not in an item."
2540 (when (save-excursion
2543 (org-beginning-of-item)
2547 (unless (bolp) (newline))
2548 (insert (match-string 0))
2549 (org-maybe-renumber-ordered-list)
2552 (defun org-insert-todo-heading (arg)
2553 "Insert a new heading with the same level and TODO state as current heading.
2554 If the heading has no TODO state, or if the state is DONE, use the first
2555 state (TODO by default). Also with prefix arg, force first state."
2557 (org-insert-heading)
2559 (org-back-to-heading)
2560 (outline-previous-heading)
2561 (looking-at org-todo-line-regexp))
2563 (not (match-beginning 2))
2564 (equal (match-string 2) org-done-string))
2565 (insert (car org-todo-keywords) " ")
2566 (insert (match-string 2) " ")))
2568 (defun org-promote-subtree ()
2569 "Promote the entire subtree.
2570 See also `org-promote'."
2573 (org-map-tree 'org-promote)))
2575 (defun org-demote-subtree ()
2576 "Demote the entire subtree. See `org-demote'.
2577 See also `org-promote'."
2580 (org-map-tree 'org-demote)))
2582 (defun org-do-promote ()
2583 "Promote the current heading higher up the tree.
2584 If the region is active in `transient-mark-mode', promote all headings
2588 (if (org-region-active-p)
2589 (org-map-region 'org-promote (region-beginning) (region-end))
2591 (org-fix-position-after-promote))
2593 (defun org-do-demote ()
2594 "Demote the current heading lower down the tree.
2595 If the region is active in `transient-mark-mode', demote all headings
2599 (if (org-region-active-p)
2600 (org-map-region 'org-demote (region-beginning) (region-end))
2602 (org-fix-position-after-promote))
2604 (defun org-fix-position-after-promote ()
2605 "Make sure that after pro/demotion cursor position is right."
2606 (and (equal (char-after) ?\ )
2607 (equal (char-before) ?*)
2610 (defun org-promote ()
2611 "Promote the current heading higher up the tree.
2612 If the region is active in `transient-mark-mode', promote all headings
2614 (org-back-to-heading t)
2615 (let* ((level (save-match-data (funcall outline-level)))
2616 (up-head (make-string (1- level) ?*)))
2617 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2618 (replace-match up-head nil t)
2619 ;; Fixup tag positioning
2620 (and org-auto-align-tags (org-set-tags nil t))
2621 (if org-adapt-indentation
2622 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2624 (defun org-demote ()
2625 "Demote the current heading lower down the tree.
2626 If the region is active in `transient-mark-mode', demote all headings
2628 (org-back-to-heading t)
2629 (let* ((level (save-match-data (funcall outline-level)))
2630 (down-head (make-string (1+ level) ?*)))
2631 (replace-match down-head nil t)
2632 ;; Fixup tag positioning
2633 (and org-auto-align-tags (org-set-tags nil t))
2634 (if org-adapt-indentation
2635 (org-fixup-indentation "^ " " " "^\\S-"))))
2637 (defun org-map-tree (fun)
2638 "Call FUN for every heading underneath the current one."
2639 (org-back-to-heading)
2640 (let ((level (outline-level)))
2644 (outline-next-heading)
2645 (> (funcall outline-level) level))
2649 (defun org-map-region (fun beg end)
2650 "Call FUN for every heading between BEG and END."
2651 (let ((org-ignore-region t))
2653 (setq end (copy-marker end))
2655 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2659 (outline-next-heading)
2664 (defun org-fixup-indentation (from to prohibit)
2665 "Change the indentation in the current entry by re-replacing FROM with TO.
2666 However, if the regexp PROHIBIT matches at all, don't do anything.
2667 This is being used to change indentation along with the length of the
2668 heading marker. But if there are any lines which are not indented, nothing
2671 (let ((end (save-excursion (outline-next-heading)
2673 (unless (save-excursion (re-search-forward prohibit end t))
2674 (while (re-search-forward from end t)
2676 (beginning-of-line 2)))
2677 (move-marker end nil))))
2679 ;;; Vertical tree motion, cutting and pasting of subtrees
2681 (defun org-move-subtree-up (&optional arg)
2682 "Move the current subtree up past ARG headlines of the same level."
2684 (org-move-subtree-down (- (prefix-numeric-value arg))))
2686 (defun org-move-subtree-down (&optional arg)
2687 "Move the current subtree down past ARG headlines of the same level."
2689 (setq arg (prefix-numeric-value arg))
2690 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2691 'outline-get-last-sibling))
2692 (ins-point (make-marker))
2696 (org-back-to-heading)
2699 (save-excursion (outline-end-of-heading)
2700 (setq folded (org-invisible-p)))
2701 (outline-end-of-subtree))
2702 (outline-next-heading)
2704 ;; Find insertion point, with error handling
2707 (or (and (funcall movfunc) (looking-at outline-regexp))
2708 (progn (goto-char beg)
2709 (error "Cannot move past superior level or buffer limit")))
2710 (setq cnt (1- cnt)))
2712 ;; Moving forward - still need to move over subtree
2713 (progn (outline-end-of-subtree)
2714 (outline-next-heading)
2715 (if (not (or (looking-at (concat "^" outline-regexp))
2718 (move-marker ins-point (point))
2719 (setq txt (buffer-substring beg end))
2720 (delete-region beg end)
2722 (goto-char ins-point)
2723 (if folded (hide-subtree))
2724 (move-marker ins-point nil)))
2726 (defvar org-subtree-clip ""
2727 "Clipboard for cut and paste of subtrees.
2728 This is actually only a copy of the kill, because we use the normal kill
2729 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2731 (defvar org-subtree-clip-folded nil
2732 "Was the last copied subtree folded?
2733 This is used to fold the tree back after pasting.")
2735 (defun org-cut-subtree ()
2736 "Cut the current subtree into the clipboard.
2737 This is a short-hand for marking the subtree and then cutting it."
2739 (org-copy-subtree 'cut))
2741 (defun org-copy-subtree (&optional cut)
2742 "Cut the current subtree into the clipboard.
2743 This is a short-hand for marking the subtree and then copying it.
2744 If CUT is non nil, actually cut the subtree."
2746 (let (beg end folded)
2747 (org-back-to-heading)
2750 (save-excursion (outline-end-of-heading)
2751 (setq folded (org-invisible-p)))
2752 (outline-end-of-subtree))
2753 (if (equal (char-after) ?\n) (forward-char 1))
2757 (setq org-subtree-clip-folded folded)
2758 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2759 (setq org-subtree-clip (current-kill 0))
2760 (message "%s: Subtree with %d characters"
2761 (if cut "Cut" "Copied")
2762 (length org-subtree-clip)))))
2764 (defun org-paste-subtree (&optional level tree)
2765 "Paste the clipboard as a subtree, with modification of headline level.
2766 The entire subtree is promoted or demoted in order to match a new headline
2767 level. By default, the new level is derived from the visible headings
2768 before and after the insertion point, and taken to be the inferior headline
2769 level of the two. So if the previous visible heading is level 3 and the
2770 next is level 4 (or vice versa), level 4 will be used for insertion.
2771 This makes sure that the subtree remains an independent subtree and does
2772 not swallow low level entries.
2774 You can also force a different level, either by using a numeric prefix
2775 argument, or by inserting the heading marker by hand. For example, if the
2776 cursor is after \"*****\", then the tree will be shifted to level 5.
2778 If you want to insert the tree as is, just use \\[yank].
2780 If optional TREE is given, use this text instead of the kill ring."
2782 (unless (org-kill-is-subtree-p tree)
2784 (substitute-command-keys
2785 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2786 (let* ((txt (or tree (current-kill 0)))
2787 (^re (concat "^\\(" outline-regexp "\\)"))
2788 (re (concat "\\(" outline-regexp "\\)"))
2789 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2791 (old-level (if (string-match ^re txt)
2792 (- (match-end 0) (match-beginning 0))
2794 (force-level (cond (level (prefix-numeric-value level))
2796 ^re_ (buffer-substring (point-at-bol) (point)))
2797 (- (match-end 0) (match-beginning 0)))
2799 (previous-level (save-excursion
2802 (outline-previous-visible-heading 1)
2804 (- (match-end 0) (match-beginning 0))
2807 (next-level (save-excursion
2810 (outline-next-visible-heading 1)
2812 (- (match-end 0) (match-beginning 0))
2815 (new-level (or force-level (max previous-level next-level)))
2816 (shift (if (or (= old-level -1)
2818 (= old-level new-level))
2820 (- new-level old-level)))
2822 (delta (if (> shift 0) -1 1))
2823 (func (if (> shift 0) 'org-demote 'org-promote))
2825 ;; Remove the forces level indicator
2827 (delete-region (point-at-bol) (point)))
2828 ;; Make sure we start at the beginning of an empty line
2829 (if (not (bolp)) (insert "\n"))
2830 (if (not (looking-at "[ \t]*$"))
2831 (progn (insert "\n") (backward-char 1)))
2837 ;; Shift if necessary
2839 (message "Pasted at level %d, without shift" new-level)
2841 (narrow-to-region beg end)
2842 (while (not (= shift 0))
2843 (org-map-region func (point-min) (point-max))
2844 (setq shift (+ delta shift)))
2845 (goto-char (point-min))
2846 (message "Pasted at level %d, with shift by %d levels"
2848 (if (and (eq org-subtree-clip (current-kill 0))
2849 org-subtree-clip-folded)
2850 ;; The tree was folded before it was killed/copied
2853 (defun org-kill-is-subtree-p (&optional txt)
2854 "Check if the current kill is an outline subtree, or a set of trees.
2855 Returns nil if kill does not start with a headline, or if the first
2856 headline level is not the largest headline level in the tree.
2857 So this will actually accept several entries of equal levels as well,
2858 which is OK for `org-paste-subtree'.
2859 If optional TXT is given, check this string instead of the current kill."
2860 (let* ((kill (or txt (current-kill 0) ""))
2861 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2862 (- (match-end 0) (match-beginning 0))))
2863 (re (concat "^" outline-regexp))
2865 (if (not start-level)
2866 nil ;; does not even start with a heading
2868 (while (setq start (string-match re kill (1+ start)))
2869 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2873 ;;; Plain list items
2875 (defun org-at-item-p ()
2876 "Is point in a line starting a hand-formatted item?"
2877 (let ((llt org-plain-list-ordered-item-terminator))
2879 (goto-char (point-at-bol))
2882 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2883 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2884 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
2885 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
2887 (defun org-get-indentation ()
2888 "Get the indentation of the current line, ionterpreting tabs."
2890 (beginning-of-line 1)
2891 (skip-chars-forward " \t")
2894 (defun org-beginning-of-item ()
2895 "Go to the beginning of the current hand-formatted item.
2896 If the cursor is not in an item, throw an error."
2898 (limit (save-excursion (org-back-to-heading)
2899 (beginning-of-line 2) (point)))
2902 (beginning-of-line 1)
2903 (beginning-of-line 1)
2904 (skip-chars-forward " \t")
2905 (setq ind (current-column))
2908 (beginning-of-line 0)
2909 (if (< (point) limit) (throw 'exit nil))
2910 (unless (looking-at " \t]*$")
2911 (skip-chars-forward " \t")
2912 (setq ind1 (current-column))
2914 (throw 'exit (org-at-item-p))))))
2917 (error "Not in an item")))))
2919 (defun org-end-of-item ()
2920 "Go to the beginning of the current hand-formatted item.
2921 If the cursor is not in an item, throw an error."
2923 (limit (save-excursion (outline-next-heading) (point)))
2924 (ind (save-excursion
2925 (org-beginning-of-item)
2926 (skip-chars-forward " \t")
2931 (beginning-of-line 2)
2932 (if (>= (point) limit) (throw 'exit t))
2933 (unless (looking-at "[ \t]*$")
2934 (skip-chars-forward " \t")
2935 (setq ind1 (current-column))
2936 (if (<= ind1 ind) (throw 'exit t)))))
2937 (beginning-of-line 1)
2939 (error "Not in an item"))))
2941 (defun org-move-item-down (arg)
2942 "Move the plain list item at point down, i.e. swap with following item.
2943 Subitems (items with larger indentation are considered part of the item,
2944 so this really moves item trees."
2946 (let (beg end ind ind1 (pos (point)) txt)
2947 (org-beginning-of-item)
2949 (setq ind (org-get-indentation))
2952 (setq ind1 (org-get-indentation))
2953 (if (and (org-at-item-p) (= ind ind1))
2956 (setq txt (buffer-substring beg end))
2958 (delete-region beg end))
2962 (org-maybe-renumber-ordered-list))
2964 (error "Cannot move this item further down"))))
2966 (defun org-move-item-up (arg)
2967 "Move the plain list item at point up, i.e. swap with previous item.
2968 Subitems (items with larger indentation are considered part of the item,
2969 so this really moves item trees."
2971 (let (beg end ind ind1 (pos (point)) txt)
2972 (org-beginning-of-item)
2974 (setq ind (org-get-indentation))
2980 (beginning-of-line 0)
2981 (if (looking-at "[ \t]*$")
2983 (if (<= (setq ind1 (org-get-indentation)) ind)
2986 (org-beginning-of-item)
2987 (error (goto-char beg)
2988 (error "Cannot move this item further up")))
2989 (setq ind1 (org-get-indentation))
2990 (if (and (org-at-item-p) (= ind ind1))
2992 (setq txt (buffer-substring beg end))
2994 (delete-region beg end))
2998 (org-maybe-renumber-ordered-list))
3000 (error "Cannot move this item further up"))))
3002 (defun org-maybe-renumber-ordered-list ()
3003 "Renumber the ordered list at point if setup allows it.
3004 This tests the user option `org-auto-renumber-ordered-lists' before
3005 doing the renumbering."
3006 (and org-auto-renumber-ordered-lists
3009 (org-renumber-ordered-list 1)))
3011 (defun org-get-string-indentation (s)
3012 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3013 (let ((n -1) (i 0) (w tab-width) c)
3015 (while (< (setq n (1+ n)) (length s))
3017 (cond ((= c ?\ ) (setq i (1+ i)))
3018 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3019 (t (throw 'exit t)))))
3022 (defun org-renumber-ordered-list (arg)
3023 "Renumber an ordered plain list.
3024 Cursor neext to be in the first line of an item, the line that starts
3025 with something like \"1.\" or \"2)\"."
3027 (unless (and (org-at-item-p)
3028 (match-beginning 3))
3029 (error "This is not an ordered list"))
3030 (let ((line (org-current-line))
3031 (col (current-column))
3032 (ind (org-get-string-indentation
3033 (buffer-substring (point-at-bol) (match-beginning 3))))
3034 ;; (term (substring (match-string 3) -1))
3036 ;; find where this list begins
3040 (beginning-of-line 0)
3041 (if (looking-at "[ \t]*$") (throw 'next t))
3042 (skip-chars-forward " \t") (setq ind1 (current-column))
3043 (if (or (< ind1 ind)
3045 (not (org-at-item-p))))
3047 ;; Walk forward and replace these numbers
3051 (beginning-of-line 2)
3052 (if (eobp) (throw 'exit nil))
3053 (if (looking-at "[ \t]*$") (throw 'next nil))
3054 (skip-chars-forward " \t") (setq ind1 (current-column))
3055 (if (> ind1 ind) (throw 'next t))
3056 (if (< ind1 ind) (throw 'exit t))
3057 (if (not (org-at-item-p)) (throw 'exit nil))
3058 (if (not (match-beginning 3))
3059 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3060 (delete-region (match-beginning 3) (1- (match-end 3)))
3061 (goto-char (match-beginning 3))
3062 (insert (format "%d" (setq n (1+ n)))))))
3064 (move-to-column col)))
3066 (defvar org-last-indent-begin-marker (make-marker))
3067 (defvar org-last-indent-end-marker (make-marker))
3070 (defun org-outdent-item (arg)
3071 "Outdent a local list item."
3073 (org-indent-item (- arg)))
3075 (defun org-indent-item (arg)
3076 "Indent a local list item."
3078 (unless (org-at-item-p)
3079 (error "Not on an item"))
3080 (let (beg end ind ind1)
3081 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3082 (setq beg org-last-indent-begin-marker
3083 end org-last-indent-end-marker)
3084 (org-beginning-of-item)
3085 (setq beg (move-marker org-last-indent-begin-marker (point)))
3087 (setq end (move-marker org-last-indent-end-marker (point))))
3089 (skip-chars-forward " \t") (setq ind (current-column))
3090 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3091 (while (< (point) end)
3092 (beginning-of-line 1)
3093 (skip-chars-forward " \t") (setq ind1 (current-column))
3094 (delete-region (point-at-bol) (point))
3095 (indent-to-column (+ ind1 arg))
3096 (beginning-of-line 2))
3101 (defun org-archive-subtree ()
3102 "Move the current subtree to the archive.
3103 The archive can be a certain top-level heading in the current file, or in
3104 a different file. The tree will be moved to that location, the subtree
3105 heading be marked DONE, and the current time will be added."
3107 ;; Save all relevant TODO keyword-relatex variables
3108 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3109 (tr-org-todo-keywords org-todo-keywords)
3110 (tr-org-todo-interpretation org-todo-interpretation)
3111 (tr-org-done-string org-done-string)
3112 (tr-org-todo-regexp org-todo-regexp)
3113 (tr-org-todo-line-regexp org-todo-line-regexp)
3114 (this-buffer (current-buffer))
3115 file heading buffer level newfile-p)
3116 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3118 (setq file (format (match-string 1 org-archive-location)
3119 (file-name-nondirectory (buffer-file-name)))
3120 heading (match-string 2 org-archive-location)))
3121 (error "Invalid `org-archive-location'"))
3122 (if (> (length file) 0)
3123 (setq newfile-p (not (file-exists-p file))
3124 buffer (find-file-noselect file))
3125 (setq buffer (current-buffer)))
3127 (error "Cannot access file \"%s\"" file))
3128 (if (and (> (length heading) 0)
3129 (string-match "^\\*+" heading))
3130 (setq level (match-end 0))
3131 (setq heading nil level 0))
3133 ;; We first only copy, in case something goes wrong
3134 ;; we need to protect this-command, to avoid kill-region sets it,
3135 ;; which would lead to duplication of subtrees
3136 (let (this-command) (org-copy-subtree))
3138 ;; Enforce org-mode for the archive buffer
3139 (if (not (eq major-mode 'org-mode))
3140 ;; Force the mode for future visits.
3141 (let ((org-insert-mode-line-in-empty-file t))
3142 (call-interactively 'org-mode)))
3144 (goto-char (point-max))
3145 (insert (format "\nArchived entries from file %s\n\n"
3146 (buffer-file-name this-buffer))))
3147 ;; Force the TODO keywords of the original buffer
3148 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3149 (org-todo-keywords tr-org-todo-keywords)
3150 (org-todo-interpretation tr-org-todo-interpretation)
3151 (org-done-string tr-org-done-string)
3152 (org-todo-regexp tr-org-todo-regexp)
3153 (org-todo-line-regexp tr-org-todo-line-regexp))
3154 (goto-char (point-min))
3157 (if (re-search-forward
3158 (concat "\\(^\\|\r\\)"
3159 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3161 (goto-char (match-end 0))
3162 ;; Heading not found, just insert it at the end
3163 (goto-char (point-max))
3164 (or (bolp) (insert "\n"))
3165 (insert "\n" heading "\n")
3167 ;; Make the heading visible, and the following as well
3168 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3169 (if (re-search-forward
3170 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3172 (progn (goto-char (match-beginning 0)) (insert "\n")
3173 (beginning-of-line 0))
3174 (goto-char (point-max)) (insert "\n")))
3175 (goto-char (point-max)) (insert "\n"))
3177 (org-paste-subtree (1+ level))
3178 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3179 (if org-archive-mark-done
3180 (org-todo (length org-todo-keywords)))
3181 ;; Move cursor to right after the TODO keyword
3182 (when org-archive-stamp-time
3183 (beginning-of-line 1)
3184 (looking-at org-todo-line-regexp)
3185 (goto-char (or (match-end 2) (match-beginning 3)))
3186 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3189 ;; Save the buffer, if it is not the same buffer.
3190 (if (not (eq this-buffer buffer)) (save-buffer))))
3191 ;; Here we are back in the original buffer. Everything seems to have
3192 ;; worked. So now cut the tree and finish up.
3193 (let (this-command) (org-cut-subtree))
3194 (if (looking-at "[ \t]*$") (kill-line))
3195 (message "Subtree archived %s"
3196 (if (eq this-buffer buffer)
3197 (concat "under heading: " heading)
3198 (concat "in file: " (abbreviate-file-name file))))))
3202 (defun org-complete (&optional arg)
3203 "Perform completion on word at point.
3204 At the beginning of a headline, this completes TODO keywords as given in
3205 `org-todo-keywords'.
3206 If the current word is preceded by a backslash, completes the TeX symbols
3207 that are supported for HTML support.
3208 If the current word is preceded by \"#+\", completes special words for
3209 setting file options.
3210 At all other locations, this simply calls `ispell-complete-word'."
3213 (let* ((end (point))
3214 (beg1 (save-excursion
3215 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3216 (skip-chars-backward "a-zA-Z_")
3218 (beg (save-excursion
3219 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3220 (skip-chars-backward "a-zA-Z0-9_:$")
3222 (camel (equal (char-before beg) ?*))
3223 (tag (equal (char-before beg1) ?:))
3224 (texp (equal (char-before beg) ?\\))
3225 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3228 (completion-ignore-case opt)
3235 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3236 (cons (match-string 2 x) (match-string 1 x)))
3237 (org-split-string (org-get-current-options) "\n")))
3241 ((string-match "\\`\\*+[ \t]*\\'"
3242 (buffer-substring (point-at-bol) beg))
3244 (mapcar 'list org-todo-keywords))
3248 (goto-char (point-min))
3249 (while (re-search-forward org-todo-line-regexp nil t)
3250 (push (list (org-make-org-heading-camel (match-string 3)))
3253 (tag (setq type :tag beg beg1)
3254 (org-get-buffer-tags))
3255 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3256 (pattern (buffer-substring-no-properties beg end))
3257 (completion (try-completion pattern table)))
3258 (cond ((eq completion t)
3259 (if (equal type :opt)
3260 (insert (substring (cdr (assoc (upcase pattern) table))
3261 (length pattern)))))
3263 (message "Can't find completion for \"%s\"" pattern)
3265 ((not (string= pattern completion))
3266 (delete-region beg end)
3267 (if (string-match " +$" completion)
3268 (setq completion (replace-match "" t t completion)))
3270 (if (get-buffer-window "*Completions*")
3271 (delete-window (get-buffer-window "*Completions*")))
3272 (if (assoc completion table)
3273 (if (eq type :todo) (insert " ")
3274 (if (eq type :tag) (insert ":"))))
3275 (if (and (equal type :opt) (assoc completion table))
3276 (message "%s" (substitute-command-keys
3277 "Press \\[org-complete] again to insert example settings"))))
3279 (message "Making completion list...")
3280 (let ((list (sort (all-completions pattern table) 'string<)))
3281 (with-output-to-temp-buffer "*Completions*"
3282 (display-completion-list list)))
3283 (message "Making completion list...%s" "done"))))))
3285 ;;; Comments, TODO and DEADLINE
3287 (defun org-toggle-comment ()
3288 "Change the COMMENT state of an entry."
3291 (org-back-to-heading)
3292 (if (looking-at (concat outline-regexp
3293 "\\( +\\<" org-comment-string "\\>\\)"))
3294 (replace-match "" t t nil 1)
3295 (if (looking-at outline-regexp)
3297 (goto-char (match-end 0))
3298 (insert " " org-comment-string))))))
3300 (defvar org-last-todo-state-is-todo nil
3301 "This is non-nil when the last TODO state change led to a TODO state.
3302 If the last change removed the TODO tag or switched to DONE, then
3305 (defun org-todo (&optional arg)
3306 "Change the TODO state of an item.
3307 The state of an item is given by a keyword at the start of the heading,
3309 *** TODO Write paper
3312 The different keywords are specified in the variable `org-todo-keywords'. By
3313 default the available states are \"TODO\" and \"DONE\".
3314 So for this example: when the item starts with TODO, it is changed to DONE.
3315 When it starts with DONE, the DONE is removed. And when neither TODO nor
3316 DONE are present, add TODO at the beginning of the heading.
3318 With prefix arg, use completion to determined the new state. With numeric
3319 prefix arg, switch to that state."
3322 (org-back-to-heading)
3323 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3324 (or (looking-at (concat " +" org-todo-regexp " *"))
3326 (let* ((this (match-string 1))
3327 (completion-ignore-case t)
3328 (member (member this org-todo-keywords))
3332 ;; Read a state with completion
3333 (completing-read "State: " (mapcar (lambda(x) (list x))
3338 (if tail (car tail) nil)
3339 (car org-todo-keywords)))
3341 (if (equal member org-todo-keywords)
3344 (nth (- (length org-todo-keywords) (length tail) 2)
3348 ;; user requests a specific state
3349 (nth (1- (prefix-numeric-value arg))
3351 ((null member) (car org-todo-keywords))
3352 ((null tail) nil) ;; -> first entry
3353 ((eq org-todo-interpretation 'sequence)
3355 ((memq org-todo-interpretation '(type priority))
3356 (if (eq this-command last-command)
3358 (if (> (length tail) 0) org-done-string nil)))
3360 (next (if state (concat " " state " ") " ")))
3361 (replace-match next t t)
3362 (setq org-last-todo-state-is-todo
3363 (not (equal state org-done-string)))
3365 (if (equal state org-done-string)
3369 ;; Fixup tag positioning
3370 (and org-auto-align-tags (org-set-tags nil t))
3371 (run-hooks 'org-after-todo-state-change-hook)))
3372 ;; Fixup cursor location if close to the keyword
3373 (if (and (outline-on-heading-p)
3375 (save-excursion (beginning-of-line 1)
3376 (looking-at org-todo-line-regexp))
3377 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3379 (goto-char (or (match-end 2) (match-end 1)))
3382 (defun org-log-done (&optional undone)
3383 "Add a time stamp logging that a TODO entry has been closed.
3384 When UNDONE is non-nil, remove such a time stamg again."
3388 (org-back-to-heading t)
3390 (looking-at (concat outline-regexp " *"))
3391 (goto-char (match-end 0))
3392 (setq col (current-column))
3393 (outline-next-heading)
3396 (when (re-search-forward (concat
3398 (regexp-quote org-closed-string)
3399 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3400 (delete-region (match-beginning 1) (match-end 1)))
3402 (org-back-to-heading t)
3403 (skip-chars-forward "^\n\r")
3404 (goto-char (min (1+ (point)) (point-max)))
3405 (when (not (member (char-before) '(?\r ?\n)))
3408 (insert org-closed-string " "
3410 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3414 (defun org-show-todo-tree (arg)
3415 "Make a compact tree which shows all headlines marked with TODO.
3416 The tree will show the lines where the regexp matches, and all higher
3417 headlines above the match.
3418 With \\[universal-argument] prefix, also show the DONE entries.
3419 With a numeric prefix N, construct a sparse tree for the Nth element
3420 of `org-todo-keywords'."
3422 (let ((case-fold-search nil)
3424 (cond ((null arg) org-not-done-regexp)
3425 ((equal arg '(4)) org-todo-regexp)
3426 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3427 (regexp-quote (nth (1- (prefix-numeric-value arg))
3428 org-todo-keywords)))
3429 (t (error "Invalid prefix argument: %s" arg)))))
3430 (message "%d TODO entries found"
3431 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3433 (defun org-deadline ()
3434 "Insert the DEADLINE: string to make a deadline.
3435 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3436 to modify it to the correct date."
3439 org-deadline-string " "
3440 (format-time-string (car org-time-stamp-formats)
3441 (org-read-date nil 'to-time)))
3442 (message "%s" (substitute-command-keys
3443 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3445 (defun org-schedule ()
3446 "Insert the SCHEDULED: string to schedule a TODO item.
3447 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3448 to modify it to the correct date."
3451 org-scheduled-string " "
3452 (format-time-string (car org-time-stamp-formats)
3453 (org-read-date nil 'to-time)))
3454 (message "%s" (substitute-command-keys
3455 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3458 (defun org-occur (regexp &optional callback)
3459 "Make a compact tree which shows all matches of REGEXP.
3460 The tree will show the lines where the regexp matches, and all higher
3461 headlines above the match. It will also show the heading after the match,
3462 to make sure editing the matching entry is easy.
3463 if CALLBACK is non-nil, it is a function which is called to confirm
3464 that the match should indeed be shown."
3465 (interactive "sRegexp: ")
3466 (org-remove-occur-highlights nil nil t)
3467 (setq regexp (org-check-occur-regexp regexp))
3470 (goto-char (point-min))
3472 (while (re-search-forward regexp nil t)
3473 (when (or (not callback)
3474 (save-match-data (funcall callback)))
3476 (org-highlight-new-match (match-beginning 0) (match-end 0))
3477 (org-show-hierarchy-above))))
3478 (make-local-hook 'before-change-functions) ; needed for XEmacs
3479 (add-hook 'before-change-functions 'org-remove-occur-highlights
3481 (run-hooks 'org-occur-hook)
3483 (message "%d match(es) for regexp %s" cnt regexp))
3486 (defun org-show-hierarchy-above ()
3487 "Make sure point and the headings hierarchy above is visible."
3489 (if (org-on-heading-p t)
3490 (org-flag-heading nil) ; only show the heading
3491 (and (org-invisible-p) (org-show-hidden-entry))) ; show entire entry
3493 (and org-show-following-heading
3494 (outline-next-heading)
3495 (org-flag-heading nil))) ; show the next heading
3496 (when org-show-hierarchy-above
3497 (save-excursion ; show all higher headings
3498 (while (and (condition-case nil
3499 (progn (org-up-heading-all 1) t)
3502 (org-flag-heading nil))))))
3504 ;; Overlay compatibility functions
3505 (defun org-make-overlay (beg end &optional buffer)
3506 (if org-xemacs-p (make-extent beg end buffer) (make-overlay beg end buffer)))
3507 (defun org-delete-overlay (ovl)
3508 (if org-xemacs-p (delete-extent ovl) (delete-overlay ovl)))
3509 (defun org-detatch-overlay (ovl)
3510 (if org-xemacs-p (detach-extent ovl) (delete-overlay ovl)))
3511 (defun org-move-overlay (ovl beg end &optional buffer)
3513 (set-extent-endpoints ovl beg end buffer)
3514 (move-overlay ovl beg end buffer)))
3515 (defun org-overlay-put (ovl prop value)
3517 (set-extent-property ovl prop value)
3518 (overlay-put ovl prop value)))
3520 (defvar org-occur-highlights nil)
3521 (defun org-highlight-new-match (beg end)
3522 "Highlight from BEG to END and mark the highlight is an occur headline."
3523 (let ((ov (org-make-overlay beg end)))
3524 (org-overlay-put ov 'face 'secondary-selection)
3525 (push ov org-occur-highlights)))
3527 (defun org-remove-occur-highlights (&optional beg end noremove)
3528 "Remove the occur highlights from the buffer.
3529 BEG and END are ignored. If NOREMOVE is nil, remove this function
3530 from the before-change-functions in the current buffer."
3532 (mapc 'org-delete-overlay org-occur-highlights)
3533 (setq org-occur-highlights nil)
3535 (remove-hook 'before-change-functions
3536 'org-remove-occur-highlights 'local)))
3540 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3541 "Regular expression matching the priority indicator.")
3543 (defvar org-remove-priority-next-time nil)
3545 (defun org-priority-up ()
3546 "Increase the priority of the current item."
3550 (defun org-priority-down ()
3551 "Decrease the priority of the current item."
3553 (org-priority 'down))
3555 (defun org-priority (&optional action)
3556 "Change the priority of an item by ARG.
3557 ACTION can be set, up, or down."
3559 (setq action (or action 'set))
3560 (let (current new news have remove)
3562 (org-back-to-heading)
3563 (if (looking-at org-priority-regexp)
3564 (setq current (string-to-char (match-string 2))
3566 (setq current org-default-priority))
3569 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3570 (setq new (read-char-exclusive))
3571 (cond ((equal new ?\ ) (setq remove t))
3572 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3573 (error "Priority must be between `%c' and `%c'"
3574 ?A org-lowest-priority))))
3576 (setq new (1- current)))
3578 (setq new (1+ current)))
3579 (t (error "Invalid action")))
3580 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3581 (setq news (format "%c" new))
3584 (replace-match "" t t nil 1)
3585 (replace-match news t t nil 2))
3587 (error "No priority cookie found in line")
3588 (looking-at org-todo-line-regexp)
3591 (goto-char (match-end 2))
3592 (insert " [#" news "]"))
3593 (goto-char (match-beginning 3))
3594 (insert "[#" news "] ")))))
3596 (message "Priority removed")
3597 (message "Priority of current item set to %s" news))))
3600 (defun org-get-priority (s)
3601 "Find priority cookie and return priority."
3603 (if (not (string-match org-priority-regexp s))
3604 (* 1000 (- org-lowest-priority org-default-priority))
3605 (* 1000 (- org-lowest-priority
3606 (string-to-char (match-string 2 s)))))))
3610 (defvar org-last-changed-timestamp nil)
3612 (defun org-time-stamp (arg)
3613 "Prompt for a date/time and insert a time stamp.
3614 If the user specifies a time like HH:MM, or if this command is called
3615 with a prefix argument, the time stamp will contain date and time.
3616 Otherwise, only the date will be included. All parts of a date not
3617 specified by the user will be filled in from the current date/time.
3618 So if you press just return without typing anything, the time stamp
3619 will represent the current date/time. If there is already a timestamp
3620 at the cursor, it will be modified."
3622 (let ((fmt (if arg (cdr org-time-stamp-formats)
3623 (car org-time-stamp-formats)))
3624 (org-time-was-given nil)
3627 ((and (org-at-timestamp-p)
3628 (eq last-command 'org-time-stamp)
3629 (eq this-command 'org-time-stamp))
3631 (setq time (let ((this-command this-command))
3632 (org-read-date arg 'totime)))
3633 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3634 (insert (format-time-string fmt time)))
3635 ((org-at-timestamp-p)
3636 (setq time (let ((this-command this-command))
3637 (org-read-date arg 'totime)))
3638 (and (org-at-timestamp-p) (replace-match
3639 (setq org-last-changed-timestamp
3640 (format-time-string fmt time))
3642 (message "Timestamp updated"))
3644 (setq time (let ((this-command this-command))
3645 (org-read-date arg 'totime)))
3646 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3647 (insert (format-time-string fmt time))))))
3649 (defun org-time-stamp-inactive (&optional arg)
3650 "Insert an inactive time stamp.
3651 An inactive time stamp is enclosed in square brackets instead of angle
3652 brackets. It is inactive in the sense that it does not trigger agenda entries,
3653 does not link to the calendar and cannot be changed with the S-cursor keys.
3654 So these are more for recording a certain time/date."
3655 ;; FIXME: Would it be better not to ask for a date/time here?
3657 (let ((fmt (if arg (cdr org-time-stamp-formats)
3658 (car org-time-stamp-formats)))
3659 (org-time-was-given nil)
3661 (setq time (org-read-date arg 'totime))
3662 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3663 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3664 (insert (format-time-string fmt time))))
3666 (defvar org-date-ovl (org-make-overlay 1 1))
3667 (org-overlay-put org-date-ovl 'face 'org-warning)
3668 (org-detatch-overlay org-date-ovl)
3670 ;;; FIXME: Make the function take "Fri" as "next friday"
3671 ;;; because these are mostly being used to record the current time.
3672 (defun org-read-date (&optional with-time to-time)
3673 "Read a date and make things smooth for the user.
3674 The prompt will suggest to enter an ISO date, but you can also enter anything
3675 which will at least partially be understood by `parse-time-string'.
3676 Unrecognized parts of the date will default to the current day, month ,year,
3677 hour and minute. For example,
3678 3-2-5 --> 2003-02-05
3679 feb 15 --> currentyear-02-15
3680 sep 12 9 --> 2009-09-12
3681 12:45 --> today 12:45
3682 22 sept 0:34 --> currentyear-09-22 0:34
3683 12 --> currentyear-currentmonth-12
3685 The function understands only English month and weekday abbreviations,
3686 but this can be configured with the variables `parse-time-months' and
3687 `parse-time-weekdays'.
3689 While prompting, a calendar is popped up - you can also select the
3690 date with the mouse (button 1). The calendar shows a period of three
3691 month. To scroll it to other months, use the keys `>' and `<'.
3692 If you don't like the calendar, turn it off with
3693 \(setq org-popup-calendar-for-date-prompt nil).
3695 With optional argument TO-TIME, the date will immediately be converted
3696 to an internal time.
3697 With an optional argument WITH-TIME, the prompt will suggest to also
3698 insert a time. Note that when WITH-TIME is not set, you can still
3699 enter a time, and this function will inform the calling routine about
3700 this change. The calling routine may then choose to change the format
3701 used to insert the time stamp into the buffer to include the time."
3702 (let* ((default-time
3703 ;; Default time is either today, or, when entering a range,
3707 (concat org-ts-regexp "--\\=")
3711 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3712 (parse-time-string (match-string 1))))
3714 (calendar-move-hook nil)
3715 (view-diary-entries-initially nil)
3716 (timestr (format-time-string
3717 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3718 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3720 second minute hour day month year tl)
3722 (if org-popup-calendar-for-date-prompt
3723 ;; Also show a calendar for date selection
3724 ;; Copied (with modifications) from planner.el by John Wiegley
3726 (save-window-excursion
3728 (calendar-forward-day (- (time-to-days default-time)
3729 (calendar-absolute-from-gregorian
3730 (calendar-current-date))))
3731 (org-eval-in-calendar nil)
3732 (let* ((old-map (current-local-map))
3733 (map (copy-keymap calendar-mode-map))
3734 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3735 (define-key map (kbd "RET") 'org-calendar-select)
3736 (define-key map (if org-xemacs-p [button1] [mouse-1])
3737 'org-calendar-select-mouse)
3738 (define-key map (if org-xemacs-p [button2] [mouse-2])
3739 'org-calendar-select-mouse)
3740 (define-key minibuffer-local-map [(meta shift left)]
3741 (lambda () (interactive)
3742 (org-eval-in-calendar '(calendar-backward-month 1))))
3743 (define-key minibuffer-local-map [(meta shift right)]
3744 (lambda () (interactive)
3745 (org-eval-in-calendar '(calendar-forward-month 1))))
3746 (define-key minibuffer-local-map [(shift up)]
3747 (lambda () (interactive)
3748 (org-eval-in-calendar '(calendar-backward-week 1))))
3749 (define-key minibuffer-local-map [(shift down)]
3750 (lambda () (interactive)
3751 (org-eval-in-calendar '(calendar-forward-week 1))))
3752 (define-key minibuffer-local-map [(shift left)]
3753 (lambda () (interactive)
3754 (org-eval-in-calendar '(calendar-backward-day 1))))
3755 (define-key minibuffer-local-map [(shift right)]
3756 (lambda () (interactive)
3757 (org-eval-in-calendar '(calendar-forward-day 1))))
3758 (define-key minibuffer-local-map ">"
3759 (lambda () (interactive)
3760 (org-eval-in-calendar '(scroll-calendar-left 1))))
3761 (define-key minibuffer-local-map "<"
3762 (lambda () (interactive)
3763 (org-eval-in-calendar '(scroll-calendar-right 1))))
3767 (setq ans (read-string prompt "" nil nil))
3768 (setq ans (or ans1 ans2 ans)))
3769 (use-local-map old-map)))))
3770 ;; Naked prompt only
3771 (setq ans (read-string prompt "" nil timestr)))
3772 (org-detatch-overlay org-date-ovl)
3775 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3777 (setq year (if (match-end 2)
3778 (string-to-number (match-string 2 ans))
3779 (string-to-number (format-time-string "%Y")))
3780 month (string-to-number (match-string 3 ans))
3781 day (string-to-number (match-string 4 ans)))
3782 (if (< year 100) (setq year (+ 2000 year)))
3783 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3785 (setq tl (parse-time-string ans)
3786 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3787 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3788 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3789 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3790 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3791 second (or (nth 0 tl) 0))
3792 (if (and (boundp 'org-time-was-given)
3794 (setq org-time-was-given t))
3795 (if (< year 100) (setq year (+ 2000 year)))
3797 (encode-time second minute hour day month year)
3798 (if (or (nth 1 tl) (nth 2 tl))
3799 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3800 (format "%04d-%02d-%02d" year month day)))))
3802 (defun org-eval-in-calendar (form)
3803 "Eval FORM in the calendar window and return to current window.
3804 Also, store the cursor date in variable ans2."
3805 (let ((sw (selected-window)))
3806 (select-window (get-buffer-window "*Calendar*"))
3808 (when (calendar-cursor-to-date)
3809 (let* ((date (calendar-cursor-to-date))
3810 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3811 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3812 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
3813 (select-window sw)))
3815 (defun org-calendar-select ()
3816 "Return to `org-read-date' with the date currently selected.
3817 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3819 (when (calendar-cursor-to-date)
3820 (let* ((date (calendar-cursor-to-date))
3821 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3822 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3823 (if (active-minibuffer-window) (exit-minibuffer))))
3825 (defun org-calendar-select-mouse (ev)
3826 "Return to `org-read-date' with the date currently selected.
3827 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3829 (mouse-set-point ev)
3830 (when (calendar-cursor-to-date)
3831 (let* ((date (calendar-cursor-to-date))
3832 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3833 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3834 (if (active-minibuffer-window) (exit-minibuffer))))
3836 (defun org-check-deadlines (ndays)
3837 "Check if there are any deadlines due or past due.
3838 A deadline is considered due if it happens within `org-deadline-warning-days'
3839 days from today's date. If the deadline appears in an entry marked DONE,
3840 it is not shown. The prefix arg NDAYS can be used to test that many
3841 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3843 (let* ((org-warn-days
3845 ((equal ndays '(4)) 100000)
3846 (ndays (prefix-numeric-value ndays))
3847 (t org-deadline-warning-days)))
3848 (case-fold-search nil)
3849 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3852 (and (let ((d1 (time-to-days (current-time)))
3854 (org-time-string-to-time (match-string 1)))))
3855 (< (- d2 d1) org-warn-days))
3856 (not (org-entry-is-done-p))))))
3857 (message "%d deadlines past-due or due within %d days"
3858 (org-occur regexp callback)
3861 (defun org-evaluate-time-range (&optional to-buffer)
3862 "Evaluate a time range by computing the difference between start and end.
3863 Normally the result is just printed in the echo area, but with prefix arg
3864 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3865 If the time range is actually in a table, the result is inserted into the
3867 For time difference computation, a year is assumed to be exactly 365
3868 days in order to avoid rounding problems."
3871 (unless (org-at-date-range-p)
3872 (goto-char (point-at-bol))
3873 (re-search-forward org-tr-regexp (point-at-eol) t))
3874 (if (not (org-at-date-range-p))
3875 (error "Not at a time-stamp range, and none found in current line")))
3876 (let* ((ts1 (match-string 1))
3877 (ts2 (match-string 2))
3878 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3879 (match-end (match-end 0))
3880 (time1 (org-time-string-to-time ts1))
3881 (time2 (org-time-string-to-time ts2))
3882 (t1 (time-to-seconds time1))
3883 (t2 (time-to-seconds time2))
3884 (diff (abs (- t2 t1)))
3885 (negative (< (- t2 t1) 0))
3886 ;; (ys (floor (* 365 24 60 60)))
3889 (fy "%dy %dd %02d:%02d")
3891 (fd "%dd %02d:%02d")
3895 ;; FIXME: Should I re-introduce years, make year refer to same date?
3896 ;; This would be the only useful way to have years, actually.
3898 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3900 d (floor (/ diff ds)) diff (mod diff ds)
3901 h (floor (/ diff hs)) diff (mod diff hs)
3902 m (floor (/ diff 60)))
3903 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3905 d (floor (+ (/ diff ds) 0.5))
3908 (message (org-make-tdiff-string y d h m))
3909 (when (org-at-table-p)
3910 (goto-char match-end)
3912 (and (looking-at " *|") (goto-char (match-end 0))))
3914 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3916 (if negative (insert " -"))
3917 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3918 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3919 (insert " " (format fh h m))))
3920 (if align (org-table-align))
3921 (message "Time difference inserted"))))
3923 (defun org-make-tdiff-string (y d h m)
3926 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3928 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3930 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3932 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3934 (apply 'format fmt (nreverse l))))
3936 (defun org-time-string-to-time (s)
3937 (apply 'encode-time (org-parse-time-string s)))
3939 (defun org-parse-time-string (s &optional nodefault)
3940 "Parse the standard Org-mode time string.
3941 This should be a lot faster than the normal `parse-time-string'.
3942 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3943 hour and minute fields will be nil if not given."
3944 (if (string-match org-ts-regexp1 s)
3946 (if (or (match-beginning 8) (not nodefault))
3947 (string-to-number (or (match-string 8 s) "0")))
3948 (if (or (match-beginning 7) (not nodefault))
3949 (string-to-number (or (match-string 7 s) "0")))
3950 (string-to-number (match-string 4 s))
3951 (string-to-number (match-string 3 s))
3952 (string-to-number (match-string 2 s))
3956 (defun org-timestamp-up (&optional arg)
3957 "Increase the date item at the cursor by one.
3958 If the cursor is on the year, change the year. If it is on the month or
3959 the day, change that.
3960 With prefix ARG, change by that many units."
3962 (org-timestamp-change (prefix-numeric-value arg)))
3964 (defun org-timestamp-down (&optional arg)
3965 "Decrease the date item at the cursor by one.
3966 If the cursor is on the year, change the year. If it is on the month or
3967 the day, change that.
3968 With prefix ARG, change by that many units."
3970 (org-timestamp-change (- (prefix-numeric-value arg))))
3972 (defun org-timestamp-up-day (&optional arg)
3973 "Increase the date in the time stamp by one day.
3974 With prefix ARG, change that many days."
3976 (if (and (not (org-at-timestamp-p))
3979 (org-timestamp-change (prefix-numeric-value arg) 'day)))
3981 (defun org-timestamp-down-day (&optional arg)
3982 "Decrease the date in the time stamp by one day.
3983 With prefix ARG, change that many days."
3985 (if (and (not (org-at-timestamp-p))
3988 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
3990 (defsubst org-pos-in-match-range (pos n)
3991 (and (match-beginning n)
3992 (<= (match-beginning n) pos)
3993 (>= (match-end n) pos)))
3995 (defun org-at-timestamp-p ()
3996 "Determine if the cursor is in or at a timestamp."
3998 (let* ((tsr org-ts-regexp2)
4000 (ans (or (looking-at tsr)
4002 (skip-chars-backward "^<\n\r\t")
4003 (if (> (point) 1) (backward-char 1))
4004 (and (looking-at tsr)
4005 (> (- (match-end 0) pos) -1))))))
4006 (and (boundp 'org-ts-what)
4009 ((org-pos-in-match-range pos 2) 'year)
4010 ((org-pos-in-match-range pos 3) 'month)
4011 ((org-pos-in-match-range pos 7) 'hour)
4012 ((org-pos-in-match-range pos 8) 'minute)
4013 ((or (org-pos-in-match-range pos 4)
4014 (org-pos-in-match-range pos 5)) 'day)
4018 (defun org-timestamp-change (n &optional what)
4019 "Change the date in the time stamp at point.
4020 The date will be changed by N times WHAT. WHAT can be `day', `month',
4021 `year', `minute', `second'. If WHAT is not given, the cursor position
4022 in the timestamp determines what will be changed."
4023 (let ((fmt (car org-time-stamp-formats))
4027 (if (not (org-at-timestamp-p))
4028 (error "Not at a timestamp"))
4029 (setq org-ts-what (or what org-ts-what))
4030 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4031 (- (match-end 0) (match-beginning 0))))
4033 (cdr org-time-stamp-formats)
4034 (car org-time-stamp-formats)))
4035 (setq ts (match-string 0))
4037 (setq time0 (org-parse-time-string ts))
4041 (list (or (car time0) 0))
4042 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4043 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4044 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4045 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4046 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4048 (if (eq what 'calendar)
4052 (set-buffer "*Calendar*")
4053 (calendar-cursor-to-date)))))
4054 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4055 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4056 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4057 (setcar time0 (or (car time0) 0))
4058 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4059 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4060 (setq time (apply 'encode-time time0))))
4061 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4063 ;; Try to recenter the calendar window, if any
4064 (if (and org-calendar-follow-timestamp-change
4065 (get-buffer-window "*Calendar*" t)
4066 (memq org-ts-what '(day month year)))
4067 (org-recenter-calendar (time-to-days time)))))
4069 (defun org-recenter-calendar (date)
4070 "If the calendar is visible, recenter it to DATE."
4071 (let* ((win (selected-window))
4072 (cwin (get-buffer-window "*Calendar*" t))
4073 (calendar-move-hook nil))
4075 (select-window cwin)
4076 (calendar-goto-date (if (listp date) date
4077 (calendar-gregorian-from-absolute date)))
4078 (select-window win))))
4080 (defun org-goto-calendar (&optional arg)
4081 "Go to the Emacs calendar at the current date.
4082 If there is a time stamp in the current line, go to that date.
4083 A prefix ARG can be used force the current date."
4085 (let ((tsr org-ts-regexp) diff
4086 (calendar-move-hook nil)
4087 (view-diary-entries-initially nil))
4088 (if (or (org-at-timestamp-p)
4090 (beginning-of-line 1)
4091 (looking-at (concat ".*" tsr))))
4092 (let ((d1 (time-to-days (current-time)))
4094 (org-time-string-to-time (match-string 1)))))
4095 (setq diff (- d2 d1))))
4097 (calendar-goto-today)
4098 (if (and diff (not arg)) (calendar-forward-day diff))))
4100 (defun org-date-from-calendar ()
4101 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4102 If there is already a time stamp at the cursor position, update it."
4104 (org-timestamp-change 0 'calendar))
4106 ;;; Agenda, and Diary Integration
4110 (defvar org-agenda-mode-map (make-sparse-keymap)
4111 "Keymap for `org-agenda-mode'.")
4113 (defvar org-agenda-menu)
4114 (defvar org-agenda-follow-mode nil)
4115 (defvar org-agenda-show-log nil)
4116 (defvar org-agenda-buffer-name "*Org Agenda*")
4117 (defvar org-agenda-redo-command nil)
4118 (defvar org-agenda-mode-hook nil)
4119 (defvar org-agenda-type nil)
4120 (defvar org-agenda-force-single-file nil)
4123 (defun org-agenda-mode ()
4124 "Mode for time-sorted view on action items in Org-mode files.
4126 The following commands are available:
4128 \\{org-agenda-mode-map}"
4130 (kill-all-local-variables)
4131 (setq major-mode 'org-agenda-mode)
4132 (setq mode-name "Org-Agenda")
4133 (use-local-map org-agenda-mode-map)
4134 (easy-menu-add org-agenda-menu)
4135 (if org-startup-truncated (setq truncate-lines t))
4136 (make-local-hook 'post-command-hook) ; Needed for XEmacs
4137 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4138 (make-local-hook 'pre-command-hook) ; Needed for XEmacs
4139 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4140 (unless org-agenda-keep-modes
4141 (setq org-agenda-follow-mode nil
4142 org-agenda-show-log nil))
4144 '("Agenda") "Agenda Files"
4148 (if (get 'org-agenda-files 'org-restrict)
4149 "Restricted to single file"
4151 '(customize-variable 'org-agenda-files)
4152 (not (get 'org-agenda-files 'org-restrict)))
4154 (mapcar 'org-file-menu-entry (org-agenda-files))))
4155 (org-agenda-set-mode-name)
4157 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4158 (list 'org-agenda-mode-hook)))
4160 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4161 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4162 (define-key org-agenda-mode-map " " 'org-agenda-show)
4163 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4164 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4165 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4166 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4167 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4168 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4169 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4170 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4171 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4172 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4173 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4174 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4176 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4177 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4178 (while l (define-key org-agenda-mode-map
4179 (int-to-string (pop l)) 'digit-argument)))
4181 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4182 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4183 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4184 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4185 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4186 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4187 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4188 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4189 (define-key org-agenda-mode-map "n" 'next-line)
4190 (define-key org-agenda-mode-map "p" 'previous-line)
4191 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4192 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4193 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4194 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4195 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4196 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4197 (eval-after-load "calendar"
4198 '(define-key calendar-mode-map org-calendar-to-agenda-key
4199 'org-calendar-goto-agenda))
4200 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4201 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4202 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4203 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4204 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4205 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4206 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4207 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4208 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4209 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4210 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4211 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4212 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4213 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4214 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4215 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4216 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4217 "Local keymap for agenda entries from Org-mode.")
4219 (define-key org-agenda-keymap
4220 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4221 (define-key org-agenda-keymap
4222 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4224 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4228 ["Show" org-agenda-show t]
4229 ["Go To (other window)" org-agenda-goto t]
4230 ["Go To (one window)" org-agenda-switch-to t]
4231 ["Follow Mode" org-agenda-follow-mode
4232 :style toggle :selected org-agenda-follow-mode :active t]
4234 ["Cycle TODO" org-agenda-todo t]
4235 ["Set Tags" org-agenda-set-tags t]
4237 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4238 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4240 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4242 ["Set Priority" org-agenda-priority t]
4243 ["Increase Priority" org-agenda-priority-up t]
4244 ["Decrease Priority" org-agenda-priority-down t]
4245 ["Show Priority" org-agenda-show-priority t])
4247 ;; ["New agenda command" org-agenda t]
4248 ["Rebuild buffer" org-agenda-redo t]
4250 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4251 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4252 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4254 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4255 :style radio :selected (equal org-agenda-ndays 1)]
4256 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4257 :style radio :selected (equal org-agenda-ndays 7)]
4259 ["Show Logbook entries" org-agenda-log-mode
4260 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4261 ["Include Diary" org-agenda-toggle-diary
4262 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4263 ["Use Time Grid" org-agenda-toggle-time-grid
4264 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4266 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4267 ("Calendar Commands"
4268 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4269 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4270 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4271 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4272 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4273 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4275 ["Quit" org-agenda-quit t]
4276 ["Exit and Release Buffers" org-agenda-exit t]
4280 (defun org-agenda (arg)
4281 "Dispatch agenda commands to collect entries to the agenda buffer.
4282 Prompts for a character to select a command. Any prefix arg will be passed
4283 on to the selected command. The default selections are:
4285 a Call `org-agenda' to display the agenda for the current day or week.
4286 t Call `org-todo-list' to display the global todo list.
4287 T Call `org-todo-list' to display the global todo list, select only
4288 entries with a specific TODO keyword (the user get a prompt).
4289 m Call `org-tags-view' to display headlines with tags matching
4290 a condition (the user is prompted for the condition).
4291 M like `m', but select only TODO entries, no ordinary headlines.
4293 More commands can be added by configuring the variable
4294 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4295 searches can be pre-defined in this way.
4297 If the current buffer is in Org-mode and visiting a file, you can also
4298 first press `1' to indicate that the agenda should be temporarily (until the
4299 next use of \\[org-agenda]) restricted to the current file."
4302 (let ((restrict-ok (and (buffer-file-name) (eq major-mode 'org-mode)))
4303 (custom org-agenda-custom-commands)
4304 c entry key type string)
4305 (put 'org-agenda-files 'org-restrict nil)
4306 (save-window-excursion
4307 (delete-other-windows)
4308 (switch-to-buffer-other-window " *Agenda Commands*")
4311 "Press key for an agenda command:
4312 --------------------------------
4313 a Agenda for current week or day
4314 t List of all TODO entries T Entries with special TODO kwd
4315 m Match a TAGS query M Like m, but only TODO entries.
4316 C Configure your own agenda commands")
4317 (while (setq entry (pop custom))
4318 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4319 (insert (format "\n%-4s%-14s: %s"
4322 ((eq type 'tags) "Tags query")
4323 ((eq type 'todo) "TODO keyword")
4324 ((eq type 'tags-tree) "Tags tree")
4325 ((eq type 'todo-tree) "TODO kwd tree")
4326 ((eq type 'occur-tree) "Occur tree")
4328 (org-string-props string 'face 'org-link))))
4329 (goto-char (point-min))
4330 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4331 (message "Press key for agenda command%s"
4332 (if restrict-ok ", or [1] to restrict to current file" ""))
4333 (setq c (read-char-exclusive))
4337 (put 'org-agenda-files 'org-restrict (list (buffer-file-name)))
4338 (error "Cannot restrict agenda to current buffer"))
4339 (message "Press key for agenda command%s"
4340 (if restrict-ok " (restricted to current file)" ""))
4341 (setq c (read-char-exclusive))
4343 (require 'calendar) ; FIXME: can we avoid this for some commands?
4344 ;; For example the todo list should not need it (but does...)
4346 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4347 ((equal c ?a) (call-interactively 'org-agenda-list))
4348 ((equal c ?t) (call-interactively 'org-todo-list))
4350 (setq current-prefix-arg (or arg '(4)))
4351 (call-interactively 'org-todo-list))
4352 ((equal c ?m) (call-interactively 'org-tags-view))
4354 (setq current-prefix-arg (or arg '(4)))
4355 (call-interactively 'org-tags-view))
4356 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4357 (setq type (nth 1 entry) string (nth 2 entry))
4360 (org-tags-view current-prefix-arg string))
4362 (org-todo-list string))
4363 ((eq type 'tags-tree)
4364 (org-check-for-org-mode)
4365 (org-tags-sparse-tree current-prefix-arg string))
4366 ((eq type 'todo-tree)
4367 (org-check-for-org-mode)
4368 (org-occur (concat "^" outline-regexp "[ \t]*"
4369 (regexp-quote string) "\\>")))
4370 ((eq type 'occur-tree)
4371 (org-check-for-org-mode)
4373 (t (error "Invalid custom agenda command type %s" type))))
4374 (t (error "Invalid key"))))))
4376 (defun org-check-for-org-mode ()
4377 "Make sure current buffer is in org-mode. Error if not."
4378 (or (eq major-mode 'org-mode)
4379 (error "Cannot execute org-mode agenda command on buffer in %s."
4382 (defun org-fit-agenda-window ()
4383 "Fit the window to the buffer size."
4384 (and org-fit-agenda-window
4385 (fboundp 'fit-window-to-buffer)
4386 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4387 (/ (frame-height) 2))))
4389 (defun org-agenda-files ()
4390 "Get the list of agenda files."
4391 (or (get 'org-agenda-files 'org-restrict)
4394 (defvar org-agenda-markers nil
4395 "List of all currently active markers created by `org-agenda'.")
4396 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4397 "Creation time of the last agenda marker.")
4399 (defun org-agenda-new-marker (&optional pos)
4400 "Return a new agenda marker.
4401 Org-mode keeps a list of these markers and resets them when they are
4403 (let ((m (copy-marker (or pos (point)))))
4404 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4405 (push m org-agenda-markers)
4408 (defun org-agenda-maybe-reset-markers (&optional force)
4409 "Reset markers created by `org-agenda'. But only if they are old enough."
4411 (> (- (time-to-seconds (current-time))
4412 org-agenda-last-marker-time)
4414 (while org-agenda-markers
4415 (move-marker (pop org-agenda-markers) nil))))
4417 (defvar org-agenda-new-buffers nil
4418 "Buffers created to visit agenda files.")
4420 (defun org-get-agenda-file-buffer (file)
4421 "Get a buffer visiting FILE. If the buffer needs to be created, add
4422 it to the list of buffers which might be released later."
4423 (let ((buf (find-buffer-visiting file)))
4425 buf ; just return it
4426 ;; Make a new buffer and remember it
4427 (setq buf (find-file-noselect file))
4428 (if buf (push buf org-agenda-new-buffers))
4431 (defun org-release-buffers (blist)
4432 "Release all buffers in list, asking the user for confirmation when needed.
4433 When a buffer is unmodified, it is just killed. When modified, it is saved
4434 \(if the user agrees) and then killed."
4436 (while (setq buf (pop blist))
4437 (setq file (buffer-file-name buf))
4438 (when (and (buffer-modified-p buf)
4440 (y-or-n-p (format "Save file %s? " file)))
4441 (with-current-buffer buf (save-buffer)))
4442 (kill-buffer buf))))
4444 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4446 (defun org-timeline (&optional include-all keep-modes)
4447 "Show a time-sorted view of the entries in the current org file.
4448 Only entries with a time stamp of today or later will be listed. With
4449 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4450 under the current date.
4451 If the buffer contains an active region, only check the region for
4455 (org-agenda-maybe-reset-markers 'force)
4456 (org-compile-prefix-format org-timeline-prefix-format)
4458 (dotodo include-all)
4459 (doclosed org-agenda-show-log)
4460 (org-agenda-keep-modes keep-modes)
4461 (entry (buffer-file-name))
4462 (org-agenda-files (list (buffer-file-name)))
4463 (date (calendar-current-date))
4464 (win (selected-window))
4466 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4467 (end (if (org-region-active-p) (region-end) (point-max)))
4468 (day-numbers (org-get-all-dates beg end 'no-ranges
4469 t doclosed)) ; always include today
4470 (today (time-to-days (current-time)))
4471 (org-respect-restriction t)
4475 (setq org-agenda-redo-command
4477 (list 'switch-to-buffer-other-window (current-buffer))
4478 (list 'org-timeline (list 'quote include-all) t)))
4480 ;; Remove past dates from the list of dates.
4481 (setq day-numbers (delq nil (mapcar (lambda(x)
4482 (if (>= x today) x nil))
4484 (switch-to-buffer-other-window
4485 (get-buffer-create org-agenda-buffer-name))
4486 (setq buffer-read-only nil)
4488 (org-agenda-mode) (setq buffer-read-only nil)
4489 (set (make-local-variable 'org-agenda-type) 'timeline)
4490 (if doclosed (push :closed args))
4491 (push :timestamp args)
4492 (if dotodo (push :todo args))
4493 (while (setq d (pop day-numbers))
4494 (if (and (>= d today)
4499 (insert (make-string 79 ?-) "\n")))
4500 (setq date (calendar-gregorian-from-absolute d))
4502 (setq rtn (apply 'org-agenda-get-day-entries
4504 (if (or rtn (equal d today))
4506 (insert (calendar-day-name date) " "
4507 (number-to-string (extract-calendar-day date)) " "
4508 (calendar-month-name (extract-calendar-month date)) " "
4509 (number-to-string (extract-calendar-year date)) "\n")
4510 (put-text-property s (1- (point)) 'face
4513 (put-text-property s (1- (point)) 'org-today t))
4514 (insert (org-finalize-agenda-entries rtn) "\n")
4515 (put-text-property s (1- (point)) 'day d))))
4516 (goto-char (point-min))
4517 (setq buffer-read-only t)
4518 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4520 (when (not org-select-timeline-window)
4525 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4526 "Produce a weekly view from all files in variable `org-agenda-files'.
4527 The view will be for the current week, but from the overview buffer you
4528 will be able to go to other weeks.
4529 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4530 also be shown, under the current date.
4531 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4532 on the days are also shown. See the variable `org-log-done' for how
4534 START-DAY defaults to TODAY, or to the most recent match for the weekday
4535 given in `org-agenda-start-on-weekday'.
4536 NDAYS defaults to `org-agenda-ndays'."
4538 (org-agenda-maybe-reset-markers 'force)
4539 (org-compile-prefix-format org-agenda-prefix-format)
4541 (let* ((org-agenda-start-on-weekday
4542 (if (or (equal ndays 1)
4543 (and (null ndays) (equal 1 org-agenda-ndays)))
4544 nil org-agenda-start-on-weekday))
4545 (org-agenda-keep-modes keep-modes)
4546 (files (copy-sequence (org-agenda-files)))
4547 (win (selected-window))
4548 (today (time-to-days (current-time)))
4549 (sd (or start-day today))
4550 (start (if (or (null org-agenda-start-on-weekday)
4551 (< org-agenda-ndays 7))
4553 (let* ((nt (calendar-day-of-week
4554 (calendar-gregorian-from-absolute sd)))
4555 (n1 org-agenda-start-on-weekday)
4557 (- sd (+ (if (< d 0) 7 0) d)))))
4558 (day-numbers (list start))
4559 (inhibit-redisplay t)
4560 s e rtn rtnall file date d start-pos end-pos todayp nd)
4561 (setq org-agenda-redo-command
4562 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4563 ;; Make the list of days
4564 (setq ndays (or ndays org-agenda-ndays)
4567 (push (1+ (car day-numbers)) day-numbers)
4568 (setq ndays (1- ndays)))
4569 (setq day-numbers (nreverse day-numbers))
4570 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4572 (delete-other-windows)
4573 (switch-to-buffer-other-window
4574 (get-buffer-create org-agenda-buffer-name))))
4575 (setq buffer-read-only nil)
4577 (org-agenda-mode) (setq buffer-read-only nil)
4578 (set (make-local-variable 'org-agenda-type) 'agenda)
4579 (set (make-local-variable 'starting-day) (car day-numbers))
4580 (set (make-local-variable 'include-all-loc) include-all)
4581 (when (and (or include-all org-agenda-include-all-todo)
4582 (member today day-numbers))
4583 (setq files (org-agenda-files)
4585 (while (setq file (pop files))
4587 (org-check-agenda-file file)
4588 (setq date (calendar-gregorian-from-absolute today)
4589 rtn (org-agenda-get-day-entries
4591 (setq rtnall (append rtnall rtn))))
4593 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4594 (add-text-properties (point-min) (1- (point))
4595 (list 'face 'org-link))
4596 (insert (org-finalize-agenda-entries rtnall) "\n")))
4597 (while (setq d (pop day-numbers))
4598 (setq date (calendar-gregorian-from-absolute d)
4600 (if (or (setq todayp (= d today))
4601 (and (not start-pos) (= d sd)))
4602 (setq start-pos (point))
4603 (if (and start-pos (not end-pos))
4604 (setq end-pos (point))))
4605 (setq files (org-agenda-files)
4607 (while (setq file (pop files))
4609 (org-check-agenda-file file)
4610 (if org-agenda-show-log
4611 (setq rtn (org-agenda-get-day-entries
4613 :deadline :scheduled :timestamp :closed))
4614 (setq rtn (org-agenda-get-day-entries
4616 :deadline :scheduled :timestamp)))
4617 (setq rtnall (append rtnall rtn))))
4618 (if org-agenda-include-diary
4620 (require 'diary-lib)
4621 (setq rtn (org-get-entries-from-diary date))
4622 (setq rtnall (append rtnall rtn))))
4623 (if (or rtnall org-agenda-show-all-dates)
4625 (insert (format "%-9s %2d %s %4d\n"
4626 (calendar-day-name date)
4627 (extract-calendar-day date)
4628 (calendar-month-name (extract-calendar-month date))
4629 (extract-calendar-year date)))
4630 (put-text-property s (1- (point)) 'face
4633 (org-finalize-agenda-entries
4634 (org-agenda-add-time-grid-maybe
4637 (put-text-property s (1- (point)) 'day d))))
4638 (goto-char (point-min))
4639 (setq buffer-read-only t)
4640 (org-fit-agenda-window)
4641 (unless (and (pos-visible-in-window-p (point-min))
4642 (pos-visible-in-window-p (point-max)))
4643 (goto-char (1- (point-max)))
4645 (if (not (pos-visible-in-window-p (or start-pos 1)))
4647 (goto-char (or start-pos 1))
4649 (goto-char (or start-pos 1))
4650 (if (not org-select-agenda-window) (select-window win))
4653 (defvar org-select-this-todo-keyword nil)
4656 (defun org-todo-list (arg &optional keep-modes)
4657 "Show all TODO entries from all agenda file in a single list.
4658 The prefix arg can be used to select a specific TODO keyword and limit
4659 the list to these. When using \\[universal-argument], you will be prompted
4660 for a keyword. A numeric prefix directly selects the Nth keyword in
4661 `org-todo-keywords'."
4663 (org-agenda-maybe-reset-markers 'force)
4664 (org-compile-prefix-format org-agenda-prefix-format)
4665 (let* ((org-agenda-keep-modes keep-modes)
4666 (today (time-to-days (current-time)))
4667 (date (calendar-gregorian-from-absolute today))
4668 (win (selected-window))
4669 (kwds org-todo-keywords)
4670 (completion-ignore-case t)
4671 (org-select-this-todo-keyword
4672 (if (stringp arg) arg
4673 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
4674 rtn rtnall files file pos)
4675 (when (equal arg '(4))
4676 (setq org-select-this-todo-keyword
4677 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4679 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4680 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4682 (delete-other-windows)
4683 (switch-to-buffer-other-window
4684 (get-buffer-create org-agenda-buffer-name))))
4685 (setq buffer-read-only nil)
4687 (org-agenda-mode) (setq buffer-read-only nil)
4688 (set (make-local-variable 'org-agenda-type) 'todo)
4689 (set (make-local-variable 'last-arg) arg)
4690 (set (make-local-variable 'org-todo-keywords) kwds)
4691 (set (make-local-variable 'org-agenda-redo-command)
4692 '(org-todo-list (or current-prefix-arg last-arg) t))
4693 (setq files (org-agenda-files)
4695 (while (setq file (pop files))
4697 (org-check-agenda-file file)
4698 (setq rtn (org-agenda-get-day-entries file date :todo))
4699 (setq rtnall (append rtnall rtn))))
4700 (insert "Global list of TODO items of type: ")
4701 (add-text-properties (point-min) (1- (point))
4702 (list 'face 'org-link))
4704 (insert (or org-select-this-todo-keyword "ALL") "\n")
4705 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4708 "Available with `N r': (0)ALL "
4710 (mapconcat (lambda (x)
4711 (format "(%d)%s" (setq n (1+ n)) x))
4712 org-todo-keywords " "))
4714 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4716 (insert (org-finalize-agenda-entries rtnall) "\n"))
4717 (goto-char (point-min))
4718 (setq buffer-read-only t)
4719 (org-fit-agenda-window)
4720 (if (not org-select-agenda-window) (select-window win))))
4722 (defun org-check-agenda-file (file)
4723 "Make sure FILE exists. If not, ask user what to do."
4724 ;; FIXME: this does not correctly change the menus
4725 ;; Could probably be fixed by explicitly going to the buffer where
4726 ;; the call originated.
4727 (when (not (file-exists-p file))
4728 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
4730 (let ((r (downcase (read-char-exclusive))))
4733 (org-remove-file file)
4734 (throw 'nextfile t))
4735 (t (error "Abort"))))))
4737 (defun org-agenda-check-type (error &rest types)
4738 "Check if agenda buffer is of allowed type.
4739 If ERROR is non-nil, throw an error, otherwise just return nil."
4740 (if (memq org-agenda-type types)
4743 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
4746 (defun org-agenda-quit ()
4747 "Exit agenda by removing the window or the buffer."
4749 (let ((buf (current-buffer)))
4750 (if (not (one-window-p)) (delete-window))
4752 (org-agenda-maybe-reset-markers 'force)))
4754 (defun org-agenda-exit ()
4755 "Exit agenda by removing the window or the buffer.
4756 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
4757 Org-mode buffers visited directly by the user will not be touched."
4759 (org-release-buffers org-agenda-new-buffers)
4760 (setq org-agenda-new-buffers nil)
4763 (defun org-agenda-redo ()
4765 When this is the global TODO list, a prefix argument will be interpreted."
4767 (message "Rebuilding agenda buffer...")
4768 (eval org-agenda-redo-command)
4769 (message "Rebuilding agenda buffer...done"))
4771 (defun org-agenda-goto-today ()
4774 (org-agenda-check-type t 'timeline 'agenda)
4775 (if (boundp 'starting-day)
4776 (let ((cmd (car org-agenda-redo-command))
4777 (iall (nth 1 org-agenda-redo-command))
4778 (nday (nth 3 org-agenda-redo-command))
4779 (keep (nth 4 org-agenda-redo-command)))
4780 (eval (list cmd iall nil nday keep)))
4781 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4784 (defun org-agenda-later (arg)
4785 "Go forward in time by `org-agenda-ndays' days.
4786 With prefix ARG, go forward that many times `org-agenda-ndays'."
4788 (org-agenda-check-type t 'agenda)
4789 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4790 (+ starting-day (* arg org-agenda-ndays)) nil t))
4792 (defun org-agenda-earlier (arg)
4793 "Go back in time by `org-agenda-ndays' days.
4794 With prefix ARG, go back that many times `org-agenda-ndays'."
4796 (org-agenda-check-type t 'agenda)
4797 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
4798 (- starting-day (* arg org-agenda-ndays)) nil t))
4800 (defun org-agenda-week-view ()
4801 "Switch to weekly view for agenda."
4803 (org-agenda-check-type t 'agenda)
4804 (setq org-agenda-ndays 7)
4805 (org-agenda-list include-all-loc
4806 (or (get-text-property (point) 'day)
4809 (org-agenda-set-mode-name)
4810 (message "Switched to week view"))
4812 (defun org-agenda-day-view ()
4813 "Switch to weekly view for agenda."
4815 (org-agenda-check-type t 'agenda)
4816 (setq org-agenda-ndays 1)
4817 (org-agenda-list include-all-loc
4818 (or (get-text-property (point) 'day)
4821 (org-agenda-set-mode-name)
4822 (message "Switched to day view"))
4824 (defun org-agenda-next-date-line (&optional arg)
4825 "Jump to the next line indicating a date in agenda buffer."
4827 (org-agenda-check-type t 'agenda 'timeline)
4828 (beginning-of-line 1)
4829 (if (looking-at "^\\S-") (forward-char 1))
4830 (if (not (re-search-forward "^\\S-" nil t arg))
4833 (error "No next date after this line in this buffer")))
4834 (goto-char (match-beginning 0)))
4836 (defun org-agenda-previous-date-line (&optional arg)
4837 "Jump to the next line indicating a date in agenda buffer."
4839 (org-agenda-check-type t 'agenda 'timeline)
4840 (beginning-of-line 1)
4841 (if (not (re-search-backward "^\\S-" nil t arg))
4842 (error "No previous date before this line in this buffer")))
4844 ;; Initialize the highlight
4845 (defvar org-hl (org-make-overlay 1 1))
4846 (org-overlay-put org-hl 'face 'highlight)
4848 (defun org-highlight (begin end &optional buffer)
4849 "Highlight a region with overlay."
4850 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
4851 org-hl begin end (or buffer (current-buffer))))
4853 (defun org-unhighlight ()
4854 "Detach overlay INDEX."
4855 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
4858 (defun org-agenda-follow-mode ()
4859 "Toggle follow mode in an agenda buffer."
4861 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
4862 (org-agenda-set-mode-name)
4863 (message "Follow mode is %s"
4864 (if org-agenda-follow-mode "on" "off")))
4866 (defun org-agenda-log-mode ()
4867 "Toggle follow mode in an agenda buffer."
4869 (org-agenda-check-type t 'agenda 'timeline)
4870 (setq org-agenda-show-log (not org-agenda-show-log))
4871 (org-agenda-set-mode-name)
4873 (message "Log mode is %s"
4874 (if org-agenda-show-log "on" "off")))
4876 (defun org-agenda-toggle-diary ()
4877 "Toggle follow mode in an agenda buffer."
4879 (org-agenda-check-type t 'agenda)
4880 (setq org-agenda-include-diary (not org-agenda-include-diary))
4882 (org-agenda-set-mode-name)
4883 (message "Diary inclusion turned %s"
4884 (if org-agenda-include-diary "on" "off")))
4886 (defun org-agenda-toggle-time-grid ()
4887 "Toggle follow mode in an agenda buffer."
4889 (org-agenda-check-type t 'agenda)
4890 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
4892 (org-agenda-set-mode-name)
4893 (message "Time-grid turned %s"
4894 (if org-agenda-use-time-grid "on" "off")))
4896 (defun org-agenda-set-mode-name ()
4897 "Set the mode name to indicate all the small mode settings."
4899 (concat "Org-Agenda"
4900 (if (equal org-agenda-ndays 1) " Day" "")
4901 (if (equal org-agenda-ndays 7) " Week" "")
4902 (if org-agenda-follow-mode " Follow" "")
4903 (if org-agenda-include-diary " Diary" "")
4904 (if org-agenda-use-time-grid " Grid" "")
4905 (if org-agenda-show-log " Log" "")))
4906 (force-mode-line-update))
4908 (defun org-agenda-post-command-hook ()
4909 (and (eolp) (not (bolp)) (backward-char 1))
4910 (if (and org-agenda-follow-mode
4911 (get-text-property (point) 'org-marker))
4914 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
4916 (defun org-get-entries-from-diary (date)
4917 "Get the (Emacs Calendar) diary entries for DATE."
4918 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4919 (diary-display-hook '(fancy-diary-display))
4920 (list-diary-entries-hook
4921 (cons 'org-diary-default-entry list-diary-entries-hook))
4922 (diary-file-name-prefix-function nil) ; turn this feature off
4923 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
4925 (org-disable-agenda-to-diary t))
4927 (save-window-excursion
4928 (list-diary-entries date 1)))
4929 (if (not (get-buffer fancy-diary-buffer))
4931 (with-current-buffer fancy-diary-buffer
4932 (setq buffer-read-only nil)
4933 (if (= (point-max) 1)
4936 ;; Omit the date and other unnecessary stuff
4937 (org-agenda-cleanup-fancy-diary)
4938 ;; Add prefix to each line and extend the text properties
4939 (if (= (point-max) 1)
4941 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4942 (set-buffer-modified-p nil)
4943 (kill-buffer fancy-diary-buffer)))
4945 (setq entries (org-split-string entries "\n"))
4949 (setq x (org-format-agenda-item "" x "Diary" 'time))
4950 ;; Extend the text properties to the beginning of the line
4951 (add-text-properties
4953 (text-properties-at (1- (length x)) x)
4958 (defun org-agenda-cleanup-fancy-diary ()
4959 "Remove unwanted stuff in buffer created by fancy-diary-display.
4960 This gets rid of the date, the underline under the date, and
4961 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4962 date. Itt also removes lines that contain only whitespace."
4963 (goto-char (point-min))
4964 (if (looking-at ".*?:[ \t]*")
4967 (re-search-forward "\n=+$" nil t)
4969 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4970 (re-search-forward "\n=+$" nil t)
4971 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4972 (goto-char (point-min))
4973 (while (re-search-forward "^ +\n" nil t)
4975 (goto-char (point-min))
4976 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4977 (replace-match "")))
4979 ;; Make sure entries from the diary have the right text properties.
4980 (eval-after-load "diary-lib"
4981 '(if (boundp 'diary-modify-entry-list-string-function)
4982 ;; We can rely on the hook, nothing to do
4984 ;; Hook not avaiable, must use advice to make this work
4985 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
4986 "Make the position visible."
4987 (if (and org-disable-agenda-to-diary ;; called from org-agenda
4990 (setq string (org-modify-diary-entry-string string))))))
4992 (defun org-modify-diary-entry-string (string)
4993 "Add text properties to string, allowing org-mode to act on it."
4994 (add-text-properties
4996 (list 'mouse-face 'highlight
4997 'keymap org-agenda-keymap
5000 "mouse-2 or RET jump to diary file %s"
5001 (abbreviate-file-name (buffer-file-name)))
5002 'org-agenda-diary-link t
5003 'org-marker (org-agenda-new-marker (point-at-bol)))
5007 (defun org-diary-default-entry ()
5008 "Add a dummy entry to the diary.
5009 Needed to avoid empty dates which mess up holiday display."
5010 ;; Catch the error if dealing with the new add-to-diary-alist
5011 (when org-disable-agenda-to-diary
5013 (add-to-diary-list original-date "Org-mode dummy" "")
5015 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5017 (defun org-cycle-agenda-files ()
5018 "Cycle through the files in `org-agenda-files'.
5019 If the current buffer visits an agenda file, find the next one in the list.
5020 If the current buffer does not, find the first agenda file."
5022 (let ((files (append org-agenda-files (list (car org-agenda-files))))
5023 (tcf (if (buffer-file-name) (file-truename (buffer-file-name))))
5025 (unless files (error "No agenda files"))
5027 (while (setq file (pop files))
5028 (if (equal (file-truename file) tcf)
5030 (find-file (car files))
5032 (find-file (car org-agenda-files)))))
5034 (defun org-agenda-file-to-end (&optional file)
5035 "Move/add the current file to the end of the agenda fiole list.
5036 I the file is not present in the list, it is appended ot the list. If it is
5037 present, it is moved there."
5039 (org-agenda-file-to-front 'to-end file))
5041 (defun org-agenda-file-to-front (&optional to-end file)
5042 "Move/add the current file to the top of the agenda file list.
5043 If the file is not present in the list, it is added to the front. If it is
5044 present, it is moved there. With optional argument TO-END, add/move to the
5047 (let ((file-alist (mapcar (lambda (x)
5048 (cons (file-truename x) x))
5050 (ctf (file-truename (buffer-file-name)))
5052 (setq x (assoc ctf file-alist) had x)
5054 (if (not x) (setq x (cons ctf (abbreviate-file-name (buffer-file-name)))))
5056 (setq file-alist (append (delq x file-alist) (list x)))
5057 (setq file-alist (cons x (delq x file-alist))))
5058 (setq org-agenda-files (mapcar 'cdr file-alist))
5059 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5060 (customize-save-variable 'org-agenda-files org-agenda-files))
5061 (org-install-agenda-files-menu)
5062 (message "File %s to %s of agenda file list"
5063 (if had "moved" "added") (if to-end "end" "front"))))
5065 (defun org-remove-file (&optional file)
5066 "Remove current file from the list of files in variable `org-agenda-files'.
5067 These are the files which are being checked for agenda entries.
5068 Optional argument FILE means, use this file instead of the current."
5070 (let* ((file (or file (buffer-file-name)))
5071 (true-file (file-truename file))
5072 (afile (abbreviate-file-name file))
5073 (files (delq nil (mapcar
5075 (if (equal true-file
5078 org-agenda-files))))
5079 (if (not (= (length files) (length org-agenda-files)))
5081 (setq org-agenda-files files)
5082 (customize-save-variable 'org-agenda-files org-agenda-files)
5083 (org-install-agenda-files-menu)
5084 (message "Removed file: %s" afile))
5085 (message "File was not in list: %s" afile))))
5087 (defun org-file-menu-entry (file)
5088 (vector file (list 'find-file file) t))
5089 ;; FIXME: Maybe we removed a buffer visited through the menu from
5090 ;; org-agenda-new-buffers, so that the buffer will not be removed
5091 ;; when exiting the agenda????
5093 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5094 "Return a list of all relevant day numbers from BEG to END buffer positions.
5095 If NO-RANGES is non-nil, include only the start and end dates of a range,
5096 not every single day in the range. If FORCE-TODAY is non-nil, make
5097 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5098 inactive time stamps (those in square brackets) are included."
5099 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5100 dates date day day1 day2 ts1 ts2)
5102 (setq dates (list (time-to-days (current-time)))))
5105 (while (re-search-forward re end t)
5106 (setq day (time-to-days (org-time-string-to-time
5107 (substring (match-string 1) 0 10))))
5108 (or (memq day dates) (push day dates)))
5111 (while (re-search-forward org-tr-regexp end t)
5112 (setq ts1 (substring (match-string 1) 0 10)
5113 ts2 (substring (match-string 2) 0 10)
5114 day1 (time-to-days (org-time-string-to-time ts1))
5115 day2 (time-to-days (org-time-string-to-time ts2)))
5116 (while (< (setq day1 (1+ day1)) day2)
5117 (or (memq day1 dates) (push day1 dates)))))
5121 (defun org-diary (&rest args)
5122 "Return diary information from org-files.
5123 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5124 It accesses org files and extracts information from those files to be
5125 listed in the diary. The function accepts arguments specifying what
5126 items should be listed. The following arguments are allowed:
5128 :timestamp List the headlines of items containing a date stamp or
5129 date range matching the selected date. Deadlines will
5130 also be listed, on the expiration day.
5132 :deadline List any deadlines past due, or due within
5133 `org-deadline-warning-days'. The listing occurs only
5134 in the diary for *today*, not at any other date. If
5135 an entry is marked DONE, it is no longer listed.
5137 :scheduled List all items which are scheduled for the given date.
5138 The diary for *today* also contains items which were
5139 scheduled earlier and are not yet marked DONE.
5141 :todo List all TODO items from the org-file. This may be a
5142 long list - so this is not turned on by default.
5143 Like deadlines, these entries only show up in the
5144 diary for *today*, not at any other date.
5146 The call in the diary file should look like this:
5148 &%%(org-diary) ~/path/to/some/orgfile.org
5150 Use a separate line for each org file to check. Or, if you omit the file name,
5151 all files listed in `org-agenda-files' will be checked automatically:
5155 If you don't give any arguments (as in the example above), the default
5156 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5159 &%%(org-diary :deadline :timestamp :scheduled)
5161 The function expects the lisp variables `entry' and `date' to be provided
5162 by the caller, because this is how the calendar works. Don't use this
5163 function from a program - use `org-agenda-get-day-entries' instead."
5164 (org-agenda-maybe-reset-markers)
5165 (org-compile-prefix-format org-agenda-prefix-format)
5166 (setq args (or args '(:deadline :scheduled :timestamp)))
5167 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5171 ;; If this is called during org-agenda, don't return any entries to
5172 ;; the calendar. Org Agenda will list these entries itself.
5173 (if org-disable-agenda-to-diary (setq files nil))
5174 (while (setq file (pop files))
5175 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5176 (setq results (append results rtn)))
5178 (concat (org-finalize-agenda-entries results) "\n"))))
5179 (defvar org-category-table nil)
5180 (defun org-get-category-table ()
5181 "Get the table of categories and positions in current buffer."
5184 (goto-char (point-min))
5185 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5186 (push (cons (point) (org-trim (match-string 2))) tbl)))
5188 (defun org-get-category (&optional pos)
5189 "Get the category applying to position POS."
5190 (if (not org-category-table)
5192 ((null org-category)
5194 (if (buffer-file-name)
5195 (file-name-sans-extension
5196 (file-name-nondirectory (buffer-file-name)))
5198 ((symbolp org-category) (symbol-name org-category))
5200 (let ((tbl org-category-table)
5201 (pos (or pos (point))))
5202 (while (and tbl (> (caar tbl) pos))
5204 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5205 org-category-table))))))
5207 (defun org-agenda-get-day-entries (file date &rest args)
5208 "Does the work for `org-diary' and `org-agenda'.
5209 FILE is the path to a file to be checked for entries. DATE is date like
5210 the one returned by `calendar-current-date'. ARGS are symbols indicating
5211 which kind of entries should be extracted. For details about these, see
5212 the documentation of `org-diary'."
5213 (setq args (or args '(:deadline :scheduled :timestamp)))
5214 (let* ((org-startup-with-deadline-check nil)
5215 (org-startup-folded nil)
5216 (buffer (if (file-exists-p file)
5217 (org-get-agenda-file-buffer file)
5218 (error "No such file %s" file)))
5221 ;; If file does not exist, make sure an error message ends up in diary
5222 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5223 (with-current-buffer buffer
5224 (unless (eq major-mode 'org-mode)
5225 (error "Agenda file %s is not in `org-mode'" file))
5226 (setq org-category-table (org-get-category-table))
5227 (let ((case-fold-search nil))
5230 (if org-respect-restriction
5231 (if (org-region-active-p)
5232 ;; Respect a region to restrict search
5233 (narrow-to-region (region-beginning) (region-end)))
5234 ;; If we work for the calendar or many files,
5235 ;; get rid of any restriction
5237 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5238 (while (setq arg (pop args))
5240 ((and (eq arg :todo)
5241 (equal date (calendar-current-date)))
5242 (setq rtn (org-agenda-get-todos))
5243 (setq results (append results rtn)))
5244 ((eq arg :timestamp)
5245 (setq rtn (org-agenda-get-blocks))
5246 (setq results (append results rtn))
5247 (setq rtn (org-agenda-get-timestamps))
5248 (setq results (append results rtn)))
5249 ((eq arg :scheduled)
5250 (setq rtn (org-agenda-get-scheduled))
5251 (setq results (append results rtn)))
5253 (setq rtn (org-agenda-get-closed))
5254 (setq results (append results rtn)))
5255 ((and (eq arg :deadline)
5256 (equal date (calendar-current-date)))
5257 (setq rtn (org-agenda-get-deadlines))
5258 (setq results (append results rtn))))))))
5261 (defun org-entry-is-done-p ()
5262 "Is the current entry marked DONE?"
5264 (and (re-search-backward "[\r\n]\\*" nil t)
5265 (looking-at org-nl-done-regexp))))
5267 (defun org-at-date-range-p ()
5268 "Is the cursor inside a date range?"
5272 (let ((pos (point)))
5273 (skip-chars-backward "^<\r\n")
5274 (skip-chars-backward "<")
5275 (and (looking-at org-tr-regexp)
5276 (>= (match-end 0) pos)
5278 (skip-chars-backward "^<\r\n")
5279 (skip-chars-backward "<")
5280 (and (looking-at org-tr-regexp)
5281 (>= (match-end 0) pos)
5285 (defun org-agenda-get-todos ()
5286 "Return the TODO information for agenda display."
5287 (let* ((props (list 'face nil
5288 'done-face 'org-done
5289 'mouse-face 'highlight
5290 'keymap org-agenda-keymap
5292 (format "mouse-2 or RET jump to org file %s"
5293 (abbreviate-file-name (buffer-file-name)))))
5294 (regexp (concat "[\n\r]\\*+ *\\("
5295 (if org-select-this-todo-keyword
5296 (concat "\\<\\(" org-select-this-todo-keyword
5298 org-not-done-regexp)
5300 marker priority category
5302 (goto-char (point-min))
5303 (while (re-search-forward regexp nil t)
5304 (goto-char (match-beginning 1))
5305 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5306 category (org-get-category)
5307 txt (org-format-agenda-item "" (match-string 1) category)
5309 (+ (org-get-priority txt)
5310 (if org-todo-kwd-priority-p
5311 (- org-todo-kwd-max-priority -2
5313 (member (match-string 2) org-todo-keywords)))
5315 (add-text-properties
5316 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5317 'priority priority 'category category)
5321 (goto-char (match-end 1)))
5324 (defconst org-agenda-no-heading-message
5325 "No heading for this item in buffer or region")
5327 (defun org-agenda-get-timestamps ()
5328 "Return the date stamp information for agenda display."
5329 (let* ((props (list 'face nil
5330 'mouse-face 'highlight
5331 'keymap org-agenda-keymap
5333 (format "mouse-2 or RET jump to org file %s"
5334 (abbreviate-file-name (buffer-file-name)))))
5335 (regexp (regexp-quote
5338 (car org-time-stamp-formats)
5339 (apply 'encode-time ; DATE bound by calendar
5340 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5342 marker hdmarker deadlinep scheduledp donep tmp priority category
5344 (goto-char (point-min))
5345 (while (re-search-forward regexp nil t)
5346 (if (not (save-match-data (org-at-date-range-p)))
5348 (setq marker (org-agenda-new-marker (match-beginning 0))
5349 category (org-get-category (match-beginning 0))
5350 tmp (buffer-substring (max (point-min)
5351 (- (match-beginning 0)
5352 org-ds-keyword-length))
5353 (match-beginning 0))
5354 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5355 deadlinep (string-match org-deadline-regexp tmp)
5356 scheduledp (string-match org-scheduled-regexp tmp)
5357 donep (org-entry-is-done-p))
5358 (if (string-match ">" timestr)
5359 ;; substring should only run to end of time stamp
5360 (setq timestr (substring timestr 0 (match-end 0))))
5362 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5364 (goto-char (match-end 1))
5365 (setq hdmarker (org-agenda-new-marker))
5366 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5367 (setq txt (org-format-agenda-item
5369 (if deadlinep "Deadline: " "")
5370 (if scheduledp "Scheduled: " ""))
5371 (match-string 1) category timestr)))
5372 (setq txt org-agenda-no-heading-message))
5373 (setq priority (org-get-priority txt))
5374 (add-text-properties
5375 0 (length txt) (append (list 'org-marker marker
5376 'org-hd-marker hdmarker) props)
5379 (add-text-properties
5382 (if donep 'org-done 'org-warning)
5383 'undone-face 'org-warning
5384 'done-face 'org-done
5386 'priority (+ 100 priority))
5389 (add-text-properties
5391 (list 'face 'org-scheduled-today
5392 'undone-face 'org-scheduled-today
5393 'done-face 'org-done
5395 priority (+ 99 priority))
5397 (add-text-properties
5399 (list 'priority priority 'category category) txt)))
5401 (outline-next-heading))))
5404 (defun org-agenda-get-closed ()
5405 "Return the loggedd TODO entries for agenda display."
5406 (let* ((props (list 'mouse-face 'highlight
5407 'keymap org-agenda-keymap
5409 (format "mouse-2 or RET jump to org file %s"
5410 (abbreviate-file-name (buffer-file-name)))))
5412 "\\<" org-closed-string " *\\["
5416 (car org-time-stamp-formats)
5417 (apply 'encode-time ; DATE bound by calendar
5418 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5420 marker hdmarker priority category
5422 (goto-char (point-min))
5423 (while (re-search-forward regexp nil t)
5424 (if (not (save-match-data (org-at-date-range-p)))
5426 (setq marker (org-agenda-new-marker (match-beginning 0))
5427 category (org-get-category (match-beginning 0))
5428 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5429 ;; donep (org-entry-is-done-p)
5431 (if (string-match "\\]" timestr)
5432 ;; substring should only run to end of time stamp
5433 (setq timestr (substring timestr 0 (match-end 0))))
5435 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5437 (goto-char (match-end 1))
5438 (setq hdmarker (org-agenda-new-marker))
5439 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5440 (setq txt (org-format-agenda-item
5442 (match-string 1) category timestr)))
5443 (setq txt org-agenda-no-heading-message))
5444 (setq priority 100000)
5445 (add-text-properties
5446 0 (length txt) (append (list 'org-marker marker
5447 'org-hd-marker hdmarker
5451 'undone-face 'org-warning
5452 'done-face 'org-done) props)
5455 (outline-next-heading))))
5458 (defun org-agenda-get-deadlines ()
5459 "Return the deadline information for agenda display."
5460 (let* ((wdays org-deadline-warning-days)
5461 (props (list '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 org-deadline-time-regexp)
5467 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5468 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5469 d2 diff pos pos1 category
5471 (goto-char (point-min))
5472 (while (re-search-forward regexp nil t)
5473 (setq pos (1- (match-beginning 1))
5475 (org-time-string-to-time (match-string 1)))
5477 ;; When to show a deadline in the calendar:
5478 ;; If the expiration is within wdays warning time.
5479 ;; Past-due deadlines are only shown on the current date
5480 (if (and (< diff wdays) todayp (not (= diff 0)))
5482 (setq category (org-get-category))
5483 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5485 (goto-char (match-end 0))
5486 (setq pos1 (match-end 1))
5487 (setq head (buffer-substring-no-properties
5489 (progn (skip-chars-forward "^\r\n")
5491 (if (string-match org-looking-at-done-regexp head)
5493 (setq txt (org-format-agenda-item
5494 (format "In %3d d.: " diff) head category))))
5495 (setq txt org-agenda-no-heading-message))
5497 (add-text-properties
5500 (list 'org-marker (org-agenda-new-marker pos)
5501 'org-hd-marker (org-agenda-new-marker pos1)
5502 'priority (+ (- 10 diff) (org-get-priority txt))
5504 'face (cond ((<= diff 0) 'org-warning)
5505 ((<= diff 5) 'org-scheduled-previously)
5508 ((<= diff 0) 'org-warning)
5509 ((<= diff 5) 'org-scheduled-previously)
5511 'done-face 'org-done)
5517 (defun org-agenda-get-scheduled ()
5518 "Return the scheduled information for agenda display."
5519 (let* ((props (list 'face 'org-scheduled-previously
5520 'undone-face 'org-scheduled-previously
5521 'done-face 'org-done
5522 'mouse-face 'highlight
5523 'keymap org-agenda-keymap
5525 (format "mouse-2 or RET jump to org file %s"
5526 (abbreviate-file-name (buffer-file-name)))))
5527 (regexp org-scheduled-time-regexp)
5528 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5529 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5530 d2 diff pos pos1 category
5532 (goto-char (point-min))
5533 (while (re-search-forward regexp nil t)
5534 (setq pos (1- (match-beginning 1))
5536 (org-time-string-to-time (match-string 1)))
5538 ;; When to show a scheduled item in the calendar:
5539 ;; If it is on or past the date.
5540 (if (and (< diff 0) todayp)
5542 (setq category (org-get-category))
5543 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5545 (goto-char (match-end 0))
5546 (setq pos1 (match-end 1))
5547 (setq head (buffer-substring-no-properties
5549 (progn (skip-chars-forward "^\r\n") (point))))
5550 (if (string-match org-looking-at-done-regexp head)
5552 (setq txt (org-format-agenda-item
5553 (format "Sched.%2dx: " (- 1 diff)) head
5555 (setq txt org-agenda-no-heading-message))
5557 (add-text-properties
5559 (append (list 'org-marker (org-agenda-new-marker pos)
5560 'org-hd-marker (org-agenda-new-marker pos1)
5561 'priority (+ (- 5 diff) (org-get-priority txt))
5567 (defun org-agenda-get-blocks ()
5568 "Return the date-range information for agenda display."
5569 (let* ((props (list 'face nil
5570 'mouse-face 'highlight
5571 'keymap org-agenda-keymap
5573 (format "mouse-2 or RET jump to org file %s"
5574 (abbreviate-file-name (buffer-file-name)))))
5575 (regexp org-tr-regexp)
5576 (d0 (calendar-absolute-from-gregorian date))
5577 marker hdmarker ee txt d1 d2 s1 s2 timestr category)
5578 (goto-char (point-min))
5579 (while (re-search-forward regexp nil t)
5580 (setq timestr (match-string 0)
5583 d1 (time-to-days (org-time-string-to-time s1))
5584 d2 (time-to-days (org-time-string-to-time s2)))
5585 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5586 ;; Only allow days between the limits, because the normal
5587 ;; date stamps will catch the limits.
5589 (setq marker (org-agenda-new-marker (point)))
5590 (setq category (org-get-category))
5591 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5593 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5594 (goto-char (match-end 1))
5595 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5596 (setq txt (org-format-agenda-item
5597 (format (if (= d1 d2) "" "(%d/%d): ")
5598 (1+ (- d0 d1)) (1+ (- d2 d1)))
5599 (match-string 1) category
5600 (if (= d0 d1) timestr))))
5601 (setq txt org-agenda-no-heading-message))
5602 (add-text-properties
5603 0 (length txt) (append (list 'org-marker marker
5604 'org-hd-marker hdmarker
5605 'priority (org-get-priority txt)
5610 (outline-next-heading))
5611 ;; Sort the entries by expiration date.
5614 (defconst org-plain-time-of-day-regexp
5617 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5620 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5622 "Regular expression to match a plain time or time range.
5623 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5624 groups carry important information:
5626 1 the first time, range or not
5627 8 the second time, if it is a range.")
5629 (defconst org-stamp-time-of-day-regexp
5631 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5632 "\\([012][0-9]:[0-5][0-9]\\)>"
5634 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5635 "Regular expression to match a timestamp time or time range.
5636 After a match, the following groups carry important information:
5638 1 date plus weekday, for backreferencing to make sure both times on same day
5639 2 the first time, range or not
5640 4 the second time, if it is a range.")
5642 (defvar org-prefix-has-time nil
5643 "A flag, set by `org-compile-prefix-format'.
5644 The flag is set if the currently compiled format contains a `%t'.")
5646 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
5647 "Format TXT to be inserted into the agenda buffer.
5648 In particular, it adds the prefix and corresponding text properties. EXTRA
5649 must be a string and replaces the `%s' specifier in the prefix format.
5650 CATEGORY (string, symbol or nil) may be used to overule the default
5651 category taken from local variable or file name. It will replace the `%c'
5652 specifier in the format. DOTIME, when non-nil, indicates that a
5653 time-of-day should be extracted from TXT for sorting of this entry, and for
5654 the `%t' specifier in the format. When DOTIME is a string, this string is
5655 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5656 only the correctly processes TXT should be returned - this is used by
5657 `org-agenda-change-all-lines'."
5659 ;; Diary entries sometimes have extra whitespace at the beginning
5660 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5661 (let* ((category (or category
5663 (if (buffer-file-name)
5664 (file-name-sans-extension
5665 (file-name-nondirectory (buffer-file-name)))
5667 time ;; needed for the eval of the prefix format
5668 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5669 (time-of-day (and dotime (org-get-time-of-day ts)))
5670 stamp plain s0 s1 s2 rtn)
5671 (when (and dotime time-of-day org-prefix-has-time)
5672 ;; Extract starting and ending time and move them to prefix
5673 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5674 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5675 (setq s0 (match-string 0 ts)
5676 s1 (match-string (if plain 1 2) ts)
5677 s2 (match-string (if plain 8 4) ts))
5679 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5680 ;; them, we might want to remove them there to avoid duplication.
5681 ;; The user can turn this off with a variable.
5682 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5683 (string-match (concat (regexp-quote s0) " *") txt)
5684 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5685 (= (match-beginning 0) 0)
5687 (setq txt (replace-match "" nil nil txt))))
5688 ;; Normalize the time(s) to 24 hour
5689 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5690 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5692 ;; Create the final string
5695 ;; Prepare the variables needed in the eval of the compiled format
5696 (setq time (cond (s2 (concat s1 "-" s2))
5697 (s1 (concat s1 "......"))
5700 category (if (symbolp category) (symbol-name category) category))
5701 ;; Evaluate the compiled format
5702 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5704 ;; And finally add the text properties
5705 (add-text-properties
5706 0 (length rtn) (list 'category (downcase category)
5707 'prefix-length (- (length rtn) (length txt))
5708 'time-of-day time-of-day
5713 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
5715 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
5716 ((and todayp (member 'today (car org-agenda-time-grid))))
5717 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
5718 ((member 'weekly (car org-agenda-time-grid)))
5719 (t (throw 'exit list)))
5720 (let* ((have (delq nil (mapcar
5721 (lambda (x) (get-text-property 1 'time-of-day x))
5723 (string (nth 1 org-agenda-time-grid))
5724 (gridtimes (nth 2 org-agenda-time-grid))
5725 (req (car org-agenda-time-grid))
5726 (remove (member 'remove-match req))
5728 (if (and (member 'require-timed req) (not have))
5729 ;; don't show empty grid
5731 (while (setq time (pop gridtimes))
5732 (unless (and remove (member time have))
5733 (setq time (int-to-string time))
5734 (push (org-format-agenda-item
5735 nil string "" ;; FIXME: put a category for the grid?
5736 (concat (substring time 0 -2) ":" (substring time -2)))
5739 1 (length (car new)) 'face 'org-time-grid (car new))))
5740 (if (member 'time-up org-agenda-sorting-strategy)
5742 (append list new)))))
5744 (defun org-compile-prefix-format (format)
5745 "Compile the prefix format into a Lisp form that can be evaluated.
5746 The resulting form is returned and stored in the variable
5747 `org-prefix-format-compiled'."
5748 (setq org-prefix-has-time nil)
5749 (let ((start 0) varform vars var (s format) c f opt)
5750 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
5752 (setq var (cdr (assoc (match-string 4 s)
5753 '(("c" . category) ("t" . time) ("s" . extra))))
5754 c (or (match-string 3 s) "")
5755 opt (match-beginning 1)
5756 start (1+ (match-beginning 0)))
5757 (if (equal var 'time) (setq org-prefix-has-time t))
5758 (setq f (concat "%" (match-string 2 s) "s"))
5761 `(if (equal "" ,var)
5763 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
5764 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
5765 (setq s (replace-match "%s" t nil s))
5766 (push varform vars))
5767 (setq vars (nreverse vars))
5768 (setq org-prefix-format-compiled `(format ,s ,@vars))))
5770 (defun org-get-time-of-day (s &optional string)
5771 "Check string S for a time of day.
5772 If found, return it as a military time number between 0 and 2400.
5773 If not found, return nil.
5774 The optional STRING argument forces conversion into a 5 character wide string
5780 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
5782 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
5783 (let* ((t0 (+ (* 100
5784 (+ (string-to-number (match-string 1 s))
5785 (if (and (match-beginning 4)
5786 (equal (downcase (match-string 4 s)) "pm"))
5788 (if (match-beginning 3)
5789 (string-to-number (match-string 3 s))
5791 (t1 (concat " " (int-to-string t0))))
5792 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
5794 (defun org-finalize-agenda-entries (list)
5795 "Sort and concatenate the agenda items."
5796 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
5798 (defsubst org-cmp-priority (a b)
5799 "Compare the priorities of string a and b."
5800 (let ((pa (or (get-text-property 1 'priority a) 0))
5801 (pb (or (get-text-property 1 'priority b) 0)))
5802 (cond ((> pa pb) +1)
5806 (defsubst org-cmp-category (a b)
5807 "Compare the string values of categories of strings a and b."
5808 (let ((ca (or (get-text-property 1 'category a) ""))
5809 (cb (or (get-text-property 1 'category b) "")))
5810 (cond ((string-lessp ca cb) -1)
5811 ((string-lessp cb ca) +1)
5814 (defsubst org-cmp-time (a b)
5815 "Compare the time-of-day values of strings a and b."
5816 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
5817 (ta (or (get-text-property 1 'time-of-day a) def))
5818 (tb (or (get-text-property 1 'time-of-day b) def)))
5819 (cond ((< ta tb) -1)
5823 (defun org-entries-lessp (a b)
5824 "Predicate for sorting agenda entries."
5825 ;; The following variables will be used when the form is evaluated.
5826 (let* ((time-up (org-cmp-time a b))
5827 (time-down (if time-up (- time-up) nil))
5828 (priority-up (org-cmp-priority a b))
5829 (priority-down (if priority-up (- priority-up) nil))
5830 (category-up (org-cmp-category a b))
5831 (category-down (if category-up (- category-up) nil))
5832 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
5834 (eval (cons 'or org-agenda-sorting-strategy))
5835 '((-1 . t) (1 . nil) (nil . nil))))))
5837 (defun org-agenda-show-priority ()
5838 "Show the priority of the current item.
5839 This priority is composed of the main priority given with the [#A] cookies,
5840 and by additional input from the age of a schedules or deadline entry."
5842 (let* ((pri (get-text-property (point-at-bol) 'priority)))
5843 (message "Priority is %d" (if pri pri -1000))))
5845 (defun org-agenda-goto (&optional highlight)
5846 "Go to the Org-mode file which contains the item at point."
5848 (let* ((marker (or (get-text-property (point) 'org-marker)
5849 (org-agenda-error)))
5850 (buffer (marker-buffer marker))
5851 (pos (marker-position marker)))
5852 (switch-to-buffer-other-window buffer)
5855 (when (eq major-mode 'org-mode)
5856 (org-show-hidden-entry)
5858 (and (outline-next-heading)
5859 (org-flag-heading nil)))) ; show the next heading
5860 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
5862 (defun org-agenda-switch-to ()
5863 "Go to the Org-mode file which contains the item at point."
5865 (let* ((marker (or (get-text-property (point) 'org-marker)
5866 (org-agenda-error)))
5867 (buffer (marker-buffer marker))
5868 (pos (marker-position marker)))
5869 (switch-to-buffer buffer)
5870 (delete-other-windows)
5873 (when (eq major-mode 'org-mode)
5874 (org-show-hidden-entry)
5876 (and (outline-next-heading)
5877 (org-flag-heading nil)))))) ; show the next heading
5879 (defun org-agenda-goto-mouse (ev)
5880 "Go to the Org-mode file which contains the item at the mouse click."
5882 (mouse-set-point ev)
5885 (defun org-agenda-show ()
5886 "Display the Org-mode file which contains the item at point."
5888 (let ((win (selected-window)))
5890 (select-window win)))
5892 (defun org-agenda-recenter (arg)
5893 "Display the Org-mode file which contains the item at point and recenter."
5895 (let ((win (selected-window)))
5898 (select-window win)))
5900 (defun org-agenda-show-mouse (ev)
5901 "Display the Org-mode file which contains the item at the mouse click."
5903 (mouse-set-point ev)
5906 (defun org-agenda-check-no-diary ()
5907 "Check if the entry is a diary link and abort if yes."
5908 (if (get-text-property (point) 'org-agenda-diary-link)
5909 (org-agenda-error)))
5911 (defun org-agenda-error ()
5912 (error "Command not allowed in this line"))
5914 (defvar org-last-heading-marker (make-marker)
5915 "Marker pointing to the headline that last changed its TODO state
5916 by a remote command from the agenda.")
5918 (defun org-agenda-todo (&optional arg)
5919 "Cycle TODO state of line at point, also in Org-mode file.
5920 This changes the line at point, all other lines in the agenda referring to
5921 the same tree node, and the headline of the tree node in the Org-mode file."
5923 (org-agenda-check-no-diary)
5924 (let* ((col (current-column))
5925 (marker (or (get-text-property (point) 'org-marker)
5926 (org-agenda-error)))
5927 (buffer (marker-buffer marker))
5928 (pos (marker-position marker))
5929 (hdmarker (get-text-property (point) 'org-hd-marker))
5930 (buffer-read-only nil)
5932 (with-current-buffer buffer
5935 (org-show-hidden-entry)
5937 (and (outline-next-heading)
5938 (org-flag-heading nil))) ; show the next heading
5941 (setq newhead (org-get-heading))
5943 (org-back-to-heading)
5944 (move-marker org-last-heading-marker (point))))
5945 (beginning-of-line 1)
5947 (org-agenda-change-all-lines newhead hdmarker 'fixface))
5948 (move-to-column col)))
5950 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
5951 "Change all lines in the agenda buffer which match hdmarker.
5952 The new content of the line will be NEWHEAD (as modified by
5953 `org-format-agenda-item'). HDMARKER is checked with
5954 `equal' against all `org-hd-marker' text properties in the file.
5955 If FIXFACE is non-nil, the face of each item is modified acording to
5956 the new TODO state."
5957 (let* (props m pl undone-face done-face finish new dotime cat)
5958 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
5960 (goto-char (point-max))
5961 (beginning-of-line 1)
5963 (setq finish (bobp))
5964 (when (and (setq m (get-text-property (point) 'org-hd-marker))
5966 (setq props (text-properties-at (point))
5967 dotime (get-text-property (point) 'dotime)
5968 cat (get-text-property (point) 'category)
5969 new (org-format-agenda-item "x" newhead cat dotime 'noprefix)
5970 pl (get-text-property (point) 'prefix-length)
5971 undone-face (get-text-property (point) 'undone-face)
5972 done-face (get-text-property (point) 'done-face))
5974 (if (looking-at ".*")
5976 (replace-match new t t)
5977 (beginning-of-line 1)
5978 (add-text-properties (point-at-bol) (point-at-eol) props)
5980 (add-text-properties
5981 (point-at-bol) (point-at-eol)
5983 (if org-last-todo-state-is-todo
5984 undone-face done-face))))
5985 (beginning-of-line 1))
5986 (error "Line update did not work")))
5987 (beginning-of-line 0)))))
5989 (defun org-agenda-priority-up ()
5990 "Increase the priority of line at point, also in Org-mode file."
5992 (org-agenda-priority 'up))
5994 (defun org-agenda-priority-down ()
5995 "Decrease the priority of line at point, also in Org-mode file."
5997 (org-agenda-priority 'down))
5999 (defun org-agenda-priority (&optional force-direction)
6000 "Set the priority of line at point, also in Org-mode file.
6001 This changes the line at point, all other lines in the agenda referring to
6002 the same tree node, and the headline of the tree node in the Org-mode file."
6004 (org-agenda-check-no-diary)
6005 (let* ((marker (or (get-text-property (point) 'org-marker)
6006 (org-agenda-error)))
6007 (buffer (marker-buffer marker))
6008 (pos (marker-position marker))
6009 (hdmarker (get-text-property (point) 'org-hd-marker))
6010 (buffer-read-only nil)
6012 (with-current-buffer buffer
6015 (org-show-hidden-entry)
6017 (and (outline-next-heading)
6018 (org-flag-heading nil))) ; show the next heading
6019 (funcall 'org-priority force-direction)
6021 (setq newhead (org-get-heading)))
6022 (org-agenda-change-all-lines newhead hdmarker)
6023 (beginning-of-line 1)))
6025 (defun org-agenda-set-tags ()
6026 "Set tags for the current headline."
6028 (org-agenda-check-no-diary)
6029 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6030 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6031 (org-agenda-error)))
6032 (buffer (marker-buffer hdmarker))
6033 (pos (marker-position hdmarker))
6034 (buffer-read-only nil)
6036 (with-current-buffer buffer
6039 (org-show-hidden-entry)
6041 (and (outline-next-heading)
6042 (org-flag-heading nil))) ; show the next heading
6043 (call-interactively 'org-set-tags)
6045 (setq newhead (org-get-heading)))
6046 (org-agenda-change-all-lines newhead hdmarker)
6047 (beginning-of-line 1)))
6049 (defun org-agenda-date-later (arg &optional what)
6050 "Change the date of this item to one day later."
6052 (org-agenda-check-type t 'agenda 'timeline)
6053 (org-agenda-check-no-diary)
6054 (let* ((marker (or (get-text-property (point) 'org-marker)
6055 (org-agenda-error)))
6056 (buffer (marker-buffer marker))
6057 (pos (marker-position marker)))
6058 (with-current-buffer buffer
6061 (if (not (org-at-timestamp-p))
6062 (error "Cannot find time stamp"))
6063 (org-timestamp-change arg (or what 'day))
6064 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6066 (defun org-agenda-date-earlier (arg &optional what)
6067 "Change the date of this item to one day earlier."
6069 (org-agenda-date-later (- arg) what))
6071 (defun org-agenda-date-prompt (arg)
6072 "Change the date of this item. Date is prompted for, with default today.
6073 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6074 be used to request time specification in the time stamp."
6076 (org-agenda-check-type t 'agenda 'timeline)
6077 (org-agenda-check-no-diary)
6078 (let* ((marker (or (get-text-property (point) 'org-marker)
6079 (org-agenda-error)))
6080 (buffer (marker-buffer marker))
6081 (pos (marker-position marker)))
6082 (with-current-buffer buffer
6085 (if (not (org-at-timestamp-p))
6086 (error "Cannot find time stamp"))
6087 (org-time-stamp arg)
6088 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6090 (defun org-get-heading ()
6091 "Return the heading of the current entry, without the stars."
6093 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6094 ;;FIXME???????? (and (bolp) (end-of-line 1))
6095 (if (and (re-search-backward "[\r\n]\\*" nil t)
6096 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6100 (defun org-agenda-diary-entry ()
6101 "Make a diary entry, like the `i' command from the calendar.
6102 All the standard commands work: block, weekly etc"
6104 (org-agenda-check-type t 'agenda 'timeline)
6105 (require 'diary-lib)
6107 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6108 (read-char-exclusive)))
6109 (cmd (cdr (assoc char
6110 '((?d . insert-diary-entry)
6111 (?w . insert-weekly-diary-entry)
6112 (?m . insert-monthly-diary-entry)
6113 (?y . insert-yearly-diary-entry)
6114 (?a . insert-anniversary-diary-entry)
6115 (?b . insert-block-diary-entry)
6116 (?c . insert-cyclic-diary-entry)))))
6117 (oldf (symbol-function 'calendar-cursor-to-date))
6119 (mark (or (mark t) (point))))
6121 (error "No command associated with <%c>" char))
6122 (unless (and (get-text-property point 'day)
6123 (or (not (equal ?b char))
6124 (get-text-property mark 'day)))
6125 (error "Don't know which date to use for diary entry"))
6126 ;; We implement this by hacking the `calendar-cursor-to-date' function
6127 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6128 (let ((calendar-mark-ring
6129 (list (calendar-gregorian-from-absolute
6130 (or (get-text-property mark 'day)
6131 (get-text-property point 'day))))))
6134 (fset 'calendar-cursor-to-date
6135 (lambda (&optional error)
6136 (calendar-gregorian-from-absolute
6137 (get-text-property point 'day))))
6138 (call-interactively cmd))
6139 (fset 'calendar-cursor-to-date oldf)))))
6142 (defun org-agenda-execute-calendar-command (cmd)
6143 "Execute a calendar command from the agenda, with the date associated to
6144 the cursor position."
6145 (org-agenda-check-type t 'agenda 'timeline)
6146 (require 'diary-lib)
6147 (unless (get-text-property (point) 'day)
6148 (error "Don't know which date to use for calendar command"))
6149 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6151 (date (calendar-gregorian-from-absolute
6152 (get-text-property point 'day)))
6153 (displayed-day (extract-calendar-day date))
6154 (displayed-month (extract-calendar-month date))
6155 (displayed-year (extract-calendar-year date)))
6158 (fset 'calendar-cursor-to-date
6159 (lambda (&optional error)
6160 (calendar-gregorian-from-absolute
6161 (get-text-property point 'day))))
6162 (call-interactively cmd))
6163 (fset 'calendar-cursor-to-date oldf))))
6165 (defun org-agenda-phases-of-moon ()
6166 "Display the phases of the moon for the 3 months around the cursor date."
6168 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6170 (defun org-agenda-holidays ()
6171 "Display the holidays for the 3 months around the cursor date."
6173 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6175 (defun org-agenda-sunrise-sunset (arg)
6176 "Display sunrise and sunset for the cursor date.
6177 Latitude and longitude can be specified with the variables
6178 `calendar-latitude' and `calendar-longitude'. When called with prefix
6179 argument, latitude and longitude will be prompted for."
6181 (let ((calendar-longitude (if arg nil calendar-longitude))
6182 (calendar-latitude (if arg nil calendar-latitude))
6183 (calendar-location-name
6184 (if arg "the given coordinates" calendar-location-name)))
6185 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6187 (defun org-agenda-goto-calendar ()
6188 "Open the Emacs calendar with the date at the cursor."
6190 (org-agenda-check-type t 'agenda 'timeline)
6191 (let* ((day (or (get-text-property (point) 'day)
6192 (error "Don't know which date to open in calendar")))
6193 (date (calendar-gregorian-from-absolute day))
6194 (calendar-move-hook nil)
6195 (view-diary-entries-initially nil))
6197 (calendar-goto-date date)))
6199 (defun org-calendar-goto-agenda ()
6200 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6201 This is a command that has to be installed in `calendar-mode-map'."
6203 (org-agenda-list nil (calendar-absolute-from-gregorian
6204 (calendar-cursor-to-date))
6207 (defun org-agenda-convert-date ()
6209 (org-agenda-check-type t 'agenda 'timeline)
6210 (let ((day (get-text-property (point) 'day))
6213 (error "Don't know which date to convert"))
6214 (setq date (calendar-gregorian-from-absolute day))
6216 "Gregorian: " (calendar-date-string date) "\n"
6217 "ISO: " (calendar-iso-date-string date) "\n"
6218 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6219 "Julian: " (calendar-julian-date-string date) "\n"
6220 "Astron. JD: " (calendar-astro-date-string date)
6221 " (Julian date number at noon UTC)\n"
6222 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6223 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6224 "French: " (calendar-french-date-string date) "\n"
6225 "Mayan: " (calendar-mayan-date-string date) "\n"
6226 "Coptic: " (calendar-coptic-date-string date) "\n"
6227 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6228 "Persian: " (calendar-persian-date-string date) "\n"
6229 "Chinese: " (calendar-chinese-date-string date) "\n"))
6230 (with-output-to-temp-buffer "*Dates*"
6232 (if (fboundp 'fit-window-to-buffer)
6233 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6237 (defun org-scan-tags (action matcher &optional todo-only)
6238 "Scan headline tags with inheritance and produce output ACTION.
6239 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6240 evaluated, testing if a given set of tags qualifies a headline for
6241 inclusion. When TODO-ONLY is non-nil, only lines with a TDOD keyword
6242 d are included in the output."
6243 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6244 (mapconcat 'regexp-quote
6245 (nreverse (cdr (reverse org-todo-keywords)))
6247 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_:]+:\\)?[ \t]*[\n\r]"))
6248 (props (list 'face nil
6249 'done-face 'org-done
6251 'mouse-face 'highlight
6252 'keymap org-agenda-keymap
6254 (format "mouse-2 or RET jump to org file %s"
6255 (abbreviate-file-name (buffer-file-name)))))
6257 tags tags-list tags-alist (llast 0) rtn level category i txt
6261 (goto-char (point-min))
6262 (when (eq action 'sparse-tree) (hide-sublevels 1))
6263 (while (re-search-forward re nil t)
6264 (setq todo (if (match-end 1) (match-string 2))
6265 tags (if (match-end 4) (match-string 4)))
6266 (goto-char (setq lspos (1+ (match-beginning 0))))
6267 (setq level (outline-level)
6268 category (org-get-category))
6269 (setq i llast llast level)
6270 ;; remove tag lists from same and sublevels
6272 (when (setq entry (assoc i tags-alist))
6273 (setq tags-alist (delete entry tags-alist)))
6277 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6279 (cons (cons level tags) tags-alist)))
6280 ;; compile tags for current headline
6282 (if org-use-tag-inheritance
6283 (apply 'append (mapcar 'cdr tags-alist))
6285 (when (and (or (not todo-only) todo)
6287 ;; list this headline
6288 (if (eq action 'sparse-tree)
6290 (org-show-hierarchy-above))
6291 (setq txt (org-format-agenda-item
6294 (if org-tags-match-list-sublevels
6295 (make-string (1- level) ?.) "")
6299 (setq marker (org-agenda-new-marker))
6300 (add-text-properties
6302 (append (list 'org-marker marker 'org-hd-marker marker
6307 ;; if we are to skip sublevels, jump to end of subtree
6309 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6312 (defun org-tags-sparse-tree (&optional arg match)
6313 "Create a sparse tree according to tags search string MATCH.
6314 MATCH can contain positive and negative selection of tags, like
6315 \"+WORK+URGENT-WITHBOSS\"."
6317 (let ((org-show-following-heading nil)
6318 (org-show-hierarchy-above nil))
6319 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6321 (defun org-make-tags-matcher (match)
6322 "Create the TAGS matcher form for the tags-selecting string MATCH."
6324 ;; Get a new match request, with completion
6325 (setq org-last-tags-completion-table
6326 (or (org-get-buffer-tags)
6327 org-last-tags-completion-table))
6328 (setq match (completing-read
6329 "Tags: " 'org-tags-completion-function nil nil nil
6330 'org-tags-history)))
6331 ;; parse the string and create a lisp form
6332 (let ((match0 match) minus tag mm matcher orterms term orlist)
6333 (setq orterms (org-split-string match "|"))
6334 (while (setq term (pop orterms))
6335 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_]+\\)" term)
6336 (setq minus (and (match-end 1)
6337 (equal (match-string 1 term) "-"))
6338 tag (match-string 2 term)
6339 term (substring term (match-end 0))
6340 mm (list 'member (downcase tag) 'tags-list)
6341 mm (if minus (list 'not mm) mm))
6343 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6346 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6347 ;; Return the string and lisp forms of the matcher
6348 (cons match0 matcher)))
6351 (defun org-tags-view (&optional todo-only match keep-modes)
6352 "Show all headlines for all `org-agenda-files' matching a TAGS criterions.
6353 The prefix arg TODO-ONLY limits the search to TODO entries."
6355 (org-agenda-maybe-reset-markers 'force)
6356 (org-compile-prefix-format org-agenda-prefix-format)
6357 (let* ((org-agenda-keep-modes keep-modes)
6358 (org-tags-match-list-sublevels
6359 (if todo-only t org-tags-match-list-sublevels))
6360 (win (selected-window))
6361 (completion-ignore-case t)
6362 rtn rtnall files file pos matcher
6364 (setq matcher (org-make-tags-matcher match)
6365 match (car matcher) matcher (cdr matcher))
6366 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6368 (delete-other-windows)
6369 (switch-to-buffer-other-window
6370 (get-buffer-create org-agenda-buffer-name))))
6371 (setq buffer-read-only nil)
6373 (org-agenda-mode) (setq buffer-read-only nil)
6374 (set (make-local-variable 'org-agenda-type) 'tags)
6375 (set (make-local-variable 'org-agenda-redo-command)
6376 (list 'org-tags-view (list 'quote todo-only)
6377 (list 'if 'current-prefix-arg nil match) t))
6378 (setq files (org-agenda-files)
6380 (while (setq file (pop files))
6382 (org-check-agenda-file file)
6383 (setq buffer (if (file-exists-p file)
6384 (org-get-agenda-file-buffer file)
6385 (error "No such file %s" file)))
6387 ;; If file does not exist, merror message to agenda
6389 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6390 rtnall (append rtnall rtn))
6391 (with-current-buffer buffer
6392 (unless (eq major-mode 'org-mode)
6393 (error "Agenda file %s is not in `org-mode'" file))
6396 (if org-respect-restriction
6397 (if (org-region-active-p)
6398 ;; Respect a region to restrict search
6399 (narrow-to-region (region-beginning) (region-end)))
6400 ;; If we work for the calendar or many files,
6401 ;; get rid of any restriction
6403 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6404 (setq rtnall (append rtnall rtn))))))))
6405 (insert "Headlines with TAGS match: ")
6406 (add-text-properties (point-min) (1- (point))
6407 (list 'face 'org-link))
6410 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6412 (insert "Press `C-u r' to search again with new search string\n")
6413 (add-text-properties pos (1- (point)) (list 'face 'org-link))
6415 (insert (mapconcat 'identity rtnall "\n")))
6416 (goto-char (point-min))
6417 (setq buffer-read-only t)
6418 (org-fit-agenda-window)
6419 (if (not org-select-agenda-window) (select-window win))))
6421 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
6422 (defun org-set-tags (&optional arg just-align)
6423 "Set the tags for the current headline.
6424 With prefix ARG, realign all tags in headings in the current buffer."
6426 (let* (;(inherit (org-get-inherited-tags))
6427 (re (concat "^" outline-regexp))
6428 (col (current-column))
6429 (current (org-get-tags))
6433 (goto-char (point-min))
6434 (while (re-search-forward re nil t)
6435 (org-set-tags nil t))
6436 (message "All tags realigned to column %d" org-tags-column))
6439 (setq org-last-tags-completion-table
6440 (or (org-get-buffer-tags)
6441 org-last-tags-completion-table))
6443 (let ((org-add-colon-after-tag-completion t))
6444 (completing-read "Tags: " 'org-tags-completion-function
6445 nil nil current 'org-tags-history)))
6446 (while (string-match "[-+&]+" tags)
6447 (setq tags (replace-match ":" t t tags)))
6448 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
6449 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
6450 (unless (string-match "^:" tags) (setq tags (concat ":" tags)))))
6451 (if (equal current "")
6454 (or empty (insert " ")))
6455 (beginning-of-line 1)
6456 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
6457 (setq hd (match-string 1))
6458 (delete-region (match-beginning 0) (match-end 0))
6459 (insert (org-trim hd) (if empty "" " ")))
6460 (unless (equal tags "")
6461 (move-to-column (max (current-column)
6462 (if (> org-tags-column 0)
6464 (- (- org-tags-column) (length tags))))
6467 (move-to-column col))))
6469 (defun org-tags-completion-function (string predicate &optional flag)
6470 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
6471 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
6472 (setq s1 (match-string 1 string)
6473 s2 (match-string 2 string))
6474 (setq s1 "" s2 string))
6478 (setq rtn (try-completion s2 ctable))
6480 (concat s1 s2 (substring rtn (length s2))
6481 (if (and org-add-colon-after-tag-completion
6487 (all-completions s2 ctable)
6494 (defun org-get-tags ()
6495 "Get the TAGS string in the current headline."
6496 (unless (org-on-heading-p)
6497 (error "Not on a heading"))
6499 (beginning-of-line 1)
6500 (if (looking-at ".*[ \t]\\(:[A-Za-z_:]+:\\)[ \t]*\\(\r\\|$\\)")
6504 (defun org-get-buffer-tags ()
6505 "Get a table of all tags used in the buffer, for completion."
6508 (goto-char (point-min))
6509 (while (re-search-forward "[ \t]:\\([A-Za-z_:]+\\):[ \t\r\n]" nil t)
6510 (mapc (lambda (x) (add-to-list 'tags x))
6511 (org-split-string (match-string 1) ":"))))
6512 (mapcar 'list tags)))
6516 (defun org-find-file-at-mouse (ev)
6517 "Open file link or URL at mouse."
6519 (mouse-set-point ev)
6520 (org-open-at-point 'in-emacs))
6522 (defun org-open-at-mouse (ev)
6523 "Open file link or URL at mouse."
6525 (mouse-set-point ev)
6526 (org-open-at-point))
6528 (defun org-open-at-point (&optional in-emacs)
6529 "Open link at or after point.
6530 If there is no link at point, this function will search forward up to
6531 the end of the current subtree.
6532 Normally, files will be opened by an appropriate application. If the
6533 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6535 (org-remove-occur-highlights nil nil t)
6536 (if (org-at-timestamp-p)
6537 (org-agenda-list nil (time-to-days (org-time-string-to-time
6538 (substring (match-string 1) 0 10)))
6540 (let (type path line search (pos (point)))
6543 (skip-chars-backward
6544 (concat (if org-allow-space-in-links "^" "^ ")
6545 org-non-link-chars))
6546 (when (looking-at org-link-regexp)
6547 (setq type (match-string 1)
6548 path (match-string 2))
6551 (skip-chars-backward "^ \t\n\r")
6552 (when (looking-at "\\(:[A-Za-z_:]+\\):[ \t\r\n]")
6554 path (match-string 1))
6555 (while (string-match ":" path)
6556 (setq path (replace-match "+" t t path)))
6559 (skip-chars-backward "a-zA-Z_")
6560 (when (looking-at org-camel-regexp)
6561 (setq type "camel" path (match-string 0))
6562 (if (equal (char-before) ?*)
6563 (setq path (concat "*" path))))
6566 (when (re-search-forward
6570 (progn (outline-end-of-subtree) (max pos (point)))
6571 (error (end-of-line 1) (point))))
6573 (setq type (match-string 1)
6574 path (match-string 2)))))
6576 (error "No link found"))
6577 ;; Remove any trailing spaces in path
6578 (if (string-match " +\\'" path)
6579 (setq path (replace-match "" t t path)))
6583 ((string= type "tags")
6584 (org-tags-view path in-emacs))
6585 ((string= type "camel")
6588 (cond ((equal in-emacs '(4)) 'occur)
6589 ((equal in-emacs '(16)) 'org-occur)
6592 ((string= type "file")
6593 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
6594 (setq line (string-to-number (match-string 1 path))
6595 path (substring path 0 (match-beginning 0)))
6596 (if (string-match "::\\(.+\\)\\'" path)
6597 (setq search (match-string 1 path)
6598 path (substring path 0 (match-beginning 0)))))
6599 (org-open-file path in-emacs line search))
6601 ((string= type "news")
6602 (org-follow-gnus-link path))
6604 ((string= type "bbdb")
6605 (org-follow-bbdb-link path))
6607 ((string= type "gnus")
6608 (let (group article)
6609 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6610 (error "Error in Gnus link"))
6611 (setq group (match-string 1 path)
6612 article (match-string 3 path))
6613 (org-follow-gnus-link group article)))
6615 ((string= type "vm")
6616 (let (folder article)
6617 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6618 (error "Error in VM link"))
6619 (setq folder (match-string 1 path)
6620 article (match-string 3 path))
6621 ;; in-emacs is the prefix arg, will be interpreted as read-only
6622 (org-follow-vm-link folder article in-emacs)))
6624 ((string= type "wl")
6625 (let (folder article)
6626 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6627 (error "Error in Wanderlust link"))
6628 (setq folder (match-string 1 path)
6629 article (match-string 3 path))
6630 (org-follow-wl-link folder article)))
6632 ((string= type "rmail")
6633 (let (folder article)
6634 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6635 (error "Error in RMAIL link"))
6636 (setq folder (match-string 1 path)
6637 article (match-string 3 path))
6638 (org-follow-rmail-link folder article)))
6640 ((string= type "shell")
6642 (while (string-match "@{" cmd)
6643 (setq cmd (replace-match "<" t t cmd)))
6644 (while (string-match "@}" cmd)
6645 (setq cmd (replace-match ">" t t cmd)))
6646 (if (or (not org-confirm-shell-links)
6647 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
6652 (browse-url-at-point))))))
6654 (defun org-link-search (s &optional type)
6655 "Search for a link search option.
6656 When S is a CamelCaseWord, search for a target, or for a sentence containing
6657 the words. If S is surrounded by forward slashes, it is interpreted as a
6658 regular expression. In org-mode files, this will create an `org-occur'
6659 sparse tree. In ordinary files, `occur' will be used to list matched.
6660 If the current buffer is in `dired-mode', grep will be used to search
6662 (let ((case-fold-search t)
6666 words re0 re1 re2 re3 re4 re5 reall)
6667 (cond ((string-match "^/\\(.*\\)/$" s)
6668 ;; A regular expression
6670 ((eq major-mode 'org-mode)
6671 (org-occur (match-string 1 s)))
6672 ;;((eq major-mode 'dired-mode)
6673 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6674 (t (org-do-occur (match-string 1 s)))))
6675 ((string-match (concat "^" org-camel-regexp) s)
6677 (if (equal (string-to-char s) ?*)
6678 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
6681 (remove-text-properties
6683 '(face nil mouse-face nil keymap nil fontified nil) s)
6684 ;; Make a series of regular expressions to find a match
6685 (setq words (org-camel-to-words s)
6686 re0 (concat "<<" (regexp-quote s0) ">>")
6687 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
6688 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
6689 re1 (concat pre re2 post)
6690 re3 (concat pre re4 post)
6691 re5 (concat pre ".*" re4)
6692 re2 (concat pre re2)
6693 re4 (concat pre re4)
6694 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6695 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6699 ((eq type 'org-occur) (org-occur reall))
6700 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6701 (t (goto-char (point-min))
6702 (if (or (re-search-forward re0 nil t)
6703 (re-search-forward re1 nil t)
6704 (re-search-forward re2 nil t)
6705 (re-search-forward re3 nil t)
6706 (re-search-forward re4 nil t)
6707 (re-search-forward re5 nil t))
6708 (goto-char (match-beginning 0))
6710 (error "No match")))))
6712 ;; Normal string-search
6713 (goto-char (point-min))
6714 (if (search-forward s nil t)
6715 (goto-char (match-beginning 0))
6716 (error "No match"))))))
6718 (defun org-do-occur (regexp &optional cleanup)
6719 "Call the Emacs command `occur'.
6720 If CLEANUP is non-nil, remove the printout of the regular expression
6721 in the *Occur* buffer. This is useful if the regex is long and not useful
6725 (let ((cwin (selected-window)) win beg end)
6726 (when (setq win (get-buffer-window "*Occur*"))
6727 (select-window win))
6728 (goto-char (point-min))
6729 (when (re-search-forward "match[a-z]+" nil t)
6730 (setq beg (match-end 0))
6731 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6732 (setq end (1- (match-beginning 0)))))
6733 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
6734 (goto-char (point-min))
6735 (select-window cwin))))
6737 (defun org-camel-to-words (s)
6738 "Split \"CamelCaseWords\" to (\"Camel \" \"Case\" \"Words\")."
6739 (let ((case-fold-search nil)
6741 (while (string-match "[a-z][A-Z]" s)
6742 (push (substring s 0 (1+ (match-beginning 0))) words)
6743 (setq s (substring s (1+ (match-beginning 0)))))
6744 (nreverse (cons s words))))
6746 (defun org-follow-bbdb-link (name)
6747 "Follow a BBDB link to NAME."
6749 (let ((inhibit-redisplay t))
6751 ;; Exact match on name
6752 (bbdb-name (concat "\\`" name "\\'") nil)
6753 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6754 ;; Exact match on name
6755 (bbdb-company (concat "\\`" name "\\'") nil)
6756 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6757 ;; Partial match on name
6758 (bbdb-name name nil)
6759 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6760 ;; Partial match on company
6761 (bbdb-company name nil)
6762 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
6763 ;; General match including network address and notes
6765 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
6766 (delete-window (get-buffer-window "*BBDB*"))
6767 (error "No matching BBDB record")))))
6769 (defun org-follow-gnus-link (&optional group article)
6770 "Follow a Gnus link to GROUP and ARTICLE."
6772 (funcall (cdr (assq 'gnus org-link-frame-setup)))
6773 (if group (gnus-fetch-group group))
6775 (or (gnus-summary-goto-article article nil 'force)
6776 (if (fboundp 'gnus-summary-insert-cached-articles)
6778 (gnus-summary-insert-cached-articles)
6779 (gnus-summary-goto-article article nil 'force))
6780 (message "Message could not be found.")))))
6782 (defun org-follow-vm-link (&optional folder article readonly)
6783 "Follow a VM link to FOLDER and ARTICLE."
6785 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
6786 ;; ange-ftp or efs or tramp access
6787 (let ((user (or (match-string 1 folder) (user-login-name)))
6788 (host (match-string 2 folder))
6789 (file (match-string 3 folder)))
6792 ;; use tramp to access the file
6794 (setq folder (format "[%s@%s]%s" user host file))
6795 (setq folder (format "/%s@%s:%s" user host file))))
6797 ;; use ange-ftp or efs
6798 (require (if org-xemacs-p 'efs 'ange-ftp))
6799 (setq folder (format "/%s@%s:%s" user host file))))))
6801 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
6804 (vm-select-folder-buffer)
6806 (let ((case-fold-search t))
6807 (goto-char (point-min))
6808 (if (not (re-search-forward
6809 (concat "^" "message-id: *" (regexp-quote article))))
6810 (error "Could not find the specified message in this folder"))
6813 (vm-beginning-of-message)
6816 (defun org-follow-wl-link (folder article)
6817 "Follow a Wanderlust link to FOLDER and ARTICLE."
6818 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
6819 (if article (wl-summary-jump-to-msg-by-message-id article))
6820 (wl-summary-redisplay))
6822 (defun org-follow-rmail-link (folder article)
6823 "Follow an RMAIL link to FOLDER and ARTICLE."
6824 (let (message-number)
6826 (save-window-excursion
6827 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6828 (setq message-number
6831 (goto-char (point-max))
6832 (if (re-search-backward
6833 (concat "^Message-ID:\\s-+" (regexp-quote
6836 (rmail-what-message))))))
6839 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
6840 (rmail-show-message message-number)
6842 (error "Message not found"))))
6844 (defun org-open-file (path &optional in-emacs line search)
6845 "Open the file at PATH.
6846 First, this expands any special file name abbreviations. Then the
6847 configuration variable `org-file-apps' is checked if it contains an
6848 entry for this file type, and if yes, the corresponding command is launched.
6849 If no application is found, Emacs simply visits the file.
6850 With optional argument IN-EMACS, Emacs will visit the file.
6851 Optional LINE specifies a line to go to, optional SEARCH a string to
6852 search for. If LINE or SEARCH is given, the file will always be
6854 If the file does not exist, an error is thrown."
6855 (setq in-emacs (or in-emacs line search))
6856 (let* ((file (if (equal path "")
6858 (convert-standard-filename (org-expand-file-name path))))
6859 (dfile (downcase file))
6861 (if (and (not (file-exists-p file))
6862 (not org-open-non-existing-files))
6863 (error "No such file: %s" file))
6864 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
6865 (setq ext (match-string 1 dfile))
6866 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
6867 (setq ext (match-string 1 dfile))))
6868 (setq apps (append org-file-apps (org-default-apps)))
6871 (setq cmd (or (cdr (assoc ext apps))
6872 (cdr (assoc t apps)))))
6874 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
6875 (setq cmd (format cmd (concat "\"" file "\"")))
6876 (save-window-excursion
6877 (shell-command (concat cmd " & &"))))
6880 (unless (equal (file-truename file) (file-truename (buffer-file-name)))
6881 (funcall (cdr (assq 'file org-link-frame-setup)) file))
6882 (if line (goto-line line)
6883 (if search (org-link-search search))))
6886 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
6888 (defun org-default-apps ()
6889 "Return the default applications for this operating system."
6891 ((eq system-type 'darwin)
6892 org-file-apps-defaults-macosx)
6893 ((eq system-type 'windows-nt)
6894 org-file-apps-defaults-windowsnt)
6895 (t org-file-apps-defaults-gnu)))
6897 (defun org-expand-file-name (path)
6898 "Replace special path abbreviations and expand the file name."
6899 (expand-file-name path))
6902 (defvar org-insert-link-history nil
6903 "Minibuffer history for links inserted with `org-insert-link'.")
6905 (defvar org-stored-links nil
6906 "Contains the links stored with `org-store-link'.")
6909 (defun org-store-link (arg)
6910 "\\<org-mode-map>Store an org-link to the current location.
6911 This link can later be inserted into an org-buffer with
6912 \\[org-insert-link].
6913 For some link types, a prefix arg is interpreted:
6914 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6915 For file links, arg negates `org-context-in-file-links'."
6920 ((eq major-mode 'bbdb-mode)
6921 (setq cpltxt (concat
6923 (or (bbdb-record-name (bbdb-current-record))
6924 (bbdb-record-company (bbdb-current-record))))
6925 link (org-make-link cpltxt)))
6927 ((eq major-mode 'calendar-mode)
6928 (let ((cd (calendar-cursor-to-date)))
6931 (car org-time-stamp-formats)
6933 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6936 ((or (eq major-mode 'vm-summary-mode)
6937 (eq major-mode 'vm-presentation-mode))
6938 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
6939 (vm-follow-summary-cursor)
6941 (vm-select-folder-buffer)
6942 (let* ((message (car vm-message-pointer))
6943 (folder (buffer-file-name))
6944 (subject (vm-su-subject message))
6945 (author (vm-su-full-name message))
6946 (message-id (vm-su-message-id message)))
6947 (setq folder (abbreviate-file-name folder))
6948 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
6950 (setq folder (replace-match "" t t folder)))
6951 (setq cpltxt (concat author " on: " subject))
6952 (setq link (concat cpltxt "\n "
6954 "vm:" folder "#" message-id))))))
6956 ((eq major-mode 'wl-summary-mode)
6957 (let* ((msgnum (wl-summary-message-number))
6958 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
6959 msgnum 'message-id))
6960 (wl-message-entity (elmo-msgdb-overview-get-entity
6961 msgnum (wl-summary-buffer-msgdb)))
6962 (author (wl-summary-line-from)) ; FIXME: how to get author name?
6963 (subject "???")) ; FIXME: How to get subject of email?
6964 (setq cpltxt (concat author " on: " subject))
6965 (setq link (concat cpltxt "\n "
6967 "wl:" wl-summary-buffer-folder-name
6970 ((eq major-mode 'rmail-mode)
6973 (rmail-narrow-to-non-pruned-header)
6974 (let ((folder (buffer-file-name))
6975 (message-id (mail-fetch-field "message-id"))
6976 (author (mail-fetch-field "from"))
6977 (subject (mail-fetch-field "subject")))
6978 (setq cpltxt (concat author " on: " subject))
6979 (setq link (concat cpltxt "\n "
6981 "rmail:" folder "#" message-id)))))))
6983 ((eq major-mode 'gnus-group-mode)
6984 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
6985 (gnus-group-group-name)) ; version
6986 ((fboundp 'gnus-group-name)
6989 (setq cpltxt (concat
6990 (if (org-xor arg org-usenet-links-prefer-google)
6991 "http://groups.google.com/groups?group="
6994 link (org-make-link cpltxt))))
6996 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
6997 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
6998 (gnus-summary-beginning-of-article)
6999 (let* ((group (car gnus-article-current))
7000 (article (cdr gnus-article-current))
7001 (header (gnus-summary-article-header article))
7002 (author (mail-header-from header))
7003 (message-id (mail-header-id header))
7004 (date (mail-header-date header))
7005 (subject (gnus-summary-subject-string)))
7006 (setq cpltxt (concat author " on: " subject))
7007 (if (org-xor arg org-usenet-links-prefer-google)
7011 (format "http://groups.google.com/groups?as_umsgid=%s"
7012 (org-fixup-message-id-for-http message-id))))
7013 (setq link (concat cpltxt "\n"
7016 "#" (number-to-string article)))))))
7018 ((eq major-mode 'w3-mode)
7019 (setq cpltxt (url-view-url t)
7020 link (org-make-link cpltxt)))
7021 ((eq major-mode 'w3m-mode)
7022 (setq cpltxt w3m-current-url
7023 link (org-make-link cpltxt)))
7025 ((eq major-mode 'org-mode)
7026 ;; Just link to current headline
7027 (setq cpltxt (concat "file:"
7028 (abbreviate-file-name (buffer-file-name))))
7029 ;; Add a context search string
7030 (when (org-xor org-context-in-file-links arg)
7032 (skip-chars-backward "a-zA-Z<")
7033 (looking-at (concat "<<\\(" org-camel-regexp "\\)>>")))
7034 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7037 (org-make-org-heading-camel
7039 ((org-on-heading-p) nil)
7040 ((org-region-active-p)
7041 (buffer-substring (region-beginning) (region-end)))
7042 (t (buffer-substring (point-at-bol) (point-at-eol))))
7044 (setq link (org-make-link cpltxt)))
7047 ;; Just link to this file here.
7048 (setq cpltxt (concat "file:"
7049 (abbreviate-file-name (buffer-file-name))))
7050 ;; Add a context string
7051 (when (org-xor org-context-in-file-links arg)
7054 (org-make-org-heading-camel
7055 (if (org-region-active-p)
7056 (buffer-substring (region-beginning) (region-end))
7057 (buffer-substring (point-at-bol) (point-at-eol)))))))
7058 (setq link (org-make-link cpltxt)))
7061 (error "Cannot link to a buffer which is not visiting a file"))
7063 (t (setq link nil)))
7065 (if (and (interactive-p) link)
7067 (setq org-stored-links
7068 (cons (cons (or cpltxt link) link) org-stored-links))
7069 (message "Stored: %s" (or cpltxt link)))
7072 (defun org-make-org-heading-camel (&optional string)
7073 "Make a CamelCase string for S or the current headline."
7075 (let ((s (or string (org-get-heading))))
7077 ;; We are using a headline, clean up garbage in there.
7078 (if (string-match org-todo-regexp s)
7079 (setq s (replace-match "" t t s)))
7080 (setq s (org-trim s))
7081 (if (string-match (concat "^\\(" org-quote-string "\\|"
7082 org-comment-string "\\)") s)
7083 (setq s (replace-match "" t t s)))
7084 (while (string-match org-ts-regexp s)
7085 (setq s (replace-match "" t t s))))
7086 (while (string-match "[^a-zA-Z_ \t]+" s)
7087 (setq s (replace-match " " t t s)))
7088 (or string (setq s (concat "*" s))) ; Add * for headlines
7089 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7091 (defun org-make-link (&rest strings)
7092 "Concatenate STRINGS, format resulting string with `org-link-format'."
7093 (format org-link-format (apply 'concat strings)))
7095 (defun org-xor (a b)
7099 (defun org-get-header (header)
7100 "Find a header field in the current buffer."
7102 (goto-char (point-min))
7103 (let ((case-fold-search t) s)
7106 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7107 (setq s (match-string 1)))
7108 (while (string-match "\"" s)
7109 (setq s (replace-match "" t t s)))
7110 (if (string-match "[<(].*" s)
7111 (setq s (replace-match "" t t s))))
7112 ((eq header 'message-id)
7113 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7114 (setq s (match-string 1))))
7115 ((eq header 'subject)
7116 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7117 (setq s (match-string 1)))))
7118 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7119 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7123 (defun org-fixup-message-id-for-http (s)
7124 "Replace special characters in a message id, so it can be used in an http query."
7125 (while (string-match "<" s)
7126 (setq s (replace-match "%3C" t t s)))
7127 (while (string-match ">" s)
7128 (setq s (replace-match "%3E" t t s)))
7129 (while (string-match "@" s)
7130 (setq s (replace-match "%40" t t s)))
7133 (defun org-insert-link (&optional complete-file)
7134 "Insert a link. At the prompt, enter the link.
7136 Completion can be used to select a link previously stored with
7137 `org-store-link'. When the empty string is entered (i.e. if you just
7138 press RET at the prompt), the link defaults to the most recently
7139 stored link. As SPC triggers completion in the minibuffer, you need to
7140 use M-SPC or C-q SPC to force the insertion of a space character.
7142 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7143 selected using completion. The path to the file will be relative to
7144 the current directory if the file is in the current directory or a
7145 subdirectory. Otherwise, the link will be the absolute path as
7146 completed in the minibuffer (i.e. normally ~/path/to/file).
7148 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7149 is in the current directory or below."
7151 (let ((link (if complete-file
7152 (read-file-name "File: ")
7154 "Link: " org-stored-links nil nil nil
7155 org-insert-link-history
7156 (or (car (car org-stored-links))))))
7158 (if (or (not link) (equal link ""))
7159 (error "No links available"))
7161 (let ((pwd (file-name-as-directory (expand-file-name "."))))
7163 ((equal complete-file '(16))
7166 "file:" (abbreviate-file-name (expand-file-name link)))))
7167 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7168 (expand-file-name link))
7171 "file:" (match-string 1 (expand-file-name link)))))
7172 (t (insert (org-make-link "file:" link)))))
7173 (setq linktxt (cdr (assoc link org-stored-links)))
7174 (if (not org-keep-stored-link-after-insertion)
7175 (setq org-stored-links (delq (assoc link org-stored-links)
7177 (if (not linktxt) (setq link (org-make-link link)))
7178 (setq link (or linktxt link))
7179 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
7180 (let* ((path (match-string 1 link))
7181 (case-fold-search nil)
7182 (search (match-string 2 link)))
7183 (when (save-match-data
7184 (equal (file-truename (buffer-file-name))
7185 (file-truename path)))
7186 (if (save-match-data
7187 (string-match (concat "^" org-camel-regexp "$") search))
7188 (setq link (replace-match search t t link)
7190 (setq link (replace-match (concat "<file:::" search ">")
7192 (let ((lines (org-split-string link "\n")))
7193 (insert (car lines))
7194 (setq matched (or matched (string-match org-link-regexp (car lines))))
7195 (setq lines (cdr lines))
7199 (beginning-of-line 0)
7200 (looking-at "[ \t]+\\S-"))
7202 (setq matched (or matched
7203 (string-match org-link-regexp (car lines))))
7204 (insert (car lines))
7205 (setq lines (cdr lines))))
7207 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
7209 ;;; Hooks for remember.el
7211 (defun org-remember-annotation ()
7212 "Return a link to the current location as an annotation for remember.el.
7213 If you are using Org-mode files as target for data storage with
7214 remember.el, then the annotations should include a link compatible with the
7215 conventions in Org-mode. This function returns such a link."
7216 (org-store-link nil))
7218 (defconst org-remember-help
7219 "Select a destination location for the note.
7220 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
7221 RET at beg-of-buf -> Append to file as level 2 headline
7222 RET on headline -> Store as sublevel entry to current headline
7223 <left>/<right> -> before/after current headline, same headings level")
7226 (defun org-remember-handler ()
7227 "Store stuff from remember.el into an org file.
7228 First prompts for an org file. If the user just presses return, the value
7229 of `org-default-notes-file' is used.
7230 Then the command offers the headings tree of the selected file in order to
7231 file the text at a specific location.
7232 You can either immediately press RET to get the note appended to the
7233 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
7234 find a better place. Then press RET or <left> or <right> in insert the note.
7236 Key Cursor position Note gets inserted
7237 -----------------------------------------------------------------------------
7238 RET buffer-start as level 2 heading at end of file
7239 RET on headline as sublevel of the heading at cursor
7240 RET no heading at cursor position, level taken from context.
7241 Or use prefix arg to specify level manually.
7242 <left> on headline as same level, before current heading
7243 <right> on headline as same level, after current heading
7245 So the fastest way to store the note is to press RET RET to append it to
7246 the default file. This way your current train of thought is not
7247 interrupted, in accordance with the principles of remember.el. But with
7248 little extra effort, you can push it directly to the correct location.
7250 Before being stored away, the function ensures that the text has a
7251 headline, i.e. a first line that starts with a \"*\". If not, a headline
7252 is constructed from the current date and some additional data.
7254 If the variable `org-adapt-indentation' is non-nil, the entire text is
7255 also indented so that it starts in the same column as the headline
7256 \(i.e. after the stars).
7258 See also the variable `org-reverse-note-order'."
7260 (let* ((txt (buffer-substring (point-min) (point-max)))
7261 (fastp current-prefix-arg)
7262 (file (if fastp org-default-notes-file (org-get-org-file)))
7263 (visiting (find-buffer-visiting file))
7264 (org-startup-with-deadline-check nil)
7265 (org-startup-folded nil)
7266 spos level indent reversed)
7267 ;; Modify text so that it becomes a nice subtree which can be inserted
7268 ;; into an org tree.
7269 (let* ((lines (split-string txt "\n"))
7271 (lines (cdr lines)))
7272 (if (string-match "^\\*+" first)
7273 ;; Is already a headline
7274 (setq indent (make-string (- (match-end 0) (match-beginning 0)
7276 ;; We need to add a headline: Use time and first buffer line
7277 (setq lines (cons first lines)
7278 first (concat "* " (current-time-string)
7279 " (" (remember-buffer-desc) ")")
7281 (if org-adapt-indentation
7282 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
7283 (setq txt (concat first "\n"
7284 (mapconcat 'identity lines "\n"))))
7287 (find-file-noselect file))
7288 (with-current-buffer (get-file-buffer file)
7289 (setq reversed (org-notes-order-reversed-p))
7293 ;; Ask the User for a location
7294 (setq spos (if fastp 1 (org-get-location
7296 org-remember-help)))
7297 (if (not spos) (throw 'quit nil)) ; return nil to show we did
7298 ; not handle this note
7301 ;; Put it at the start or end, as level 2
7304 (goto-char (if reversed (point-min) (point-max)))
7305 (if (not (bolp)) (newline))
7306 (org-paste-subtree (or current-prefix-arg 2) txt)))
7307 ((and (org-on-heading-p nil) (not current-prefix-arg))
7308 ;; Put it below this entry, at the beg/end of the subtree
7309 (org-back-to-heading)
7310 (setq level (outline-level))
7312 (outline-end-of-heading)
7313 (outline-end-of-subtree))
7314 (if (not (bolp)) (newline))
7315 (beginning-of-line 1)
7316 (org-paste-subtree (1+ level) txt))
7318 ;; Put it right there, with automatic level determined by
7319 ;; org-paste-subtree or from prefix arg
7320 (org-paste-subtree current-prefix-arg txt)))
7321 (when remember-save-after-remembering
7323 (if (not visiting) (kill-buffer (current-buffer)))))))))
7324 t) ;; return t to indicate that we took care of this note.
7326 (defun org-get-org-file ()
7327 "Read a filename, with default directory `org-directory'."
7328 (let ((default (or org-default-notes-file remember-data-file)))
7329 (read-file-name (format "File name [%s]: " default)
7330 (file-name-as-directory org-directory)
7333 (defun org-notes-order-reversed-p ()
7334 "Check if the current file should receive notes in reversed order."
7336 ((not org-reverse-note-order) nil)
7337 ((eq t org-reverse-note-order) t)
7338 ((not (listp org-reverse-note-order)) nil)
7340 (let ((all org-reverse-note-order)
7342 (while (setq entry (pop all))
7343 (if (string-match (car entry) (buffer-file-name))
7344 (throw 'exit (cdr entry))))
7349 ;; Watch out: Here we are talking about two different kind of tables.
7350 ;; Most of the code is for the tables created with the Org-mode table editor.
7351 ;; Sometimes, we talk about tables created and edited with the table.el
7352 ;; Emacs package. We call the former org-type tables, and the latter
7353 ;; table.el-type tables.
7356 (defun org-before-change-function (beg end)
7357 "Every change indicates that a table might need an update."
7358 (setq org-table-may-need-update t))
7360 (defconst org-table-line-regexp "^[ \t]*|"
7361 "Detects an org-type table line.")
7362 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
7363 "Detects an org-type table line.")
7364 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
7365 "Detects a table line marked for automatic recalculation.")
7366 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
7367 "Detects a table line marked for automatic recalculation.")
7368 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
7369 "Detects a table line marked for automatic recalculation.")
7370 (defconst org-table-hline-regexp "^[ \t]*|-"
7371 "Detects an org-type table hline.")
7372 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
7373 "Detects a table-type table hline.")
7374 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
7375 "Detects an org-type or table-type table.")
7376 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
7377 "Searching from within a table (any type) this finds the first line
7378 outside the table.")
7379 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
7380 "Searching from within a table (any type) this finds the first line
7381 outside the table.")
7383 (defun org-table-create-with-table.el ()
7384 "Use the table.el package to insert a new table.
7385 If there is already a table at point, convert between Org-mode tables
7386 and table.el tables."
7390 ((org-at-table.el-p)
7391 (if (y-or-n-p "Convert table to Org-mode table? ")
7392 (org-table-convert)))
7394 (if (y-or-n-p "Convert table to table.el table? ")
7395 (org-table-convert)))
7396 (t (call-interactively 'table-insert))))
7398 (defun org-table-create (&optional size)
7399 "Query for a size and insert a table skeleton.
7400 SIZE is a string Columns x Rows like for example \"3x2\"."
7403 (setq size (read-string
7404 (concat "Table size Columns x Rows [e.g. "
7405 org-table-default-size "]: ")
7406 "" nil org-table-default-size)))
7408 (let* ((pos (point))
7409 (indent (make-string (current-column) ?\ ))
7410 (split (org-split-string size " *x *"))
7411 (rows (string-to-number (nth 1 split)))
7412 (columns (string-to-number (car split)))
7413 (line (concat (apply 'concat indent "|" (make-list columns " |"))
7415 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
7416 (point-at-bol) (point)))
7417 (beginning-of-line 1)
7419 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
7420 (dotimes (i rows) (insert line))
7423 ;; Insert a hline after the first row.
7430 (defun org-table-convert-region (beg0 end0 nspace)
7431 "Convert region to a table.
7432 The region goes from BEG0 to END0, but these borders will be moved
7433 slightly, to make sure a beginning of line in the first line is included.
7434 When NSPACE is non-nil, it indicates the minimum number of spaces that
7435 separate columns (default: just one space)"
7436 (let* ((beg (min beg0 end0))
7437 (end (max beg0 end0))
7441 (beginning-of-line 1)
7442 (setq beg (move-marker (make-marker) (point)))
7444 (if (bolp) (backward-char 1) (end-of-line 1))
7445 (setq end (move-marker (make-marker) (point)))
7446 ;; Lets see if this is tab-separated material. If every nonempty line
7447 ;; contains a tab, we will assume that it is tab-separated material
7451 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
7452 (if nspace (setq tabsep nil))
7455 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
7456 (max 1 (prefix-numeric-value nspace)))))
7458 (while (re-search-forward re end t)
7459 (replace-match "|" t t))
7464 (defun org-table-import (file arg)
7465 "Import FILE as a table.
7466 The file is assumed to be tab-separated. Such files can be produced by most
7467 spreadsheet and database applications. If no tabs (at least one per line)
7468 are found, lines will be split on whitespace into fields."
7469 (interactive "f\nP")
7470 (or (bolp) (newline))
7473 (insert-file-contents file)
7474 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
7476 (defun org-table-export ()
7477 "Export table as a tab-separated file.
7478 Such a file can be imported into a spreadsheet program like Excel."
7480 (let* ((beg (org-table-begin))
7481 (end (org-table-end))
7482 (table (buffer-substring beg end))
7483 (file (read-file-name "Export table to: "))
7485 (unless (or (not (file-exists-p file))
7486 (y-or-n-p (format "Overwrite file %s? " file)))
7488 (with-current-buffer (find-file-noselect file)
7489 (setq buf (current-buffer))
7493 (goto-char (point-min))
7494 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
7495 (replace-match "" t t)
7497 (goto-char (point-min))
7498 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
7499 (replace-match "" t t)
7500 (goto-char (min (1+ (point)) (point-max))))
7501 (goto-char (point-min))
7502 (while (re-search-forward "^-[-+]*$" nil t)
7504 (if (looking-at "\n")
7506 (goto-char (point-min))
7507 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
7508 (replace-match "\t" t t))
7512 (defvar org-table-aligned-begin-marker (make-marker)
7513 "Marker at the beginning of the table last aligned.
7514 Used to check if cursor still is in that table, to minimize realignment.")
7515 (defvar org-table-aligned-end-marker (make-marker)
7516 "Marker at the end of the table last aligned.
7517 Used to check if cursor still is in that table, to minimize realignment.")
7518 (defvar org-table-last-alignment nil
7519 "List of flags for flushright alignment, from the last re-alignment.
7520 This is being used to correctly align a single field after TAB or RET.")
7521 ;; FIXME: The following is currently not used.
7522 (defvar org-table-last-column-widths nil
7523 "List of max width of fields in each column.
7524 This is being used to correctly align a single field after TAB or RET.")
7526 (defvar org-last-recalc-line nil)
7528 (defun org-table-align ()
7529 "Align the table at point by aligning all vertical bars."
7531 ;; (message "align") (sit-for 2)
7534 (beg (org-table-begin))
7535 (end (org-table-end))
7536 ;; Current cursor position
7537 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7538 (colpos (org-table-current-column))
7539 (winstart (window-start))
7540 text lines (new "") lengths l typenums ty fields maxfields i
7542 (indent "") cnt frac
7544 (spaces (if (org-in-invisibility-spec-p '(org-table))
7545 org-table-spaces-around-invisible-separators
7546 org-table-spaces-around-separators))
7550 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
7552 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
7555 ;; (message "Aligning table...")
7557 (setq lines (org-split-string
7558 (buffer-substring-no-properties beg end) "\n"))
7559 ;; Store the indentation of the first line
7560 (if (string-match "^ *" (car lines))
7561 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
7563 (setq lines (mapcar (lambda (l)
7564 (if (string-match "^ *|-" l)
7566 (if (string-match "[ \t]+$" l)
7567 (substring l 0 (match-beginning 0))
7570 ;; Get the data fields
7571 (setq fields (mapcar
7573 (org-split-string l " *| *"))
7574 (delq nil (copy-sequence lines))))
7575 ;; How many fields in the longest line?
7577 (setq maxfields (apply 'max (mapcar 'length fields)))
7579 (kill-region beg end)
7580 (org-table-create org-table-default-size)
7581 (error "Empty table - created default table")))
7582 ;; A list of empty string to fill any short rows on output
7583 (setq emptystrings (make-list maxfields ""))
7584 ;; Get the maximum length of a field and the most common datatype
7587 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
7588 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
7590 (push (apply 'max 1 (mapcar 'length column)) lengths)
7591 ;; compute the fraction stepwise, ignoring empty fields
7592 (setq cnt 0 frac 0.0)
7597 (setq frac ( / (+ (* frac cnt)
7598 (if (string-match org-table-number-regexp x) 1 0))
7599 (setq cnt (1+ cnt))))))
7601 (push (>= frac org-table-number-fraction) typenums))
7602 (setq lengths (nreverse lengths)
7603 typenums (nreverse typenums))
7604 (setq org-table-last-alignment typenums
7605 org-table-last-column-widths lengths)
7606 ;; Compute the formats needed for output of the table
7607 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
7608 (while (setq l (pop lengths))
7609 (setq ty (if (pop typenums) "" "-")) ; number types flushright
7610 (setq rfmt (concat rfmt (format rfmt1 ty l))
7611 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
7612 (setq rfmt (concat rfmt "\n")
7613 hfmt (concat (substring hfmt 0 -1) "|\n"))
7614 ;; Produce the new table
7616 ;; (setq l (pop lines))
7618 ;; (setq new (concat new (apply 'format rfmt
7619 ;; (append (pop fields) emptystrings))))
7620 ;; (setq new (concat new hfmt))))
7621 (setq new (mapconcat
7623 (if l (apply 'format rfmt
7624 (append (pop fields) emptystrings))
7627 ;; Replace the old one
7628 (delete-region beg end)
7629 (move-marker end nil)
7630 (move-marker org-table-aligned-begin-marker (point))
7632 (move-marker org-table-aligned-end-marker (point))
7633 ;; Try to move to the old location (approximately)
7635 (set-window-start (selected-window) winstart 'noforce)
7636 (org-table-goto-column colpos)
7637 (setq org-table-may-need-update nil)
7638 (if (org-in-invisibility-spec-p '(org-table))
7639 (org-table-add-invisible-to-vertical-lines))
7642 (defun org-table-begin (&optional table-type)
7643 "Find the beginning of the table and return its position.
7644 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
7646 (if (not (re-search-backward
7647 (if table-type org-table-any-border-regexp
7648 org-table-border-regexp)
7650 (error "Can't find beginning of table")
7651 (goto-char (match-beginning 0))
7652 (beginning-of-line 2)
7655 (defun org-table-end (&optional table-type)
7656 "Find the end of the table and return its position.
7657 With argument TABLE-TYPE, go to the end of a table.el-type table."
7659 (if (not (re-search-forward
7660 (if table-type org-table-any-border-regexp
7661 org-table-border-regexp)
7663 (goto-char (point-max))
7664 (goto-char (match-beginning 0)))
7667 (defun org-table-justify-field-maybe (&optional new)
7668 "Justify the current field, text to left, number to right.
7669 Optional argument NEW may specify text to replace the current field content."
7671 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
7672 ((org-at-table-hline-p)
7673 ;; FIXME: I used to enforce realign here, but I think this is not needed.
7674 ;; (setq org-table-may-need-update t)
7677 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
7679 (< (point) org-table-aligned-begin-marker)
7680 (>= (point) org-table-aligned-end-marker)))
7681 ;; This is not the same table, force a full re-align
7682 (setq org-table-may-need-update t))
7683 (t ;; realign the current field, based on previous full realign
7684 (let* ((pos (point)) s
7685 (col (org-table-current-column))
7686 (num (nth (1- col) org-table-last-alignment))
7689 (skip-chars-backward "^|\n")
7690 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
7692 (setq s (match-string 1)
7694 l (max 1 (- (match-end 0) (match-beginning 0) 3))
7695 e (not (= (match-beginning 2) (match-end 2))))
7696 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
7697 l (if e "|" (setq org-table-may-need-update t) ""))
7700 (if (<= (length new) l)
7701 (setq n (format f new t t)) ;; FIXME: why t t?????
7702 (setq n (concat new "|") org-table-may-need-update t)))
7704 (let (org-table-may-need-update)
7705 (replace-match n))))
7706 (setq org-table-may-need-update t))
7707 (goto-char pos))))))
7709 (defun org-table-next-field ()
7710 "Go to the next field in the current table, creating new lines as needed.
7711 Before doing so, re-align the table if necessary."
7713 (org-table-maybe-eval-formula)
7714 (org-table-maybe-recalculate-line)
7715 (if (and org-table-automatic-realign
7716 org-table-may-need-update)
7718 (let ((end (org-table-end)))
7719 (if (org-at-table-hline-p)
7723 (re-search-forward "|" end)
7724 (if (looking-at "[ \t]*$")
7725 (re-search-forward "|" end))
7726 (if (and (looking-at "-")
7727 org-table-tab-jumps-over-hlines
7728 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
7729 (goto-char (match-beginning 1)))
7730 (if (looking-at "-")
7732 (beginning-of-line 0)
7733 (org-table-insert-row 'below))
7734 (if (looking-at " ") (forward-char 1))))
7736 (org-table-insert-row 'below)))))
7738 (defun org-table-previous-field ()
7739 "Go to the previous field in the table.
7740 Before doing so, re-align the table if necessary."
7742 (org-table-justify-field-maybe)
7743 (org-table-maybe-recalculate-line)
7744 (if (and org-table-automatic-realign
7745 org-table-may-need-update)
7747 (if (org-at-table-hline-p)
7749 (re-search-backward "|" (org-table-begin))
7750 (re-search-backward "|" (org-table-begin))
7751 (while (looking-at "|\\(-\\|[ \t]*$\\)")
7752 (re-search-backward "|" (org-table-begin)))
7753 (if (looking-at "| ?")
7754 (goto-char (match-end 0))))
7756 (defun org-table-next-row ()
7757 "Go to the next row (same column) in the current table.
7758 Before doing so, re-align the table if necessary."
7760 (org-table-maybe-eval-formula)
7761 (org-table-maybe-recalculate-line)
7762 (if (or (looking-at "[ \t]*$")
7763 (save-excursion (skip-chars-backward " \t") (bolp)))
7765 (if (and org-table-automatic-realign
7766 org-table-may-need-update)
7768 (let ((col (org-table-current-column)))
7769 (beginning-of-line 2)
7770 (if (or (not (org-at-table-p))
7771 (org-at-table-hline-p))
7773 (beginning-of-line 0)
7774 (org-table-insert-row 'below)))
7775 (org-table-goto-column col)
7776 (skip-chars-backward "^|\n\r")
7777 (if (looking-at " ") (forward-char 1)))))
7779 (defun org-table-copy-down (n)
7780 "Copy a field down in the current column.
7781 If the field at the cursor is empty, copy into it the content of the nearest
7782 non-empty field above. With argument N, use the Nth non-empty field.
7783 If the current field is not empty, it is copied down to the next row, and
7784 the cursor is moved with it. Therefore, repeating this command causes the
7785 column to be filled row-by-row.
7786 If the variable `org-table-copy-increment' is non-nil and the field is an
7787 integer, it will be incremented while copying."
7789 (let* ((colpos (org-table-current-column))
7790 (field (org-table-get-field))
7791 (non-empty (string-match "[^ \t]" field))
7792 (beg (org-table-begin))
7794 (org-table-check-inside-data-field)
7797 (setq txt (org-trim field))
7798 (org-table-next-row)
7799 (org-table-blank-field))
7803 (while (progn (beginning-of-line 1)
7804 (re-search-backward org-table-dataline-regexp
7806 (org-table-goto-column colpos t)
7807 (if (and (looking-at
7808 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
7809 (= (setq n (1- n)) 0))
7810 (throw 'exit (match-string 1))))))))
7813 (if (and org-table-copy-increment
7814 (string-match "^[0-9]+$" txt))
7815 (setq txt (format "%d" (+ (string-to-number txt) 1))))
7817 (org-table-maybe-recalculate-line)
7819 (error "No non-empty field found"))))
7821 (defun org-table-check-inside-data-field ()
7822 "Is point inside a table data field?
7823 I.e. not on a hline or before the first or after the last column?
7824 This actually throws an error, so it aborts the current command."
7825 (if (or (not (org-at-table-p))
7826 (= (org-table-current-column) 0)
7827 (org-at-table-hline-p)
7828 (looking-at "[ \t]*$"))
7829 (error "Not in table data field")))
7831 (defvar org-table-clip nil
7832 "Clipboard for table regions.")
7834 (defun org-table-blank-field ()
7835 "Blank the current table field or active region."
7837 (org-table-check-inside-data-field)
7838 (if (and (interactive-p) (org-region-active-p))
7839 (let (org-table-clip)
7840 (org-table-cut-region (region-beginning) (region-end)))
7841 (skip-chars-backward "^|")
7843 (if (looking-at "|[^|\n]+")
7844 (let* ((pos (match-beginning 0))
7845 (match (match-string 0))
7846 (len (length match)))
7847 (replace-match (concat "|" (make-string (1- len) ?\ )))
7848 (goto-char (+ 2 pos))
7849 (substring match 1)))))
7851 (defun org-table-get-field (&optional n replace)
7852 "Return the value of the field in column N of current row.
7853 N defaults to current field.
7854 If REPLACE is a string, replace field with this value. The return value
7855 is always the old value."
7856 (and n (org-table-goto-column n))
7857 (skip-chars-backward "^|\n")
7859 (if (looking-at "|[^|\r\n]*")
7860 (let* ((pos (match-beginning 0))
7861 (val (buffer-substring (1+ pos) (match-end 0))))
7863 (replace-match (concat "|" replace)))
7864 (goto-char (min (point-at-eol) (+ 2 pos)))
7866 (forward-char 1) ""))
7868 (defun org-table-current-column ()
7869 "Find out which column we are in.
7870 When called interactively, column is also displayed in echo area."
7872 (if (interactive-p) (org-table-check-inside-data-field))
7874 (let ((cnt 0) (pos (point)))
7875 (beginning-of-line 1)
7876 (while (search-forward "|" pos t)
7877 (setq cnt (1+ cnt)))
7878 (if (interactive-p) (message "This is table column %d" cnt))
7881 (defun org-table-goto-column (n &optional on-delim force)
7882 "Move the cursor to the Nth column in the current table line.
7883 With optional argument ON-DELIM, stop with point before the left delimiter
7885 If there are less than N fields, just go to after the last delimiter.
7886 However, when FORCE is non-nil, create new columns if necessary."
7888 (let ((pos (point-at-eol)))
7889 (beginning-of-line 1)
7891 (while (and (> (setq n (1- n)) -1)
7892 (or (search-forward "|" pos t)
7894 (progn (end-of-line 1)
7895 (skip-chars-backward "^|")
7897 ; (backward-char 2) t)))))
7898 (when (and force (not (looking-at ".*|")))
7899 (save-excursion (end-of-line 1) (insert " | ")))
7902 (if (looking-at " ") (forward-char 1))))))
7904 (defun org-at-table-p (&optional table-type)
7905 "Return t if the cursor is inside an org-type table.
7906 If TABLE-TYPE is non-nil, also check for table.el-type tables."
7907 (if org-enable-table-editor
7909 (beginning-of-line 1)
7910 (looking-at (if table-type org-table-any-line-regexp
7911 org-table-line-regexp)))
7914 (defun org-at-table.el-p ()
7915 "Return t if and only if we are at a table.el table."
7916 (and (org-at-table-p 'any)
7918 (goto-char (org-table-begin 'any))
7919 (looking-at org-table1-hline-regexp))))
7921 (defun org-table-recognize-table.el ()
7922 "If there is a table.el table nearby, recognize it and move into it."
7923 (if org-table-tab-recognizes-table.el
7924 (if (org-at-table.el-p)
7926 (beginning-of-line 1)
7927 (if (looking-at org-table-dataline-regexp)
7929 (if (looking-at org-table1-hline-regexp)
7931 (beginning-of-line 2)
7932 (if (looking-at org-table-any-border-regexp)
7933 (beginning-of-line -1)))))
7934 (if (re-search-forward "|" (org-table-end t) t)
7937 (if (table--at-cell-p (point))
7939 (message "recognizing table.el table...")
7940 (table-recognize-table)
7941 (message "recognizing table.el table...done")))
7942 (error "This should not happen..."))
7947 (defun org-at-table-hline-p ()
7948 "Return t if the cursor is inside a hline in a table."
7949 (if org-enable-table-editor
7951 (beginning-of-line 1)
7952 (looking-at org-table-hline-regexp))
7955 (defun org-table-insert-column ()
7956 "Insert a new column into the table."
7958 (if (not (org-at-table-p))
7959 (error "Not at a table"))
7960 (org-table-find-dataline)
7961 (let* ((col (max 1 (org-table-current-column)))
7962 (beg (org-table-begin))
7963 (end (org-table-end))
7964 ;; Current cursor position
7965 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7968 (while (< (point) end)
7969 (if (org-at-table-hline-p)
7971 (org-table-goto-column col t)
7973 (beginning-of-line 2))
7974 (move-marker end nil)
7976 (org-table-goto-column colpos)
7978 (org-table-modify-formulas 'insert col)))
7980 (defun org-table-find-dataline ()
7981 "Find a dataline in the current table, which is needed for column commands."
7982 (if (and (org-at-table-p)
7983 (not (org-at-table-hline-p)))
7985 (let ((col (current-column))
7986 (end (org-table-end)))
7987 (move-to-column col)
7988 (while (and (< (point) end)
7989 (or (not (= (current-column) col))
7990 (org-at-table-hline-p)))
7991 (beginning-of-line 2)
7992 (move-to-column col))
7993 (if (and (org-at-table-p)
7994 (not (org-at-table-hline-p)))
7997 "Please position cursor in a data line for column operations")))))
7999 (defun org-table-delete-column ()
8000 "Delete a column into the table."
8002 (if (not (org-at-table-p))
8003 (error "Not at a table"))
8004 (org-table-find-dataline)
8005 (org-table-check-inside-data-field)
8006 (let* ((col (org-table-current-column))
8007 (beg (org-table-begin))
8008 (end (org-table-end))
8009 ;; Current cursor position
8010 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8013 (while (< (point) end)
8014 (if (org-at-table-hline-p)
8016 (org-table-goto-column col t)
8017 (and (looking-at "|[^|\n]+|")
8018 (replace-match "|")))
8019 (beginning-of-line 2))
8020 (move-marker end nil)
8022 (org-table-goto-column colpos)
8024 (org-table-modify-formulas 'remove col)))
8026 (defun org-table-move-column-right ()
8027 "Move column to the right."
8029 (org-table-move-column nil))
8030 (defun org-table-move-column-left ()
8031 "Move column to the left."
8033 (org-table-move-column 'left))
8035 (defun org-table-move-column (&optional left)
8036 "Move the current column to the right. With arg LEFT, move to the left."
8038 (if (not (org-at-table-p))
8039 (error "Not at a table"))
8040 (org-table-find-dataline)
8041 (org-table-check-inside-data-field)
8042 (let* ((col (org-table-current-column))
8043 (col1 (if left (1- col) col))
8044 (beg (org-table-begin))
8045 (end (org-table-end))
8046 ;; Current cursor position
8047 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8048 (colpos (if left (1- col) (1+ col))))
8049 (if (and left (= col 1))
8050 (error "Cannot move column further left"))
8051 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8052 (error "Cannot move column further right"))
8054 (while (< (point) end)
8055 (if (org-at-table-hline-p)
8057 (org-table-goto-column col1 t)
8058 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8059 (replace-match "|\\2|\\1|")))
8060 (beginning-of-line 2))
8061 (move-marker end nil)
8063 (org-table-goto-column colpos)
8065 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
8067 (defun org-table-move-row-down ()
8068 "move table row down."
8070 (org-table-move-row nil))
8071 (defun org-table-move-row-up ()
8072 "move table row up."
8074 (org-table-move-row 'up))
8076 (defun org-table-move-row (&optional up)
8077 "Move the current table line down. With arg UP, move it up."
8079 (let ((col (current-column))
8083 (beginning-of-line tonew)
8084 (if (not (org-at-table-p))
8087 (error "Cannot move row further")))
8089 (beginning-of-line 1)
8091 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8092 (delete-region (point) (1+ (point-at-eol)))
8093 (beginning-of-line tonew)
8095 (beginning-of-line 0)
8096 (move-to-column col)))
8098 (defun org-table-insert-row (&optional arg)
8099 "Insert a new row above the current line into the table.
8100 With prefix ARG, insert below the current line."
8102 (if (not (org-at-table-p))
8103 (error "Not at a table"))
8104 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
8106 (if (string-match "^[ \t]*|-" line)
8107 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
8108 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
8109 ;; Fix the first field if necessary
8110 (setq new (concat new))
8111 (if (string-match "^[ \t]*| *[#$] *|" line)
8112 (setq new (replace-match (match-string 0 line) t t new)))
8113 (beginning-of-line (if arg 2 1))
8114 (let (org-table-may-need-update)
8115 (insert-before-markers new)
8116 (insert-before-markers "\n"))
8117 (beginning-of-line 0)
8118 (re-search-forward "| ?" (point-at-eol) t)
8119 (and org-table-may-need-update (org-table-align))))
8121 (defun org-table-insert-hline (&optional arg)
8122 "Insert a horizontal-line below the current line into the table.
8123 With prefix ARG, insert above the current line."
8125 (if (not (org-at-table-p))
8126 (error "Not at a table"))
8127 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
8128 (col (current-column))
8130 (if (string-match "^[ \t]*|-" line)
8132 (mapcar (lambda (x) (if (member x '(?| ?+))
8133 (prog1 (if start ?+ ?|) (setq start t))
8137 (mapcar (lambda (x) (if (equal x ?|)
8138 (prog1 (if start ?+ ?|) (setq start t))
8141 (beginning-of-line (if arg 1 2))
8142 (apply 'insert line)
8143 (if (equal (char-before (point)) ?+)
8144 (progn (backward-delete-char 1) (insert "|")))
8146 (beginning-of-line 0)
8147 (move-to-column col)))
8149 (defun org-table-kill-row ()
8150 "Delete the current row or horizontal line from the table."
8152 (if (not (org-at-table-p))
8153 (error "Not at a table"))
8154 (let ((col (current-column)))
8155 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8156 (if (not (org-at-table-p)) (beginning-of-line 0))
8157 (move-to-column col)))
8159 (defun org-table-sort-lines (beg end numericp)
8160 "Sort table lines in region.
8161 Point and mark define the first and last line to include. Both point and
8162 mark should be in the column that is used for sorting. For example, to
8163 sort according to column 3, put the mark in the first line to sort, in
8164 table column 3. Put point into the last line to be included in the sorting,
8165 also in table column 3. The command will prompt for the sorting method (n for
8166 numerical, a for alphanumeric)."
8167 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
8168 (setq numericp (string-match "[nN]" numericp))
8169 (org-table-align) ;; Just to be safe
8170 (let* (bcol ecol cmp column lns)
8172 (org-table-check-inside-data-field)
8173 (setq column (org-table-current-column)
8174 beg (move-marker (make-marker) (point-at-bol)))
8176 (org-table-check-inside-data-field)
8177 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
8180 (org-table-goto-column column)
8181 (skip-chars-backward "^|")
8182 (setq bcol (current-column))
8183 (org-table-goto-column (1+ column))
8184 (skip-chars-backward "^|")
8185 (setq ecol (1- (current-column)))
8186 (setq cmp (if numericp
8187 (lambda (a b) (< (car a) (car b)))
8188 (lambda (a b) (string< (car a) (car b)))))
8189 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8190 (split-string (buffer-substring beg end) "\n")))
8192 (setq lns (mapcar (lambda(x)
8193 (cons (string-to-number (car x)) (cdr x)))
8195 (delete-region beg end)
8196 (move-marker beg nil)
8197 (move-marker end nil)
8198 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
8199 (message "%d lines sorted %s based on column %d"
8201 (if numericp "numerically" "alphabetically") column)))
8203 (defun org-table-cut-region (beg end)
8204 "Copy region in table to the clipboard and blank all relevant fields."
8206 (org-table-copy-region beg end 'cut))
8208 (defun org-table-copy-region (beg end &optional cut)
8209 "Copy rectangular region in table to clipboard.
8210 A special clipboard is used which can only be accessed
8211 with `org-table-paste-rectangle'"
8213 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8215 (rpl (if cut " " nil)))
8217 (org-table-check-inside-data-field)
8218 (setq l01 (count-lines (point-min) (point))
8219 c01 (org-table-current-column))
8221 (org-table-check-inside-data-field)
8222 (setq l02 (count-lines (point-min) (point))
8223 c02 (org-table-current-column))
8224 (setq l1 (min l01 l02) l2 (max l01 l02)
8225 c1 (min c01 c02) c2 (max c01 c02))
8229 (if (> l1 l2) (throw 'exit t))
8231 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8232 (setq cols nil ic1 c1 ic2 c2)
8233 (while (< ic1 (1+ ic2))
8234 (push (org-table-get-field ic1 rpl) cols)
8235 (setq ic1 (1+ ic1)))
8236 (push (nreverse cols) region)
8237 (setq l1 (1+ l1)))))
8238 (setq org-table-clip (nreverse region))
8239 (if cut (org-table-align))
8242 (defun org-table-paste-rectangle ()
8243 "Paste a rectangular region into a table.
8244 The upper right corner ends up in the current field. All involved fields
8245 will be overwritten. If the rectangle does not fit into the present table,
8246 the table is enlarged as needed. The process ignores horizontal separator
8249 (unless (and org-table-clip (listp org-table-clip))
8250 (error "First cut/copy a region to paste!"))
8251 (org-table-check-inside-data-field)
8252 (let* ((clip org-table-clip)
8253 (line (count-lines (point-min) (point)))
8254 (col (org-table-current-column))
8255 (org-enable-table-editor t)
8256 (org-table-automatic-realign nil)
8258 (while (setq cols (pop clip))
8259 (while (org-at-table-hline-p) (beginning-of-line 2))
8260 (if (not (org-at-table-p))
8261 (progn (end-of-line 0) (org-table-next-field)))
8263 (while (setq field (pop cols))
8264 (org-table-goto-column c nil 'force)
8265 (org-table-get-field nil field)
8267 (beginning-of-line 2))
8269 (org-table-goto-column col)
8272 (defun org-table-convert ()
8273 "Convert from `org-mode' table to table.el and back.
8274 Obviously, this only works within limits. When an Org-mode table is
8275 converted to table.el, all horizontal separator lines get lost, because
8276 table.el uses these as cell boundaries and has no notion of horizontal lines.
8277 A table.el table can be converted to an Org-mode table only if it does not
8278 do row or column spanning. Multiline cells will become multiple cells.
8279 Beware, Org-mode does not test if the table can be successfully converted - it
8280 blindly applies a recipe that works for simple tables."
8283 (if (org-at-table.el-p)
8284 ;; convert to Org-mode table
8285 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8286 (end (move-marker (make-marker) (org-table-end t))))
8287 (table-unrecognize-region beg end)
8289 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8292 (if (org-at-table-p)
8293 ;; convert to table.el table
8294 (let ((beg (move-marker (make-marker) (org-table-begin)))
8295 (end (move-marker (make-marker) (org-table-end))))
8296 ;; first, get rid of all horizontal lines
8298 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
8300 ;; insert a hline before first
8302 (org-table-insert-hline 'above)
8303 ;; insert a hline after each line
8304 (while (progn (beginning-of-line 2) (< (point) end))
8305 (org-table-insert-hline))
8307 (setq end (move-marker end (org-table-end)))
8308 ;; replace "+" at beginning and ending of hlines
8309 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
8310 (replace-match "\\1+-"))
8312 (while (re-search-forward "-|[ \t]*$" end t)
8313 (replace-match "-+"))
8316 (defun org-table-wrap-region (arg)
8317 "Wrap several fields in a column like a paragraph.
8318 This is useful if you'd like to spread the contents of a field over several
8319 lines, in order to keep the table compact.
8321 If there is an active region, and both point and mark are in the same column,
8322 the text in the column is wrapped to minimum width for the given number of
8323 lines. Generally, this makes the table more compact. A prefix ARG may be
8324 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
8325 formats the selected text to two lines. If the region was longer than 2
8326 lines, the remaining lines remain empty. A negative prefix argument reduces
8327 the current number of lines by that amount. The wrapped text is pasted back
8328 into the table. If you formatted it to more lines than it was before, fields
8329 further down in the table get overwritten - so you might need to make space in
8332 If there is no region, the current field is split at the cursor position and
8333 the text fragment to the right of the cursor is prepended to the field one
8336 If there is no region, but you specify a prefix ARG, the current field gets
8337 blank, and the content is appended to the field above."
8339 (org-table-check-inside-data-field)
8340 (if (org-region-active-p)
8341 ;; There is a region: fill as a paragraph
8342 (let ((beg (region-beginning))
8344 (org-table-cut-region (region-beginning) (region-end))
8345 (if (> (length (car org-table-clip)) 1)
8346 (error "Region must be limited to single column"))
8347 (setq nlines (if arg
8349 (+ (length org-table-clip) arg)
8351 (length org-table-clip)))
8352 (setq org-table-clip
8353 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
8356 (org-table-paste-rectangle))
8357 ;; No region, split the current field at point
8359 ;; combine with field above
8360 (let ((s (org-table-blank-field))
8361 (col (org-table-current-column)))
8362 (beginning-of-line 0)
8363 (while (org-at-table-hline-p) (beginning-of-line 0))
8364 (org-table-goto-column col)
8365 (skip-chars-forward "^|")
8366 (skip-chars-backward " ")
8367 (insert " " (org-trim s))
8370 (when (looking-at "\\([^|]+\\)+|")
8371 (let ((s (match-string 1)))
8372 (replace-match " |")
8373 (goto-char (match-beginning 0))
8374 (org-table-next-row)
8375 (insert (org-trim s) " ")
8376 (org-table-align))))))
8379 "Remove whitespace at beginning and end of string."
8380 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
8381 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
8384 (defun org-wrap (string &optional width lines)
8385 "Wrap string to either a number of lines, or a width in characters.
8386 If WIDTH is non-nil, the string is wrapped to that width, however many lines
8387 that costs. If there is a word longer than WIDTH, the text is actually
8388 wrapped to the length of that word.
8389 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
8390 many lines, whatever width that takes.
8391 The return value is a list of lines, without newlines at the end."
8392 (let* ((words (org-split-string string "[ \t\n]+"))
8393 (maxword (apply 'max (mapcar 'length words)))
8396 (org-do-wrap words (max maxword width)))
8399 (setq ll (org-do-wrap words maxword))
8400 (if (<= (length ll) lines)
8403 (while (> (length ll) lines)
8405 (setq ll (org-do-wrap words w)))
8407 (t (error "Cannot wrap this")))))
8410 (defun org-do-wrap (words width)
8411 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
8414 (setq line (pop words))
8415 (while (and words (< (+ (length line) (length (car words))) width))
8416 (setq line (concat line " " (pop words))))
8417 (setq lines (push line lines)))
8420 ;; FIXME: I think I can make this more efficient
8421 (defun org-split-string (string &optional separators)
8422 "Splits STRING into substrings at SEPARATORS.
8423 No empty strings are returned if there are matches at the beginning
8425 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
8429 (while (and (string-match rexp string
8431 (= start (match-beginning 0))
8432 (< start (length string)))
8434 (< (match-beginning 0) (length string)))
8436 (or (eq (match-beginning 0) 0)
8437 (and (eq (match-beginning 0) (match-end 0))
8438 (eq (match-beginning 0) start))
8440 (cons (substring string start (match-beginning 0))
8442 (setq start (match-end 0)))
8443 (or (eq start (length string))
8445 (cons (substring string start)
8449 (defun org-table-add-invisible-to-vertical-lines ()
8450 "Add an `invisible' property to vertical lines of current table."
8452 (let* ((beg (org-table-begin))
8453 (end (org-table-end))
8457 (while (< (point) end)
8458 (setq end1 (point-at-eol))
8459 (if (looking-at org-table-dataline-regexp)
8460 (while (re-search-forward "|" end1 t)
8461 (add-text-properties (1- (point)) (point)
8462 '(invisible org-table)))
8463 (while (re-search-forward "[+|]" end1 t)
8464 (add-text-properties (1- (point)) (point)
8465 '(invisible org-table))))
8466 (beginning-of-line 2)))))
8468 (defun org-table-toggle-vline-visibility (&optional arg)
8469 "Toggle the visibility of table vertical lines.
8470 The effect is immediate and on all tables in the file.
8471 With prefix ARG, make lines invisible when ARG is positive, make lines
8472 visible when ARG is not positive"
8475 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
8476 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
8477 (t (if (org-in-invisibility-spec-p '(org-table))
8480 (if (eq action 'off)
8482 (org-remove-from-invisibility-spec '(org-table))
8483 (org-table-map-tables 'org-table-align)
8484 (message "Vertical table lines visible")
8485 (if (org-at-table-p)
8487 (org-add-to-invisibility-spec '(org-table))
8488 (org-table-map-tables 'org-table-align)
8489 (message "Vertical table lines invisible"))
8490 (redraw-frame (selected-frame))))
8492 (defun org-table-map-tables (function)
8493 "Apply FUNCTION to the start of all tables in the buffer."
8497 (goto-char (point-min))
8498 (while (re-search-forward org-table-any-line-regexp nil t)
8499 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
8500 (beginning-of-line 1)
8501 (if (looking-at org-table-line-regexp)
8502 (save-excursion (funcall function)))
8503 (re-search-forward org-table-any-border-regexp nil 1)))))
8505 (defun org-table-sum (&optional beg end nlast)
8506 "Sum numbers in region of current table column.
8507 The result will be displayed in the echo area, and will be available
8508 as kill to be inserted with \\[yank].
8510 If there is an active region, it is interpreted as a rectangle and all
8511 numbers in that rectangle will be summed. If there is no active
8512 region and point is located in a table column, sum all numbers in that
8515 If at least one number looks like a time HH:MM or HH:MM:SS, all other
8516 numbers are assumed to be times as well (in decimal hours) and the
8517 numbers are added as such.
8519 If NLAST is a number, only the NLAST fields will actually be summed."
8522 (let (col (timecnt 0) diff h m s org-table-clip)
8524 ((and beg end)) ; beg and end given explicitly
8525 ((org-region-active-p)
8526 (setq beg (region-beginning) end (region-end)))
8528 (setq col (org-table-current-column))
8529 (goto-char (org-table-begin))
8530 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
8531 (error "No table data"))
8532 (org-table-goto-column col)
8533 ;not needed? (skip-chars-backward "^|")
8535 (goto-char (org-table-end))
8536 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
8537 (error "No table data"))
8538 (org-table-goto-column col)
8539 ;not needed? (skip-chars-forward "^|")
8540 (setq end (point))))
8541 (let* ((items (apply 'append (org-table-copy-region beg end)))
8542 (items1 (cond ((not nlast) items)
8543 ((>= nlast (length items)) items)
8544 (t (setq items (reverse items))
8545 (setcdr (nthcdr (1- nlast) items) nil)
8547 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
8549 (res (apply '+ numbers))
8550 (sres (if (= timecnt 0)
8552 (setq diff (* 3600 res)
8553 h (floor (/ diff 3600)) diff (mod diff 3600)
8554 m (floor (/ diff 60)) diff (mod diff 60)
8556 (format "%d:%02d:%02d" h m s))))
8560 (substitute-command-keys
8561 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
8562 (length numbers) sres))))
8565 (defun org-table-get-number-for-summing (s)
8567 (if (string-match "^ *|? *" s)
8568 (setq s (replace-match "" nil nil s)))
8569 (if (string-match " *|? *$" s)
8570 (setq s (replace-match "" nil nil s)))
8571 (setq n (string-to-number s))
8573 ((and (string-match "0" s)
8574 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
8575 ((string-match "\\`[ \t]+\\'" s) nil)
8576 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
8577 (let ((h (string-to-number (or (match-string 1 s) "0")))
8578 (m (string-to-number (or (match-string 2 s) "0")))
8579 (s (string-to-number (or (match-string 4 s) "0"))))
8580 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
8581 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
8585 (defun org-table-get-vertical-vector (desc &optional tbeg col)
8586 "Get a calc vector from a column, accorting to desctiptor DESC.
8587 Optional arguments TBEG and COL can give the beginning of the table and
8588 the current column, to avoid unnecessary parsing."
8590 (or tbeg (setq tbeg (org-table-begin)))
8591 (or col (setq col (org-table-current-column)))
8592 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
8594 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
8595 (setq n1 (- (match-end 1) (match-beginning 1)))
8596 (if (match-beginning 3)
8597 (setq n2 (- (match-end 2) (match-beginning 3))))
8598 (setq n (if n2 (max n1 n2) n1))
8599 (setq n1 (if n2 (min n1 n2)))
8601 (while (and (> nn 0)
8602 (re-search-backward org-table-hline-regexp tbeg t))
8603 (push (org-current-line) hline-list)
8605 (setq hline-list (nreverse hline-list))
8606 (goto-line (nth (1- n) hline-list))
8607 (when (re-search-forward org-table-dataline-regexp)
8608 (org-table-goto-column col)
8610 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
8611 (when (re-search-backward org-table-dataline-regexp)
8612 (org-table-goto-column col)
8614 (setq l (apply 'append (org-table-copy-region beg end)))
8615 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
8616 (if (equal x "") "0" x))
8618 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
8619 (setq n1 (string-to-number (match-string 1 desc))
8620 n2 (string-to-number (match-string 2 desc)))
8621 (beginning-of-line 1)
8623 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
8624 (org-table-goto-column col)
8625 (setq beg (point))))
8626 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
8627 (org-table-goto-column col)
8629 (setq l (apply 'append (org-table-copy-region beg end)))
8630 (concat "[" (mapconcat
8631 (lambda (x) (setq x (org-trim x))
8632 (if (equal x "") "0" x))
8634 ((string-match "\\([0-9]+\\)" desc)
8635 (beginning-of-line 1)
8636 (when (re-search-backward org-table-dataline-regexp tbeg t
8637 (string-to-number (match-string 0 desc)))
8638 (org-table-goto-column col)
8639 (org-trim (org-table-get-field))))))))
8641 (defvar org-table-formula-history nil)
8643 (defvar org-table-column-names nil
8644 "Alist with column names, derived from the `!' line.")
8645 (defvar org-table-column-name-regexp nil
8646 "Regular expression matching the current column names.")
8647 (defvar org-table-local-parameters nil
8648 "Alist with parameter names, derived from the `$' line.")
8649 (defvar org-table-named-field-locations nil
8650 "Alist with locations of named fields.")
8652 (defun org-table-get-formula (&optional equation named)
8653 "Read a formula from the minibuffer, offer stored formula as default."
8654 (let* ((name (car (rassoc (list (org-current-line)
8655 (org-table-current-column))
8656 org-table-named-field-locations)))
8659 (error "Not in a named field"))
8660 (int-to-string (org-table-current-column))))
8661 (dummy (and name (not named)
8662 (not (y-or-n-p "Replace named-field formula with column equation? " ))
8664 (org-table-may-need-update nil)
8665 (stored-list (org-table-get-stored-formulas))
8666 (stored (cdr (assoc scol stored-list)))
8668 ((and stored equation (string-match "^ *=? *$" equation))
8673 (format "%s formula $%s=" (if named "Field" "Column") scol)
8674 (or stored "") 'org-table-formula-history
8678 (when (not (string-match "\\S-" eq))
8680 (setq stored-list (delq (assoc scol stored-list) stored-list))
8681 (org-table-store-formulas stored-list)
8682 (error "Formula removed"))
8683 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
8684 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
8685 (if (and name (not named))
8686 ;; We set the column equation, delete the named one.
8687 (setq stored-list (delq (assoc name stored-list) stored-list)
8690 (setcdr (assoc scol stored-list) eq)
8691 (setq stored-list (cons (cons scol eq) stored-list)))
8692 (if (or mustsave (not (equal stored eq)))
8693 (org-table-store-formulas stored-list))
8696 (defun org-table-store-formulas (alist)
8697 "Store the list of formulas below the current table."
8698 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
8700 (goto-char (org-table-end))
8701 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
8702 (delete-region (point) (match-end 0)))
8704 (mapconcat (lambda (x)
8705 (concat "$" (car x) "=" (cdr x)))
8709 (defun org-table-get-stored-formulas ()
8710 "Return an alist with the t=stored formulas directly after current table."
8712 (let (scol eq eq-alist strings string seen)
8714 (goto-char (org-table-end))
8715 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
8716 (setq strings (org-split-string (match-string 2) " *:: *"))
8717 (while (setq string (pop strings))
8718 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
8719 (setq scol (match-string 1 string)
8720 eq (match-string 2 string)
8721 eq-alist (cons (cons scol eq) eq-alist))
8722 (if (member scol seen)
8723 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
8724 (push scol seen))))))
8725 (nreverse eq-alist)))
8727 (defun org-table-modify-formulas (action &rest columns)
8728 "Modify the formulas stored below the current table.
8729 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
8730 expected, for the other action only a single column number is needed."
8731 (let ((list (org-table-get-stored-formulas))
8732 (nmax (length (org-split-string
8733 (buffer-substring (point-at-bol) (point-at-eol))
8735 col col1 col2 scol si sc1 sc2)
8737 ((null list)) ; No action needed if there are no stored formulas
8738 ((eq action 'remove)
8739 (setq col (car columns)
8740 scol (int-to-string col))
8741 (org-table-replace-in-formulas list scol "INVALID")
8742 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
8743 (loop for i from (1+ col) upto nmax by 1 do
8744 (setq si (int-to-string i))
8745 (org-table-replace-in-formulas list si (int-to-string (1- i)))
8746 (if (assoc si list) (setcar (assoc si list)
8747 (int-to-string (1- i))))))
8748 ((eq action 'insert)
8749 (setq col (car columns))
8750 (loop for i from nmax downto col by 1 do
8751 (setq si (int-to-string i))
8752 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
8753 (if (assoc si list) (setcar (assoc si list)
8754 (int-to-string (1+ i))))))
8756 (setq col1 (car columns) col2 (nth 1 columns)
8757 sc1 (int-to-string col1) sc2 (int-to-string col2))
8758 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
8759 (org-table-replace-in-formulas list sc1 "ZqZ")
8760 (org-table-replace-in-formulas list sc2 sc1)
8761 (org-table-replace-in-formulas list "ZqZ" sc2)
8762 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
8763 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
8764 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
8765 (t (error "Invalid action in `org-table-modify-formulas'")))
8766 (if list (org-table-store-formulas list))))
8768 (defun org-table-replace-in-formulas (list s1 s2)
8770 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
8771 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
8772 re (concat (regexp-quote s1) "\\>"))
8773 (while (setq elt (pop list))
8775 (while (string-match re s)
8776 (setq s (replace-match s2 t t s)))
8779 (defun org-table-get-specials ()
8780 "Get the column nmaes and local parameters for this table."
8782 (let ((beg (org-table-begin)) (end (org-table-end))
8783 names name fields fields1 field cnt c v line col)
8784 (setq org-table-column-names nil
8785 org-table-local-parameters nil
8786 org-table-named-field-locations nil)
8788 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
8789 (setq names (org-split-string (match-string 1) " *| *")
8791 (while (setq name (pop names))
8793 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
8794 (push (cons name (int-to-string cnt)) org-table-column-names))))
8795 (setq org-table-column-names (nreverse org-table-column-names))
8796 (setq org-table-column-name-regexp
8797 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
8799 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
8800 (setq fields (org-split-string (match-string 1) " *| *"))
8801 (while (setq field (pop fields))
8802 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
8803 (push (cons (match-string 1 field) (match-string 2 field))
8804 org-table-local-parameters))))
8806 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
8807 (setq c (match-string 1)
8808 fields (org-split-string (match-string 2) " *| *"))
8810 (beginning-of-line (if (equal c "_") 2 0))
8811 (setq line (org-current-line) col 1)
8812 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
8813 (setq fields1 (org-split-string (match-string 1) " *| *"))))
8814 (while (and fields1 (setq field (pop fields)))
8815 (setq v (pop fields1) col (1+ col))
8816 (when (and (stringp field) (stringp v)
8817 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
8818 (push (cons field v) org-table-local-parameters)
8819 (push (list field line col) org-table-named-field-locations)))))))
8821 (defun org-this-word ()
8822 ;; Get the current word
8824 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
8825 (end (progn (skip-chars-forward "^ \t\n") (point))))
8826 (buffer-substring-no-properties beg end))))
8828 (defun org-table-maybe-eval-formula ()
8829 "Check if the current field starts with \"=\" or \":=\".
8830 If yes, store the formula and apply it."
8831 ;; We already know we are in a table. Get field will only return a formula
8832 ;; when appropriate. It might return a separator line, but no problem.
8833 (when org-table-formula-evaluate-inline
8834 (let* ((field (org-trim (or (org-table-get-field) "")))
8836 (when (string-match "^:?=\\(.*\\)" field)
8837 (setq named (equal (string-to-char field) ?:)
8838 eq (match-string 1 field))
8839 (if (fboundp 'calc-eval)
8840 (org-table-eval-formula (if named '(4) nil) eq))))))
8842 (defvar org-recalc-commands nil
8843 "List of commands triggering the reccalculation of a line.
8844 Will be filled automatically during use.")
8846 (defvar org-recalc-marks
8847 '((" " . "Unmarked: no special line, no automatic recalculation")
8848 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
8849 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
8850 ("!" . "Column name definition line. Reference in formula as $name.")
8851 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
8852 ("_" . "Names for values in row below this one.")
8853 ("^" . "Names for values in row above this one.")))
8855 (defun org-table-rotate-recalc-marks (&optional newchar)
8856 "Rotate the recalculation mark in the first column.
8857 If in any row, the first field is not consistent with a mark,
8858 insert a new column for the makers.
8859 When there is an active region, change all the lines in the region,
8860 after prompting for the marking character.
8861 After each change, a message will be displayed indication the meaning
8864 (unless (org-at-table-p) (error "Not at a table"))
8865 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
8866 (beg (org-table-begin))
8867 (end (org-table-end))
8868 (l (org-current-line))
8869 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
8870 (l2 (if (org-region-active-p) (org-current-line (region-end))))
8874 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
8875 (col (org-table-current-column))
8876 (forcenew (car (assoc newchar org-recalc-marks)))
8879 (message "Change region to what mark? Type # * ! $ or SPC: ")
8880 (setq newchar (char-to-string (read-char-exclusive))
8881 forcenew (car (assoc newchar org-recalc-marks))))
8882 (if (and newchar (not forcenew))
8883 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
8885 (if l1 (goto-line l1))
8887 (beginning-of-line 1)
8888 (unless (looking-at org-table-dataline-regexp)
8889 (error "Not at a table data line")))
8891 (org-table-goto-column 1)
8892 (org-table-insert-column)
8893 (org-table-goto-column (1+ col)))
8894 (setq epos (point-at-eol))
8896 (beginning-of-line 1)
8897 (org-table-get-field
8898 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
8900 (setq new (or forcenew
8901 (cadr (member (match-string 1) marks))))
8907 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
8908 (and (looking-at org-table-dataline-regexp)
8909 (org-table-get-field 1 (concat " " new " "))))
8911 (if (not (= epos (point-at-eol))) (org-table-align))
8913 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
8915 (defun org-table-maybe-recalculate-line ()
8916 "Recompute the current line if marked for it, and if we haven't just done it."
8918 (and org-table-allow-automatic-line-recalculation
8919 (not (and (memq last-command org-recalc-commands)
8920 (equal org-last-recalc-line (org-current-line))))
8921 (save-excursion (beginning-of-line 1)
8922 (looking-at org-table-auto-recalculate-regexp))
8923 (fboundp 'calc-eval)
8924 (org-table-recalculate) t))
8926 (defvar org-table-formula-debug nil
8927 "Non-nil means, debug table formulas.
8928 When nil, simply write \"#ERROR\" in corrupted fields.")
8931 (defsubst org-set-calc-mode (var &optional value)
8933 (setq var (assoc var '(("D" calc-angle-mode deg)
8934 ("R" calc-angle-mode rad)
8935 ("F" calc-prefer-frac t)
8936 ("S" calc-symbolic-mode t)))
8937 value (nth 2 var) var (nth 1 var)))
8938 (if (memq var modes)
8939 (setcar (cdr (memq var modes)) value)
8940 (cons var (cons value modes)))
8943 (defun org-table-eval-formula (&optional arg equation
8944 suppress-align suppress-const
8946 "Replace the table field value at the cursor by the result of a calculation.
8948 This function makes use of Dave Gillespie's calc package, in my view the
8949 most exciting program ever written for GNU Emacs. So you need to have calc
8950 installed in order to use this function.
8952 In a table, this command replaces the value in the current field with the
8953 result of a formula. It also installes the formula as the \"current\" column
8954 formula, by storing it in a special line below the table. When called
8955 with a `C-u' prefix, the current field must ba a named field, and the
8956 formula is installed as valid in only this specific field.
8958 When called, the command first prompts for a formula, which is read in
8959 the minibuffer. Previously entered formulas are available through the
8960 history list, and the last used formula is offered as a default.
8961 These stored formulas are adapted correctly when moving, inserting, or
8962 deleting columns with the corresponding commands.
8964 The formula can be any algebraic expression understood by the calc package.
8965 For details, see the Org-mode manual.
8967 This function can also be called from Lisp programs and offers
8968 additional Arguments: EQUATION can be the formula to apply. If this
8969 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
8970 used to speed-up recursive calls by by-passing unnecessary aligns.
8971 SUPPRESS-CONST suppresses the interpretation of constants in the
8972 formula, assuming that this has been done already outside the fuction.
8973 SUPPRESS-STORE means the formula should not be stored, either because
8974 it is already stored, or because it is a modified equation that should
8975 not overwrite the stored one."
8978 (org-table-check-inside-data-field)
8979 (org-table-get-specials)
8981 (ndown (if (integerp arg) arg 1))
8982 (org-table-automatic-realign nil)
8983 (case-fold-search nil)
8985 (formula (if (and equation suppress-store)
8987 (org-table-get-formula equation (equal arg '(4)))))
8988 (n0 (org-table-current-column))
8989 (modes (copy-sequence org-calc-default-modes))
8990 n form fmt x ev orig c)
8991 ;; Parse the format string. Since we have a lot of modes, this is
8992 ;; a lot of work. However, I think calc still uses most of the time.
8993 (if (string-match ";" formula)
8994 (let ((tmp (org-split-string formula ";")))
8995 (setq formula (car tmp)
8996 fmt (concat (cdr (assoc "%" org-table-local-parameters))
8998 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
8999 (setq c (string-to-char (match-string 1 fmt))
9000 n (string-to-number (or (match-string 1 fmt) "")))
9001 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
9002 (setq modes (org-set-calc-mode
9004 (list (cdr (assoc c '((?n. float) (?f. fix)
9005 (?s. sci) (?e. eng))))
9007 (setq fmt (replace-match "" t t fmt)))
9008 (while (string-match "[DRFS]" fmt)
9009 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9010 (setq fmt (replace-match "" t t fmt)))
9011 (unless (string-match "\\S-" fmt)
9013 (if (and (not suppress-const) org-table-formula-use-constants)
9014 (setq formula (org-table-formula-substitute-names formula)))
9015 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9017 (setq fields (org-split-string
9019 (point-at-bol) (point-at-eol)) " *| *"))
9020 (if org-table-formula-numbers-only
9021 (setq fields (mapcar
9022 (lambda (x) (number-to-string (string-to-number x)))
9024 (setq ndown (1- ndown))
9025 (setq form (copy-sequence formula))
9026 ;; Insert the references to fields in same row
9027 (while (string-match "\\$\\([0-9]+\\)?" form)
9028 (setq n (if (match-beginning 1)
9029 (string-to-number (match-string 1 form))
9031 x (nth (1- n) fields))
9032 (unless x (error "Invalid field specifier \"%s\""
9033 (match-string 0 form)))
9034 (if (equal x "") (setq x "0"))
9035 (setq form (replace-match (concat "(" x ")") t t form)))
9036 ;; Insert ranges in current column
9037 (while (string-match "\\&[-I0-9]+" form)
9038 (setq form (replace-match
9040 (org-table-get-vertical-vector (match-string 0 form)
9043 (setq ev (calc-eval (cons form modes)
9044 (if org-table-formula-numbers-only 'num)))
9046 (when org-table-formula-debug
9047 (with-output-to-temp-buffer "*Help*"
9048 (princ (format "Substitution history of formula
9051 $1-> %s\n" orig formula form))
9053 (princ (format " %s^\nError: %s"
9054 (make-string (car ev) ?\-) (nth 1 ev)))
9055 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9057 (if fmt (format fmt (string-to-number ev)) ev)))))
9058 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
9059 (unless (and (interactive-p) (not ndown))
9060 (unless (let (inhibit-redisplay)
9061 (y-or-n-p "Debugging Formula. Continue to next? "))
9064 (delete-window (get-buffer-window "*Help*"))
9066 (if (listp ev) (setq fmt nil ev "#ERROR"))
9067 (org-table-justify-field-maybe
9068 (if fmt (format fmt (string-to-number ev)) ev))
9069 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9070 (call-interactively 'org-return)
9072 (and down (org-table-maybe-recalculate-line))
9073 (or suppress-align (and org-table-may-need-update
9074 (org-table-align)))))
9076 (defun org-table-recalculate (&optional all noalign)
9077 "Recalculate the current table line by applying all stored formulas."
9079 (or (memq this-command org-recalc-commands)
9080 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9081 (unless (org-at-table-p) (error "Not at a table"))
9082 (org-table-get-specials)
9083 (let* ((eqlist (sort (org-table-get-stored-formulas)
9084 (lambda (a b) (string< (car a) (car b)))))
9085 (inhibit-redisplay t)
9086 (line-re org-table-dataline-regexp)
9087 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9088 (thiscol (org-table-current-column))
9089 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
9090 ;; Insert constants in all formulas
9093 (setcdr x (org-table-formula-substitute-names (cdr x)))
9096 ;; Split the equation list
9097 (while (setq eq (pop eqlist))
9098 (if (<= (string-to-char (car eq)) ?9)
9101 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9104 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9105 (goto-char (setq beg (org-table-begin)))
9106 (if (re-search-forward org-table-calculate-mark-regexp end t)
9107 ;; This is a table with marked lines, only compute selected lines
9108 (setq line-re org-table-recalculate-regexp)
9109 ;; Move forward to the first non-header line
9110 (if (and (re-search-forward org-table-dataline-regexp end t)
9111 (re-search-forward org-table-hline-regexp end t)
9112 (re-search-forward org-table-dataline-regexp end t))
9113 (setq beg (match-beginning 0))
9114 nil))) ;; just leave beg where it is
9115 (setq beg (point-at-bol)
9116 end (move-marker (make-marker) (1+ (point-at-eol)))))
9118 (and all (message "Re-applying formulas to full table..."))
9119 (while (re-search-forward line-re end t)
9120 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
9121 ;; Unprotected line, recalculate
9122 (and all (message "Re-applying formulas to full table...(line %d)"
9123 (setq cnt (1+ cnt))))
9124 (setq org-last-recalc-line (org-current-line))
9126 (while (setq entry (pop eql))
9127 (goto-line org-last-recalc-line)
9128 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9129 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
9130 (goto-line thisline)
9131 (org-table-goto-column thiscol)
9132 (or noalign (and org-table-may-need-update (org-table-align))
9133 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9134 ;; Now do the names fields
9135 (while (setq eq (pop eqlname))
9137 a (assoc name org-table-named-field-locations))
9139 (message "Re-applying formula to named field: %s" name)
9140 (goto-line (nth 1 a))
9141 (org-table-goto-column (nth 2 a))
9142 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
9143 ;; back to initial position
9144 (goto-line thisline)
9145 (org-table-goto-column thiscol)
9146 (or noalign (and org-table-may-need-update (org-table-align))
9147 (and all (message "Re-applying formulas...done")))))
9149 (defun org-table-formula-substitute-names (f)
9150 "Replace $const with values in string F."
9151 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
9152 ;; First, check for column names
9153 (while (setq start (string-match org-table-column-name-regexp f start))
9154 (setq start (1+ start))
9155 (setq a (assoc (match-string 1 f) org-table-column-names))
9156 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9157 ;; Expand ranges to vectors
9158 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
9159 (setq n1 (string-to-number (match-string 1 f))
9160 n2 (string-to-number (match-string 2 f))
9161 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
9162 s (concat "[($" (number-to-string (1- nn1)) ")"))
9163 (loop for i from nn1 upto nn2 do
9164 (setq s (concat s ",($" (int-to-string i) ")")))
9165 (setq s (concat s "]"))
9166 (if (< n2 n1) (setq s (concat "rev(" s ")")))
9167 (setq f (replace-match s t t f)))
9168 ;; Parameters and constants
9170 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
9171 (setq start (1+ start))
9172 (if (setq a (save-match-data
9173 (org-table-get-constant (match-string 1 f))))
9174 (setq f (replace-match (concat "(" a ")") t t f))))
9175 (if org-table-formula-debug
9176 (put-text-property 0 (length f) :orig-formula f1 f))
9179 (defun org-table-get-constant (const)
9180 "Find the value for a parameter or constant in a formula.
9181 Parameters get priority."
9182 (or (cdr (assoc const org-table-local-parameters))
9183 (cdr (assoc const org-table-formula-constants))
9184 (and (fboundp 'constants-get) (constants-get const))
9187 (defvar org-edit-formulas-map (make-sparse-keymap))
9188 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
9189 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
9190 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
9193 (defvar org-window-configuration)
9195 (defun org-table-edit-formulas ()
9196 "Edit the formulas of the current table in a separate buffer."
9198 (unless (org-at-table-p)
9199 (error "Not at a table"))
9200 (org-table-get-specials)
9201 (let ((eql (org-table-get-stored-formulas))
9202 (pos (move-marker (make-marker) (point)))
9203 (wc (current-window-configuration))
9205 (switch-to-buffer-other-window "*Edit Formulas*")
9208 (set (make-local-variable 'org-pos) pos)
9209 (set (make-local-variable 'org-window-configuration) wc)
9210 (use-local-map org-edit-formulas-map)
9211 (setq s "# Edit formulas and finish with `C-c C-c'.
9212 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
9213 # Use `C-c ?' to get information about $name at point.
9214 # To cancel editing, press `C-c C-q'.\n")
9215 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9217 (while (setq entry (pop eql))
9218 (when (setq loc (assoc (car entry) org-table-named-field-locations))
9219 (setq s (format "# Named formula, referring to column %d in line %d\n"
9220 (nth 2 loc) (nth 1 loc)))
9221 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9223 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
9224 (remove-text-properties 0 (length s) '(face nil) s)
9226 (goto-char (point-min))
9227 (message "Edit formulas and finish with `C-c C-c'.")))
9229 (defun org-show-variable ()
9230 "Show the location/value of the $ expression at point."
9232 (let (var (pos org-pos) (win (selected-window)) e)
9234 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
9235 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
9236 (setq var (match-string 1))
9237 (error "No variable at point")))
9239 ((setq e (assoc var org-table-named-field-locations))
9240 (switch-to-buffer-other-window (marker-buffer pos))
9241 (goto-line (nth 1 e))
9242 (org-table-goto-column (nth 2 e))
9244 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9245 ((setq e (assoc var org-table-column-names))
9246 (switch-to-buffer-other-window (marker-buffer pos))
9248 (goto-char (org-table-begin))
9249 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9252 (goto-char (match-beginning 1))
9253 (message "Named column (column %s)" (cdr e)))
9254 (error "Column name not found"))
9255 (select-window win))
9256 ((string-match "^[0-9]$" var)
9258 (switch-to-buffer-other-window (marker-buffer pos))
9260 (goto-char (org-table-begin))
9262 (if (re-search-forward org-table-dataline-regexp
9265 (goto-char (match-beginning 0))
9266 (org-table-goto-column (string-to-number var))
9267 (message "Column %s" var))
9268 (error "Column name not found"))
9269 (select-window win))
9270 ((setq e (assoc var org-table-local-parameters))
9271 (switch-to-buffer-other-window (marker-buffer pos))
9273 (goto-char (org-table-begin))
9274 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9276 (goto-char (match-beginning 1))
9277 (message "Local parameter."))
9278 (error "Parameter not found"))
9279 (select-window win))
9282 ((setq e (assoc var org-table-formula-constants))
9283 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
9284 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9285 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
9286 (t (error "Undefined name $%s" var)))))))
9288 (defun org-finish-edit-formulas (&optional arg)
9289 "Parse the buffer for formula definitions and install them.
9290 With prefix ARG, apply the new formulas to the table."
9292 (let ((pos org-pos) eql)
9293 (goto-char (point-min))
9294 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
9295 (push (cons (match-string 1) (match-string 2)) eql))
9296 (set-window-configuration org-window-configuration)
9297 (select-window (get-buffer-window (marker-buffer pos)))
9299 (unless (org-at-table-p)
9300 (error "Lost table position - cannot install formulae"))
9301 (org-table-store-formulas eql)
9302 (move-marker pos nil)
9303 (kill-buffer "*Edit Formulas*")
9305 (org-table-recalculate 'all)
9306 (message "New formulas installed - press C-u C-c C-c to apply."))))
9308 (defun org-abort-edit-formulas ()
9309 "Abort editing formulas, without installing the changes."
9311 (let ((pos org-pos))
9312 (set-window-configuration org-window-configuration)
9313 (select-window (get-buffer-window (marker-buffer pos)))
9315 (message "Formula editing aborted without installing changes")))
9317 ;;; The orgtbl minor mode
9319 ;; Define a minor mode which can be used in other modes in order to
9320 ;; integrate the org-mode table editor.
9322 ;; This is really a hack, because the org-mode table editor uses several
9323 ;; keys which normally belong to the major mode, for example the TAB and
9324 ;; RET keys. Here is how it works: The minor mode defines all the keys
9325 ;; necessary to operate the table editor, but wraps the commands into a
9326 ;; function which tests if the cursor is currently inside a table. If that
9327 ;; is the case, the table editor command is executed. However, when any of
9328 ;; those keys is used outside a table, the function uses `key-binding' to
9329 ;; look up if the key has an associated command in another currently active
9330 ;; keymap (minor modes, major mode, global), and executes that command.
9331 ;; There might be problems if any of the keys used by the table editor is
9332 ;; otherwise used as a prefix key.
9334 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
9335 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
9336 ;; addresses this by checking explicitly for both bindings.
9338 ;; The optimized version (see variable `orgtbl-optimized') takes over
9339 ;; all keys which are bound to `self-insert-command' in the *global map*.
9340 ;; Some modes bind other commands to simple characters, for example
9341 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
9342 ;; active, this binding is ignored inside tables and replaced with a
9343 ;; modified self-insert.
9345 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
9346 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
9347 In the optimized version, the table editor takes over all simple keys that
9348 normally just insert a character. In tables, the characters are inserted
9349 in a way to minimize disturbing the table structure (i.e. in overwrite mode
9350 for empty fields). Outside tables, the correct binding of the keys is
9353 The default for this option is t if the optimized version is also used in
9354 Org-mode. See the variable `org-enable-table-editor' for details. Changing
9355 this variable requires a restart of Emacs to become effective."
9359 (defvar orgtbl-mode nil
9360 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
9361 table editor in arbitrary modes.")
9362 (make-variable-buffer-local 'orgtbl-mode)
9364 (defvar orgtbl-mode-map (make-keymap)
9365 "Keymap for `orgtbl-mode'.")
9368 (defun turn-on-orgtbl ()
9369 "Unconditionally turn on `orgtbl-mode'."
9373 (defun orgtbl-mode (&optional arg)
9374 "The `org-mode' table editor as a minor mode for use in other modes."
9376 (if (eq major-mode 'org-mode)
9377 ;; Exit without error, in case some hook functions calls this
9378 ;; by accident in org-mode.
9379 (message "Orgtbl-mode is not useful in org-mode, command ignored")
9381 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
9384 (and (orgtbl-setup) (defun orgtbl-setup () nil))
9385 ;; Make sure we are first in minor-mode-map-alist
9386 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
9387 (and c (setq minor-mode-map-alist
9388 (cons c (delq c minor-mode-map-alist)))))
9389 (set (make-local-variable (quote org-table-may-need-update)) t)
9390 (make-local-hook (quote before-change-functions)) ; needed for XEmacs
9391 (add-hook 'before-change-functions 'org-before-change-function
9393 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
9394 auto-fill-inhibit-regexp)
9395 (set (make-local-variable 'auto-fill-inhibit-regexp)
9396 (if auto-fill-inhibit-regexp
9397 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
9399 (easy-menu-add orgtbl-mode-menu)
9400 (run-hooks 'orgtbl-mode-hook))
9401 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
9402 (remove-hook 'before-change-functions 'org-before-change-function t)
9403 (easy-menu-remove orgtbl-mode-menu)
9404 (force-mode-line-update 'all))))
9406 ;; Install it as a minor mode.
9407 (put 'orgtbl-mode :included t)
9408 (put 'orgtbl-mode :menu-tag "Org Table Mode")
9409 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
9411 (defun orgtbl-make-binding (fun n &rest keys)
9412 "Create a function for binding in the table minor mode.
9413 FUN is the command to call inside a table. N is used to create a unique
9414 command name. KEYS are keys that should be checked in for a command
9415 to execute outside of tables."
9418 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
9420 (concat "In tables, run `" (symbol-name fun) "'.\n"
9421 "Outside of tables, run the binding of `"
9422 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
9427 (list 'call-interactively (list 'quote fun))
9428 (list 'let '(orgtbl-mode)
9429 (list 'call-interactively
9432 (list 'key-binding k))
9434 '('orgtbl-error))))))))
9436 (defun orgtbl-error ()
9437 "Error when there is no default binding for a table key."
9439 (error "This key is has no function outside tables"))
9441 (defun orgtbl-setup ()
9442 "Setup orgtbl keymaps."
9446 '([(meta shift left)] org-table-delete-column)
9447 '([(meta left)] org-table-move-column-left)
9448 '([(meta right)] org-table-move-column-right)
9449 '([(meta shift right)] org-table-insert-column)
9450 '([(meta shift up)] org-table-kill-row)
9451 '([(meta shift down)] org-table-insert-row)
9452 '([(meta up)] org-table-move-row-up)
9453 '([(meta down)] org-table-move-row-down)
9454 '("\C-c\C-w" org-table-cut-region)
9455 '("\C-c\M-w" org-table-copy-region)
9456 '("\C-c\C-y" org-table-paste-rectangle)
9457 '("\C-c-" org-table-insert-hline)
9458 ; '([(shift tab)] org-table-previous-field)
9459 '("\C-m" org-table-next-row)
9460 (list (org-key 'S-return) 'org-table-copy-down)
9461 '([(meta return)] org-table-wrap-region)
9462 '("\C-c\C-q" org-table-wrap-region)
9463 '("\C-c?" org-table-current-column)
9464 '("\C-c " org-table-blank-field)
9465 '("\C-c+" org-table-sum)
9466 '("\C-c|" org-table-toggle-vline-visibility)
9467 '("\C-c=" org-table-eval-formula)
9468 '("\C-c'" org-table-edit-formulas)
9469 '("\C-c*" org-table-recalculate)
9470 '("\C-c^" org-table-sort-lines)
9471 '([(control ?#)] org-table-rotate-recalc-marks)))
9473 (while (setq elt (pop bindings))
9474 (setq nfunc (1+ nfunc))
9477 cmd (orgtbl-make-binding fun nfunc key))
9478 (define-key orgtbl-mode-map key cmd))
9479 ;; Special treatment needed for TAB and RET
9480 (define-key orgtbl-mode-map [(return)]
9481 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
9482 (define-key orgtbl-mode-map "\C-m"
9483 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
9484 (define-key orgtbl-mode-map [(tab)]
9485 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
9486 (define-key orgtbl-mode-map "\C-i"
9487 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
9488 (define-key orgtbl-mode-map "\C-i"
9489 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
9490 (define-key orgtbl-mode-map "\C-c\C-c"
9491 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
9492 (when orgtbl-optimized
9493 ;; If the user wants maximum table support, we need to hijack
9494 ;; some standard editing functions
9495 (org-remap orgtbl-mode-map
9496 'self-insert-command 'orgtbl-self-insert-command
9497 'delete-char 'orgtbl-delete-char
9498 'delete-backward-char 'orgtbl-delete-backward-char)
9499 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
9500 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
9502 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
9503 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
9504 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
9505 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
9507 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
9508 ["Copy Field from Above"
9509 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
9512 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
9513 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
9514 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
9515 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
9517 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
9518 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
9519 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
9520 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
9521 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
9523 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
9525 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
9526 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
9527 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
9528 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
9530 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
9531 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9532 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
9533 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
9534 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
9535 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
9536 ["Sum Column/Rectangle" org-table-sum
9537 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
9538 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
9540 (setq org-table-formula-debug (not org-table-formula-debug))
9541 :style toggle :selected org-table-formula-debug]
9545 (defun orgtbl-tab ()
9546 "Justification and field motion for `orgtbl-mode'."
9548 (org-table-justify-field-maybe)
9549 (org-table-next-field))
9551 (defun orgtbl-ret ()
9552 "Justification and field motion for `orgtbl-mode'."
9554 (org-table-justify-field-maybe)
9555 (org-table-next-row))
9557 (defun orgtbl-self-insert-command (N)
9558 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9559 If the cursor is in a table looking at whitespace, the whitespace is
9560 overwritten, and the table is not marked as requiring realignment."
9562 (if (and (org-at-table-p)
9564 (and org-table-auto-blank-field
9565 (member last-command
9566 '(orgtbl-hijacker-command-100
9567 orgtbl-hijacker-command-101
9568 orgtbl-hijacker-command-102
9569 orgtbl-hijacker-command-103
9570 orgtbl-hijacker-command-104
9571 orgtbl-hijacker-command-105))
9572 (org-table-blank-field))
9575 (looking-at "[^|\n]* +|"))
9576 (let (org-table-may-need-update)
9577 (goto-char (1- (match-end 0)))
9578 (delete-backward-char 1)
9579 (goto-char (match-beginning 0))
9580 (self-insert-command N))
9581 (setq org-table-may-need-update t)
9583 (call-interactively (key-binding (vector last-input-event))))))
9585 (defun org-force-self-insert (N)
9586 "Needed to enforce self-insert under remapping."
9588 (self-insert-command N))
9590 (defun orgtbl-delete-backward-char (N)
9591 "Like `delete-backward-char', insert whitespace at field end in tables.
9592 When deleting backwards, in tables this function will insert whitespace in
9593 front of the next \"|\" separator, to keep the table aligned. The table will
9594 still be marked for re-alignment, because a narrow field may lead to a
9595 reduced column width."
9597 (if (and (org-at-table-p)
9599 (string-match "|" (buffer-substring (point-at-bol) (point)))
9600 (looking-at ".*?|"))
9601 (let ((pos (point)))
9602 (backward-delete-char N)
9603 (skip-chars-forward "^|")
9605 (goto-char (1- pos)))
9606 (delete-backward-char N)))
9608 (defun orgtbl-delete-char (N)
9609 "Like `delete-char', but insert whitespace at field end in tables.
9610 When deleting characters, in tables this function will insert whitespace in
9611 front of the next \"|\" separator, to keep the table aligned. The table
9612 will still be marked for re-alignment, because a narrow field may lead to
9613 a reduced column width."
9615 (if (and (org-at-table-p)
9617 (not (= (char-after) ?|))
9619 (if (looking-at ".*?|")
9620 (let ((pos (point)))
9621 (replace-match (concat
9622 (substring (match-string 0) 1 -1)
9629 (defconst org-level-max 20)
9631 (defun org-export-find-first-heading-line (list)
9632 "Remove all lines from LIST which are before the first headline."
9633 (let ((orig-list list)
9634 (re (concat "^" outline-regexp)))
9636 (not (string-match re (car list))))
9638 (or list orig-list)))
9640 (defun org-skip-comments (lines)
9641 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
9642 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
9643 (re2 "^\\(\\*+\\)[ \t\n\r]")
9645 (while (setq line (pop lines))
9647 ((and (string-match re1 line)
9648 (setq level (- (match-end 1) (match-beginning 1))))
9649 ;; Beginning of a COMMENT subtree. Skip it.
9650 (while (and (setq line (pop lines))
9651 (or (not (string-match re2 line))
9652 (> (- (match-end 1) (match-beginning 1)) level))))
9653 (setq lines (cons line lines)))
9654 ((string-match "^#" line)
9655 ;; an ordinary comment line
9657 (t (setq rtn (cons line rtn)))))
9662 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
9663 "Characters for underlining headings in ASCII export.")
9665 (defconst org-html-entities
9705 ("Aring") ("AA"."Å")
9794 ("varepsilon"."ε")
9807 ("sigmaf") ("varsigma"."ς")
9815 ("thetasym") ("vartheta"."ϑ")
9818 ("bull") ("bullet"."•")
9819 ("hellip") ("dots"."…")
9829 ("larr") ("leftarrow"."←") ("gets"."←")
9830 ("uarr") ("uparrow"."↑")
9831 ("rarr") ("to"."→") ("rightarrow"."→")
9832 ("darr")("downarrow"."↓")
9833 ("harr") ("leftrightarrow"."↔")
9834 ("crarr") ("hookleftarrow"."↵") ; has round hook, not quite CR
9835 ("lArr") ("Leftarrow"."⇐")
9836 ("uArr") ("Uparrow"."⇑")
9837 ("rArr") ("Rightarrow"."⇒")
9838 ("dArr") ("Downarrow"."⇓")
9839 ("hArr") ("Leftrightarrow"."⇔")
9841 ("part") ("partial"."∂")
9842 ("exist") ("exists"."∃")
9843 ("empty") ("emptyset"."∅")
9845 ("isin") ("in"."∈")
9851 ("lowast") ("ast"."∗")
9853 ("prop") ("proptp"."∝")
9854 ("infin") ("infty"."∞")
9855 ("ang") ("angle"."∠")
9856 ("and") ("vee"."∧")
9857 ("or") ("wedge"."∨")
9863 ("cong") ("simeq"."≅")
9864 ("asymp")("approx"."≈")
9865 ("ne") ("neq"."≠")
9869 ("sub") ("subset"."⊂")
9870 ("sup") ("supset"."⊃")
9877 ("sdot") ("cdot"."⋅")
9884 ("loz") ("Diamond"."◊")
9885 ("spades") ("spadesuit"."♠")
9886 ("clubs") ("clubsuit"."♣")
9887 ("hearts") ("diamondsuit"."♥")
9888 ("diams") ("diamondsuit"."♦")
9955 "Entities for TeX->HTML translation.
9956 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
9957 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
9958 In that case, \"\\ent\" will be translated to \"&other;\".
9959 The list contains HTML entities for Latin-1, Greek and other symbols.
9960 It is supplemented by a number of commonly used TeX macros with appropriate
9961 translations. There is currently no way for users to extend this.")
9963 (defvar org-last-level nil) ; dynamically scoped variable
9965 (defun org-export-as-ascii (arg)
9966 "Export the outline as a pretty ASCII file.
9967 If there is an active region, export only the region.
9968 The prefix ARG specifies how many levels of the outline should become
9969 underlined headlines. The default is 3."
9971 (setq-default org-todo-line-regexp org-todo-line-regexp)
9974 (if (org-region-active-p) (region-beginning) (point-min))
9975 (if (org-region-active-p) (region-end) (point-max))))
9976 (lines (org-export-find-first-heading-line
9977 (org-skip-comments (org-split-string region "[\r\n]"))))
9978 (org-startup-with-deadline-check nil)
9981 (case-fold-search nil)
9982 (filename (concat (file-name-sans-extension (buffer-file-name))
9984 (buffer (find-file-noselect filename))
9985 (levels-open (make-vector org-level-max nil))
9986 (date (format-time-string "%Y/%m/%d" (current-time)))
9987 (time (format-time-string "%X" (current-time)))
9988 (author user-full-name)
9989 (title (buffer-name))
9991 (email user-mail-address)
9992 (language org-export-default-language)
9997 (setq org-last-level 1)
9998 (org-init-section-numbers)
10000 (find-file-noselect filename)
10002 ;; Search for the export key lines
10003 (org-parse-key-lines)
10005 (setq lang-words (or (assoc language org-export-language-setup)
10006 (assoc "en" org-export-language-setup)))
10007 (if org-export-ascii-show-new-buffer
10008 (switch-to-buffer-other-window buffer)
10009 (set-buffer buffer))
10012 (if options (org-parse-export-options options))
10013 (setq umax (if arg (prefix-numeric-value arg)
10014 org-export-headline-levels))
10017 (if title (org-insert-centered title ?=))
10019 (if (or author email)
10020 (insert (concat (nth 1 lang-words) ": " (or author "")
10021 (if email (concat " <" email ">") "")
10023 (if (and date time)
10024 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
10025 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
10029 (if org-export-with-toc
10031 (insert (nth 3 lang-words) "\n"
10032 (make-string (length (nth 3 lang-words)) ?=) "\n")
10033 (mapcar '(lambda (line)
10034 (if (string-match org-todo-line-regexp
10036 ;; This is a headline
10038 (setq level (- (match-end 1) (match-beginning 1))
10039 txt (match-string 3 line)
10041 (or (and (match-beginning 2)
10042 (not (equal (match-string 2 line)
10045 (and (= level umax)
10046 (org-search-todo-below
10047 line lines level))))
10048 (setq txt (org-html-expand-for-ascii txt))
10050 (if org-export-with-section-numbers
10051 (setq txt (concat (org-section-number level)
10053 (if (<= level umax)
10056 (make-string (* (1- level) 4) ?\ )
10057 (format (if todo "%s (*)\n" "%s\n") txt))
10058 (setq org-last-level level))
10062 (org-init-section-numbers)
10063 (while (setq line (pop lines))
10064 ;; Remove the quoted HTML tags.
10065 (setq line (org-html-expand-for-ascii line))
10067 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10069 (setq level (- (match-end 1) (match-beginning 1))
10070 txt (match-string 2 line))
10071 (org-ascii-level-start level txt umax))
10072 (t (insert line "\n"))))
10075 (goto-char (point-min))))
10077 (defun org-search-todo-below (line lines level)
10078 "Search the subtree below LINE for any TODO entries."
10079 (let ((rest (cdr (memq line lines)))
10080 (re org-todo-line-regexp)
10083 (while (setq line (pop rest))
10084 (if (string-match re line)
10086 (setq lv (- (match-end 1) (match-beginning 1))
10087 todo (and (match-beginning 2)
10088 (not (equal (match-string 2 line)
10089 org-done-string))))
10091 (if (<= lv level) (throw 'exit nil))
10092 (if todo (throw 'exit t))))))))
10094 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
10095 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
10096 (defun org-html-expand-for-ascii (line)
10097 "Handle quoted HTML for ASCII export."
10098 (if org-export-html-expand
10099 (while (string-match "@<[^<>\n]*>" line)
10100 ;; We just remove the tags for now.
10101 (setq line (replace-match "" nil nil line))))
10104 (defun org-insert-centered (s &optional underline)
10105 "Insert the string S centered and underline it with character UNDERLINE."
10106 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
10107 (insert (make-string ind ?\ ) s "\n")
10109 (insert (make-string ind ?\ )
10110 (make-string (length s) underline)
10113 (defun org-ascii-level-start (level title umax)
10114 "Insert a new level in ASCII export."
10117 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
10118 (if (or (not (equal (char-before) ?\n))
10119 (not (equal (char-before (1- (point))) ?\n)))
10121 (setq char (nth (- umax level) (reverse org-ascii-underline)))
10122 (if org-export-with-section-numbers
10123 (setq title (concat (org-section-number level) " " title)))
10124 (insert title "\n" (make-string (string-width title) char) "\n"))))
10126 (defun org-export-copy-visible ()
10127 "Copy the visible part of the buffer to another buffer, for printing.
10128 Also removes the first line of the buffer if it specifies a mode,
10129 and all options lines."
10131 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
10133 (buffer (find-file-noselect filename))
10135 (org-make-options-regexp
10136 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
10137 "STARTUP" "ARCHIVE"
10138 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
10139 (if org-noutline-p "\\(\n\\|$\\)" "")))
10141 (with-current-buffer buffer
10145 (setq s (goto-char (point-min)))
10146 (while (not (= (point) (point-max)))
10147 (goto-char (org-find-invisible))
10148 (append-to-buffer buffer s (point))
10149 (setq s (goto-char (org-find-visible)))))
10150 (switch-to-buffer-other-window buffer)
10152 (goto-char (point-min))
10153 (if (looking-at ".*-\\*- mode:.*\n")
10154 (replace-match ""))
10155 (while (re-search-forward ore nil t)
10156 (replace-match ""))
10157 (goto-char (point-min))))
10159 (defun org-find-visible ()
10160 (if (featurep 'noutline)
10162 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10163 (get-char-property s 'invisible)))
10165 (skip-chars-forward "^\n")
10167 (defun org-find-invisible ()
10168 (if (featurep 'noutline)
10170 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10171 (not (get-char-property s 'invisible))))
10173 (skip-chars-forward "^\r")
10178 (defun org-get-current-options ()
10179 "Return a string with current options as keyword options.
10180 Does include HTML export options as well as TODO and CATEGORY stuff."
10186 #+TEXT: Some descriptive text to be emitted. Several lines OK.
10187 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
10194 (buffer-name) (user-full-name) user-mail-address org-export-default-language
10195 org-export-headline-levels
10196 org-export-with-section-numbers
10197 org-export-with-toc
10198 org-export-preserve-breaks
10199 org-export-html-expand
10200 org-export-with-fixed-width
10201 org-export-with-tables
10202 org-export-with-sub-superscripts
10203 org-export-with-emphasize
10204 org-export-with-TeX-macros
10205 (file-name-nondirectory (buffer-file-name))
10206 (if (equal org-todo-interpretation 'sequence)
10207 (mapconcat 'identity org-todo-keywords " ")
10208 "TODO FEEDBACK VERIFY DONE")
10209 (if (equal org-todo-interpretation 'type)
10210 (mapconcat 'identity org-todo-keywords " ")
10211 "Me Jason Marie DONE")
10212 (cdr (assoc org-startup-folded
10213 '((nil . "nofold")(t . "fold")(content . "content"))))
10214 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
10215 org-archive-location
10218 (defun org-insert-export-options-template ()
10219 "Insert into the buffer a template with information for exporting."
10221 (if (not (bolp)) (newline))
10222 (let ((s (org-get-current-options)))
10223 (and (string-match "#\\+CATEGORY" s)
10224 (setq s (substring s 0 (match-beginning 0))))
10227 (defun org-toggle-fixed-width-section (arg)
10228 "Toggle the fixed-width export.
10229 If there is no active region, the QUOTE keyword at the current headline is
10230 inserted or removed. When present, it causes the text between this headline
10231 and the next to be exported as fixed-width text, and unmodified.
10232 If there is an active region, this command adds or removes a colon as the
10233 first character of this line. If the first character of a line is a colon,
10234 this line is also exported in fixed-width font."
10237 (regionp (org-region-active-p))
10238 (beg (if regionp (region-beginning) (point)))
10239 (end (if regionp (region-end)))
10240 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
10241 (re "[ \t]*\\(:\\)")
10246 (setq cc (current-column))
10247 (beginning-of-line 1)
10248 (setq off (looking-at re))
10249 (while (> nlines 0)
10250 (setq nlines (1- nlines))
10251 (beginning-of-line 1)
10254 (move-to-column cc t)
10257 ((and off (looking-at re))
10258 (replace-match "" t t nil 1))
10259 ((not off) (move-to-column cc t) (insert ":")))
10262 (org-back-to-heading)
10263 (if (looking-at (concat outline-regexp
10264 "\\( +\\<" org-quote-string "\\>\\)"))
10265 (replace-match "" t t nil 1)
10266 (if (looking-at outline-regexp)
10268 (goto-char (match-end 0))
10269 (insert " " org-quote-string))))))))
10271 (defun org-export-as-html-and-open (arg)
10272 "Export the outline as HTML and immediately open it with a browser.
10273 If there is an active region, export only the region.
10274 The prefix ARG specifies how many levels of the outline should become
10275 headlines. The default is 3. Lower levels will become bulleted lists."
10277 (org-export-as-html arg 'hidden)
10278 (org-open-file (buffer-file-name)))
10280 (defun org-export-as-html-batch ()
10281 "Call `org-export-as-html', may be used in batch processing as
10283 --load=$HOME/lib/emacs/org.el
10284 --eval \"(setq org-export-headline-levels 2)\"
10285 --visit=MyFile --funcall org-export-as-html-batch"
10286 (org-export-as-html org-export-headline-levels 'hidden))
10288 (defun org-export-as-html (arg &optional hidden)
10289 "Export the outline as a pretty HTML file.
10290 If there is an active region, export only the region.
10291 The prefix ARG specifies how many levels of the outline should become
10292 headlines. The default is 3. Lower levels will become bulleted lists."
10294 (setq-default org-todo-line-regexp org-todo-line-regexp)
10295 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
10296 (setq-default org-done-string org-done-string)
10297 (let* ((style org-export-html-style)
10298 (region-p (org-region-active-p))
10301 (if region-p (region-beginning) (point-min))
10302 (if region-p (region-end) (point-max))))
10304 (org-skip-comments (org-split-string region "[\r\n]")))
10305 (lines (org-export-find-first-heading-line all_lines))
10306 (level 0) (line "") (origline "") txt todo
10308 (filename (concat (file-name-sans-extension (buffer-file-name))
10310 (buffer (find-file-noselect filename))
10311 (levels-open (make-vector org-level-max nil))
10312 (date (format-time-string "%Y/%m/%d" (current-time)))
10313 (time (format-time-string "%X" (current-time)))
10314 (author user-full-name)
10315 (title (buffer-name))
10317 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
10320 (in-local-list nil)
10321 (local-list-num nil)
10322 (local-list-indent nil)
10323 (llt org-plain-list-ordered-item-terminator)
10324 (email user-mail-address)
10325 (language org-export-default-language)
10330 ;; FIXME: The following returns always nil under XEmacs
10331 (coding-system (and (fboundp 'coding-system-get)
10332 (boundp 'buffer-file-coding-system)
10333 buffer-file-coding-system))
10334 (coding-system-for-write (or coding-system coding-system-for-write))
10335 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
10336 (charset (and coding-system
10337 (coding-system-get coding-system 'mime-charset)))
10339 table-buffer table-orig-buffer
10340 ind start-is-num starter
10342 (message "Exporting...")
10344 (setq org-last-level 1)
10345 (org-init-section-numbers)
10347 ;; Search for the export key lines
10348 (org-parse-key-lines)
10349 (setq lang-words (or (assoc language org-export-language-setup)
10350 (assoc "en" org-export-language-setup)))
10352 ;; Switch to the output buffer
10353 (if (or hidden (not org-export-html-show-new-buffer))
10354 (set-buffer buffer)
10355 (switch-to-buffer-other-window buffer))
10358 (let ((case-fold-search nil))
10359 (if options (org-parse-export-options options))
10360 (setq umax (if arg (prefix-numeric-value arg)
10361 org-export-headline-levels))
10365 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
10366 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
10367 <html lang=\"%s\"><head>
10369 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
10370 <meta name=generator content=\"Org-mode\">
10371 <meta name=generated content=\"%s %s\">
10372 <meta name=author content=\"%s\">
10376 language (org-html-expand title) (or charset "iso-8859-1")
10377 date time author style))
10378 (if title (insert (concat "<H1 class=\"title\">"
10379 (org-html-expand title) "</H1>\n")))
10380 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
10381 (if email (insert (concat "<a href=\"mailto:" email "\"><"
10382 email "></a>\n")))
10383 (if (or author email) (insert "<br>\n"))
10384 (if (and date time) (insert (concat (nth 2 lang-words) ": "
10385 date " " time "<br>\n")))
10386 (if text (insert (concat "<p>\n" (org-html-expand text))))
10387 (if org-export-with-toc
10389 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
10391 (mapcar '(lambda (line)
10392 (if (string-match org-todo-line-regexp line)
10393 ;; This is a headline
10395 (setq level (- (match-end 1) (match-beginning 1))
10396 txt (save-match-data
10398 (match-string 3 line)))
10400 (or (and (match-beginning 2)
10401 (not (equal (match-string 2 line)
10404 (and (= level umax)
10405 (org-search-todo-below
10406 line lines level))))
10407 (if org-export-with-section-numbers
10408 (setq txt (concat (org-section-number level)
10410 (if (<= level umax)
10412 (setq head-count (+ head-count 1))
10413 (if (> level org-last-level)
10415 (setq cnt (- level org-last-level))
10416 (while (>= (setq cnt (1- cnt)) 0)
10419 (if (< level org-last-level)
10421 (setq cnt (- org-last-level level))
10422 (while (>= (setq cnt (1- cnt)) 0)
10428 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
10429 "<li><a href=\"#sec-%d\">%s</a>\n")
10431 (setq org-last-level level))
10434 (while (> org-last-level 0)
10435 (setq org-last-level (1- org-last-level))
10436 (insert "</ul>\n"))
10438 (setq head-count 0)
10439 (org-init-section-numbers)
10441 (while (setq line (pop lines) origline line)
10444 ;; end of quote section?
10445 (when (and inquote (string-match "^\\*+" line))
10446 (insert "</pre>\n")
10447 (setq inquote nil))
10448 ;; inside a quote section?
10450 (insert (org-html-protect line) "\n")
10451 (throw 'nextline nil))
10454 (when (and org-export-with-fixed-width
10455 (string-match "^[ \t]*:\\(.*\\)" line))
10456 (when (not infixed)
10458 (insert "<pre>\n"))
10459 (insert (org-html-protect (match-string 1 line)) "\n")
10461 (not (string-match "^[ \t]*\\(:.*\\)"
10464 (insert "</pre>\n"))
10465 (throw 'nextline nil))
10467 ;; Protect the links
10469 (while (string-match org-link-maybe-angles-regexp line start)
10470 (setq start (match-end 0))
10471 (setq line (replace-match
10472 (concat "\000" (match-string 1 line) "\000")
10475 ;; replace "&" by "&", "<" and ">" by "<" and ">"
10476 ;; handle @<..> HTML tags (replace "@>..<" by "<..>")
10477 (setq line (org-html-expand line))
10479 ;; Format the links
10481 (while (string-match org-protected-link-regexp line start)
10482 (setq start (- (match-end 0) 2))
10483 (setq type (match-string 1 line))
10485 ((member type '("http" "https" "ftp" "mailto" "news"))
10487 (setq line (replace-match
10488 ; "<a href=\"\\1:\\2\"><\\1:\\2></a>"
10489 "<a href=\"\\1:\\2\">\\1:\\2</a>"
10491 ((string= type "file")
10493 (let* ((filename (match-string 2 line))
10494 (abs-p (file-name-absolute-p filename))
10495 (thefile (if abs-p (expand-file-name filename) filename))
10496 (thefile (save-match-data
10497 (if (string-match ":[0-9]+$" thefile)
10498 (replace-match "" t t thefile)
10502 (string-match (org-image-file-name-regexp) thefile))))
10503 (setq line (replace-match
10504 (if (and org-export-html-inline-images
10506 (concat "<img src=\"" thefile "\"/>")
10507 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
10510 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
10511 (setq line (replace-match
10512 "<i><\\1:\\2></i>" nil nil line)))))
10515 (if (and (string-match org-todo-line-regexp line)
10516 (match-beginning 2))
10517 (if (equal (match-string 2 line) org-done-string)
10518 (setq line (replace-match
10519 "<span class=\"done\">\\2</span>"
10521 (setq line (replace-match "<span class=\"todo\">\\2</span>"
10525 (if (string-match org-deadline-line-regexp line)
10527 (if (save-match-data
10528 (string-match "<a href"
10529 (substring line 0 (match-beginning 0))))
10530 nil ; Don't do the replacement - it is inside a link
10531 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
10532 nil nil line 1)))))
10534 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10535 ;; This is a headline
10536 (setq level (- (match-end 1) (match-beginning 1))
10537 txt (match-string 2 line))
10538 (if (<= level umax) (setq head-count (+ head-count 1)))
10539 (when in-local-list
10540 ;; Close any local lists before inserting a new header line
10541 (while local-list-num
10542 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
10543 (pop local-list-num))
10544 (setq local-list-indent nil
10545 in-local-list nil))
10546 (org-html-level-start level txt umax
10547 (and org-export-with-toc (<= level umax))
10550 (when (string-match quote-re line)
10554 ((and org-export-with-tables
10555 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
10556 (if (not table-open)
10557 ;; New table starts
10558 (setq table-open t table-buffer nil table-orig-buffer nil))
10559 ;; Accumulate lines
10560 (setq table-buffer (cons line table-buffer)
10561 table-orig-buffer (cons origline table-orig-buffer))
10562 (when (or (not lines)
10563 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
10565 (setq table-open nil
10566 table-buffer (nreverse table-buffer)
10567 table-orig-buffer (nreverse table-orig-buffer))
10568 (insert (org-format-table-html table-buffer table-orig-buffer))))
10571 (when (and (> org-export-plain-list-max-depth 0)
10574 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10575 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10576 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
10577 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
10579 (setq ind (org-get-string-indentation line)
10580 start-is-num (match-beginning 4)
10581 starter (if (match-beginning 2) (match-string 2 line))
10582 line (substring line (match-beginning 5)))
10583 (unless (string-match "[^ \t]" line)
10584 ;; empty line. Pretend indentation is large.
10585 (setq ind (1+ (or (car local-list-indent) 1))))
10586 (while (and in-local-list
10587 (or (and (= ind (car local-list-indent))
10589 (< ind (car local-list-indent))))
10590 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
10591 (pop local-list-num) (pop local-list-indent)
10592 (setq in-local-list local-list-indent))
10595 (or (not in-local-list)
10596 (> ind (car local-list-indent)))
10597 (< (length local-list-indent)
10598 org-export-plain-list-max-depth))
10599 ;; Start new (level of ) list
10600 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
10601 (push start-is-num local-list-num)
10602 (push ind local-list-indent)
10603 (setq in-local-list t))
10605 ;; continue current list
10606 (insert "<li>\n"))))
10607 ;; Empty lines start a new paragraph. If hand-formatted lists
10608 ;; are not fully interpreted, lines starting with "-", "+", "*"
10609 ;; also start a new paragraph.
10610 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
10611 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
10613 (if org-export-html-with-timestamp
10614 (insert org-export-html-html-helper-timestamp))
10615 (insert "</body>\n</html>\n")
10618 (goto-char (point-min)))))
10620 (defun org-format-table-html (lines olines)
10621 "Find out which HTML converter to use and return the HTML code."
10622 (if (string-match "^[ \t]*|" (car lines))
10623 ;; A normal org table
10624 (org-format-org-table-html lines)
10625 ;; Table made by table.el - test for spanning
10626 (let* ((hlines (delq nil (mapcar
10628 (if (string-match "^[ \t]*\\+-" x) x
10631 (first (car hlines))
10632 (ll (and (string-match "\\S-+" first)
10633 (match-string 0 first)))
10634 (re (concat "^[ \t]*" (regexp-quote ll)))
10635 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
10637 (if (and (not spanning)
10638 (not org-export-prefer-native-exporter-for-tables))
10639 ;; We can use my own converter with HTML conversions
10640 (org-format-table-table-html lines)
10641 ;; Need to use the code generator in table.el, with the original text.
10642 (org-format-table-table-html-using-table-generate-source olines)))))
10644 (defun org-format-org-table-html (lines)
10645 "Format a table into html."
10646 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10647 (setq lines (nreverse lines))
10648 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
10649 (setq lines (nreverse lines))
10650 (let ((head (and org-export-highlight-first-table-line
10652 (lambda (x) (string-match "^[ \t]*|-" x))
10655 (setq html (concat org-export-html-table-tag "\n"))
10656 (while (setq line (pop lines))
10658 (if (string-match "^[ \t]*|-" line)
10660 (setq head nil) ;; head ends here, first time around
10661 ;; ignore this line
10662 (throw 'next-line t)))
10663 ;; Break the line into fields
10664 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10668 (mapconcat (lambda (x)
10670 (concat "<th>" x "</th>")
10671 (concat "<td>" x "</td>")))
10674 (setq html (concat html "</table>\n"))
10677 (defun org-fake-empty-table-line (line)
10678 "Replace everything except \"|\" with spaces."
10679 (let ((i (length line))
10680 (newstr (copy-sequence line)))
10683 (if (not (eq (aref newstr i) ?|))
10684 (aset newstr i ?\ )))
10687 (defun org-format-table-table-html (lines)
10688 "Format a table generated by table.el into html.
10689 This conversion does *not* use `table-generate-source' from table.el.
10690 This has the advantage that Org-mode's HTML conversions can be used.
10691 But it has the disadvantage, that no cell- or row-spanning is allowed."
10692 (let (line field-buffer
10693 (head org-export-highlight-first-table-line)
10695 (setq html (concat org-export-html-table-tag "\n"))
10696 (while (setq line (pop lines))
10697 (setq empty " ")
10699 (if (string-match "^[ \t]*\\+-" line)
10708 (if (equal x "") (setq x empty))
10710 (concat "<th>" x "</th>\n")
10711 (concat "<td>" x "</td>\n")))
10715 (setq field-buffer nil)))
10716 ;; Ignore this line
10717 (throw 'next-line t)))
10718 ;; Break the line into fields and store the fields
10719 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
10721 (setq field-buffer (mapcar
10723 (concat x "<br>" (pop fields)))
10725 (setq field-buffer fields))))
10726 (setq html (concat html "</table>\n"))
10729 (defun org-format-table-table-html-using-table-generate-source (lines)
10730 "Format a table into html, using `table-generate-source' from table.el.
10731 This has the advantage that cell- or row-spanning is allowed.
10732 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
10734 (with-current-buffer (get-buffer-create " org-tmp1 ")
10736 (insert (mapconcat 'identity lines "\n"))
10737 (goto-char (point-min))
10738 (if (not (re-search-forward "|[^+]" nil t))
10739 (error "Error processing table"))
10740 (table-recognize-table)
10741 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
10742 (table-generate-source 'html " org-tmp2 ")
10743 (set-buffer " org-tmp2 ")
10744 (buffer-substring (point-min) (point-max))))
10746 (defun org-html-protect (s)
10747 ;; convert & to &, < to < and > to >
10749 (while (string-match "&" s start)
10750 (setq s (replace-match "&" t t s)
10751 start (1+ (match-beginning 0))))
10752 (while (string-match "<" s)
10753 (setq s (replace-match "<" t t s)))
10754 (while (string-match ">" s)
10755 (setq s (replace-match ">" t t s))))
10758 (defun org-html-expand (string)
10759 "Prepare STRING for HTML export. Applies all active conversions."
10760 ;; First check if there is a link in the line - if yes, apply conversions
10761 ;; only before the start of the link.
10762 ;; FIXME: This is no longer correct, because links now have an end.
10763 (let* ((m (string-match org-link-regexp string))
10764 (s (if m (substring string 0 m) string))
10765 (r (if m (substring string m) "")))
10766 ;; convert & to &, < to < and > to >
10767 (setq s (org-html-protect s))
10768 (if org-export-html-expand
10769 (while (string-match "@<\\([^&]*\\)>" s)
10770 (setq s (replace-match "<\\1>" nil nil s))))
10771 (if org-export-with-emphasize
10772 (setq s (org-export-html-convert-emphasize s)))
10773 (if org-export-with-sub-superscripts
10774 (setq s (org-export-html-convert-sub-super s)))
10775 (if org-export-with-TeX-macros
10776 (let ((start 0) wd ass)
10777 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
10778 (setq wd (match-string 1 s))
10779 (if (setq ass (assoc wd org-html-entities))
10780 (setq s (replace-match (or (cdr ass)
10781 (concat "&" (car ass) ";"))
10783 (setq start (+ start (length wd)))))))
10786 (defun org-create-multibrace-regexp (left right n)
10787 "Create a regular expression which will match a balanced sexp.
10788 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
10789 as single character strings.
10790 The regexp returned will match the entire expression including the
10791 delimiters. It will also define a single group which contains the
10792 match except for the outermost delimiters. The maximum depth of
10793 stacked delimiters is N. Escaping delimiters is not possible."
10794 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
10797 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
10800 re (concat re or next)
10801 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
10802 (concat left "\\(" re "\\)" right)))
10804 (defvar org-match-substring-regexp
10806 "\\([^\\]\\)\\([_^]\\)\\("
10807 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
10809 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
10811 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
10812 "The regular expression matching a sub- or superscript.")
10814 (defun org-export-html-convert-sub-super (string)
10815 "Convert sub- and superscripts in STRING to HTML."
10817 (while (string-match org-match-substring-regexp string)
10818 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
10819 (setq c (or (match-string 8 string)
10820 (match-string 6 string)
10821 (match-string 5 string)))
10822 (setq string (replace-match
10823 (concat (match-string 1 string)
10824 "<" key ">" c "</" key ">")
10826 (while (string-match "\\\\\\([_^]\\)" string)
10827 (setq string (replace-match (match-string 1 string) t t string))))
10830 (defun org-export-html-convert-emphasize (string)
10831 (while (string-match
10832 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
10834 (setq string (replace-match
10835 (concat "<b>" (match-string 3 string) "</b>")
10837 (while (string-match
10838 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
10840 (setq string (replace-match
10841 (concat "<i>" (match-string 3 string) "</i>")
10843 (while (string-match
10844 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
10846 (setq string (replace-match
10847 (concat "<u>" (match-string 3 string) "</u>")
10851 (defun org-parse-key-lines ()
10852 "Find the special key lines with the information for exporters."
10855 (let ((re (org-make-options-regexp
10856 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
10858 (while (re-search-forward re nil t)
10859 (setq key (match-string 1))
10860 (cond ((string-equal key "TITLE")
10861 (setq title (match-string 2)))
10862 ((string-equal key "AUTHOR")
10863 (setq author (match-string 2)))
10864 ((string-equal key "EMAIL")
10865 (setq email (match-string 2)))
10866 ((string-equal key "LANGUAGE")
10867 (setq language (match-string 2)))
10868 ((string-equal key "TEXT")
10869 (setq text (concat text "\n" (match-string 2))))
10870 ((string-equal key "OPTIONS")
10871 (setq options (match-string 2))))))))
10873 (defun org-parse-export-options (s)
10874 "Parse the export options line."
10875 (let ((op '(("H" . org-export-headline-levels)
10876 ("num" . org-export-with-section-numbers)
10877 ("toc" . org-export-with-toc)
10878 ("\\n" . org-export-preserve-breaks)
10879 ("@" . org-export-html-expand)
10880 (":" . org-export-with-fixed-width)
10881 ("|" . org-export-with-tables)
10882 ("^" . org-export-with-sub-superscripts)
10883 ("*" . org-export-with-emphasize)
10884 ("TeX" . org-export-with-TeX-macros)))
10886 (while (setq o (pop op))
10887 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
10889 (set (make-local-variable (cdr o))
10890 (car (read-from-string (match-string 1 s))))))))
10892 (defun org-html-level-start (level title umax with-toc head-count)
10893 "Insert a new level in HTML export."
10894 (let ((l (1+ (max level umax))))
10895 (while (<= l org-level-max)
10896 (if (aref levels-open (1- l))
10898 (org-html-level-close l)
10899 (aset levels-open (1- l) nil)))
10903 (if (aref levels-open (1- level))
10904 (insert "<li>" title "<p>\n")
10905 (aset levels-open (1- level) t)
10906 (insert "<ul><li>" title "<p>\n")))
10907 (if org-export-with-section-numbers
10908 (setq title (concat (org-section-number level) " " title)))
10909 (setq level (+ level 1))
10911 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
10912 level head-count title level))
10913 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
10915 (defun org-html-level-close (&rest args)
10916 "Terminate one level in HTML export."
10919 ;; Variable holding the vector with section numbers
10920 (defvar org-section-numbers (make-vector org-level-max 0))
10922 (defun org-init-section-numbers ()
10923 "Initialize the vector for the section numbers."
10925 (numbers (nreverse (org-split-string "" "\\.")))
10926 (depth (1- (length org-section-numbers)))
10927 (i depth) number-string)
10930 (aset org-section-numbers i 0)
10931 (setq number-string (or (car numbers) "0"))
10932 (if (string-match "\\`[A-Z]\\'" number-string)
10933 (aset org-section-numbers i
10934 (- (string-to-char number-string) ?A -1))
10935 (aset org-section-numbers i (string-to-number number-string)))
10939 (defun org-section-number (&optional level)
10940 "Return a string with the current section number.
10941 When LEVEL is non-nil, increase section numbers on that level."
10942 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
10945 (aset org-section-numbers
10946 level (1+ (aref org-section-numbers level))))
10947 (setq idx (1+ level))
10948 (while (<= idx depth)
10949 (if (not (= idx 1))
10950 (aset org-section-numbers idx 0))
10951 (setq idx (1+ idx))))
10953 (while (<= idx depth)
10954 (setq n (aref org-section-numbers idx))
10955 (setq string (concat string (if (not (string= string "")) "." "")
10956 (int-to-string n)))
10957 (setq idx (1+ idx)))
10959 (if (string-match "\\`\\([@0]\\.\\)+" string)
10960 (setq string (replace-match "" nil nil string)))
10961 (if (string-match "\\(\\.0\\)+\\'" string)
10962 (setq string (replace-match "" nil nil string))))
10966 (defun org-export-icalendar-this-file ()
10967 "Export current file as an iCalendar file.
10968 The iCalendar file will be located in the same directory as the Org-mode
10969 file, but with extension `.ics'."
10971 (org-export-icalendar nil (buffer-file-name)))
10974 (defun org-export-icalendar-all-agenda-files ()
10975 "Export all files in `org-agenda-files' to iCalendar .ics files.
10976 Each iCalendar file will be located in the same directory as the Org-mode
10977 file, but with extension `.ics'."
10979 (apply 'org-export-icalendar nil org-agenda-files))
10982 (defun org-export-icalendar-combine-agenda-files ()
10983 "Export all files in `org-agenda-files' to a single combined iCalendar file.
10984 The file is stored under the name `org-combined-agenda-icalendar-file'."
10986 (apply 'org-export-icalendar t org-agenda-files))
10988 (defun org-export-icalendar (combine &rest files)
10989 "Create iCalendar files for all elements of FILES.
10990 If COMBINE is non-nil, combine all calendar entries into a single large
10991 file and store it under the name `org-combined-agenda-icalendar-file'."
10993 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
10995 (setq ical-file org-combined-agenda-icalendar-file
10996 ical-buffer (org-get-agenda-file-buffer ical-file))
10997 (set-buffer ical-buffer) (erase-buffer))
10998 (while (setq file (pop files))
11000 (org-check-agenda-file file)
11002 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
11003 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
11004 (set-buffer ical-buffer) (erase-buffer))
11005 (set-buffer (org-get-agenda-file-buffer file))
11006 (setq category (or org-category
11007 (file-name-sans-extension
11008 (file-name-nondirectory (buffer-file-name)))))
11009 (if (symbolp category) (setq category (symbol-name category)))
11010 (let ((standard-output ical-buffer))
11012 (and (not started) (setq started t)
11013 (org-start-icalendar-file org-icalendar-combined-name))
11014 (org-start-icalendar-file category))
11015 (org-print-icalendar-entries combine category)
11016 (when (or (and combine (not files)) (not combine))
11017 (org-finish-icalendar-file)
11018 (set-buffer ical-buffer)
11020 (run-hooks 'org-after-save-iCalendar-file-hook)))))
11021 (org-release-buffers org-agenda-new-buffers))))
11023 (defvar org-after-save-iCalendar-file-hook nil
11024 "Hook run after an iCalendar file has been saved.
11025 The iCalendar buffer is still current when this hook is run.
11026 A good way to use this is to tell a desktop calenndar application to re-read
11027 the iCalendar file.")
11029 (defun org-print-icalendar-entries (&optional combine category)
11030 "Print iCalendar entries for the current Org-mode file to `standard-output'.
11031 When COMBINE is non nil, add the category to each line."
11032 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
11033 (dts (org-ical-ts-to-string
11034 (format-time-string (cdr org-time-stamp-formats) (current-time))
11036 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
11038 (goto-char (point-min))
11039 (while (re-search-forward org-ts-regexp nil t)
11040 (setq pos (match-beginning 0)
11041 ts (match-string 0)
11043 hd (org-get-heading))
11044 (if (looking-at re2)
11046 (goto-char (match-end 0))
11047 (setq ts2 (match-string 1) inc nil))
11049 tmp (buffer-substring (max (point-min)
11050 (- pos org-ds-keyword-length))
11052 deadlinep (string-match org-deadline-regexp tmp)
11053 scheduledp (string-match org-scheduled-regexp tmp)
11054 ;; donep (org-entry-is-done-p)
11056 (if (or (string-match org-tr-regexp hd)
11057 (string-match org-ts-regexp hd))
11058 (setq hd (replace-match "" t t hd)))
11060 (setq hd (concat hd " (category " category ")")))
11061 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
11062 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
11063 (princ (format "BEGIN:VEVENT
11068 (org-ical-ts-to-string ts "DTSTART")
11069 (org-ical-ts-to-string ts2 "DTEND" inc)
11071 (when org-icalendar-include-todo
11072 (goto-char (point-min))
11073 (while (re-search-forward org-todo-line-regexp nil t)
11074 (setq state (match-string 1))
11075 (unless (equal state org-done-string)
11076 (setq hd (match-string 3))
11077 (if (string-match org-priority-regexp hd)
11078 (setq pri (string-to-char (match-string 2 hd))
11079 hd (concat (substring hd 0 (match-beginning 1))
11080 (substring hd (- (match-end 1)))))
11081 (setq pri org-default-priority))
11082 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
11083 (- org-lowest-priority ?A))))))
11085 (princ (format "BEGIN:VTODO
11093 (defun org-start-icalendar-file (name)
11094 "Start an iCalendar file by inserting the header."
11095 (let ((user user-full-name)
11096 (name (or name "unknown"))
11097 (timezone (cadr (current-time-zone))))
11099 (format "BEGIN:VCALENDAR
11102 PRODID:-//%s//Emacs with Org-mode//EN
11104 CALSCALE:GREGORIAN\n" name user timezone))))
11106 (defun org-finish-icalendar-file ()
11107 "Finish an iCalendar file by inserting the END statement."
11108 (princ "END:VCALENDAR\n"))
11110 (defun org-ical-ts-to-string (s keyword &optional inc)
11111 "Take a time string S and convert it to iCalendar format.
11112 KEYWORD is added in front, to make a complete line like DTSTART....
11113 When INC is non-nil, increase the hour by two (if time string contains
11114 a time), or the day by one (if it does not contain a time)."
11115 (let ((t1 (org-parse-time-string s 'nodefault))
11116 t2 fmt have-time time)
11117 (if (and (car t1) (nth 1 t1) (nth 2 t1))
11118 (setq t2 t1 have-time t)
11119 (setq t2 (org-parse-time-string s)))
11120 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
11121 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
11123 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
11124 (setq time (encode-time s mi h d m y)))
11125 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
11126 (concat keyword (format-time-string fmt time))))
11131 ;; - Bindings in Org-mode map are currently
11132 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
11133 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
11134 ;; e (?) useful from outline-mode
11135 ;; i k @ expendable from outline-mode
11136 ;; 0123456789 ! %^& ()_{} " `' free
11138 ;; Make `C-c C-x' a prefix key
11139 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
11141 ;; TAB key with modifiers
11142 (define-key org-mode-map "\C-i" 'org-cycle)
11143 (define-key org-mode-map [(meta tab)] 'org-complete)
11144 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
11145 ;; The following line is necessary under Suse GNU/Linux
11146 (unless org-xemacs-p
11147 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
11148 (define-key org-mode-map [(shift tab)] 'org-shifttab)
11150 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
11151 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
11152 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11153 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
11154 (define-key org-mode-map [(meta return)] 'org-meta-return)
11155 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
11156 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
11158 ;; Cursor keys with modifiers
11159 (define-key org-mode-map [(meta left)] 'org-metaleft)
11160 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
11161 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
11162 (define-key org-mode-map [(meta right)] 'org-metaright)
11163 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
11164 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
11165 (define-key org-mode-map [(meta up)] 'org-metaup)
11166 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
11167 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
11168 (define-key org-mode-map [(meta down)] 'org-metadown)
11169 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
11170 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
11172 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11173 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
11174 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
11175 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
11176 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
11177 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
11178 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
11179 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
11180 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
11181 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
11182 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
11183 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
11184 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
11185 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
11186 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
11187 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
11189 ;; All the other keys
11190 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
11191 (define-key org-mode-map "\C-c\C-j" 'org-goto)
11192 (define-key org-mode-map "\C-c\C-t" 'org-todo)
11193 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
11194 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
11195 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
11196 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11197 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
11198 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
11199 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11200 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
11201 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
11202 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
11203 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
11204 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
11205 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11206 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11207 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11208 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11209 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
11210 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
11211 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11212 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
11213 (define-key org-mode-map "\C-c]" 'org-remove-file)
11214 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
11215 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
11216 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
11217 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11218 (define-key org-mode-map "\C-m" 'org-return)
11219 (define-key org-mode-map "\C-c?" 'org-table-current-column)
11220 (define-key org-mode-map "\C-c " 'org-table-blank-field)
11221 (define-key org-mode-map "\C-c+" 'org-table-sum)
11222 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
11223 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
11224 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
11225 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
11226 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11227 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
11228 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11229 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
11230 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
11231 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
11232 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
11233 ;; OPML support is only an option for the future
11234 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
11235 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
11236 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
11237 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
11238 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
11239 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
11240 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
11241 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11242 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
11243 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
11244 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
11246 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11247 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11248 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11250 (defsubst org-table-p () (org-at-table-p))
11252 (defun org-self-insert-command (N)
11253 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11254 If the cursor is in a table looking at whitespace, the whitespace is
11255 overwritten, and the table is not marked as requiring realignment."
11257 (if (and (org-table-p)
11259 (and org-table-auto-blank-field
11260 (member last-command
11261 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11262 (org-table-blank-field))
11265 (looking-at "[^|\n]* +|"))
11266 (let (org-table-may-need-update)
11267 (goto-char (1- (match-end 0)))
11268 (delete-backward-char 1)
11269 (goto-char (match-beginning 0))
11270 (self-insert-command N))
11271 (setq org-table-may-need-update t)
11272 (self-insert-command N)))
11275 ;; The following two functions might still be optimized to trigger
11276 ;; re-alignment less frequently.
11278 (defun org-delete-backward-char (N)
11279 "Like `delete-backward-char', insert whitespace at field end in tables.
11280 When deleting backwards, in tables this function will insert whitespace in
11281 front of the next \"|\" separator, to keep the table aligned. The table will
11282 still be marked for re-alignment, because a narrow field may lead to a
11283 reduced column width."
11285 (if (and (org-table-p)
11287 (string-match "|" (buffer-substring (point-at-bol) (point)))
11288 (looking-at ".*?|"))
11289 (let ((pos (point)))
11290 (backward-delete-char N)
11291 (skip-chars-forward "^|")
11293 (goto-char (1- pos)))
11294 (backward-delete-char N)))
11296 (defun org-delete-char (N)
11297 "Like `delete-char', but insert whitespace at field end in tables.
11298 When deleting characters, in tables this function will insert whitespace in
11299 front of the next \"|\" separator, to keep the table aligned. The table
11300 will still be marked for re-alignment, because a narrow field may lead to
11301 a reduced column width."
11303 (if (and (org-table-p)
11305 (not (= (char-after) ?|))
11307 (if (looking-at ".*?|")
11308 (let ((pos (point)))
11309 (replace-match (concat
11310 (substring (match-string 0) 1 -1)
11315 ;; How to do this: Measure non-white length of current string
11316 ;; If equal to column width, we should realign.
11318 (defun org-remap (map &rest commands)
11319 "In MAP, remap the functions given in COMMANDS.
11320 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11323 (setq old (pop commands) new (pop commands))
11324 (if (fboundp 'command-remapping)
11325 (define-key map (vector 'remap old) new)
11326 (substitute-key-definition old new map global-map)))))
11328 (when (eq org-enable-table-editor 'optimized)
11329 ;; If the user wants maximum table support, we need to hijack
11330 ;; some standard editing functions
11331 (org-remap org-mode-map
11332 'self-insert-command 'org-self-insert-command
11333 'delete-char 'org-delete-char
11334 'delete-backward-char 'org-delete-backward-char)
11335 (define-key org-mode-map "|" 'org-force-self-insert))
11337 (defun org-shiftcursor-error ()
11338 "Throw an error because Shift-Cursor command was applied in wrong context."
11339 (error "This command is active in special context like tables, headlines or timestamps"))
11341 (defun org-shifttab ()
11342 "Global visibility cycling or move to previous table field.
11343 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
11344 See the individual commands for more information."
11347 ((org-at-table-p) (org-table-previous-field))
11348 (t (org-cycle '(4)))))
11350 (defun org-shiftmetaleft ()
11351 "Promote subtree or delete table column.
11352 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
11353 See the individual commands for more information."
11356 ((org-at-table-p) (org-table-delete-column))
11357 ((org-on-heading-p) (org-promote-subtree))
11358 ((org-at-item-p) (call-interactively 'org-outdent-item))
11359 (t (org-shiftcursor-error))))
11361 (defun org-shiftmetaright ()
11362 "Demote subtree or insert table column.
11363 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
11364 See the individual commands for more information."
11367 ((org-at-table-p) (org-table-insert-column))
11368 ((org-on-heading-p) (org-demote-subtree))
11369 ((org-at-item-p) (call-interactively 'org-indent-item))
11370 (t (org-shiftcursor-error))))
11372 (defun org-shiftmetaup (&optional arg)
11373 "Move subtree up or kill table row.
11374 Calls `org-move-subtree-up' or `org-table-kill-row' or
11375 `org-move-item-up' depending on context. See the individual commands
11376 for more information."
11379 ((org-at-table-p) (org-table-kill-row))
11380 ((org-on-heading-p) (org-move-subtree-up arg))
11381 ((org-at-item-p) (org-move-item-up arg))
11382 (t (org-shiftcursor-error))))
11383 (defun org-shiftmetadown (&optional arg)
11384 "Move subtree down or insert table row.
11385 Calls `org-move-subtree-down' or `org-table-insert-row' or
11386 `org-move-item-down', depending on context. See the individual
11387 commands for more information."
11390 ((org-at-table-p) (org-table-insert-row arg))
11391 ((org-on-heading-p) (org-move-subtree-down arg))
11392 ((org-at-item-p) (org-move-item-down arg))
11393 (t (org-shiftcursor-error))))
11395 (defun org-metaleft (&optional arg)
11396 "Promote heading or move table column to left.
11397 Calls `org-do-promote' or `org-table-move-column', depending on context.
11398 With no specific context, calls the Emacs default `backward-word'.
11399 See the individual commands for more information."
11402 ((org-at-table-p) (org-table-move-column 'left))
11403 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
11404 (t (backward-word (prefix-numeric-value arg)))))
11406 (defun org-metaright (&optional arg)
11407 "Demote subtree or move table column to right.
11408 Calls `org-do-demote' or `org-table-move-column', depending on context.
11409 With no specific context, calls the Emacs default `forward-word'.
11410 See the individual commands for more information."
11413 ((org-at-table-p) (org-table-move-column nil))
11414 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
11415 (t (forward-word (prefix-numeric-value arg)))))
11417 (defun org-metaup (&optional arg)
11418 "Move subtree up or move table row up.
11419 Calls `org-move-subtree-up' or `org-table-move-row' or
11420 `org-move-item-up', depending on context. See the individual commands
11421 for more information."
11424 ((org-at-table-p) (org-table-move-row 'up))
11425 ((org-on-heading-p) (org-move-subtree-up arg))
11426 ((org-at-item-p) (org-move-item-up arg))
11427 (t (org-shiftcursor-error))))
11429 (defun org-metadown (&optional arg)
11430 "Move subtree down or move table row down.
11431 Calls `org-move-subtree-down' or `org-table-move-row' or
11432 `org-move-item-down', depending on context. See the individual
11433 commands for more information."
11436 ((org-at-table-p) (org-table-move-row nil))
11437 ((org-on-heading-p) (org-move-subtree-down arg))
11438 ((org-at-item-p) (org-move-item-down arg))
11439 (t (org-shiftcursor-error))))
11441 (defun org-shiftup (&optional arg)
11442 "Increase item in timestamp or increase priority of current item.
11443 Calls `org-timestamp-up' or `org-priority-up', depending on context.
11444 See the individual commands for more information."
11447 ((org-at-timestamp-p) (org-timestamp-up arg))
11448 (t (org-priority-up))))
11450 (defun org-shiftdown (&optional arg)
11451 "Decrease item in timestamp or decrease priority of current item.
11452 Calls `org-timestamp-down' or `org-priority-down', depending on context.
11453 See the individual commands for more information."
11456 ((org-at-timestamp-p) (org-timestamp-down arg))
11457 (t (org-priority-down))))
11459 (defun org-shiftright ()
11460 "Next TODO keyword or timestamp one day later, depending on context."
11463 ((org-at-timestamp-p) (org-timestamp-up-day))
11464 ((org-on-heading-p) (org-todo 'right))
11465 (t (org-shiftcursor-error))))
11467 (defun org-shiftleft ()
11468 "Previous TODO keyword or timestamp one day earlier, depending on context."
11471 ((org-at-timestamp-p) (org-timestamp-down-day))
11472 ((org-on-heading-p) (org-todo 'left))
11473 (t (org-shiftcursor-error))))
11475 (defun org-copy-special ()
11476 "Copy region in table or copy current subtree.
11477 Calls `org-table-copy' or `org-copy-subtree', depending on context.
11478 See the individual commands for more information."
11480 (call-interactively
11481 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
11483 (defun org-cut-special ()
11484 "Cut region in table or cut current subtree.
11485 Calls `org-table-copy' or `org-cut-subtree', depending on context.
11486 See the individual commands for more information."
11488 (call-interactively
11489 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
11491 (defun org-paste-special (arg)
11492 "Paste rectangular region into table, or past subtree relative to level.
11493 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
11494 See the individual commands for more information."
11496 (if (org-at-table-p)
11497 (org-table-paste-rectangle)
11498 (org-paste-subtree arg)))
11500 (defun org-ctrl-c-ctrl-c (&optional arg)
11501 "Call realign table, or recognize a table.el table, or update keywords.
11502 When the cursor is inside a table created by the table.el package,
11503 activate that table. Otherwise, if the cursor is at a normal table
11504 created with org.el, re-align that table. This command works even if
11505 the automatic table editor has been turned off.
11507 If the cursor is in a headline, prompt for tags and insert them into
11508 the current line, aligned to `org-tags-column'. When in a headline and
11509 called with prefix arg, realign all tags in the current buffer.
11511 If the cursor is in one of the special #+KEYWORD lines, this triggers
11512 scanning the buffer for these lines and updating the information.
11513 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
11515 (let ((org-enable-table-editor t))
11517 ((org-on-heading-p) (org-set-tags arg))
11518 ((org-at-table.el-p)
11520 (beginning-of-line 1)
11521 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
11522 (table-recognize-table))
11524 (org-table-maybe-eval-formula)
11526 (org-table-recalculate t)
11527 (org-table-maybe-recalculate-line))
11530 (org-renumber-ordered-list (prefix-numeric-value arg)))
11531 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
11533 ((equal (match-string 1) "TBLFM")
11534 ;; Recalculate the table before this line
11536 (beginning-of-line 1)
11537 (skip-chars-backward " \r\n\t")
11538 (if (org-at-table-p) (org-table-recalculate t))))
11540 (org-mode-restart))))
11541 ((org-region-active-p)
11542 (org-table-convert-region (region-beginning) (region-end) arg))
11543 ((condition-case nil
11544 (and (region-beginning) (region-end))
11546 (if (y-or-n-p "Convert inactive region to table? ")
11547 (org-table-convert-region (region-beginning) (region-end) arg)
11549 (t (error "C-c C-c can do nothing useful at this location.")))))
11551 (defun org-mode-restart ()
11552 "Restart Org-mode, to scan again for special lines.
11553 Also updates the keyword regular expressions."
11555 (let ((org-inhibit-startup t)) (org-mode))
11556 (message "Org-mode restarted to refresh keyword and special line setup"))
11558 (defun org-return ()
11559 "Goto next table row or insert a newline.
11560 Calls `org-table-next-row' or `newline', depending on context.
11561 See the individual commands for more information."
11565 (org-table-justify-field-maybe)
11566 (org-table-next-row))
11569 (defun org-meta-return (&optional arg)
11570 "Insert a new heading or wrap a region in a table.
11571 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
11572 See the individual commands for more information."
11576 (org-table-wrap-region arg))
11577 (t (org-insert-heading arg))))
11581 ;; Define the Org-mode menus
11582 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
11584 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
11585 ["Next Field" org-cycle (org-at-table-p)]
11586 ["Previous Field" org-shifttab (org-at-table-p)]
11587 ["Next Row" org-return (org-at-table-p)]
11589 ["Blank Field" org-table-blank-field (org-at-table-p)]
11590 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
11593 ["Move Column Left" org-metaleft (org-at-table-p)]
11594 ["Move Column Right" org-metaright (org-at-table-p)]
11595 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
11596 ["Insert Column" org-shiftmetaright (org-at-table-p)])
11598 ["Move Row Up" org-metaup (org-at-table-p)]
11599 ["Move Row Down" org-metadown (org-at-table-p)]
11600 ["Delete Row" org-shiftmetaup (org-at-table-p)]
11601 ["Insert Row" org-shiftmetadown (org-at-table-p)]
11602 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
11604 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
11606 ["Copy Rectangle" org-copy-special (org-at-table-p)]
11607 ["Cut Rectangle" org-cut-special (org-at-table-p)]
11608 ["Paste Rectangle" org-paste-special (org-at-table-p)]
11609 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
11612 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
11613 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11614 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
11616 ["Recalculate line" org-table-recalculate (org-at-table-p)]
11617 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
11618 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
11620 ["Sum Column/Rectangle" org-table-sum
11621 (or (org-at-table-p) (org-region-active-p))]
11622 ["Which Column?" org-table-current-column (org-at-table-p)])
11624 (setq org-table-formula-debug (not org-table-formula-debug))
11625 :style toggle :selected org-table-formula-debug]
11627 ["Invisible Vlines" org-table-toggle-vline-visibility
11628 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
11630 ["Create" org-table-create (and (not (org-at-table-p))
11631 org-enable-table-editor)]
11632 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
11633 ["Import from File" org-table-import (not (org-at-table-p))]
11634 ["Export to File" org-table-export (org-at-table-p)]
11636 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
11638 (easy-menu-define org-org-menu org-mode-map "Org menu"
11640 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
11641 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
11642 ["Sparse Tree" org-occur t]
11643 ["Show All" show-all t]
11645 ["New Heading" org-insert-heading t]
11646 ("Navigate Headings"
11647 ["Up" outline-up-heading t]
11648 ["Next" outline-next-visible-heading t]
11649 ["Previous" outline-previous-visible-heading t]
11650 ["Next Same Level" outline-forward-same-level t]
11651 ["Previous Same Level" outline-backward-same-level t]
11653 ["Jump" org-goto t])
11655 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
11656 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
11658 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
11659 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
11660 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
11662 ["Promote Heading" org-metaleft (not (org-at-table-p))]
11663 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
11664 ["Demote Heading" org-metaright (not (org-at-table-p))]
11665 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
11667 ["Archive Subtree" org-archive-subtree t])
11670 ["TODO/DONE/-" org-todo t]
11671 ["Show TODO Tree" org-show-todo-tree t]
11672 ["Global TODO list" org-todo-list t]
11674 ["Set Priority" org-priority t]
11675 ["Priority Up" org-shiftup t]
11676 ["Priority Down" org-shiftdown t])
11677 ("Dates and Scheduling"
11678 ["Timestamp" org-time-stamp t]
11679 ["Timestamp (inactive)" org-time-stamp-inactive t]
11681 ["1 Day Later" org-timestamp-up-day t]
11682 ["1 Day Earlier" org-timestamp-down-day t]
11683 ["1 ... Later" org-shiftup t]
11684 ["1 ... Earlier" org-shiftdown t])
11685 ["Compute Time Range" org-evaluate-time-range t]
11686 ["Schedule Item" org-schedule t]
11687 ["Deadline" org-deadline t]
11689 ["Goto Calendar" org-goto-calendar t]
11690 ["Date from Calendar" org-date-from-calendar t])
11692 ["Agenda Command" org-agenda t]
11693 ("File List for Agenda")
11694 ("Special views current file"
11695 ["TODO Tree" org-show-todo-tree t]
11696 ["Check Deadlines" org-check-deadlines t]
11697 ["Timeline" org-timeline t]
11698 ["Tags Tree" org-tags-sparse-tree t])
11701 ["Store Link (Global)" org-store-link t]
11702 ["Insert Link" org-insert-link t]
11703 ["Follow Link" org-open-at-point t])
11706 ["ASCII" org-export-as-ascii t]
11707 ["Extract Visible Text" org-export-copy-visible t]
11708 ["HTML" org-export-as-html t]
11709 ["HTML and Open" org-export-as-html-and-open t]
11710 ; ["OPML" org-export-as-opml nil]
11712 ["iCalendar this file" org-export-icalendar-this-file t]
11713 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
11714 :active t :keys "C-c C-x C-i"]
11715 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
11717 ["Option Template" org-insert-export-options-template t]
11718 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
11721 ["Show Version" org-version t]
11722 ["Info Documentation" org-info t])
11724 ["Browse Org Group" org-customize t]
11726 ["Build Full Customize Menu" org-create-customize-menu
11727 (fboundp 'customize-menu-create)])
11729 ["Refresh setup" org-mode-restart t]
11732 (defun org-info (&optional node)
11733 "Read documentation for Org-mode in the info system.
11734 With optional NODE, go directly to that node."
11737 (Info-goto-node (format "(org)%s" (or node ""))))
11739 (defun org-install-agenda-files-menu ()
11741 '("Org") "File List for Agenda"
11744 ["Edit File List" (customize-variable 'org-agenda-files) t]
11745 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
11746 ["Remove Current File from List" org-remove-file t]
11747 ["Cycle through agenda files" org-cycle-agenda-files t]
11749 (mapcar 'org-file-menu-entry org-agenda-files))))
11753 (defun org-customize ()
11754 "Call the customize function with org as argument."
11756 (customize-browse 'org))
11758 (defun org-create-customize-menu ()
11759 "Create a full customization menu for Org-mode, insert it into the menu."
11761 (if (fboundp 'customize-menu-create)
11764 '("Org") "Customize"
11765 `(["Browse Org group" org-customize t]
11767 ,(customize-menu-create 'org)
11768 ["Set" Custom-set t]
11769 ["Save" Custom-save t]
11770 ["Reset to Current" Custom-reset-current t]
11771 ["Reset to Saved" Custom-reset-saved t]
11772 ["Reset to Standard Settings" Custom-reset-standard t]))
11773 (message "\"Org\"-menu now contains full customization menu"))
11774 (error "Cannot expand menu (outdated version of cus-edit.el)")))
11776 ;;; Miscellaneous stuff
11778 (defun org-move-line-down (arg)
11779 "Move the current line down. With prefix argument, move it past ARG lines."
11781 (let ((col (current-column))
11783 (beginning-of-line 1) (setq beg (point))
11784 (beginning-of-line 2) (setq end (point))
11785 (beginning-of-line (+ 1 arg))
11786 (setq pos (move-marker (make-marker) (point)))
11787 (insert (delete-and-extract-region beg end))
11789 (move-to-column col)))
11791 (defun org-move-line-up (arg)
11792 "Move the current line up. With prefix argument, move it past ARG lines."
11794 (let ((col (current-column))
11796 (beginning-of-line 1) (setq beg (point))
11797 (beginning-of-line 2) (setq end (point))
11798 (beginning-of-line (- arg))
11799 (setq pos (move-marker (make-marker) (point)))
11800 (insert (delete-and-extract-region beg end))
11802 (move-to-column col)))
11804 ;; Paragraph filling stuff.
11805 ;; We want this to be just right, so use the full arsenal.
11806 ;; FIXME: This very likely does not work correctly for XEmacs, because the
11807 ;; filladapt package works slightly differently.
11809 (defun org-set-autofill-regexps ()
11811 ;; In the paragraph separator we include headlines, because filling
11812 ;; text in a line directly attached to a headline would otherwise
11813 ;; fill the headline as well.
11814 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
11815 ;; The paragraph starter includes hand-formatted lists.
11816 (set (make-local-variable 'paragraph-start)
11817 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
11818 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
11819 ;; But only if the user has not turned off tables or fixed-width regions
11820 (set (make-local-variable 'auto-fill-inhibit-regexp)
11822 (if (or org-enable-table-editor org-enable-fixed-width-editor)
11825 (if org-enable-table-editor "|" "")
11826 (if org-enable-fixed-width-editor ":" "")
11828 ;; We use our own fill-paragraph function, to make sure that tables
11829 ;; and fixed-width regions are not wrapped. That function will pass
11830 ;; through to `fill-paragraph' when appropriate.
11831 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
11832 ;; Adaptive filling: To get full control, first make sure that
11833 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
11834 (setq adaptive-fill-regexp "\000")
11835 (setq adaptive-fill-function 'org-adaptive-fill-function))
11837 (defun org-fill-paragraph (&optional justify)
11838 "Re-align a table, pass through to fill-paragraph if no table."
11839 (let ((table-p (org-at-table-p))
11840 (table.el-p (org-at-table.el-p)))
11841 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
11842 (table.el-p t) ; skip table.el tables
11843 (table-p (org-table-align) t) ; align org-mode tables
11844 (t nil)))) ; call paragraph-fill
11846 ;; For reference, this is the default value of adaptive-fill-regexp
11847 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
11849 (defun org-adaptive-fill-function ()
11850 "Return a fill prefix for org-mode files.
11851 In particular, this makes sure hanging paragraphs for hand-formatted lists
11853 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
11854 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
11856 ;; Functions needed for Emacs/XEmacs region compatibility
11858 (defun org-region-active-p ()
11859 "Is `transient-mark-mode' on and the region active?
11860 Works on both Emacs and XEmacs."
11861 (if org-ignore-region
11864 (and zmacs-regions (region-active-p))
11865 (and transient-mark-mode mark-active))))
11867 (defun org-add-to-invisibility-spec (arg)
11868 "Add elements to `buffer-invisibility-spec'.
11869 See documentation for `buffer-invisibility-spec' for the kind of elements
11870 that can be added."
11872 ((fboundp 'add-to-invisibility-spec)
11873 (add-to-invisibility-spec arg))
11874 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
11875 (setq buffer-invisibility-spec (list arg)))
11877 (setq buffer-invisibility-spec
11878 (cons arg buffer-invisibility-spec)))))
11880 (defun org-remove-from-invisibility-spec (arg)
11881 "Remove elements from `buffer-invisibility-spec'."
11882 (if (fboundp 'remove-from-invisibility-spec)
11883 (remove-from-invisibility-spec arg)
11884 (if (consp buffer-invisibility-spec)
11885 (setq buffer-invisibility-spec
11886 (delete arg buffer-invisibility-spec)))))
11888 (defun org-in-invisibility-spec-p (arg)
11889 "Is ARG a member of `buffer-invisibility-spec'?."
11890 (if (consp buffer-invisibility-spec)
11891 (member arg buffer-invisibility-spec)
11894 (defun org-image-file-name-regexp ()
11895 "Return regexp matching the file names of images."
11896 (if (fboundp 'image-file-name-regexp)
11897 (image-file-name-regexp)
11898 (let ((image-file-name-extensions
11899 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
11900 "xbm" "xpm" "pbm" "pgm" "ppm")))
11902 (regexp-opt (nconc (mapcar 'upcase
11903 image-file-name-extensions)
11904 image-file-name-extensions)
11908 ;; Functions needed for compatibility with old outline.el.
11910 ;; Programming for the old outline.el (that uses selective display
11911 ;; instead of `invisible' text properties) is a nightmare, mostly
11912 ;; because regular expressions can no longer be anchored at
11913 ;; beginning/end of line. Therefore a number of function need special
11914 ;; treatment when the old outline.el is being used.
11916 ;; The following functions capture almost the entire compatibility code
11917 ;; between the different versions of outline-mode. The only other
11918 ;; places where this is important are the font-lock-keywords, and in
11919 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
11921 ;; C-a should go to the beginning of a *visible* line, also in the
11922 ;; new outline.el. I guess this should be patched into Emacs?
11923 (defun org-beginning-of-line ()
11924 "Go to the beginning of the current line. If that is invisible, continue
11925 to a visible line beginning. This makes the function of C-a more intuitive."
11927 (beginning-of-line 1)
11931 (if (org-invisible-p)
11932 (while (and (not (bobp)) (org-invisible-p))
11934 (beginning-of-line 1))
11935 (forward-char 1))))
11937 (when org-noutline-p
11938 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
11939 ;; FIXME: should I use substitute-key-definition to reach other bindings
11940 ;; of beginning-of-line?
11942 (defun org-invisible-p ()
11943 "Check if point is at a character currently not visible."
11945 ;; Early versions of noutline don't have `outline-invisible-p'.
11946 (if (fboundp 'outline-invisible-p)
11947 (outline-invisible-p)
11948 (get-char-property (point) 'invisible))
11950 (skip-chars-backward "^\r\n")
11951 (equal (char-before) ?\r))))
11953 (defun org-back-to-heading (&optional invisible-ok)
11954 "Move to previous heading line, or beg of this line if it's a heading.
11955 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
11957 (outline-back-to-heading invisible-ok)
11958 (if (and (memq (char-before) '(?\n ?\r))
11959 (looking-at outline-regexp))
11961 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
11965 (progn (goto-char (match-end 1))
11966 (looking-at outline-regexp)))
11967 (error "Before first heading")))))
11969 (defun org-on-heading-p (&optional invisible-ok)
11970 "Return t if point is on a (visible) heading line.
11971 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
11973 (outline-on-heading-p 'invisible-ok)
11975 (skip-chars-backward "^\n\r")
11976 (and (looking-at outline-regexp)
11979 (equal (char-before) ?\n))))))
11981 (defun org-up-heading-all (arg)
11982 "Move to the heading line of which the present line is a subheading.
11983 This function considers both visible and invisible heading lines.
11984 With argument, move up ARG levels."
11986 (if (fboundp 'outline-up-heading-all)
11987 (outline-up-heading-all arg) ; emacs 21 version of outline.el
11988 (outline-up-heading arg t)) ; emacs 22 version of outline.el
11989 (org-back-to-heading t)
11990 (looking-at outline-regexp)
11991 (if (<= (- (match-end 0) (match-beginning 0)) arg)
11992 (error "Cannot move up %d levels" arg)
11993 (re-search-backward
11994 (concat "[\n\r]" (regexp-quote
11995 (make-string (- (match-end 0) (match-beginning 0) arg)
11998 (forward-char 1))))
12000 (defun org-show-hidden-entry ()
12001 "Show an entry where even the heading is hidden."
12003 (if (not org-noutline-p)
12005 (org-back-to-heading t)
12006 (org-flag-heading nil)))
12009 (defun org-check-occur-regexp (regexp)
12010 "If REGEXP starts with \"^\", modify it to check for \\r as well.
12011 Of course, only for the old outline mode."
12014 (if (string-match "^\\^" regexp)
12015 (concat "[\n\r]" (substring regexp 1))
12018 (defun org-flag-heading (flag &optional entry)
12019 "Flag the current heading. FLAG non-nil means make invisible.
12020 When ENTRY is non-nil, show the entire entry."
12022 (org-back-to-heading t)
12023 (if (not org-noutline-p)
12024 ;; Make the current headline visible
12025 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
12026 ;; Check if we should show the entire entry
12030 (save-excursion ;; FIXME: Is this the fix for points in the -|
12031 ;; middle of text? |
12032 (and (outline-next-heading) ;; |
12033 (org-flag-heading nil)))) ; show the next heading _|
12034 (outline-flag-region (max 1 (1- (point)))
12035 (save-excursion (outline-end-of-heading) (point))
12038 (if flag ?\r ?\n))))))
12040 (defun org-end-of-subtree (&optional invisible-OK)
12041 ;; This is an exact copy of the original function, but it uses
12042 ;; `org-back-to-heading', to make it work also in invisible
12043 ;; trees. And is uses an invisible-OK argument.
12044 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
12045 (org-back-to-heading invisible-OK)
12046 (let ((opoint (point))
12048 (level (funcall outline-level)))
12049 (while (and (not (eobp))
12050 (or first (> (funcall outline-level) level)))
12052 (outline-next-heading))
12053 (if (memq (preceding-char) '(?\n ?\^M))
12055 ;; Go to end of line before heading
12057 (if (memq (preceding-char) '(?\n ?\^M))
12058 ;; leave blank line before heading
12059 (forward-char -1))))))
12061 (defun org-show-subtree ()
12062 "Show everything after this heading at deeper levels."
12063 (outline-flag-region
12066 (outline-end-of-subtree) (outline-next-heading) (point))
12067 (if org-noutline-p nil ?\n)))
12069 (defun org-show-entry ()
12070 "Show the body directly following this heading.
12071 Show the heading too, if it is currently invisible."
12074 (org-back-to-heading t)
12075 (outline-flag-region
12078 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
12079 (or (match-beginning 1) (point-max)))
12080 (if org-noutline-p nil ?\n))))
12083 (defun org-make-options-regexp (kwds)
12084 "Make a regular expression for keyword lines."
12086 (if org-noutline-p "^" "[\n\r]")
12088 (mapconcat 'regexp-quote kwds "\\|")
12090 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
12092 ;; Make `bookmark-jump' show the jump location if it was hidden.
12093 (eval-after-load "bookmark"
12094 '(if (boundp 'bookmark-after-jump-hook)
12095 ;; We can use the hook
12096 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
12097 ;; Hook not available, use advice
12098 (defadvice bookmark-jump (after org-make-visible activate)
12099 "Make the position visible."
12100 (org-bookmark-jump-unhide))))
12102 (defun org-bookmark-jump-unhide ()
12103 "Unhide the current position, to show the bookmark location."
12104 (and (eq major-mode 'org-mode)
12105 (or (org-invisible-p)
12106 (save-excursion (goto-char (max (point-min) (1- (point))))
12107 (org-invisible-p)))
12108 (org-show-hierarchy-above)))
12114 (run-hooks 'org-load-hook)
12116 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
12117 ;;; org.el ends here