1 ;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (c) 2004, 2005 Free Software Foundation
5 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around a NOTES file that contains
34 ;; information about projects as plain text. Org-mode is implemented on top
35 ;; of outline-mode - ideal to keep the content of large files well structured.
36 ;; It supports ToDo items, deadlines and time stamps, which can be extracted
37 ;; to create a daily/weekly agenda that also integrates the diary of the Emacs
38 ;; calendar. Tables are easily created with a built-in table editor. Plain
39 ;; text URL-like links connect to websites, emails (VM, RMAIL, WANDERLUST),
40 ;; Usenet messages (Gnus), BBDB entries, and any files related to the
41 ;; projects. For printing and sharing of notes, an Org-mode file (or a part
42 ;; of it) can be exported as a structured ASCII file, or as HTML.
46 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
47 ;; only need to copy the following lines to your .emacs file. The last two
48 ;; lines define *global* keys for the commands `org-store-link' and
49 ;; `org-agenda' - please choose suitable keys yourself.
51 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
52 ;; (define-key global-map "\C-cl" 'org-store-link)
53 ;; (define-key global-map "\C-ca" 'org-agenda)
55 ;; If you have downloaded Org-mode from the Web, you must byte-compile
56 ;; org.el and put it on your load path. In addition to the Emacs Lisp
57 ;; lines above, you also need to add the following lines to .emacs:
59 ;; (autoload 'org-mode "org" "Org mode" t)
60 ;; (autoload 'org-diary "org" "Diary entries from Org mode")
61 ;; (autoload 'org-agenda "org" "Multi-file agenda from Org mode" t)
62 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
63 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
64 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
66 ;; This setup will put all files with extension ".org" into Org-mode. As
67 ;; an alternative, make the first line of a file look like this:
69 ;; MY PROJECTS -*- mode: org; -*-
71 ;; which will select Org-mode for this buffer no matter what the file's
76 ;; The documentation of Org-mode can be found in the TeXInfo file. The
77 ;; distribution also contains a PDF version of it. At the homepage of
78 ;; Org-mode, you can read the same text online as HTML. There is also an
79 ;; excellent reference card made by Philip Rooke.
84 ;; - Formulas for individual fields in table.
85 ;; - Automatic recalculation in calculating tables.
86 ;; - Named fields and columns in tables.
87 ;; - Fixed bug with calling `org-archive' several times in a row.
90 ;; - Efficiency improvements: Fewer table re-alignments needed.
91 ;; - New special lines in tables, for defining names for individual cells.
94 ;; - Tables can store formulas (one per column) and compute fields.
95 ;; Not quite like a full spreadsheet, but very powerful.
96 ;; - table.el keybinding is now `C-c ~'.
97 ;; - Numeric argument to org-cycle does `show-subtree' above on level ARG.
98 ;; - Small changes to keys in agenda buffer. Affected keys:
99 ;; [w] weekly view; [d] daily view; [D] toggle diary inclusion.
103 ;; - Links inserted with C-c C-l are now by default enclosed in angle
104 ;; brackets. See the new variable `org-link-format'.
105 ;; - ">" terminates a link, this is a way to have several links in a line.
106 ;; Both "<" and ">" are no longer allowed as characters in a link.
107 ;; - Archiving of finished tasks.
108 ;; - C-<up>/<down> bindings removed, to allow access to paragraph commands.
109 ;; - Compatibility with CUA-mode (see variable `org-CUA-compatible').
110 ;; - Compatibility problems with viper-mode fixed.
111 ;; - Improved html export of tables.
112 ;; - Various clean-up changes.
115 ;; - Using `define-derived-mode' to derive `org-mode' from `outline-mode'.
118 ;; - Time-of-day specifications in agenda are extracted and placed
119 ;; into the prefix. Timed entries can be placed into a time grid for
123 ;; - "|" no longer allowed as part of a link, to allow links in tables.
124 ;; - The prefix of items in the agenda buffer can be configured.
128 ;; - Some folding incinsistencies removed.
129 ;; - BBDB links to company-only entries.
130 ;; - Bug fixes and global cleanup.
133 ;; - M-S-RET inserts a new TODO heading.
134 ;; - New startup option `content'.
135 ;; - Better visual response when TODO items in agenda change status.
136 ;; - Window positioning after visibility state changes optimized and made
137 ;; configurable. See `org-cycle-hook' and `org-occur-hook'.
140 ;; - Agenda entries from the diary are linked to the diary file, so
141 ;; adding and editing diary entries can be done directly from the agenda.
142 ;; - Many calendar/diary commands available directly from agenda.
143 ;; - Field copying in tables with S-RET does increment.
144 ;; - C-c C-x C-v extracts the visible part of the buffer for printing.
145 ;; - Moving subtrees up and down preserves the whitespace at the tree end.
148 ;; - Table editor optimized to need fewer realignments, and to keep
149 ;; table shape when typing in fields.
150 ;; - A new minor mode, orgtbl-mode, introduces the Org-mode table editor
151 ;; into arbitrary major modes.
152 ;; - Fixed bug with realignment in XEmacs.
153 ;; - Startup options can be set with special #+STARTUP line.
154 ;; - Heading following a match in org-occur can be suppressed.
157 ;; - Copyright transfer to the FSF.
158 ;; - Effect of C-u and C-u C-u in org-timeline swapped.
159 ;; - Timeline now always contains today, and `.' jumps to it.
161 ;; - cut and paste of rectangular regions in tables
162 ;; - command to convert org-mode table to table.el table and back
163 ;; - command to treat several cells like a paragraph and fill it
164 ;; - command to convert a buffer region to a table
165 ;; - import/export tables as tab-separated files (exchange with Excel)
167 ;; - Sorting mechanism for agenda items rewritten from scratch.
168 ;; - Sorting fully configurable.
169 ;; - Entries specifying a time are sorted together.
170 ;; - Completion also covers option keywords after `#-'.
174 ;; - New reference card, thanks to Philip Rooke for creating it.
175 ;; - Single file agenda renamed to "Timeline". It no longer shows
176 ;; warnings about upcoming deadlines/overdue scheduled items.
177 ;; That functionality is now limited to the (multifile) agenda.
178 ;; - When reading a date, the calendar can be manipulated with keys.
179 ;; - Link support for RMAIL and Wanderlust (from planner.el, untested).
180 ;; - Minor bug fixes and documentation improvements.
184 (eval-when-compile (require 'cl
) (require 'calendar
))
189 ;;; Customization variables
191 (defvar org-version
"3.14"
192 "The version number of the file org.el.")
193 (defun org-version ()
195 (message "Org-mode version %s" org-version
))
197 ;; The following two constants are for compatibility with different Emacs
198 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
199 ;; The compatibility code in org.el is based on these two constants.
200 (defconst org-xemacs-p
(featurep 'xemacs
)
201 "Are we running xemacs?")
202 (defconst org-noutline-p
(featurep 'noutline
)
203 "Are we using the new outline mode?")
206 "Outline-based notes management and organizer "
212 (defgroup org-startup nil
213 "Options concerning startup of Org-mode."
217 (defcustom org-CUA-compatible nil
218 "Non-nil means use alternative key bindings for S-<cursor movement>.
219 Org-mode used S-<cursor movement> for changing timestamps and priorities.
220 S-<cursor movement> is also used for example by `CUA-mode' to select text.
221 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
222 alternative bindings. Setting this variable to t will replace the following
223 keys both in Org-mode and in the Org-agenda buffer.
231 If you do not like the alternative keys, take a look at the variable
234 This option is only relevant at load-time of Org-mode. Changing it requires
235 a restart of Emacs to become effective."
239 (defvar org-disputed-keys
240 '((S-up [(shift up
)] [(meta ?p
)])
241 (S-down [(shift down
)] [(meta ?n
)])
242 (S-left [(shift left
)] [(meta ?-
)])
243 (S-right [(shift right
)] [(meta ?
+)])
244 (S-return [(shift return
)] [(control shift return
)]))
245 "Keys for which Org-mode and other modes compete.
246 This is an alist, cars are symbols for lookup, 1st element is the default key,
247 second element will be used when `org-CUA-compatible' is t.")
250 "Select a key according to `org-CUA-compatible'."
251 (nth (if org-CUA-compatible
2 1)
252 (or (assq key org-disputed-keys
)
253 (error "Invalid Key %s in `org-key'" key
))))
255 (defcustom org-startup-folded t
256 "Non-nil means, entering Org-mode will switch to OVERVIEW.
257 This can also be configured on a per-file basis by adding one of
258 the following lines anywhere in the buffer:
265 (const :tag
"nofold: show all" nil
)
266 (const :tag
"fold: overview" t
)
267 (const :tag
"content: all headlines" content
)))
269 (defcustom org-startup-truncated t
270 "Non-nil means, entering Org-mode will set `truncate-lines'.
271 This is useful since some lines containing links can be very long and
272 uninteresting. Also tables look terrible when wrapped."
276 (defcustom org-startup-with-deadline-check nil
277 "Non-nil means, entering Org-mode will run the deadline check.
278 This means, if you start editing an org file, you will get an
279 immediate reminder of any due deadlines.
280 This can also be configured on a per-file basis by adding one of
281 the following lines anywhere in the buffer:
284 #+STARTUP: nodlcheck"
288 (defcustom org-insert-mode-line-in-empty-file nil
289 "Non-nil means insert the first line setting Org-mode in empty files.
290 When the function `org-mode' is called interactively in an empty file, this
291 normally means that the file name does not automatically trigger Org-mode.
292 To ensure that the file will always be in Org-mode in the future, a
293 line enforcing Org-mode will be inserted into the buffer, if this option
298 (defgroup org-keywords nil
299 "Options concerning TODO items in Org-mode."
303 (defcustom org-todo-keywords
'("TODO" "DONE")
304 "List of TODO entry keywords.
305 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
306 considered to mean that the entry is \"done\". All the other mean that
307 action is required, and will make the entry show up in todo lists, diaries
309 The command \\[org-todo] cycles an entry through these states, and an
310 additional state where no keyword is present. For details about this
311 cycling, see also the variable `org-todo-interpretation'
312 Changes become only effective after restarting Emacs."
314 :type
'(repeat (string :tag
"Keyword")))
316 (defcustom org-todo-interpretation
'sequence
317 "Controls how TODO keywords are interpreted.
318 \\<org-mode-map>Possible values are `sequence' and `type'.
319 This variable is only relevant if `org-todo-keywords' contains more than two
320 states. There are two ways how these keywords can be used:
322 - As a sequence in the process of working on a TODO item, for example
323 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
324 org-todo-interpretation 'sequence)
326 - As different types of TODO items, for example
327 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
328 org-todo-interpretation 'type)
330 When the states are interpreted as a sequence, \\[org-todo] always cycles
331 to the next state, in order to walk through all different states. So with
332 \\[org-todo], you turn an empty entry into the state TODO. When you started
333 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
334 later to VERIFY and finally to DONE.
336 When the states are interpreted as types, \\[org-todo] still cycles through
337 when it is called several times in direct succession, in order to initially
338 select the type. However, if not called immediately after a previous
339 \\[org-todo], it switches from each type directly to DONE. So with the
340 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
341 RELAXED. If you later return to this entry and press \\[org-todo] again,
342 RELAXED will not be changed REMIND, but directly to DONE.
344 You can create a large number of types. To initially select a
345 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
346 type with completion. Of course, you can also type the keyword
347 directly into the buffer. M-TAB completes TODO keywords at the
348 beginning of a headline."
350 :type
'(choice (const sequence
)
353 (defcustom org-default-priority ?B
354 "The default priority of TODO items.
355 This is the priority an item get if no explicit priority is given."
359 (defcustom org-lowest-priority ?C
360 "The lowest priority of TODO items. A character like ?A, ?B etc."
364 (defcustom org-deadline-string
"DEADLINE:"
365 "String to mark deadline entries.
366 A deadline is this string, followed by a time stamp. Should be a word,
367 terminated by a colon. You can insert a schedule keyword and
368 a timestamp with \\[org-deadline].
369 Changes become only effective after restarting Emacs."
373 (defcustom org-scheduled-string
"SCHEDULED:"
374 "String to mark scheduled TODO entries.
375 A schedule is this string, followed by a time stamp. Should be a word,
376 terminated by a colon. You can insert a schedule keyword and
377 a timestamp with \\[org-schedule].
378 Changes become only effective after restarting Emacs."
382 (defcustom org-comment-string
"COMMENT"
383 "Entries starting with this keyword will never be exported.
384 An entry can be toggled between COMMENT and normal with
385 \\[org-toggle-comment].
386 Changes become only effective after restarting Emacs."
390 (defcustom org-after-todo-state-change-hook nil
391 "Hook which is run after the state of a TODO item was changed.
392 The new state (a string with a todo keyword, or nil) is available in the
393 Lisp variable `state'."
397 ;; Variables for pre-computed regular expressions, all buffer local
398 (defvar org-todo-kwd-priority-p nil
399 "Do TODO items have priorities?")
400 (make-variable-buffer-local 'org-todo-kwd-priority-p
)
401 (defvar org-todo-kwd-max-priority nil
402 "Maximum priority of TODO items.")
403 (make-variable-buffer-local 'org-todo-kwd-max-priority
)
404 (defvar org-ds-keyword-length
12
405 "Maximum length of the Deadline and SCHEDULED keywords.")
406 (make-variable-buffer-local 'org-ds-keyword-length
)
407 (defvar org-done-string nil
408 "The last string in `org-todo-keywords', indicating an item is DONE.")
409 (make-variable-buffer-local 'org-done-string
)
410 (defvar org-todo-regexp nil
411 "Matches any of the TODO state keywords.")
412 (make-variable-buffer-local 'org-todo-regexp
)
413 (defvar org-not-done-regexp nil
414 "Matches any of the TODO state keywords except the last one.")
415 (make-variable-buffer-local 'org-not-done-regexp
)
416 (defvar org-todo-line-regexp nil
417 "Matches a headline and puts TODO state into group 2 if present.")
418 (make-variable-buffer-local 'org-todo-line-regexp
)
419 (defvar org-nl-done-regexp nil
420 "Matches newline followed by a headline with the DONE keyword.")
421 (make-variable-buffer-local 'org-nl-done-regexp
)
422 (defvar org-looking-at-done-regexp nil
423 "Matches the DONE keyword a point.")
424 (make-variable-buffer-local 'org-looking-at-done-regexp
)
425 (defvar org-deadline-regexp nil
426 "Matches the DEADLINE keyword.")
427 (make-variable-buffer-local 'org-deadline-regexp
)
428 (defvar org-deadline-time-regexp nil
429 "Matches the DEADLINE keyword together with a time stamp.")
430 (make-variable-buffer-local 'org-deadline-time-regexp
)
431 (defvar org-deadline-line-regexp nil
432 "Matches the DEADLINE keyword and the rest of the line.")
433 (make-variable-buffer-local 'org-deadline-line-regexp
)
434 (defvar org-scheduled-regexp nil
435 "Matches the SCHEDULED keyword.")
436 (make-variable-buffer-local 'org-scheduled-regexp
)
437 (defvar org-scheduled-time-regexp nil
438 "Matches the SCHEDULED keyword together with a time stamp.")
439 (make-variable-buffer-local 'org-scheduled-time-regexp
)
441 (defvar org-category nil
442 "Variable used by org files to set a category for agenda display.
443 Such files should use a file variable to set it, for example
445 -*- mode: org; org-category: \"ELisp\"
447 or contain a special line
451 If the file does not specify a category, then file's base name
454 (defun org-set-regexps-and-options ()
455 "Precompute regular expressions for current buffer."
456 (when (eq major-mode
'org-mode
)
457 (let ((re (org-make-options-regexp
458 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
459 "STARTUP" "ARCHIVE")))
461 kwds int key value cat arch
)
465 (goto-char (point-min))
466 (while (re-search-forward re nil t
)
467 (setq key
(match-string 1) value
(match-string 2))
469 ((equal key
"CATEGORY")
470 (if (string-match "[ \t]+$" value
)
471 (setq value
(replace-match "" t t value
)))
472 (setq cat
(intern value
)))
473 ((equal key
"SEQ_TODO")
475 kwds
(append kwds
(org-split-string value splitre
))))
476 ((equal key
"PRI_TODO")
478 kwds
(append kwds
(org-split-string value splitre
))))
479 ((equal key
"TYP_TODO")
481 kwds
(append kwds
(org-split-string value splitre
))))
482 ((equal key
"STARTUP")
483 (let ((opts (org-split-string value splitre
))
484 (set '(("fold" org-startup-folded t
)
485 ("nofold" org-startup-folded nil
)
486 ("content" org-startup-folded content
)
487 ("dlcheck" org-startup-with-deadline-check t
)
488 ("nodlcheck" org-startup-with-deadline-check nil
)))
490 (while (setq l
(assoc (pop opts
) set
))
491 (setq var
(nth 1 l
) val
(nth 2 l
))
492 (set (make-local-variable var
) val
))))
493 ((equal key
"ARCHIVE")
494 (string-match " *$" value
)
495 (setq arch
(replace-match "" t t value
))
496 (remove-text-properties 0 (length arch
)
497 '(face t fontified t
) arch
)))
499 (and cat
(set (make-local-variable 'org-category
) cat
))
500 (and kwds
(set (make-local-variable 'org-todo-keywords
) kwds
))
501 (and arch
(set (make-local-variable 'org-archive-location
) arch
))
502 (and int
(set (make-local-variable 'org-todo-interpretation
) int
)))
503 ;; Compute the regular expressions and other local variables
504 (setq org-todo-kwd-priority-p
(equal org-todo-interpretation
'priority
)
505 org-todo-kwd-max-priority
(1- (length org-todo-keywords
))
506 org-ds-keyword-length
(+ 2 (max (length org-deadline-string
)
507 (length org-scheduled-string
)))
509 (nth (1- (length org-todo-keywords
)) org-todo-keywords
)
511 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
515 (mapconcat 'regexp-quote
516 (nreverse (cdr (reverse org-todo-keywords
)))
520 (concat "^\\(\\*+\\)[ \t]*\\("
521 (mapconcat 'regexp-quote org-todo-keywords
"\\|")
524 (concat "[\r\n]\\*+[ \t]+" org-done-string
"\\>")
525 org-looking-at-done-regexp
(concat "^" org-done-string
"\\>")
526 org-deadline-regexp
(concat "\\<" org-deadline-string
)
527 org-deadline-time-regexp
528 (concat "\\<" org-deadline-string
" *<\\([^>]+\\)>")
529 org-deadline-line-regexp
530 (concat "\\<\\(" org-deadline-string
"\\).*")
532 (concat "\\<" org-scheduled-string
)
533 org-scheduled-time-regexp
534 (concat "\\<" org-scheduled-string
" *<\\([^>]+\\)>"))
535 (org-set-font-lock-defaults)))
537 (defgroup org-time nil
538 "Options concerning time stamps and deadlines in Org-mode."
542 (defconst org-time-stamp-formats
'("<%Y-%m-%d %a>" .
"<%Y-%m-%d %a %H:%M>")
543 "Formats for `format-time-string' which are used for time stamps.
544 It is not recommended to change this constant.")
547 (defcustom org-deadline-warning-days
30
548 "No. of days before expiration during which a deadline becomes active.
549 This variable governs the display in the org file."
553 (defcustom org-popup-calendar-for-date-prompt t
554 "Non-nil means, pop up a calendar when prompting for a date.
555 In the calendar, the date can be selected with mouse-1. However, the
556 minibuffer will also be active, and you can simply enter the date as well.
557 When nil, only the minibuffer will be available."
561 (defcustom org-calendar-follow-timestamp-change t
562 "Non-nil means, make the calendar window follow timestamp changes.
563 When a timestamp is modified and the calendar window is visible, it will be
564 moved to the new date."
568 (defgroup org-agenda nil
569 "Options concerning agenda display Org-mode."
573 (defcustom org-agenda-files nil
574 "A list of org files for agenda/diary display.
575 Entries are added to this list with \\[org-add-file] and removed with
576 \\[org-remove-file]. You can also use customize to edit the list."
578 :type
'(repeat file
))
580 (defcustom org-select-timeline-window t
581 "Non-nil means, after creating a timeline, move cursor into Timeline window.
582 When nil, cursor will remain in the current window."
586 (defcustom org-select-agenda-window t
587 "Non-nil means, after creating an agenda, move cursor into Agenda window.
588 When nil, cursor will remain in the current window."
592 (defcustom org-fit-agenda-window t
593 "Non-nil means, change window size of agenda to fit content."
597 (defcustom org-agenda-show-all-dates t
598 "Non-nil means, `org-agenda' shows every day in the selected range.
599 When nil, only the days which actually have entries are shown."
603 ;; FIXME: First day of month works only for current month because it would
604 ;; require a variable ndays treatment.
605 (defcustom org-agenda-start-on-weekday
1
606 "Non-nil means, start the overview always on the specified weekday.
607 0 Denotes Sunday, 1 denotes Monday etc.
608 When nil, always start on the current day."
610 :type
'(choice (const :tag
"Today" nil
)
611 (const :tag
"First day of month" t
)
612 (number :tag
"Weekday No.")))
614 (defcustom org-agenda-ndays
7
615 "Number of days to include in overview display."
619 (defcustom org-agenda-include-all-todo t
620 "Non-nil means, the agenda will always contain all TODO entries.
621 When nil, date-less entries will only be shown if `org-agenda' is called
622 with a prefix argument.
623 When non-nil, the TODO entries will be listed at the top of the agenda, before
624 the entries for specific days."
628 (defcustom org-agenda-include-diary nil
629 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
633 (defcustom org-calendar-to-agenda-key
[?c
]
634 "The key to be installed in `calendar-mode-map' for switching to the agenda.
635 The command `org-calendar-goto-agenda' will be bound to this key. The
636 default is the character `c' because then`c' can be used to switch back and
637 force between agenda and calendar."
641 (defcustom org-agenda-sorting-strategy
'(time-up category-keep priority-down
)
642 "Sorting structure for the agenda items of a single day.
643 This is a list of symbols which will be used in sequence to determine
644 if an entry should be listed before another entry. The following
645 symbols are recognized.
647 time-up Put entries with time-of-day indications first, early first
648 time-down Put entries with time-of-day indications first, late first
649 category-keep Keep the default order of categories, corresponding to the
650 sequence in `org-agenda-files'.
651 category-up Sort alphabetically by category, A-Z.
652 category-down Sort alphabetically by category, Z-A.
653 priority-up Sort numerically by priority, high priority last.
654 priority-down Sort numerically by priority, high priority first.
656 The different possibilities will be tried in sequence, and testing stops
657 if one comparison returns a \"not-equal\". For example, the default
658 '(time-up category-keep priority-down)
659 means: Pull out all entries having a specified time of day and sort them,
660 in order to make a time schedule for the current day the first thing in the
661 agenda listing for the day. Of the entries without a time indication, keep
662 the grouped in categories, don't sort the categories, but keep them in
663 the sequence given in `org-agenda-files'. Within each category sort by
666 Leaving out `category-keep' would mean that items will be sorted across
667 categories by priority."
673 (const category-keep
)
675 (const category-down
)
677 (const priority-down
))))
679 (defcustom org-agenda-prefix-format
" %-12:c%?-12t% s"
680 "Format specification for the prefix of items in the agenda buffer.
681 This format works similar to a printf format, with the following meaning:
683 %c the category of the item, \"Diary\" for entries from the diary, or
684 as given by the CATEGORY keyword or derived from the file name.
685 %t the time-of-day specification if one applies to the entry, in the
687 %s Scheduling/Deadline information, a short string
689 All specifiers work basically like the standard `%s' of printf, but may
690 contain two additional characters: A question mark just after the `%' and
691 a whitespace/punctuation character just before the final letter.
693 If the first character after `%' is a question mark, the entire field
694 will only be included if the corresponding value applies to the
695 current entry. This is useful for fields which should have fixed
696 width when present, but zero width when absent. For example,
697 \"%?-12t\" will result in a 12 character time field if a time of the
698 day is specified, but will completely disappear in entries which do
701 If there is punctuation or whitespace character just before the final
702 format letter, this character will be appended to the field value if
703 the value is not empty. For example, the format \"%-12:c\" leads to
704 \"Diary: \" if the category is \"Diary\". If the category were be
705 empty, no additional colon would be interted.
707 The default value of this option is \" %-12:c%?-12t% s\", meaning:
708 - Indent the line with two space characters
709 - Give the category in a 12 chars wide field, padded with whitespace on
710 the right (because of `-'). Append a colon if there is a category
712 - If there is a time-of-day, put it into a 12 chars wide field. If no
713 time, don't put in an empty field, just skip it (because of '?').
714 - Finally, put the scheduling information and append a whitespace.
716 As another example, if you don't want the time-of-day of entries in
717 the prefix, you could use:
719 (setq org-agenda-prefix-format \" %-11:c% s\")
721 See also the variable `org-agenda-remove-times-when-in-prefix'."
725 (defcustom org-timeline-prefix-format
" % s"
726 "Like `org-agenda-prefix-format', but for the timeline of a single file."
730 (defvar org-prefix-format-compiled nil
731 "The compiled version of the most recently used prefix format.
732 Depending on which command was used last, this may be the compiled version
733 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
735 (defcustom org-agenda-use-time-grid t
736 "Non-nil means, show a time grid in the agenda schedule.
737 A time grid is a set of lines for specific times (like every two hours between
738 8:00 and 20:00. The items scheduled for a day at specific times are
739 sorted in between these lines.
740 For deails about when the grid will be shown, and what it will look like, see
741 the variable `org-agenda-time-grid'."
745 (defcustom org-agenda-time-grid
746 '((daily today require-timed
)
748 (800 1000 1200 1400 1600 1800 2000))
750 "The settings for time grid for agenda display.
751 This is a list of three items. The first item is again a list. It contains
752 symbols specifying conditions when the grid should be displayed:
754 daily if the agenda shows a single day
755 weekly if the agenda shows an entire week
756 today show grid on current date, independent of daily/weekly display
757 require-timed show grid only if at least on item has a time specification
759 The second item is a string which will be places behing the grid time.
761 The third item is a list of integers, indicating the times that should have
766 (set :greedy t
:tag
"Grid Display Options"
767 (const :tag
"Show grid in single day agenda display" daily
)
768 (const :tag
"Show grid in weekly agenda display" weekly
)
769 (const :tag
"Always show grid for today" today
)
770 (const :tag
"Show grid only if any timed entries are present"
772 (const :tag
"Skip grid times already present in an entry"
774 (string :tag
"Grid String")
775 (repeat :tag
"Grid Times" (integer :tag
"Time"))))
777 (defcustom org-agenda-remove-times-when-in-prefix t
778 "Non-nil means, remove duplicate time specifications in agenda items.
779 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
780 time-of-day specification in a headline or diary entry is extracted and
781 placed into the prefix. If this option is non-nil, the original specification
782 \(a timestamp or -range, or just a plain time(range) specification like
783 11:30-4pm) will be removed for agenda display. This makes the agenda less
785 The option can be t or nil. It may also be the symbol `beg', indicating
786 that the time should only be removed what it is located at the beginning of
787 the headline/diary entry."
790 (const :tag
"Always" t
)
791 (const :tag
"Never" nil
)
792 (const :tag
"When at beginning of entry" beg
)))
794 (defcustom org-sort-agenda-notime-is-late t
795 "Non-nil means, items without time are considered late.
796 This is only relevant for sorting. When t, items which have no explicit
797 time like 15:30 will be considered as 24:01, i.e. later than any items which
798 do have a time. When nil, the default time is before 0:00. You can use this
799 option to decide if the schedule for today should come before or after timeless
804 (defgroup org-structure nil
805 "Options concerning structure editing in Org-mode."
809 (defcustom org-cycle-hook
'(org-optimize-window-after-visibility-change)
810 "Hook that is run after `org-cycle' has changed the buffer visibility.
811 The function(s) in this hook must accept a single argument which indicates
812 the new state that was set by the most recent `org-cycle' command. The
813 argument is a symbol. After a global state change, it can have the values
814 `overview', `content', or `all'. After a local state change, it can have
815 the values `folded', `children', or `subtree'."
816 :group
'org-structure
819 (defcustom org-occur-hook
'(org-first-headline-recenter)
820 "Hook that is run after `org-occur' has constructed a sparse tree.
821 This can be used to recenter the window to show as much of the structure
823 :group
'org-structure
826 (defcustom org-adapt-indentation t
827 "Non-nil means, adapt indentation when promoting and demoting.
828 When this is set and the *entire* text in an entry is indented, the
829 indentation is increased by one space in a demotion command, and
830 decreased by one in a promotion command. If any line in the entry
831 body starts at column 0, indentation is not changed at all."
832 :group
'org-structure
835 (defcustom org-cycle-emulate-tab t
836 "Where should `org-cycle' emulate TAB.
838 white Only in completely white lines
839 t Everywhere except in headlines"
840 :group
'org-structure
841 :type
'(choice (const :tag
"Never" nil
)
842 (const :tag
"Only in completely white lines" white
)
843 (const :tag
"Everywhere except in headlines" t
)
846 (defcustom org-show-following-heading t
847 "Non-nil means, show heading following match in `org-occur'.
848 When doing an `org-occur' it is useful to show the headline which
849 follows the match, even if they do not match the regexp. This makes it
850 easier to edit directly inside the sparse tree. However, if you use
851 org-occur mainly as an overview, the following headlines are
852 unnecessary clutter."
853 :group
'org-structure
856 (defcustom org-archive-location
"%s_archive::"
857 "The location where subtrees should be archived.
858 This string consists of two parts, separated by a double-colon.
860 The first part is a file name - when omitted, archiving happens in the same
861 file. %s will be replaced by the current file name (without directory part).
862 Archiving to a different file is useful to keep archived entries from
863 contributing to the Org-mode Agenda.
865 The part after the double colon is a headline. The archived entries will be
866 filed under that headline. When omitted, the subtrees are simply filed away
867 at the end of the file, as top-level entries.
869 Here are a few examples:
871 If the current file is Projects.org, archive in file
872 Projects.org_archive, as top-level trees. This is the default.
874 \"::* Archived Tasks\"
875 Archive in the current file, under the top-level headline
876 \"* Archived Tasks\".
878 \"~/org/archive.org::\"
879 Archive in file ~/org/archive.org (absolute path), as top-level trees.
881 \"basement::** Finished Tasks\"
882 Archive in file ./basement (relative path), as level 3 trees
883 below the level 2 heading \"** Finished Tasks\".
885 You may set this option on a per-file basis by adding to the buffer a
888 #+ARCHIVE: basement::** Finished Tasks"
889 :group
'org-structure
892 (defcustom org-archive-mark-done t
893 "Non-nil means, mark archived entries as DONE."
894 :group
'org-structure
897 (defcustom org-archive-stamp-time t
898 "Non-nil means, add a time stamp to archived entries.
899 The time stamp will be added directly after the TODO state keyword in the
900 first line, so it is probably best to use this in combinations with
901 `org-archive-mark-done'."
902 :group
'org-structure
905 (defgroup org-link nil
906 "Options concerning links in Org-mode."
910 (defcustom org-link-format
"<%s>"
911 "Default format for linkes in the buffer.
912 This is a format string for printf, %s will be replaced by the link text.
913 If you want to make sure that your link is always properly terminated,
914 include angle brackets into this format, like \"<%s>\". Some people also
915 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
918 (const :tag
"\"%s\" (e.g. http://www.there.com)" "%s")
919 (const :tag
"\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
920 (const :tag
"\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
921 (string :tag
"Other" :value
"<%s>")))
923 (defcustom org-allow-space-in-links t
924 "Non-nil means, file names in links may contain space characters.
925 When nil, it becomes possible to put several links into a line.
926 Note that in tables, a link never extends accross fields, so in a table
927 it is always possible to put several links into a line.
928 Changing this varable requires a re-launch of Emacs of become effective."
932 (defcustom org-line-numbers-in-file-links t
933 "Non-nil means, file links from `org-store-link' contain line numbers.
934 The line number will be added to the file name with :NNN and interpreted
935 by the command `org-open-at-point'.
936 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
937 negates this setting for the duration of the command."
941 (defcustom org-keep-stored-link-after-insertion nil
942 "Non-nil means, keep link in list for entire session.
944 The command `org-store-link' adds a link pointing to the current
945 location to an internal list. These links accumulate during a session.
946 The command `org-insert-link' can be used to insert links into any
947 Org-mode file (offering completion for all stored links). When this
948 option is nil, every link which has been inserted once using \\[org-insert-link]
949 will be removed from the list, to make completing the unused links
954 (defcustom org-link-frame-setup
955 '((vm . vm-visit-folder-other-frame
)
956 (gnus . gnus-other-frame
)
957 (file . find-file-other-window
))
958 "Setup the frame configuration for following links.
959 When following a link with Emacs, it may often be useful to display
960 this link in another window or frame. This variable can be used to
961 set this up for the different types of links.
964 `vm-visit-folder-other-frame'
970 `find-file-other-window'
971 `find-file-other-frame'
972 For the calendar, use the variable `calendar-setup'.
973 For BBDB, it is currently only possible to display the matches in
979 (const vm-visit-folder
)
980 (const vm-visit-folder-other-window
)
981 (const vm-visit-folder-other-frame
)))
985 (const gnus-other-frame
)))
989 (const find-file-other-window
)
990 (const find-file-other-frame
)))))
992 (defcustom org-usenet-links-prefer-google nil
993 "Non-nil means, `org-store-link' will create web links to google groups.
994 When nil, Gnus will be used for such links.
995 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
996 negates this setting for the duration of the command."
1000 (defcustom org-open-non-existing-files nil
1001 "Non-nil means, `org-open-file' will open non-existing file.
1002 When nil, an error will be generated."
1006 (defcustom org-confirm-shell-links t
1007 "Non-nil means, ask for confirmation before executing shell links.
1008 The default is true, to keep new users from shooting into their own foot."
1012 (defconst org-file-apps-defaults-gnu
1024 ("eps.gz" .
"gv %s")
1026 ("mpeg" .
"plaympeg %s")
1027 ("mp3" .
"plaympeg %s")
1029 ("pdf" .
"acroread %s")
1030 ("doc" .
"soffice %s")
1031 ("ppt" .
"soffice %s")
1032 ("pps" .
"soffice %s")
1033 ("html" .
"netscape -remote openURL(%s,new-window)")
1034 ("htm" .
"netscape -remote openURL(%s,new-window)")
1035 ("xs" .
"soffice %s"))
1036 "Default file applications on a UNIX/LINUX system.
1037 See `org-file-apps'.")
1039 (defconst org-file-apps-defaults-macosx
1044 ("eps.gz" .
"gv %s")
1046 ("fig" .
"xfig %s"))
1047 "Default file applications on a MacOS X system.
1048 The system \"open\" is known as a default, but we use X11 applications
1049 for some files for which the OS does not have a good default.
1050 See `org-file-apps'.")
1052 (defconst org-file-apps-defaults-windowsnt
1053 '((t .
(w32-shell-execute "open" file
)))
1054 "Default file applications on a Windows NT system.
1055 The system \"open\" is used for most files.
1056 See `org-file-apps'.")
1058 (defcustom org-file-apps
1066 "External applications for opening `file:path' items in a document.
1067 Org-mode uses system defaults for different file types, but
1068 you can use this variable to set the application for a given file
1069 extension. The entries in this list are cons cells with a file extension
1070 and the corresponding command. Possible values for the command are:
1071 `emacs' The file will be visited by the current Emacs process.
1072 `default' Use the default application for this file type.
1073 string A command to be executed by a shell; %s will be replaced
1074 by the path to the file.
1075 sexp A Lisp form which will be evaluated. The file path will
1076 be available in the Lisp variable `file'.
1077 For more examples, see the system specific constants
1078 `org-file-apps-defaults-macosx'
1079 `org-file-apps-defaults-windowsnt'
1080 `org-file-apps-defaults-gnu'."
1083 (cons (string :tag
"Extension")
1085 (const :tag
"Visit with Emacs" 'emacs
)
1086 (const :tag
"Use system default" 'default
)
1087 (string :tag
"Command")
1088 (sexp :tag
"Lisp form")))))
1091 (defgroup org-remember nil
1092 "Options concerning interaction with remember.el."
1096 (defcustom org-directory
"~/org"
1097 "Directory with org files.
1098 This directory will be used as default to prompt for org files.
1099 Used by the hooks for remember.el."
1100 :group
'org-remember
1103 (defcustom org-default-notes-file
"~/.notes"
1104 "Default target for storing notes.
1105 Used by the hooks for remember.el. This can be a string, or nil to mean
1106 the value of `remember-data-file'."
1107 :group
'org-remember
1109 (const :tag
"Default from remember-data-file" nil
)
1112 (defcustom org-reverse-note-order nil
1113 "Non-nil means, store new notes at the beginning of a file or entry.
1114 When nil, new notes will be filed to the end of a file or entry."
1115 :group
'org-remember
1117 (const :tag
"Reverse always" t
)
1118 (const :tag
"Reverse never" nil
)
1119 (repeat :tag
"By file name regexp"
1120 (cons regexp boolean
))))
1122 (defgroup org-table nil
1123 "Options concerning tables in Org-mode."
1127 (defcustom org-enable-table-editor
'optimized
1128 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1129 When nil, such lines will be treated like ordinary lines.
1131 When equal to the symbol `optimized', the table editor will be optimized to
1133 - Use automatic overwrite mode in front of whitespace in table fields.
1134 This make the structure of the table stay in tact as long as the edited
1135 field does not exceed the column width.
1136 - Minimize the number of realigns. Normally, the table is aligned each time
1137 TAB or RET are pressed to move to another field. With optimization this
1138 happens only if changes to a field might have changed the column width.
1139 Optimization requires replacing the functions `self-insert-command',
1140 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1141 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1142 very good at guessing when a re-align will be necessary, but you can always
1143 force one with `C-c C-c'.
1145 If you would like to use the optimized version in Org-mode, but the
1146 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1148 This variable can be used to turn on and off the table editor during a session,
1149 but in order to toggle optimization, a restart is required."
1152 (const :tag
"off" nil
)
1154 (const :tag
"on, optimized" optimized
)))
1156 (defcustom org-table-default-size
"5x2"
1157 "The default size for newly created tables, Columns x Rows."
1161 (defcustom org-table-automatic-realign t
1162 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1163 When nil, aligning is only done with \\[org-table-align], or after column
1168 (defcustom org-table-spaces-around-separators
'(1 .
1)
1169 "The number of spaces to be placed before and after separators."
1171 :type
'(cons (number :tag
"Before \"|\"") (number :tag
" After \"|\"")))
1173 (defcustom org-table-spaces-around-invisible-separators
'(1 .
2)
1174 "The number of spaces to be placed before and after separators.
1175 This option applies when the column separators have been made invisible."
1177 :type
'(cons (number :tag
"Before \"|\"") (number :tag
" After \"|\"")))
1179 (defcustom org-table-number-regexp
"^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1180 "Regular expression for recognizing numbers in table columns.
1181 If a table column contains mostly numbers, it will be aligned to the
1182 right. If not, it will be aligned to the left.
1184 The default value of this option is a regular expression which allows
1185 anything which looks remotely like a number as used in scientific
1186 context. For example, all of the following will be considered a
1188 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1190 Other options offered by the customize interface are more restrictive."
1193 (const :tag
"Positive Integers"
1195 (const :tag
"Integers"
1197 (const :tag
"Floating Point Numbers"
1198 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1199 (const :tag
"Floating Point Number or Integer"
1200 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1201 (const :tag
"Exponential, Floating point, Integer"
1202 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1203 (const :tag
"Very General Number-Like"
1204 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1205 (string :tag
"Regexp:")))
1207 (defcustom org-table-number-fraction
0.5
1208 "Fraction of numbers in a column required to make the column align right.
1209 In a column all non-white fields are considered. If at least this
1210 fraction of fields is matched by `org-table-number-fraction',
1211 alignment to the right border applies."
1215 (defcustom org-export-highlight-first-table-line t
1216 "Non-nil means, highlight the first table line.
1217 In HTML export, this means use <th> instead of <td>.
1218 In tables created with table.el, this applies to the first table line.
1219 In Org-mode tables, all lines before the first horizontal separator
1220 line will be formatted with <th> tags."
1224 (defcustom org-table-tab-recognizes-table.el t
1225 "Non-nil means, TAB will automatically notice a table.el table.
1226 When it sees such a table, it moves point into it and - if necessary -
1227 calls `table-recognize-table'."
1231 ;; FIXME: Should this one be in another group? Which one?
1232 (defcustom org-enable-fixed-width-editor t
1233 "Non-nil means, lines starting with \":\" are treated as fixed-width.
1234 This currently only means, they are never auto-wrapped.
1235 When nil, such lines will be treated like ordinary lines."
1239 (defgroup org-table-calculation nil
1240 "Options concerning tables in Org-mode."
1241 :tag
"Org Table Calculation"
1244 (defcustom org-table-copy-increment t
1245 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1246 :group
'org-table-calculation
1249 (defcustom org-calc-default-modes
1250 '(calc-internal-prec 12
1251 calc-float-format
(float 5)
1253 calc-prefer-frac nil
1254 calc-symbolic-mode nil
1255 calc-date-format
(YYYY "-" MM
"-" DD
" " Www
(" " HH
":" mm
))
1256 calc-display-working-message t
1258 "List with Calc mode settings for use in calc-eval for table formulas.
1259 The list must contain alternating symbols (calc modes variables and values.
1260 Don't remove any of the default settings, just change the values. Org-mode
1261 relies on the variables to be present in the list."
1262 :group
'org-table-calculation
1265 (defcustom org-table-formula-evaluate-inline t
1266 "Non-nil means, TAB and RET evaluate a formula in current table field.
1267 If the current field starts with an equal sign, it is assumed to be a formula
1268 which should be evaluated as described in the manual and in the documentation
1269 string of the command `org-table-eval-formula'. This feature requires the
1271 When this variable is nil, formula calculation is only available through
1272 the command \\[org-table-eval-formula]."
1273 :group
'org-table-calculation
1277 (defcustom org-table-formula-use-constants t
1278 "Non-nil means, interpret constants in formulas in tables.
1279 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1280 by the value given in `org-table-formula-constants', or by a value obtained
1281 from the `constants.el' package."
1282 :group
'org-table-calculation
1285 (defcustom org-table-formula-constants nil
1286 "Alist with constant names and values, for use in table formulas.
1287 The car of each element is a name of a constant, without the `$' before it.
1288 The cdr is the value as a string. For example, if you'd like to use the
1289 speed of light in a formula, you would configure
1291 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1293 and then use it in an equation like `$1*$c'."
1294 :group
'org-table-calculation
1296 (cons (string :tag
"name")
1297 (string :tag
"value"))))
1299 (defcustom org-table-formula-numbers-only nil
1300 "Non-nil means, calculate only with numbers in table formulas.
1301 Then all input fields will be converted to a number, and the result
1302 must also be a number. When nil, calc's full potential is available
1303 in table calculations, including symbolics etc."
1304 :group
'org-table-calculation
1307 (defcustom org-table-allow-automatic-line-recalculation t
1308 "Non-nil means, lines makred with |#| or |*| will be recomputed automatically.
1309 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1310 :group
'org-table-calculation
1313 (defgroup org-export nil
1314 "Options for exporting org-listings."
1318 (defcustom org-export-language-setup
1319 '(("en" "Author" "Date" "Table of Contents")
1320 ("da" "Ophavsmand" "Dato" "Indhold")
1321 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1322 ("es" "Autor" "Fecha" "\xccndice")
1323 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1324 ("it" "Autore" "Data" "Indice")
1325 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1326 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1327 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1328 "Terms used in export text, translated to different languages.
1329 Use the variable `org-export-default-language' to set the language,
1330 or use the +OPTION lines for a per-file setting."
1334 (string :tag
"HTML language tag")
1335 (string :tag
"Author")
1336 (string :tag
"Date")
1337 (string :tag
"Table of Contents"))))
1339 (defcustom org-export-default-language
"en"
1340 "The default language of HTML export, as a string.
1341 This should have an association in `org-export-language-setup'"
1345 (defcustom org-export-headline-levels
3
1346 "The last level which is still exported as a headline.
1347 Inferior levels will produce itemize lists when exported.
1348 Note that a numeric prefix argument to an exporter function overrides
1351 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1355 (defcustom org-export-with-section-numbers t
1356 "Non-nil means, add section numbers to headlines when exporting.
1358 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1362 (defcustom org-export-with-toc t
1363 "Non-nil means, create a table of contents in exported files.
1364 The TOC contains headlines with levels up to`org-export-headline-levels'.
1366 Headlines which contain any TODO items will be marked with \"(*)\" in
1367 ASCII export, and with red color in HTML output.
1369 In HTML output, the TOC will be clickable.
1371 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1375 (defcustom org-export-preserve-breaks nil
1376 "Non-nil means, preserve all line breaks when exporting.
1377 Normally, in HTML output paragraphs will be reformatted. In ASCII
1378 export, line breaks will always be preserved, regardless of this variable.
1380 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1384 (defcustom org-export-html-inline-images t
1385 "Non-nil means, inline images into exported HTML pages.
1386 The link will still be to the original location of the image file.
1387 So if you are moving the page, lets say to your public HTML site,
1388 you will have to move the image and maybe change the link."
1392 (defcustom org-export-html-expand t
1393 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1394 When nil, these tags will be exported as plain text and therefore
1395 not be interpreted by a browser.
1397 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1401 (defcustom org-export-with-fixed-width t
1402 "Non-nil means, lines starting with \":\" will be in fixed width font.
1403 This can be used to have pre-formatted text, fragments of code etc. For
1405 : ;; Some Lisp examples
1408 will be looking just like this in also HTML. In ASCII export, this option
1411 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1415 (defcustom org-export-with-tables t
1416 "If non-nil, lines starting with \"|\" define a table.
1419 | Name | Address | Birthday |
1420 |-------------+----------+-----------|
1421 | Arthur Dent | England | 29.2.2100 |
1423 In ASCII export, this option has no effect.
1425 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1429 (defcustom org-export-prefer-native-exporter-for-tables nil
1430 "Non-nil means, always export tables created with table.el natively.
1431 Natively means, use the HTML code generator in table.el.
1432 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1433 the table does not use row- or column-spanning). This has the
1434 advantage, that the automatic HTML conversions for math symbols and
1435 sub/superscripts can be applied. Org-mode's HTML generator is also
1440 (defcustom org-export-html-table-tag
1441 "<table border=1 cellspacing=0 cellpadding=6>"
1442 "The HTML tag used to start a table.
1443 This must be a <table> tag, but you may change the options like
1444 borders and spacing."
1448 (defcustom org-export-with-emphasize t
1449 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1450 If the export target supports emphasizing text, the word will be
1451 typeset in bold, italic, or underlined, respectively. Works only for
1452 single words, but you can say: I *really* *mean* *this*.
1453 In ASCII export, this option has no effect.
1455 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1459 (defcustom org-match-sexp-depth
3
1460 "Number of stacked braces for sub/superscript matching.
1461 This has to be set before loading org.el to be effective."
1465 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1466 (defcustom org-export-with-sub-superscripts t
1467 "Non-nil means, interpret \"_\" and \"^\" for export.
1468 When this option is turned on, you can use TeX-like syntax for sub- and
1469 superscripts. Several characters after \"_\" or \"^\" will be
1470 considered as a single item - so grouping with {} is normally not
1471 needed. For example, the following things will be parsed as single
1472 sub- or superscripts.
1474 10^24 or 10^tau several digits will be considered 1 item
1475 10^-12 or 10^-tau a leading sign with digits or a word
1476 x^2-y^3 will be read as x^2 - y^3, because items are
1477 terminated by almost any nonword/nondigit char.
1478 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1480 Still, ambiguity is possible - so when in doubt use {} to enclose the
1482 In ASCII export, this option has no effect.
1484 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1488 (defcustom org-export-with-TeX-macros t
1489 "Non-nil means, interpret simple TeX-like macros when exporting.
1490 For example, HTML export converts \\alpha to α and \\AA to Å.
1491 No only real TeX macros will work here, but the standard HTML entities
1492 for math can be used as macro names as well. For a list of supported
1493 names in HTML export, see the constant `org-html-entities'.
1494 In ASCII export, this option has no effect.
1496 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1500 (defcustom org-export-html-with-timestamp nil
1501 "If non-nil, write `org-export-html-html-helper-timestamp'
1502 into the exported html text. Otherwise, the buffer will just be saved
1507 (defcustom org-export-html-html-helper-timestamp
1508 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1509 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1513 (defcustom org-export-ascii-show-new-buffer t
1514 "Non-nil means, popup buffer containing the exported ASCII text.
1515 Otherwise the buffer will just be saved to a file and stay hidden."
1519 (defcustom org-export-html-show-new-buffer nil
1520 "Non-nil means, popup buffer containing the exported html text.
1521 Otherwise, the buffer will just be saved to a file and stay hidden."
1525 (defgroup org-faces nil
1526 "Faces for highlighting in Org-mode."
1530 (defface org-level-1
;; font-lock-function-name-face
1531 '((((type tty
) (class color
)) (:foreground
"blue" :weight bold
))
1532 (((class color
) (background light
)) (:foreground
"Blue"))
1533 (((class color
) (background dark
)) (:foreground
"LightSkyBlue"))
1534 (t (:inverse-video t
:bold t
)))
1535 "Face used for level 1 headlines."
1538 (defface org-level-2
;; font-lock-variable-name-face
1539 '((((type tty
) (class color
)) (:foreground
"yellow" :weight light
))
1540 (((class color
) (background light
)) (:foreground
"DarkGoldenrod"))
1541 (((class color
) (background dark
)) (:foreground
"LightGoldenrod"))
1542 (t (:bold t
:italic t
)))
1543 "Face used for level 2 headlines."
1546 (defface org-level-3
;; font-lock-keyword-face
1547 '((((type tty
) (class color
)) (:foreground
"cyan" :weight bold
))
1548 (((class color
) (background light
)) (:foreground
"Purple"))
1549 (((class color
) (background dark
)) (:foreground
"Cyan"))
1551 "Face used for level 3 headlines."
1554 (defface org-level-4
;; font-lock-comment-face
1555 '((((type tty pc
) (class color
) (background light
)) (:foreground
"red"))
1556 (((type tty pc
) (class color
) (background dark
)) (:foreground
"red1"))
1557 (((class color
) (background light
)) (:foreground
"Firebrick"))
1558 (((class color
) (background dark
)) (:foreground
"chocolate1"))
1559 (t (:bold t
:italic t
)))
1560 "Face used for level 4 headlines."
1563 (defface org-level-5
;; font-lock-type-face
1564 '((((type tty
) (class color
)) (:foreground
"green"))
1565 (((class color
) (background light
)) (:foreground
"ForestGreen"))
1566 (((class color
) (background dark
)) (:foreground
"PaleGreen"))
1567 (t (:bold t
:underline t
)))
1568 "Face used for level 5 headlines."
1571 (defface org-level-6
;; font-lock-constant-face
1572 '((((type tty
) (class color
)) (:foreground
"magenta"))
1573 (((class color
) (background light
)) (:foreground
"CadetBlue"))
1574 (((class color
) (background dark
)) (:foreground
"Aquamarine"))
1575 (t (:bold t
:underline t
)))
1576 "Face used for level 6 headlines."
1579 (defface org-level-7
;; font-lock-builtin-face
1580 '((((type tty
) (class color
)) (:foreground
"blue" :weight light
))
1581 (((class color
) (background light
)) (:foreground
"Orchid"))
1582 (((class color
) (background dark
)) (:foreground
"LightSteelBlue"))
1584 "Face used for level 7 headlines."
1587 (defface org-level-8
;; font-lock-string-face
1588 '((((type tty
) (class color
)) (:foreground
"green"))
1589 (((class color
) (background light
)) (:foreground
"RosyBrown"))
1590 (((class color
) (background dark
)) (:foreground
"LightSalmon"))
1592 "Face used for level 8 headlines."
1595 (defface org-warning
;; font-lock-warning-face
1596 '((((type tty
) (class color
)) (:foreground
"red"))
1597 (((class color
) (background light
)) (:foreground
"Red" :bold t
))
1598 (((class color
) (background dark
)) (:foreground
"Red1" :bold t
))
1599 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1600 (t (:inverse-video t
:bold t
)))
1601 "Face for deadlines and TODO keywords."
1604 (defcustom org-fontify-done-headline nil
1605 "Non-nil means, change the face of a headline if it is marked DONE.
1606 Normally, only the TODO/DONE keyword indicates the state of a headline.
1607 When this is non-nil, the headline after the keyword is set to the
1608 `org-headline-done' as an additional indication."
1612 (defface org-headline-done
;; font-lock-string-face
1613 '((((type tty
) (class color
)) (:foreground
"green"))
1614 (((class color
) (background light
)) (:foreground
"RosyBrown"))
1615 (((class color
) (background dark
)) (:foreground
"LightSalmon"))
1617 "Face used to indicate that a headline is DONE. See also the variable
1618 `org-fontify-done-headline'."
1621 ;; Inheritance does not yet work for xemacs. So we just copy...
1623 (defface org-deadline-announce
1624 '((((type tty
) (class color
)) (:foreground
"blue" :weight bold
))
1625 (((class color
) (background light
)) (:foreground
"Blue"))
1626 (((class color
) (background dark
)) (:foreground
"LightSkyBlue"))
1627 (t (:inverse-video t
:bold t
)))
1628 "Face for upcoming deadlines."
1631 (defface org-scheduled-today
1632 '((((type tty
) (class color
)) (:foreground
"green"))
1633 (((class color
) (background light
)) (:foreground
"DarkGreen"))
1634 (((class color
) (background dark
)) (:foreground
"PaleGreen"))
1635 (t (:bold t
:underline t
)))
1636 "Face for items scheduled for a certain day."
1639 (defface org-scheduled-previously
1640 '((((type tty pc
) (class color
) (background light
)) (:foreground
"red"))
1641 (((type tty pc
) (class color
) (background dark
)) (:foreground
"red1"))
1642 (((class color
) (background light
)) (:foreground
"Firebrick"))
1643 (((class color
) (background dark
)) (:foreground
"chocolate1"))
1644 (t (:bold t
:italic t
)))
1645 "Face for items scheduled previously, and not yet done."
1648 (defface org-formula
1649 '((((type tty pc
) (class color
) (background light
)) (:foreground
"red"))
1650 (((type tty pc
) (class color
) (background dark
)) (:foreground
"red1"))
1651 (((class color
) (background light
)) (:foreground
"Firebrick"))
1652 (((class color
) (background dark
)) (:foreground
"chocolate1"))
1653 (t (:bold t
:italic t
)))
1654 "Face for items scheduled previously, and not yet done."
1658 '((((type tty
) (class color
)) (:foreground
"cyan" :weight bold
))
1659 (((class color
) (background light
)) (:foreground
"Purple"))
1660 (((class color
) (background dark
)) (:foreground
"Cyan"))
1665 (defface org-done
;; font-lock-type-face
1666 '((((type tty
) (class color
)) (:foreground
"green"))
1667 (((class color
) (background light
)) (:foreground
"ForestGreen" :bold t
))
1668 (((class color
) (background dark
)) (:foreground
"PaleGreen" :bold t
))
1669 (t (:bold t
:underline t
)))
1670 "Face used for DONE."
1673 (defface org-table
;; font-lock-function-name-face
1674 '((((type tty
) (class color
)) (:foreground
"blue" :weight bold
))
1675 (((class color
) (background light
)) (:foreground
"Blue"))
1676 (((class color
) (background dark
)) (:foreground
"LightSkyBlue"))
1677 (t (:inverse-video t
:bold t
)))
1678 "Face used for tables."
1681 (defface org-time-grid
;; font-lock-variable-name-face
1682 '((((type tty
) (class color
)) (:foreground
"yellow" :weight light
))
1683 (((class color
) (background light
)) (:foreground
"DarkGoldenrod"))
1684 (((class color
) (background dark
)) (:foreground
"LightGoldenrod"))
1685 (t (:bold t
:italic t
)))
1686 "Face used for level 2 headlines."
1689 (defvar org-level-faces
1700 (defvar org-n-levels
(length org-level-faces
))
1702 ;; Tell the compiler about dynamically scoped variables,
1703 ;; and variables from other packages
1705 (defvar zmacs-regions
)
1706 (defvar original-date
)
1707 (defvar org-transient-mark-mode
)
1708 (defvar org-old-auto-fill-inhibit-regexp
)
1709 (defvar orgtbl-mode-menu
)
1710 (defvar org-html-entities
)
1711 (defvar org-goto-start-pos
)
1712 (defvar org-cursor-color
)
1713 (defvar org-time-was-given
)
1714 (defvar org-ts-what
)
1715 (defvar mark-active
)
1717 (defvar levels-open
)
1728 (defvar starting-day
)
1729 (defvar include-all-loc
)
1730 (defvar vm-message-pointer
)
1731 (defvar vm-folder-directory
)
1732 (defvar wl-summary-buffer-elmo-folder
)
1733 (defvar wl-summary-buffer-folder-name
)
1734 (defvar gnus-group-name
)
1735 (defvar gnus-article-current
)
1736 (defvar w3m-current-url
)
1737 (defvar org-selected-point
)
1738 (defvar calendar-mode-map
)
1739 (defvar remember-save-after-remembering
)
1740 (defvar remember-data-file
))
1745 (defvar org-mode-map
(copy-keymap outline-mode-map
)
1746 "Keymap for Org-mode.")
1748 (defvar org-struct-menu
)
1749 (defvar org-org-menu
)
1750 (defvar org-tbl-menu
)
1752 ;; We use a before-change function to check if a table might need
1754 (defvar org-table-may-need-update t
1755 "Indicates of a table might need an update.
1756 This variable is set by `org-before-change-function'. `org-table-align'
1757 sets it back to nil.")
1758 (defvar org-mode-hook nil
)
1759 (defvar org-inhibit-startup nil
) ; Dynamically-scoped param.
1763 (define-derived-mode org-mode outline-mode
"Org"
1764 "Outline-based notes management and organizer, alias
1765 \"Carstens outline-mode for keeping track of everything.\"
1767 Org-mode develops organizational tasks around a NOTES file which
1768 contains information about projects as plain text. Org-mode is
1769 implemented on top of outline-mode, which is ideal to keep the content
1770 of large files well structured. It supports ToDo items, deadlines and
1771 time stamps, which magically appear in the diary listing of the Emacs
1772 calendar. Tables are easily created with a built-in table editor.
1773 Plain text URL-like links connect to websites, emails (VM), Usenet
1774 messages (Gnus), BBDB entries, and any files related to the project.
1775 For printing and sharing of notes, an Org-mode file (or a part of it)
1776 can be exported as a structured ASCII or HTML file.
1778 The following commands are available:
1781 (easy-menu-add org-org-menu
)
1782 (easy-menu-add org-tbl-menu
)
1783 (org-install-agenda-files-menu)
1784 (setq outline-regexp
"\\*+")
1785 (if org-startup-truncated
(setq truncate-lines t
))
1786 (org-set-regexps-and-options)
1787 (set (make-local-variable 'font-lock-unfontify-region-function
)
1788 'org-unfontify-region
)
1789 ;; Activate before-change-function
1790 (set (make-local-variable 'org-table-may-need-update
) t
)
1791 (make-local-hook 'before-change-functions
) ;; needed for XEmacs
1792 (add-hook 'before-change-functions
'org-before-change-function nil
1794 ;; Paragraph regular expressions
1795 (set (make-local-variable 'paragraph-separate
) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1796 (set (make-local-variable 'paragraph-start
) "\f\\|[ ]*$\\|\\([*\f]+\\)")
1797 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
1798 (set (make-local-variable 'auto-fill-inhibit-regexp
)
1800 (if (or org-enable-table-editor org-enable-fixed-width-editor
)
1803 (if org-enable-table-editor
"|" "")
1804 (if org-enable-fixed-width-editor
":" "")
1806 (set (make-local-variable 'fill-paragraph-function
) 'org-fill-paragraph
)
1807 ;; Settings for Calc embedded mode
1808 (set (make-local-variable 'calc-embedded-open-formula
) "|\\|\n")
1809 (set (make-local-variable 'calc-embedded-close-formula
) "|\\|\n")
1810 (if (and org-insert-mode-line-in-empty-file
1812 (= (point-min) (point-max)))
1813 (insert " -*- mode: org -*-\n\n"))
1815 ;; Get rid of Outline menus, they are not needed
1816 ;; Need to do this here because define-derived-mode sets up
1817 ;; the keymap so late.
1820 (delete-menu-item '("Headings"))
1821 (delete-menu-item '("Show"))
1822 (delete-menu-item '("Hide"))
1823 (set-menubar-dirty-flag))
1824 (define-key org-mode-map
[menu-bar headings
] 'undefined
)
1825 (define-key org-mode-map
[menu-bar hide
] 'undefined
)
1826 (define-key org-mode-map
[menu-bar show
] 'undefined
))
1828 (unless org-inhibit-startup
1829 (if org-startup-with-deadline-check
1830 (call-interactively 'org-check-deadlines
)
1832 ((eq org-startup-folded t
)
1834 ((eq org-startup-folded
'content
)
1835 (let ((this-command 'org-cycle
) (last-command 'org-cycle
))
1836 (org-cycle '(4)) (org-cycle '(4))))))))
1838 (defun org-fill-paragraph (&optional justify
)
1839 "Re-align a table, pass through to fill-paragraph if no table."
1841 (beginning-of-line 1)
1842 (looking-at "\\s-*\\(|\\|\\+-+\\)")))
1844 (defsubst org-current-line
(&optional pos
)
1845 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos
(point)))))
1849 (defvar org-mouse-map
(make-sparse-keymap))
1850 (define-key org-mouse-map
1851 (if org-xemacs-p
[button2] [mouse-2]) 'org-open-at-mouse)
1852 (define-key org-mouse-map
1853 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
1855 (require 'font-lock)
1857 (defconst org-non-link-chars "\t\n\r|<>\000")
1858 (defconst org-link-regexp
1859 (if org-allow-space-in-links
1861 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
1863 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
1865 "Regular expression for matching links.")
1866 (defconst org-link-maybe-angles-regexp
1867 (concat "<?\\(" org-link-regexp "\\)>?")
1868 "Matches a link and optionally surrounding angle brackets.")
1869 (defconst org-protected-link-regexp
1870 (concat "\000" org-link-regexp "\000")
1871 "Matches a link and optionally surrounding angle brackets.")
1873 (defconst org-ts-lengths
1874 (cons (length (format-time-string (car org-time-stamp-formats)))
1875 (length (format-time-string (cdr org-time-stamp-formats))))
1876 "This holds the lengths of the two different time formats.")
1877 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*\\)>"
1878 "Regular expression for fast time stamp matching.")
1879 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
1880 "Regular expression matching time strings for analysis.")
1881 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
1882 "Regular expression matching time stamps, with groups.")
1883 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
1884 "Regular expression matching a time stamp range.")
1885 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
1886 org-ts-regexp "\\)?")
1887 "Regular expression matching a time stamp or time stamp range.")
1889 (defun org-activate-links (limit)
1890 "Run through the buffer and add overlays to links."
1891 (if (re-search-forward org-link-regexp limit t)
1893 (add-text-properties (match-beginning 0) (match-end 0)
1894 (list 'mouse-face 'highlight
1895 'keymap org-mouse-map))
1898 (defun org-activate-dates (limit)
1899 "Run through the buffer and add overlays to dates."
1900 (if (re-search-forward org-tsr-regexp limit t)
1902 (add-text-properties (match-beginning 0) (match-end 0)
1903 (list 'mouse-face 'highlight
1904 'keymap org-mouse-map))
1907 (defun org-font-lock-level ()
1909 (org-back-to-heading t)
1910 (- (match-end 0) (match-beginning 0))))
1912 (defvar org-font-lock-keywords nil)
1914 (defun org-set-font-lock-defaults ()
1915 (let ((org-font-lock-extra-keywords
1917 '(org-activate-links (0 'org-link))
1918 '(org-activate-dates (0 'org-link))
1919 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
1920 '(1 'org-warning t))
1921 (list (concat "\\[#[A-Z]\\]") '(0 'org-warning t))
1922 (list (concat "\\<" org-deadline-string) '(0 'org-warning t))
1923 (list (concat "\\<" org-scheduled-string) '(0 'org-warning t))
1924 ;; '("\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
1926 ;; '("\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
1928 ;; '("\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
1930 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string "\\)\\>")
1931 '(1 'org-warning t))
1932 '("^#.*" (0 'font-lock-comment-face t))
1933 (if org-fontify-done-headline
1934 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
1935 '(1 'org-done t) '(2 'org-headline-done t))
1936 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
1938 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
1940 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
1941 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
1942 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
1944 (set (make-local-variable 'org-font-lock-keywords)
1946 (if org-noutline-p ; FIXME: I am not sure if eval will work
1947 ; on XEmacs if noutline is ever ported
1948 '((eval . (list "^\\(\\*+\\).*"
1950 (% (- (match-end 1) (match-beginning 1) 1)
1954 '(("^\\(\\(\\*+\\)[^\r\n]*\\)[\n\r]"
1955 (1 (nth (% (- (match-end 2) (match-beginning 2) 1)
1959 org-font-lock-extra-keywords))
1960 (set (make-local-variable 'font-lock-defaults)
1961 '(org-font-lock-keywords t nil nil backward-paragraph))
1962 (kill-local-variable 'font-lock-keywords) nil))
1964 (defun org-unfontify-region (beg end &optional maybe_loudly)
1965 "Remove fontification and activation overlays from links."
1966 (font-lock-default-unfontify-region beg end)
1967 (let* ((buffer-undo-list t)
1968 (inhibit-read-only t) (inhibit-point-motion-hooks t)
1969 (inhibit-modification-hooks t)
1970 deactivate-mark buffer-file-name buffer-file-truename)
1971 (remove-text-properties beg end '(mouse-face nil keymap nil))))
1973 ;;; Visibility cycling
1975 (defvar org-cycle-global-status nil)
1976 (defvar org-cycle-subtree-status nil)
1977 (defun org-cycle (&optional arg)
1978 "Visibility cycling for Org-mode.
1980 - When this function is called with a prefix argument, rotate the entire
1981 buffer through 3 states (global cycling)
1982 1. OVERVIEW: Show only top-level headlines.
1983 2. CONTENTS: Show all headlines of all levels, but no body text.
1984 3. SHOW ALL: Show everything.
1986 - When point is at the beginning of a headline, rotate the subtree started
1987 by this line through 3 different states (local cycling)
1988 1. FOLDED: Only the main headline is shown.
1989 2. CHILDREN: The main headline and the direct children are shown. From
1990 this state, you can move to one of the children and
1992 3. SUBTREE: Show the entire subtree, including body text.
1994 - When there is a numeric prefix, go up to a heading with level ARG, do
1995 a `show-subtree' and return to the previous cursor position. If ARG
1996 is negative, go up that many levels.
1998 - When point is not at the beginning of a headline, execute
1999 `indent-relative', like TAB normally does. See the option
2000 `org-cycle-emulate-tab' for details.
2002 - Special case: if point is the the beginning of the buffer and there is
2003 no headline in line 1, this function will act as if called with prefix arg."
2006 (if (or (and (bobp) (not (looking-at outline-regexp)))
2008 ;; special case: use global cycling
2013 ((org-at-table-p 'any)
2014 ;; Enter the table or move to the next field in the table
2015 (or (org-table-recognize-table.el)
2017 (org-table-justify-field-maybe)
2018 (org-table-next-field))))
2020 ((eq arg t) ;; Global cycling
2023 ((and (eq last-command this-command)
2024 (eq org-cycle-global-status 'overview))
2025 ;; We just created the overview - now do table of contents
2026 ;; This can be slow in very large buffers, so indicate action
2027 (message "CONTENTS...")
2029 ;; Visit all headings and show their offspring
2030 (goto-char (point-max))
2032 (while (and (progn (condition-case nil
2033 (outline-previous-visible-heading 1)
2034 (error (goto-char (point-min))))
2036 (looking-at outline-regexp))
2038 (if (bobp) (throw 'exit nil))))
2039 (message "CONTENTS...done"))
2040 (setq org-cycle-global-status 'contents)
2041 (run-hook-with-args 'org-cycle-hook 'contents))
2043 ((and (eq last-command this-command)
2044 (eq org-cycle-global-status 'contents))
2045 ;; We just showed the table of contents - now show everything
2047 (message "SHOW ALL")
2048 (setq org-cycle-global-status 'all)
2049 (run-hook-with-args 'org-cycle-hook 'all))
2052 ;; Default action: go to overview
2054 (message "OVERVIEW")
2055 (setq org-cycle-global-status 'overview)
2056 (run-hook-with-args 'org-cycle-hook 'overview))))
2059 ;; Show-subtree, ARG levels up from here.
2061 (org-back-to-heading)
2062 (outline-up-heading (if (< arg 0) (- arg)
2063 (- (outline-level) arg)))
2064 (org-show-subtree)))
2066 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2067 ;; At a heading: rotate between three different views
2068 (org-back-to-heading)
2069 (let ((goal-column 0) eoh eol eos)
2070 ;; First, some boundaries
2072 (org-back-to-heading)
2074 (beginning-of-line 2)
2075 (while (and (not (eobp)) ;; this is like `next-line'
2076 (get-char-property (1- (point)) 'invisible))
2077 (beginning-of-line 2)) (setq eol (point)))
2078 (outline-end-of-heading) (setq eoh (point))
2079 (outline-end-of-subtree) (setq eos (point))
2080 (outline-next-heading))
2081 ;; Find out what to do next and set `this-command'
2084 ;; Nothing is hidden behind this heading
2085 (message "EMPTY ENTRY")
2086 (setq org-cycle-subtree-status nil))
2088 ;; Entire subtree is hidden in one line: open it
2091 (message "CHILDREN")
2092 (setq org-cycle-subtree-status 'children)
2093 (run-hook-with-args 'org-cycle-hook 'children))
2094 ((and (eq last-command this-command)
2095 (eq org-cycle-subtree-status 'children))
2096 ;; We just showed the children, now show everything.
2099 (setq org-cycle-subtree-status 'subtree)
2100 (run-hook-with-args 'org-cycle-hook 'subtree))
2102 ;; Default action: hide the subtree.
2105 (setq org-cycle-subtree-status 'folded)
2106 (run-hook-with-args 'org-cycle-hook 'folded)))))
2109 (buffer-read-only (org-back-to-heading))
2110 ((if (and (eq org-cycle-emulate-tab 'white)
2111 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2113 (eq org-cycle-emulate-tab t))
2114 (if (and (looking-at "[ \n\r\t]")
2115 (string-match "^[ \t]*$" (buffer-substring
2116 (point-at-bol) (point))))
2118 (beginning-of-line 1)
2119 (and (looking-at "[ \t]+") (replace-match ""))))
2123 (org-back-to-heading)
2126 (defun org-optimize-window-after-visibility-change (state)
2127 "Adjust the window after a change in outline visibility.
2128 This function is the default value of the hook `org-cycle-hook'."
2130 ((eq state 'overview) (org-first-headline-recenter 1))
2131 ((eq state 'content) nil)
2132 ((eq state 'all) nil)
2133 ((eq state 'folded) nil)
2134 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2135 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2137 (defun org-subtree-end-visible-p ()
2138 "Is the end of the current subtree visible?"
2139 (pos-visible-in-window-p
2140 (save-excursion (outline-end-of-subtree) (point))))
2142 (defun org-first-headline-recenter (&optional N)
2143 "Move cursor to the first headline and recenter the headline.
2144 Optional argument N means, put the headline into the Nth line of the window."
2145 (goto-char (point-min))
2146 (when (re-search-forward (concat "^" outline-regexp) nil t)
2148 (recenter (prefix-numeric-value N))))
2150 (defvar org-goto-window-configuration nil)
2151 (defvar org-goto-marker nil)
2152 (defvar org-goto-map (make-sparse-keymap))
2153 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2154 (while (setq cmd (pop cmds))
2155 (substitute-key-definition cmd cmd org-goto-map global-map)))
2156 (define-key org-goto-map "\C-m" 'org-goto-ret)
2157 (define-key org-goto-map [(left)] 'org-goto-left)
2158 (define-key org-goto-map [(right)] 'org-goto-right)
2159 (define-key org-goto-map [(?q)] 'org-goto-quit)
2160 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2161 (define-key org-goto-map "\C-i" 'org-cycle)
2162 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2163 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2164 (define-key org-goto-map "n" 'outline-next-visible-heading)
2165 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2166 (define-key org-goto-map "f" 'outline-forward-same-level)
2167 (define-key org-goto-map "b" 'outline-backward-same-level)
2168 (define-key org-goto-map "u" 'outline-up-heading)
2169 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2170 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2171 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2172 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2173 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2174 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2175 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2177 (defconst org-goto-help
2178 "Select a location to jump to, press RET
2179 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2182 "Go to a different location of the document, keeping current visibility.
2184 When you want to go to a different location in a document, the fastest way
2185 is often to fold the entire buffer and then dive into the tree. This
2186 method has the disadvantage, that the previous location will be folded,
2187 which may not be what you want.
2189 This command works around this by showing a copy of the current buffer in
2190 overview mode. You can dive into the tree in that copy, to find the
2191 location you want to reach. When pressing RET, the command returns to the
2192 original buffer in which the visibility is still unchanged. It then jumps
2193 to the new location, making it and the headline hierarchy above it visible."
2195 (let* ((org-goto-start-pos (point))
2197 (org-get-location (current-buffer) org-goto-help)))
2200 (goto-char selected-point)
2201 (if (org-invisible-p) (org-show-hierarchy-above)))
2204 (defun org-get-location (buf help)
2205 "Let the user select a location in the Org-mode buffer BUF.
2206 This function uses a recursive edit. It returns the selected position
2208 (let (org-selected-point)
2210 (save-window-excursion
2211 (delete-other-windows)
2212 (switch-to-buffer (get-buffer-create "*org-goto*"))
2213 (with-output-to-temp-buffer "*Help*"
2215 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2216 (setq buffer-read-only nil)
2219 (let ((org-startup-truncated t)
2220 (org-startup-folded t)
2221 (org-startup-with-deadline-check nil))
2223 (setq buffer-read-only t)
2224 (if (boundp 'org-goto-start-pos)
2225 (goto-char org-goto-start-pos)
2226 (goto-char (point-min)))
2227 (org-beginning-of-line)
2228 (message "Select location and press RET")
2229 ;; now we make sure that during selection, ony very few keys work
2230 ;; and that it is impossible to switch to another window.
2231 (let ((gm (current-global-map))
2232 (overriding-local-map org-goto-map))
2235 (use-global-map org-goto-map)
2237 (use-global-map gm)))))
2238 (kill-buffer "*org-goto*")
2239 org-selected-point))
2241 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2242 (defun org-goto-ret (&optional arg)
2243 "Finish org-goto by going to the new location."
2245 (setq org-selected-point (point)
2246 current-prefix-arg arg)
2249 (defun org-goto-left ()
2250 "Finish org-goto by going to the new location."
2252 (if (org-on-heading-p)
2254 (beginning-of-line 1)
2255 (setq org-selected-point (point)
2256 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2258 (error "Not on a heading")))
2260 (defun org-goto-right ()
2261 "Finish org-goto by going to the new location."
2263 (if (org-on-heading-p)
2265 (outline-end-of-subtree)
2266 (or (eobp) (forward-char 1))
2267 (setq org-selected-point (point)
2268 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2270 (error "Not on a heading")))
2272 (defun org-goto-quit ()
2273 "Finish org-goto without cursor motion."
2275 (setq org-selected-point nil)
2278 ;;; Promotion, Demotion, Inserting new headlines
2280 (defvar org-ignore-region nil
2281 "To temporarily disable the active region.")
2283 (defun org-insert-heading ()
2284 "Insert a new heading with same depth at point."
2286 (let* ((head (save-excursion
2288 (org-back-to-heading)
2289 (error (outline-next-heading)))
2290 (prog1 (match-string 0)
2291 (funcall outline-level)))))
2292 (unless (bolp) (newline))
2295 (save-excursion (newline-and-indent)))
2296 (unless (equal (char-before) ?\ )
2298 (run-hooks 'org-insert-heading-hook)))
2300 (defun org-insert-todo-heading (arg)
2301 "Insert a new heading with the same level and TODO state as current heading.
2302 If the heading has no TODO state, or if the state is DONE, use the first
2303 state (TODO by default). Also with prefix arg, force first state."
2305 (org-insert-heading)
2307 (org-back-to-heading)
2308 (outline-previous-heading)
2309 (looking-at org-todo-line-regexp))
2311 (not (match-beginning 2))
2312 (equal (match-string 2) org-done-string))
2313 (insert (car org-todo-keywords) " ")
2314 (insert (match-string 2) " ")))
2316 (defun org-promote-subtree ()
2317 "Promote the entire subtree.
2318 See also `org-promote'."
2321 (org-map-tree 'org-promote)))
2323 (defun org-demote-subtree ()
2324 "Demote the entire subtree. See `org-demote'.
2325 See also `org-promote'."
2328 (org-map-tree 'org-demote)))
2330 (defun org-do-promote ()
2331 "Promote the current heading higher up the tree.
2332 If the region is active in `transient-mark-mode', promote all headings
2336 (if (org-region-active-p)
2337 (org-map-region 'org-promote (region-beginning) (region-end))
2339 (org-fix-position-after-promote))
2341 (defun org-do-demote ()
2342 "Demote the current heading lower down the tree.
2343 If the region is active in `transient-mark-mode', demote all headings
2347 (if (org-region-active-p)
2348 (org-map-region 'org-demote (region-beginning) (region-end))
2350 (org-fix-position-after-promote))
2352 (defun org-fix-position-after-promote ()
2353 "Make sure that after pro/demotion cursor position is right."
2354 (and (equal (char-after) ?\ )
2355 (equal (char-before) ?*)
2358 (defun org-promote ()
2359 "Promote the current heading higher up the tree.
2360 If the region is active in `transient-mark-mode', promote all headings
2362 (org-back-to-heading t)
2363 (let* ((level (save-match-data (funcall outline-level)))
2364 (up-head (make-string (1- level) ?*)))
2365 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2366 (replace-match up-head nil t)
2367 (if org-adapt-indentation
2368 (org-fixup-indentation "^ " "" "^ ?\\S-"))))
2370 (defun org-demote ()
2371 "Demote the current heading lower down the tree.
2372 If the region is active in `transient-mark-mode', demote all headings
2374 (org-back-to-heading t)
2375 (let* ((level (save-match-data (funcall outline-level)))
2376 (down-head (make-string (1+ level) ?*)))
2377 (replace-match down-head nil t)
2378 (if org-adapt-indentation
2379 (org-fixup-indentation "^ " " " "^\\S-"))))
2381 (defun org-map-tree (fun)
2382 "Call FUN for every heading underneath the current one."
2383 (org-back-to-heading)
2384 (let ((level (outline-level)))
2388 (outline-next-heading)
2389 (> (funcall outline-level) level))
2393 (defun org-map-region (fun beg end)
2394 "Call FUN for every heading between BEG and END."
2395 (let ((org-ignore-region t))
2397 (setq end (copy-marker end))
2399 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2403 (outline-next-heading)
2408 (defun org-fixup-indentation (from to prohibit)
2409 "Change the indentation in the current entry by re-replacing FROM with TO.
2410 However, if the regexp PROHIBIT matches at all, don't do anything.
2411 This is being used to change indentation along with the length of the
2412 heading marker. But if there are any lines which are not indented, nothing
2415 (let ((end (save-excursion (outline-next-heading)
2417 (unless (save-excursion (re-search-forward prohibit end t))
2418 (while (re-search-forward from end t)
2420 (beginning-of-line 2)))
2421 (move-marker end nil))))
2423 ;;; Vertical tree motion, cutting and pasting of subtrees
2425 (defun org-move-subtree-up (&optional arg)
2426 "Move the current subtree up past ARG headlines of the same level."
2428 (org-move-subtree-down (- (prefix-numeric-value arg))))
2430 (defun org-move-subtree-down (&optional arg)
2431 "Move the current subtree down past ARG headlines of the same level."
2433 (setq arg (prefix-numeric-value arg))
2434 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2435 'outline-get-last-sibling))
2436 (ins-point (make-marker))
2440 (org-back-to-heading)
2443 (save-excursion (outline-end-of-heading)
2444 (setq folded (org-invisible-p)))
2445 (outline-end-of-subtree))
2446 (outline-next-heading)
2448 ;; Find insertion point, with error handling
2451 (or (and (funcall movfunc) (looking-at outline-regexp))
2452 (progn (goto-char beg)
2453 (error "Cannot move past superior level or buffer limit")))
2454 (setq cnt (1- cnt)))
2456 ;; Moving forward - still need to move over subtree
2457 (progn (outline-end-of-subtree)
2458 (outline-next-heading)
2459 (if (not (or (looking-at (concat "^" outline-regexp))
2462 (move-marker ins-point (point))
2463 (setq txt (buffer-substring beg end))
2464 (delete-region beg end)
2466 (goto-char ins-point)
2467 (if folded (hide-subtree))
2468 (move-marker ins-point nil)))
2470 (defvar org-subtree-clip ""
2471 "Clipboard for cut and paste of subtrees.
2472 This is actually only a copy of the kill, because we use the normal kill
2473 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2475 (defvar org-subtree-clip-folded nil
2476 "Was the last copied subtree folded?
2477 This is used to fold the tree back after pasting.")
2479 (defun org-cut-subtree ()
2480 "Cut the current subtree into the clipboard.
2481 This is a short-hand for marking the subtree and then cutting it."
2483 (org-copy-subtree 'cut))
2485 (defun org-copy-subtree (&optional cut)
2486 "Cut the current subtree into the clipboard.
2487 This is a short-hand for marking the subtree and then copying it.
2488 If CUT is non nil, actually cut the subtree."
2490 (let (beg end folded)
2491 (org-back-to-heading)
2494 (save-excursion (outline-end-of-heading)
2495 (setq folded (org-invisible-p)))
2496 (outline-end-of-subtree))
2497 (if (equal (char-after) ?\n) (forward-char 1))
2501 (setq org-subtree-clip-folded folded)
2502 (if cut (kill-region beg end) (copy-region-as-kill beg end))
2503 (setq org-subtree-clip (current-kill 0))
2504 (message "%s: Subtree with %d characters"
2505 (if cut "Cut" "Copied")
2506 (length org-subtree-clip)))))
2508 (defun org-paste-subtree (&optional level tree)
2509 "Paste the clipboard as a subtree, with modification of headline level.
2510 The entire subtree is promoted or demoted in order to match a new headline
2511 level. By default, the new level is derived from the visible headings
2512 before and after the insertion point, and taken to be the inferior headline
2513 level of the two. So if the previous visible heading is level 3 and the
2514 next is level 4 (or vice versa), level 4 will be used for insertion.
2515 This makes sure that the subtree remains an independent subtree and does
2516 not swallow low level entries.
2518 You can also force a different level, either by using a numeric prefix
2519 argument, or by inserting the heading marker by hand. For example, if the
2520 cursor is after \"*****\", then the tree will be shifted to level 5.
2522 If you want to insert the tree as is, just use \\[yank].
2524 If optional TREE is given, use this text instead of the kill ring."
2526 (unless (org-kill-is-subtree-p tree)
2528 (substitute-command-keys
2529 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
2530 (let* ((txt (or tree (current-kill 0)))
2531 (^re (concat "^\\(" outline-regexp "\\)"))
2532 (re (concat "\\(" outline-regexp "\\)"))
2533 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
2535 (old-level (if (string-match ^re txt)
2536 (- (match-end 0) (match-beginning 0))
2538 (force-level (cond (level (prefix-numeric-value level))
2540 ^re_ (buffer-substring (point-at-bol) (point)))
2541 (- (match-end 0) (match-beginning 0)))
2543 (previous-level (save-excursion
2546 (outline-previous-visible-heading 1)
2548 (- (match-end 0) (match-beginning 0))
2551 (next-level (save-excursion
2554 (outline-next-visible-heading 1)
2556 (- (match-end 0) (match-beginning 0))
2559 (new-level (or force-level (max previous-level next-level)))
2560 (shift (if (or (= old-level -1)
2562 (= old-level new-level))
2564 (- new-level old-level)))
2566 (delta (if (> shift 0) -1 1))
2567 (func (if (> shift 0) 'org-demote 'org-promote))
2569 ;; Remove the forces level indicator
2571 (delete-region (point-at-bol) (point)))
2572 ;; Make sure we start at the beginning of an empty line
2573 (if (not (bolp)) (insert "\n"))
2574 (if (not (looking-at "[ \t]*$"))
2575 (progn (insert "\n") (backward-char 1)))
2581 ;; Shift if necessary
2583 (message "Pasted at level %d, without shift" new-level)
2585 (narrow-to-region beg end)
2586 (while (not (= shift 0))
2587 (org-map-region func (point-min) (point-max))
2588 (setq shift (+ delta shift)))
2589 (goto-char (point-min))
2590 (message "Pasted at level %d, with shift by %d levels"
2592 (if (and (eq org-subtree-clip (current-kill 0))
2593 org-subtree-clip-folded)
2594 ;; The tree was folded before it was killed/copied
2597 (defun org-kill-is-subtree-p (&optional txt)
2598 "Check if the current kill is an outline subtree, or a set of trees.
2599 Returns nil if kill does not start with a headline, or if the first
2600 headline level is not the largest headline level in the tree.
2601 So this will actually accept several entries of equal levels as well,
2602 which is OK for `org-paste-subtree'.
2603 If optional TXT is given, check this string instead of the current kill."
2604 (let* ((kill (or txt (current-kill 0) ""))
2605 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
2606 (- (match-end 0) (match-beginning 0))))
2607 (re (concat "^" outline-regexp))
2609 (if (not start-level)
2610 nil ;; does not even start with a heading
2612 (while (setq start (string-match re kill (1+ start)))
2613 (if (< (- (match-end 0) (match-beginning 0)) start-level)
2617 (defun org-archive-subtree ()
2618 "Move the current subtree to the archive.
2619 The archive can be a certain top-level heading in the current file, or in
2620 a different file. The tree will be moved to that location, the subtree
2621 heading be marked DONE, and the current time will be added."
2623 ;; Save all relevant TODO keyword-relatex variables
2624 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
2625 (tr-org-todo-keywords org-todo-keywords)
2626 (tr-org-todo-interpretation org-todo-interpretation)
2627 (tr-org-done-string org-done-string)
2628 (tr-org-todo-regexp org-todo-regexp)
2629 (tr-org-todo-line-regexp org-todo-line-regexp)
2630 (this-buffer (current-buffer))
2631 file heading buffer level newfile-p)
2632 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
2634 (setq file (format (match-string 1 org-archive-location)
2635 (file-name-nondirectory (buffer-file-name)))
2636 heading (match-string 2 org-archive-location)))
2637 (error "Invalid `org-archive-location'"))
2638 (if (> (length file) 0)
2639 (setq newfile-p (not (file-exists-p file))
2640 buffer (find-file-noselect file))
2641 (setq buffer (current-buffer)))
2643 (error "Cannot access file \"%s\"" file))
2644 (if (and (> (length heading) 0)
2645 (string-match "^\\*+" heading))
2646 (setq level (match-end 0))
2647 (setq heading nil level 0))
2649 ;; We first only copy, in case something goes wrong
2650 ;; we need to protect this-command, to avoid kill-region sets it,
2651 ;; which would lead to duplication of subtrees
2652 (let (this-command) (org-copy-subtree))
2654 ;; Enforce org-mode for the archive buffer
2655 (if (not (eq major-mode 'org-mode))
2656 ;; Force the mode for future visits.
2657 (let ((org-insert-mode-line-in-empty-file t))
2658 (call-interactively 'org-mode)))
2660 (goto-char (point-max))
2661 (insert (format "\nArchived entries from file %s\n\n"
2662 (buffer-file-name this-buffer))))
2663 ;; Force the TODO keywords of the original buffer
2664 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
2665 (org-todo-keywords tr-org-todo-keywords)
2666 (org-todo-interpretation tr-org-todo-interpretation)
2667 (org-done-string tr-org-done-string)
2668 (org-todo-regexp tr-org-todo-regexp)
2669 (org-todo-line-regexp tr-org-todo-line-regexp))
2670 (goto-char (point-min))
2673 (if (re-search-forward
2674 (concat "\\(^\\|\r\\)"
2675 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
2677 (goto-char (match-end 0))
2678 ;; Heading not found, just insert it at the end
2679 (goto-char (point-max))
2680 (or (bolp) (insert "\n"))
2681 (insert "\n" heading "\n")
2683 ;; Make the heading visible, and the following as well
2684 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
2685 (if (re-search-forward
2686 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
2688 (progn (goto-char (match-beginning 0)) (insert "\n")
2689 (beginning-of-line 0))
2690 (goto-char (point-max)) (insert "\n")))
2691 (goto-char (point-max)) (insert "\n"))
2693 (org-paste-subtree (1+ level))
2694 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
2695 (if org-archive-mark-done
2696 (org-todo (length org-todo-keywords)))
2697 ;; Move cursor to right after the TODO keyword
2698 (when org-archive-stamp-time
2699 (beginning-of-line 1)
2700 (looking-at org-todo-line-regexp)
2701 (goto-char (or (match-end 2) (match-beginning 3)))
2702 (insert "(" (format-time-string (cdr org-time-stamp-formats)
2705 ;; Save the buffer, if it is not the same buffer.
2706 (if (not (eq this-buffer buffer)) (save-buffer))))
2707 ;; Here we are back in the original buffer. Everything seems to have
2708 ;; worked. So now cut the tree and finish up.
2709 (let (this-command) (org-cut-subtree))
2710 (if (looking-at "[ \t]*$") (kill-line))
2711 (message "Subtree archived %s"
2712 (if (eq this-buffer buffer)
2713 (concat "under heading: " heading)
2714 (concat "in file: " (abbreviate-file-name file))))))
2718 (defun org-complete (&optional arg)
2719 "Perform completion on word at point.
2720 At the beginning of a headline, this completes TODO keywords as given in
2721 `org-todo-keywords'.
2722 If the current word is preceded by a backslash, completes the TeX symbols
2723 that are supported for HTML support.
2724 If the current word is preceded by \"#+\", completes special words for
2725 setting file options.
2726 At all other locations, this simply calls `ispell-complete-word'."
2729 (let* ((end (point))
2730 (beg (save-excursion
2731 (if (equal (char-before (point)) ?\ ) (backward-char 1))
2732 (skip-chars-backward "a-zA-Z0-9_:$")
2734 (texp (equal (char-before beg) ?\\))
2735 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
2738 (pattern (buffer-substring-no-properties beg end))
2739 (completion-ignore-case opt)
2745 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
2746 (cons (match-string 2 x) (match-string 1 x)))
2747 (org-split-string (org-get-current-options) "\n")))
2751 ((string-match "\\`\\*+[ \t]*\\'"
2752 (buffer-substring (point-at-bol) beg))
2754 (mapcar 'list org-todo-keywords))
2755 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
2756 (completion (try-completion pattern table)))
2757 (cond ((eq completion t)
2758 (if (equal type :opt)
2759 (insert (substring (cdr (assoc (upcase pattern) table))
2760 (length pattern)))))
2762 (message "Can't find completion for \"%s\"" pattern)
2764 ((not (string= pattern completion))
2765 (delete-region beg end)
2766 (if (string-match " +$" completion)
2767 (setq completion (replace-match "" t t completion)))
2769 (if (get-buffer-window "*Completions*")
2770 (delete-window (get-buffer-window "*Completions*")))
2771 (if (and (eq type :todo)
2772 (assoc completion table))
2774 (if (and (equal type :opt) (assoc completion table))
2775 (message (substitute-command-keys
2776 "Press \\[org-complete] again to insert example settings"))))
2778 (message "Making completion list...")
2779 (let ((list (sort (all-completions pattern table) 'string<)))
2780 (with-output-to-temp-buffer "*Completions*"
2781 (display-completion-list list)))
2782 (message "Making completion list...%s" "done"))))))
2784 ;;; Comments, TODO and DEADLINE
2786 (defun org-toggle-comment ()
2787 "Change the COMMENT state of an entry."
2790 (org-back-to-heading)
2791 (if (looking-at (concat outline-regexp
2792 "\\( +\\<" org-comment-string "\\>\\)"))
2793 (replace-match "" t t nil 1)
2794 (if (looking-at outline-regexp)
2796 (goto-char (match-end 0))
2797 (insert " " org-comment-string))))))
2799 (defvar org-last-todo-state-is-todo nil
2800 "This is non-nil when the last TODO state change led to a TODO state.
2801 If the last change removed the TODO tag or switched to DONE, then
2804 (defun org-todo (&optional arg)
2805 "Change the TODO state of an item.
2806 The state of an item is given by a keyword at the start of the heading,
2808 *** TODO Write paper
2811 The different keywords are specified in the variable `org-todo-keywords'. By
2812 default the available states are \"TODO\" and \"DONE\".
2813 So for this example: when the item starts with TODO, it is changed to DONE.
2814 When it starts with DONE, the DONE is removed. And when neither TODO nor
2815 DONE are present, add TODO at the beginning of the heading.
2817 With prefix arg, use completion to determined the new state. With numeric
2818 prefix arg, switch to that state."
2821 (org-back-to-heading)
2822 (if (looking-at outline-regexp) (goto-char (match-end 0)))
2823 (or (looking-at (concat " +" org-todo-regexp " *"))
2825 (let* ((this (match-string 1))
2826 (completion-ignore-case t)
2827 (member (member this org-todo-keywords))
2831 ;; Read a state with completion
2832 (completing-read "State: " (mapcar (lambda(x) (list x))
2836 ;; user requests a specific state
2837 (nth (1- (prefix-numeric-value arg))
2839 ((null member) (car org-todo-keywords))
2840 ((null tail) nil) ;; -> first entry
2841 ((eq org-todo-interpretation 'sequence)
2843 ((memq org-todo-interpretation '(type priority))
2844 (if (eq this-command last-command)
2846 (if (> (length tail) 0) org-done-string nil)))
2848 (next (if state (concat " " state " ") " ")))
2849 (replace-match next t t)
2850 (setq org-last-todo-state-is-todo
2851 (not (equal state org-done-string)))
2852 (run-hooks 'org-after-todo-state-change-hook)))
2853 ;; Fixup cursor location if close to the keyword
2854 (if (and (outline-on-heading-p)
2856 (save-excursion (beginning-of-line 1)
2857 (looking-at org-todo-line-regexp))
2858 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
2860 (goto-char (or (match-end 2) (match-end 1)))
2863 (defun org-show-todo-tree (arg)
2864 "Make a compact tree which shows all headlines marked with TODO.
2865 The tree will show the lines where the regexp matches, and all higher
2866 headlines above the match."
2868 (let ((case-fold-search nil)
2869 (kwd-re (if arg org-todo-regexp org-not-done-regexp)))
2870 (message "%d TODO entries found"
2871 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
2873 (defun org-deadline ()
2874 "Insert the DEADLINE: string to make a deadline.
2875 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2876 to modify it to the correct date."
2879 org-deadline-string " "
2880 (format-time-string (car org-time-stamp-formats)
2881 (org-read-date nil 'to-time)))
2882 (message (substitute-command-keys
2883 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2885 (defun org-schedule ()
2886 "Insert the SCHEDULED: string to schedule a TODO item.
2887 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
2888 to modify it to the correct date."
2891 org-scheduled-string " "
2892 (format-time-string (car org-time-stamp-formats)
2893 (org-read-date nil 'to-time)))
2894 (message (substitute-command-keys
2895 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
2898 (defun org-occur (regexp &optional callback)
2899 "Make a compact tree which shows all matches of REGEXP.
2900 The tree will show the lines where the regexp matches, and all higher
2901 headlines above the match. It will also show the heading after the match,
2902 to make sure editing the matching entry is easy.
2903 if CALLBACK is non-nil, it is a function which is called to confirm
2904 that the match should indeed be shown."
2905 (interactive "sRegexp: ")
2906 (setq regexp (org-check-occur-regexp regexp))
2909 (goto-char (point-min))
2911 (while (re-search-forward regexp nil t)
2912 (when (or (not callback)
2915 (org-show-hierarchy-above))))
2916 (run-hooks 'org-occur-hook)
2918 (message "%d match(es) for regexp %s" cnt regexp))
2921 (defun org-show-hierarchy-above ()
2922 "Make sure point and the headings hierarchy above is visible."
2923 (if (org-on-heading-p t)
2924 (org-flag-heading nil) ; only show the heading
2925 (org-show-hidden-entry)) ; show entire entry
2927 (and org-show-following-heading
2928 (outline-next-heading)
2929 (org-flag-heading nil))) ; show the next heading
2930 (save-excursion ; show all higher headings
2931 (while (condition-case nil
2932 (progn (org-up-heading-all 1) t)
2934 (org-flag-heading nil))))
2938 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
2939 "Regular expression matching the priority indicator.")
2941 (defvar org-remove-priority-next-time nil)
2943 (defun org-priority-up ()
2944 "Increase the priority of the current item."
2948 (defun org-priority-down ()
2949 "Decrease the priority of the current item."
2951 (org-priority 'down))
2953 (defun org-priority (&optional action)
2954 "Change the priority of an item by ARG.
2955 ACTION can be set, up, or down."
2957 (setq action (or action 'set))
2958 (let (current new news have remove)
2960 (org-back-to-heading)
2961 (if (looking-at org-priority-regexp)
2962 (setq current (string-to-char (match-string 2))
2964 (setq current org-default-priority))
2967 (message (format "Priority A-%c, SPC to remove: " org-lowest-priority))
2968 (setq new (read-char-exclusive))
2969 (cond ((equal new ?\ ) (setq remove t))
2970 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
2971 (error "Priority must be between `%c' and `%c'"
2972 ?A org-lowest-priority))))
2974 (setq new (1- current)))
2976 (setq new (1+ current)))
2977 (t (error "Invalid action")))
2978 (setq new (min (max ?A (upcase new)) org-lowest-priority))
2979 (setq news (format "%c" new))
2982 (replace-match "" t t nil 1)
2983 (replace-match news t t nil 2))
2985 (error "No priority cookie found in line")
2986 (looking-at org-todo-line-regexp)
2989 (goto-char (match-end 2))
2990 (insert " [#" news "]"))
2991 (goto-char (match-beginning 3))
2992 (insert "[#" news "] ")))))
2994 (message "Priority removed")
2995 (message "Priority of current item set to %s" news))))
2998 (defun org-get-priority (s)
2999 "Find priority cookie and return priority."
3001 (if (not (string-match org-priority-regexp s))
3002 (* 1000 (- org-lowest-priority org-default-priority))
3003 (* 1000 (- org-lowest-priority
3004 (string-to-char (match-string 2 s)))))))
3008 (defvar org-last-changed-timestamp nil)
3010 (defun org-time-stamp (arg)
3011 "Prompt for a date/time and insert a time stamp.
3012 If the user specifies a time like HH:MM, or if this command is called
3013 with a prefix argument, the time stamp will contain date and time.
3014 Otherwise, only the date will be included. All parts of a date not
3015 specified by the user will be filled in from the current date/time.
3016 So if you press just return without typing anything, the time stamp
3017 will represent the current date/time. If there is already a timestamp
3018 at the cursor, it will be modified."
3020 (let ((fmt (if arg (cdr org-time-stamp-formats)
3021 (car org-time-stamp-formats)))
3022 (org-time-was-given nil)
3025 ((and (org-at-timestamp-p)
3026 (eq last-command 'org-time-stamp)
3027 (eq this-command 'org-time-stamp))
3029 (setq time (let ((this-command this-command))
3030 (org-read-date arg 'totime)))
3031 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3032 (insert (format-time-string fmt time)))
3033 ((org-at-timestamp-p)
3034 (setq time (let ((this-command this-command))
3035 (org-read-date arg 'totime)))
3036 (and (org-at-timestamp-p) (replace-match
3037 (setq org-last-changed-timestamp
3038 (format-time-string fmt time))
3040 (message "Timestamp updated"))
3042 (setq time (let ((this-command this-command))
3043 (org-read-date arg 'totime)))
3044 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3045 (insert (format-time-string fmt time))))))
3047 ;;; FIXME: Make the function take "Fri" as "next friday"
3048 (defun org-read-date (&optional with-time to-time)
3049 "Read a date and make things smooth for the user.
3050 The prompt will suggest to enter an ISO date, but you can also enter anything
3051 which will at least partially be understood by `parse-time-string'.
3052 Unrecognized parts of the date will default to the current day, month ,year,
3053 hour and minute. For example,
3054 3-2-5 --> 2003-02-05
3055 feb 15 --> currentyear-02-15
3056 sep 12 9 --> 2009-09-12
3057 12:45 --> today 12:45
3058 22 sept 0:34 --> currentyear-09-22 0:34
3059 12 --> currentyear-currentmonth-12
3061 The function understands only English month and weekday abbreviations,
3062 but this can be configured with the variables `parse-time-months' and
3063 `parse-time-weekdays'.
3065 While prompting, a calendar is popped up - you can also select the
3066 date with the mouse (button 1). The calendar shows a period of three
3067 month. To scroll it to other months, use the keys `>' and `<'.
3068 If you don't like the calendar, turn it off with
3069 \(setq org-popup-calendar-for-date-prompt nil).
3071 With optional argument TO-TIME, the date will immediately be converted
3072 to an internal time.
3073 With an optional argument WITH-TIME, the prompt will suggest to also
3074 insert a time. Note that when WITH-TIME is not set, you can still
3075 enter a time, and this function will inform the calling routine about
3076 this change. The calling routine may then choose to change the format
3077 used to insert the time stamp into the buffer to include the time."
3078 (let* ((default-time
3079 ;; Default time is either today, or, when entering a range,
3083 (concat org-ts-regexp "--\\=")
3087 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3088 (parse-time-string (match-string 1))))
3090 (timestr (format-time-string
3091 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3092 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3094 second minute hour day month year tl)
3096 (if org-popup-calendar-for-date-prompt
3097 ;; Also show a calendar for date selection
3098 ;; Copied (with modifications) from planner.el by John Wiegley
3100 (save-window-excursion
3102 (calendar-forward-day (- (time-to-days default-time)
3103 (calendar-absolute-from-gregorian
3104 (calendar-current-date))))
3105 (let* ((old-map (current-local-map))
3106 (map (copy-keymap calendar-mode-map))
3107 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
3108 (define-key map (kbd "RET") 'org-calendar-select)
3109 (define-key map (if org-xemacs-p [button1] [mouse-1])
3110 'org-calendar-select)
3111 (define-key minibuffer-local-map [(meta shift left)]
3112 (lambda () (interactive)
3113 (org-eval-in-calendar '(calendar-backward-month 1))))
3114 (define-key minibuffer-local-map [(meta shift right)]
3115 (lambda () (interactive)
3116 (org-eval-in-calendar '(calendar-forward-month 1))))
3117 (define-key minibuffer-local-map [(shift up)]
3118 (lambda () (interactive)
3119 (org-eval-in-calendar '(calendar-backward-week 1))))
3120 (define-key minibuffer-local-map [(shift down)]
3121 (lambda () (interactive)
3122 (org-eval-in-calendar '(calendar-forward-week 1))))
3123 (define-key minibuffer-local-map [(shift left)]
3124 (lambda () (interactive)
3125 (org-eval-in-calendar '(calendar-backward-day 1))))
3126 (define-key minibuffer-local-map [(shift right)]
3127 (lambda () (interactive)
3128 (org-eval-in-calendar '(calendar-forward-day 1))))
3129 (define-key minibuffer-local-map ">"
3130 (lambda () (interactive)
3131 (org-eval-in-calendar '(scroll-calendar-left 1))))
3132 (define-key minibuffer-local-map "<"
3133 (lambda () (interactive)
3134 (org-eval-in-calendar '(scroll-calendar-right 1))))
3138 (setq ans (read-string prompt "" nil nil))
3139 (setq ans (or ans1 ans2 ans)))
3140 (use-local-map old-map)))))
3141 ;; Naked prompt only
3142 (setq ans (read-string prompt "" nil timestr)))
3145 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
3147 (setq year (if (match-end 2)
3148 (string-to-number (match-string 2 ans))
3149 (string-to-number (format-time-string "%Y")))
3150 month (string-to-number (match-string 3 ans))
3151 day (string-to-number (match-string 4 ans)))
3152 (if (< year 100) (setq year (+ 2000 year)))
3153 (setq ans (replace-match (format "%04d-%02d-%02d" year month day)
3155 (setq tl (parse-time-string ans)
3156 year (or (nth 5 tl) (string-to-number (format-time-string "%Y")))
3157 month (or (nth 4 tl) (string-to-number (format-time-string "%m")))
3158 day (or (nth 3 tl) (string-to-number (format-time-string "%d")))
3159 hour (or (nth 2 tl) (string-to-number (format-time-string "%H")))
3160 minute (or (nth 1 tl) (string-to-number (format-time-string "%M")))
3161 second (or (nth 0 tl) 0))
3162 (if (and (boundp 'org-time-was-given)
3164 (setq org-time-was-given t))
3165 (if (< year 100) (setq year (+ 2000 year)))
3167 (encode-time second minute hour day month year)
3168 (if (or (nth 1 tl) (nth 2 tl))
3169 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
3170 (format "%04d-%02d-%02d" year month day)))))
3172 (defun org-eval-in-calendar (form)
3173 "Eval FORM in the calendar window and return to current window.
3174 Also, store the cursor date in variable ans2."
3175 (let ((sw (selected-window)))
3176 (select-window (get-buffer-window "*Calendar*"))
3178 (when (calendar-cursor-to-date)
3179 (let* ((date (calendar-cursor-to-date))
3180 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3181 (setq ans2 (format-time-string "%Y-%m-%d" time))))
3182 (select-window sw)))
3184 (defun org-calendar-select ()
3185 "Return to `org-read-date' with the date currently selected.
3186 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
3188 (when (calendar-cursor-to-date)
3189 (let* ((date (calendar-cursor-to-date))
3190 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
3191 (setq ans1 (format-time-string "%Y-%m-%d" time)))
3192 (if (active-minibuffer-window) (exit-minibuffer))))
3194 (defun org-check-deadlines (ndays)
3195 "Check if there are any deadlines due or past due.
3196 A deadline is considered due if it happens within `org-deadline-warning-days'
3197 days from today's date. If the deadline appears in an entry marked DONE,
3198 it is not shown. The prefix arg NDAYS can be used to test that many
3199 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
3201 (let* ((org-warn-days
3203 ((equal ndays '(4)) 100000)
3204 (ndays (prefix-numeric-value ndays))
3205 (t org-deadline-warning-days)))
3206 (case-fold-search nil)
3207 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
3210 (and (let ((d1 (time-to-days (current-time)))
3212 (org-time-string-to-time (match-string 1)))))
3213 (< (- d2 d1) org-warn-days))
3214 (not (org-entry-is-done-p))))))
3215 (message "%d deadlines past-due or due within %d days"
3216 (org-occur regexp callback)
3219 (defun org-evaluate-time-range (&optional to-buffer)
3220 "Evaluate a time range by computing the difference between start and end.
3221 Normally the result is just printed in the echo area, but with prefix arg
3222 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
3223 If the time range is actually in a table, the result is inserted into the
3225 For time difference computation, a year is assumed to be exactly 365
3226 days in order to avoid rounding problems."
3229 (unless (org-at-date-range-p)
3230 (goto-char (point-at-bol))
3231 (re-search-forward org-tr-regexp (point-at-eol) t))
3232 (if (not (org-at-date-range-p))
3233 (error "Not at a time-stamp range, and none found in current line")))
3234 (let* ((ts1 (match-string 1))
3235 (ts2 (match-string 2))
3236 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
3237 (match-end (match-end 0))
3238 (time1 (org-time-string-to-time ts1))
3239 (time2 (org-time-string-to-time ts2))
3240 (t1 (time-to-seconds time1))
3241 (t2 (time-to-seconds time2))
3242 (diff (abs (- t2 t1)))
3243 (negative (< (- t2 t1) 0))
3244 ;; (ys (floor (* 365 24 60 60)))
3247 (fy "%dy %dd %02d:%02d")
3249 (fd "%dd %02d:%02d")
3253 ;; FIXME: Should I re-introduce years, make year refer to same date?
3254 ;; This would be the only useful way to have years, actually.
3256 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3258 d (floor (/ diff ds)) diff (mod diff ds)
3259 h (floor (/ diff hs)) diff (mod diff hs)
3260 m (floor (/ diff 60)))
3261 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
3263 d (floor (+ (/ diff ds) 0.5))
3266 (message (org-make-tdiff-string y d h m))
3267 (when (org-at-table-p)
3268 (goto-char match-end)
3270 (and (looking-at " *|") (goto-char (match-end 0))))
3272 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
3274 (if negative (insert " -"))
3275 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
3276 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
3277 (insert " " (format fh h m))))
3278 (if align (org-table-align))
3279 (message "Time difference inserted"))))
3281 (defun org-make-tdiff-string (y d h m)
3284 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
3286 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
3288 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
3290 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
3292 (apply 'format fmt (nreverse l))))
3294 (defun org-time-string-to-time (s)
3295 (apply 'encode-time (org-parse-time-string s)))
3297 (defun org-parse-time-string (s &optional nodefault)
3298 "Parse the standard Org-mode time string.
3299 This should be a lot faster than the normal `parse-time-string'.
3300 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
3301 hour and minute fields will be nil if not given."
3302 (if (string-match org-ts-regexp1 s)
3304 (if (or (match-beginning 8) (not nodefault))
3305 (string-to-number (or (match-string 8 s) "0")))
3306 (if (or (match-beginning 7) (not nodefault))
3307 (string-to-number (or (match-string 7 s) "0")))
3308 (string-to-number (match-string 4 s))
3309 (string-to-number (match-string 3 s))
3310 (string-to-number (match-string 2 s))
3314 (defun org-timestamp-up (&optional arg)
3315 "Increase the date item at the cursor by one.
3316 If the cursor is on the year, change the year. If it is on the month or
3317 the day, change that.
3318 With prefix ARG, change by that many units."
3320 (org-timestamp-change (prefix-numeric-value arg)))
3322 (defun org-timestamp-down (&optional arg)
3323 "Decrease the date item at the cursor by one.
3324 If the cursor is on the year, change the year. If it is on the month or
3325 the day, change that.
3326 With prefix ARG, change by that many units."
3328 (org-timestamp-change (- (prefix-numeric-value arg))))
3330 (defun org-timestamp-up-day (&optional arg)
3331 "Increase the date in the time stamp by one day.
3332 With prefix ARG, change that many days."
3334 (org-timestamp-change (prefix-numeric-value arg) 'day))
3336 (defun org-timestamp-down-day (&optional arg)
3337 "Decrease the date in the time stamp by one day.
3338 With prefix ARG, change that many days."
3340 (org-timestamp-change (- (prefix-numeric-value arg)) 'day))
3342 (defsubst org-pos-in-match-range (pos n)
3343 (and (match-beginning n)
3344 (<= (match-beginning n) pos)
3345 (>= (match-end n) pos)))
3347 (defun org-at-timestamp-p ()
3348 "Determine if the cursor is or at a timestamp."
3350 (let* ((tsr org-ts-regexp2)
3352 (ans (or (looking-at tsr)
3354 (skip-chars-backward "^<\n\r\t")
3355 (if (> (point) 1) (backward-char 1))
3356 (and (looking-at tsr)
3357 (> (- (match-end 0) pos) -1))))))
3358 (and (boundp 'org-ts-what)
3361 ((org-pos-in-match-range pos 2) 'year)
3362 ((org-pos-in-match-range pos 3) 'month)
3363 ((org-pos-in-match-range pos 7) 'hour)
3364 ((org-pos-in-match-range pos 8) 'minute)
3365 ((or (org-pos-in-match-range pos 4)
3366 (org-pos-in-match-range pos 5)) 'day)
3370 (defun org-timestamp-change (n &optional what)
3371 "Change the date in the time stamp at point.
3372 The date will be changed by N times WHAT. WHAT can be `day', `month',
3373 `year', `minute', `second'. If WHAT is not given, the cursor position
3374 in the timestamp determines what will be changed."
3375 (let ((fmt (car org-time-stamp-formats))
3379 (if (not (org-at-timestamp-p))
3380 (error "Not at a timestamp"))
3381 (setq org-ts-what (or what org-ts-what))
3382 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
3383 (- (match-end 0) (match-beginning 0))))
3385 (cdr org-time-stamp-formats)
3386 (car org-time-stamp-formats)))
3387 (setq ts (match-string 0))
3389 (setq time0 (org-parse-time-string ts))
3393 (list (or (car time0) 0))
3394 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
3395 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
3396 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
3397 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
3398 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
3400 (if (eq what 'calendar)
3404 (set-buffer "*Calendar*")
3405 (calendar-cursor-to-date)))))
3406 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
3407 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
3408 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
3409 (setcar time0 (or (car time0) 0))
3410 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
3411 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
3412 (setq time (apply 'encode-time time0))))
3413 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
3415 ;; Try to recenter the calendar window, if any
3416 (if (and org-calendar-follow-timestamp-change
3417 (get-buffer-window "*Calendar*" t)
3418 (memq org-ts-what '(day month year)))
3419 (org-recenter-calendar (time-to-days time)))))
3421 (defun org-recenter-calendar (date)
3422 "If the calendar is visible, recenter it to DATE."
3423 (let* ((win (selected-window))
3424 (cwin (get-buffer-window "*Calendar*" t)))
3426 (select-window cwin)
3427 (calendar-goto-date (if (listp date) date
3428 (calendar-gregorian-from-absolute date)))
3429 (select-window win))))
3431 (defun org-goto-calendar (&optional arg)
3432 "Go to the Emacs calendar at the current date.
3433 If there is a time stamp in the current line, go to that date.
3434 A prefix ARG can be used force the current date."
3436 (let ((tsr org-ts-regexp) diff)
3437 (if (or (org-at-timestamp-p)
3439 (beginning-of-line 1)
3440 (looking-at (concat ".*" tsr))))
3441 (let ((d1 (time-to-days (current-time)))
3443 (org-time-string-to-time (match-string 1)))))
3444 (setq diff (- d2 d1))))
3446 (calendar-goto-today)
3447 (if (and diff (not arg)) (calendar-forward-day diff))))
3449 (defun org-date-from-calendar ()
3450 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
3451 If there is already a time stamp at the cursor position, update it."
3453 (org-timestamp-change 0 'calendar))
3455 ;;; Agenda, and Diary Integration
3459 (defvar org-agenda-mode-map (make-sparse-keymap)
3460 "Keymap for `org-agenda-mode'.")
3462 (defvar org-agenda-menu)
3463 (defvar org-agenda-follow-mode nil)
3464 (defvar org-agenda-buffer-name "*Org Agenda*")
3465 (defvar org-agenda-redo-command nil)
3466 (defvar org-agenda-mode-hook nil)
3469 (defun org-agenda-mode ()
3470 "Mode for time-sorted view on action items in Org-mode files.
3472 The following commands are available:
3474 \\{org-agenda-mode-map}"
3476 (kill-all-local-variables)
3477 (setq major-mode 'org-agenda-mode)
3478 (setq mode-name "Org-Agenda")
3479 (use-local-map org-agenda-mode-map)
3480 (easy-menu-add org-agenda-menu)
3481 (if org-startup-truncated (setq truncate-lines t))
3482 (add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
3483 (add-hook 'pre-command-hook 'org-unhighlight nil 'local)
3484 (setq org-agenda-follow-mode nil)
3486 '("Agenda") "Agenda Files"
3489 ["Edit File List" (customize-variable 'org-agenda-files) t]
3491 (mapcar 'org-file-menu-entry org-agenda-files)))
3492 (org-agenda-set-mode-name)
3494 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
3495 org-agenda-mode-hook))
3497 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
3498 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
3499 (define-key org-agenda-mode-map " " 'org-agenda-show)
3500 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
3501 (define-key org-agenda-mode-map "o" 'delete-other-windows)
3502 (define-key org-agenda-mode-map "l" 'org-agenda-recenter)
3503 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
3504 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
3505 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
3506 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
3507 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
3508 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
3510 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
3511 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3512 (while l (define-key org-agenda-mode-map
3513 (int-to-string (pop l)) 'digit-argument)))
3515 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
3516 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
3517 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
3518 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
3519 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
3520 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
3521 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
3522 (define-key org-agenda-mode-map "n" 'next-line)
3523 (define-key org-agenda-mode-map "p" 'previous-line)
3524 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
3525 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
3526 (define-key org-agenda-mode-map "," 'org-agenda-priority)
3527 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
3528 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
3529 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
3530 (eval-after-load "calendar"
3531 '(define-key calendar-mode-map org-calendar-to-agenda-key
3532 'org-calendar-goto-agenda))
3533 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
3534 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
3535 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
3536 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
3537 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
3538 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
3539 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
3540 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
3541 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
3542 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
3543 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
3544 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
3545 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
3547 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
3548 "Local keymap for agenda entries from Org-mode.")
3550 (define-key org-agenda-keymap
3551 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
3552 (define-key org-agenda-keymap
3553 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
3555 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
3559 ["Show" org-agenda-show t]
3560 ["Go To (other window)" org-agenda-goto t]
3561 ["Go To (one window)" org-agenda-switch-to t]
3562 ["Follow Mode" org-agenda-follow-mode
3563 :style toggle :selected org-agenda-follow-mode :active t]
3565 ["Cycle TODO" org-agenda-todo t]
3567 ["Reschedule +1 day" org-agenda-date-later t]
3568 ["Reschedule -1 day" org-agenda-date-earlier t]
3570 ["Reschedule to ..." org-agenda-date-prompt t])
3572 ["Set Priority" org-agenda-priority t]
3573 ["Increase Priority" org-agenda-priority-up t]
3574 ["Decrease Priority" org-agenda-priority-down t]
3575 ["Show Priority" org-agenda-show-priority t])
3577 ["Rebuild buffer" org-agenda-redo t]
3578 ["Goto Today" org-agenda-goto-today t]
3579 ["Next Dates" org-agenda-later (local-variable-p 'starting-day)]
3580 ["Previous Dates" org-agenda-earlier (local-variable-p 'starting-day)]
3582 ["Day View" org-agenda-day-view :active (local-variable-p 'starting-day)
3583 :style radio :selected (equal org-agenda-ndays 1)]
3584 ["Week View" org-agenda-week-view :active (local-variable-p 'starting-day)
3585 :style radio :selected (equal org-agenda-ndays 7)]
3587 ["Include Diary" org-agenda-toggle-diary
3588 :style toggle :selected org-agenda-include-diary :active t]
3589 ["Use Time Grid" org-agenda-toggle-time-grid
3590 :style toggle :selected org-agenda-use-time-grid :active t]
3592 ["New Diary Entry" org-agenda-diary-entry t]
3593 ("Calendar Commands"
3594 ["Goto Calendar" org-agenda-goto-calendar t]
3595 ["Phases of the Moon" org-agenda-phases-of-moon t]
3596 ["Sunrise/Sunset" org-agenda-sunrise-sunset t]
3597 ["Holidays" org-agenda-holidays t]
3598 ["Convert" org-agenda-convert-date t])
3600 ["Quit" org-agenda-quit t]
3601 ["Exit and Release Buffers" org-agenda-exit t]
3604 (defvar org-agenda-markers nil
3605 "List of all currently active markers created by `org-agenda'.")
3606 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
3607 "Creation time of the last agenda marker.")
3609 (defun org-agenda-new-marker (&optional pos)
3610 "Return a new agenda marker.
3611 Org-mode keeps a list of these markers and resets them when they are
3613 (let ((m (copy-marker (or pos (point)))))
3614 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
3615 (push m org-agenda-markers)
3618 (defun org-agenda-maybe-reset-markers (&optional force)
3619 "Reset markers created by `org-agenda'. But only if they are old enough."
3621 (> (- (time-to-seconds (current-time))
3622 org-agenda-last-marker-time)
3624 (while org-agenda-markers
3625 (move-marker (pop org-agenda-markers) nil))))
3627 (defvar org-agenda-new-buffers nil
3628 "Buffers created to visit agenda files.")
3630 (defun org-get-agenda-file-buffer (file)
3631 "Get a buffer visiting FILE. If the buffer needs to be created, add
3632 it to the list of buffers which might be released later."
3633 (let ((buf (find-buffer-visiting file)))
3635 buf ; just return it
3636 ;; Make a new buffer and remember it
3637 (setq buf (find-file-noselect file))
3638 (if buf (push buf org-agenda-new-buffers))
3641 (defun org-release-buffers (blist)
3642 "Release all buffers in list, asking the user for confirmation when needed.
3643 When a buffer is unmodified, it is just killed. When modified, it is saved
3644 \(if the user agrees) and then killed."
3646 (while (setq buf (pop blist))
3647 (setq file (buffer-file-name buf))
3648 (when (and (buffer-modified-p buf)
3650 (y-or-n-p (format "Save file %s? " file)))
3651 (with-current-buffer buf (save-buffer)))
3652 (kill-buffer buf))))
3654 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
3656 (defun org-timeline (&optional include-all)
3657 "Show a time-sorted view of the entries in the current org file.
3658 Only entries with a time stamp of today or later will be listed. With
3659 one \\[universal-argument] prefix argument, past entries will also be listed.
3660 With two \\[universal-argument] prefixes, all unfinished TODO items will also be shown,
3661 under the current date.
3662 If the buffer contains an active region, only check the region for
3666 (org-agenda-maybe-reset-markers 'force)
3667 (org-compile-prefix-format org-timeline-prefix-format)
3668 (let* ((dopast include-all)
3669 (dotodo (equal include-all '(16)))
3670 (entry (buffer-file-name))
3671 (org-agenda-files (list (buffer-file-name)))
3672 (date (calendar-current-date))
3673 (win (selected-window))
3675 (beg (if (org-region-active-p) (region-beginning) (point-min)))
3676 (end (if (org-region-active-p) (region-end) (point-max)))
3677 (day-numbers (org-get-all-dates beg end 'no-ranges
3678 t)) ; always include today
3679 (today (time-to-days (current-time)))
3680 (org-respect-restriction t)
3683 (setq org-agenda-redo-command
3685 (list 'switch-to-buffer-other-window (current-buffer))
3686 (list 'org-timeline (list 'quote include-all))))
3688 ;; Remove past dates from the list of dates.
3689 (setq day-numbers (delq nil (mapcar (lambda(x)
3690 (if (>= x today) x nil))
3692 (switch-to-buffer-other-window
3693 (get-buffer-create org-agenda-buffer-name))
3694 (setq buffer-read-only nil)
3696 (org-agenda-mode) (setq buffer-read-only nil)
3697 (while (setq d (pop day-numbers))
3698 (if (and (>= d today)
3703 (insert (make-string 79 ?-) "\n")))
3704 (setq date (calendar-gregorian-from-absolute d))
3707 (setq rtn (org-agenda-get-day-entries
3708 entry date :todo :timestamp))
3709 (setq rtn (org-agenda-get-day-entries entry date :timestamp)))
3710 (if (or rtn (equal d today))
3712 (insert (calendar-day-name date) " "
3713 (number-to-string (extract-calendar-day date)) " "
3714 (calendar-month-name (extract-calendar-month date)) " "
3715 (number-to-string (extract-calendar-year date)) "\n")
3716 (put-text-property s (1- (point)) 'face
3719 (put-text-property s (1- (point)) 'org-today t))
3720 (insert (org-finalize-agenda-entries rtn) "\n")
3721 (put-text-property s (1- (point)) 'day d))))
3722 (goto-char (point-min))
3723 (setq buffer-read-only t)
3724 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3726 (when (not org-select-timeline-window)
3731 (defun org-agenda (&optional include-all start-day ndays)
3732 "Produce a weekly view from all files in variable `org-agenda-files'.
3733 The view will be for the current week, but from the overview buffer you
3734 will be able to go to other weeks.
3735 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
3736 also be shown, under the current date.
3737 START-DAY defaults to TODAY, or to the most recent match for the weekday
3738 given in `org-agenda-start-on-weekday'.
3739 NDAYS defaults to `org-agenda-ndays'."
3741 (org-agenda-maybe-reset-markers 'force)
3742 (org-compile-prefix-format org-agenda-prefix-format)
3744 (let* ((org-agenda-start-on-weekday
3745 (if (or (equal ndays 1)
3746 (and (null ndays) (equal 1 org-agenda-ndays)))
3747 nil org-agenda-start-on-weekday))
3748 (files (copy-sequence org-agenda-files))
3749 (win (selected-window))
3750 (today (time-to-days (current-time)))
3751 (sd (or start-day today))
3752 (start (if (or (null org-agenda-start-on-weekday)
3753 (< org-agenda-ndays 7))
3755 (let* ((nt (calendar-day-of-week
3756 (calendar-gregorian-from-absolute sd)))
3757 (n1 org-agenda-start-on-weekday)
3759 (- sd (+ (if (< d 0) 7 0) d)))))
3760 (day-numbers (list start))
3761 (inhibit-redisplay t)
3762 s e rtn rtnall file date d start-pos end-pos todayp nd)
3763 (setq org-agenda-redo-command
3764 (list 'org-agenda (list 'quote include-all) start-day ndays))
3765 ;; Make the list of days
3766 (setq ndays (or ndays org-agenda-ndays)
3769 (push (1+ (car day-numbers)) day-numbers)
3770 (setq ndays (1- ndays)))
3771 (setq day-numbers (nreverse day-numbers))
3772 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
3774 (delete-other-windows)
3775 (switch-to-buffer-other-window
3776 (get-buffer-create org-agenda-buffer-name))))
3777 (setq buffer-read-only nil)
3779 (org-agenda-mode) (setq buffer-read-only nil)
3780 (set (make-local-variable 'starting-day) (car day-numbers))
3781 (set (make-local-variable 'include-all-loc) include-all)
3782 (when (and (or include-all org-agenda-include-all-todo)
3783 (member today day-numbers))
3784 (setq files org-agenda-files
3786 (while (setq file (pop files))
3788 (org-check-agenda-file file)
3789 (setq date (calendar-gregorian-from-absolute today)
3790 rtn (org-agenda-get-day-entries
3792 (setq rtnall (append rtnall rtn))))
3794 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
3795 (add-text-properties (point-min) (1- (point))
3796 (list 'face 'org-link))
3797 (insert (org-finalize-agenda-entries rtnall) "\n")))
3798 (while (setq d (pop day-numbers))
3799 (setq date (calendar-gregorian-from-absolute d)
3801 (if (or (setq todayp (= d today))
3802 (and (not start-pos) (= d sd)))
3803 (setq start-pos (point))
3804 (if (and start-pos (not end-pos))
3805 (setq end-pos (point))))
3806 (setq files org-agenda-files
3808 (while (setq file (pop files))
3810 (org-check-agenda-file file)
3811 (setq rtn (org-agenda-get-day-entries file date))
3812 (setq rtnall (append rtnall rtn))))
3813 (if org-agenda-include-diary
3815 (require 'diary-lib)
3816 (setq rtn (org-get-entries-from-diary date))
3817 (setq rtnall (append rtnall rtn))))
3818 (if (or rtnall org-agenda-show-all-dates)
3820 (insert (format "%-9s %2d %s %4d\n"
3821 (calendar-day-name date)
3822 (extract-calendar-day date)
3823 (calendar-month-name (extract-calendar-month date))
3824 (extract-calendar-year date)))
3825 (put-text-property s (1- (point)) 'face
3828 (org-finalize-agenda-entries ;; FIXME: condition needed
3829 (org-agenda-add-time-grid-maybe
3832 (put-text-property s (1- (point)) 'day d))))
3833 (goto-char (point-min))
3834 (setq buffer-read-only t)
3835 (if org-fit-agenda-window
3836 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
3837 (/ (frame-height) 2)))
3838 (unless (and (pos-visible-in-window-p (point-min))
3839 (pos-visible-in-window-p (point-max)))
3840 (goto-char (1- (point-max)))
3842 (if (not (pos-visible-in-window-p (or start-pos 1)))
3844 (goto-char (or start-pos 1))
3846 (goto-char (or start-pos 1))
3847 (if (not org-select-agenda-window) (select-window win))
3850 (defun org-check-agenda-file (file)
3851 "Make sure FILE exists. If not, ask user what to do."
3852 ;; FIXME: this does not correctly change the menus
3853 ;; Could probably be fixed by explicitly going to the buffer.
3854 (when (not (file-exists-p file))
3855 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
3857 (let ((r (downcase (read-char-exclusive))))
3860 (org-remove-file file)
3861 (throw 'nextfile t))
3862 (t (error "Abort"))))))
3864 (defun org-agenda-quit ()
3865 "Exit agenda by removing the window or the buffer."
3867 (let ((buf (current-buffer)))
3868 (if (not (one-window-p)) (delete-window))
3870 (org-agenda-maybe-reset-markers 'force)))
3872 (defun org-agenda-exit ()
3873 "Exit agenda by removing the window or the buffer.
3874 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
3875 Org-mode buffers visited directly by the user will not be touched."
3877 (org-release-buffers org-agenda-new-buffers)
3878 (setq org-agenda-new-buffers nil)
3881 (defun org-agenda-redo ()
3884 (eval org-agenda-redo-command))
3886 (defun org-agenda-goto-today ()
3889 (if (boundp 'starting-day)
3890 (let ((cmd (car org-agenda-redo-command))
3891 (iall (nth 1 org-agenda-redo-command))
3892 (nday (nth 3 org-agenda-redo-command)))
3893 (eval (list cmd iall nil nday)))
3894 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
3897 (defun org-agenda-later (arg)
3898 "Go forward in time by `org-agenda-ndays' days.
3899 With prefix ARG, go forward that many times `org-agenda-ndays'."
3901 (unless (boundp 'starting-day)
3902 (error "Not allowed"))
3903 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3904 (+ starting-day (* arg org-agenda-ndays))))
3906 (defun org-agenda-earlier (arg)
3907 "Go back in time by `org-agenda-ndays' days.
3908 With prefix ARG, go back that many times `org-agenda-ndays'."
3910 (unless (boundp 'starting-day)
3911 (error "Not allowed"))
3912 (org-agenda (if (boundp 'include-all-loc) include-all-loc nil)
3913 (- starting-day (* arg org-agenda-ndays))))
3915 (defun org-agenda-week-view ()
3916 "Switch to weekly view for agenda."
3918 (unless (boundp 'starting-day)
3919 (error "Not allowed"))
3920 (setq org-agenda-ndays 7)
3921 (org-agenda include-all-loc
3922 (or (get-text-property (point) 'day)
3924 (org-agenda-set-mode-name)
3925 (message "Switched to week view"))
3927 (defun org-agenda-day-view ()
3928 "Switch to weekly view for agenda."
3930 (unless (boundp 'starting-day)
3931 (error "Not allowed"))
3932 (setq org-agenda-ndays 1)
3933 (org-agenda include-all-loc
3934 (or (get-text-property (point) 'day)
3936 (org-agenda-set-mode-name)
3937 (message "Switched to day view"))
3939 (defun org-agenda-next-date-line (&optional arg)
3940 "Jump to the next line indicating a date in agenda buffer."
3942 (beginning-of-line 1)
3943 (if (looking-at "^\\S-") (forward-char 1))
3944 (if (not (re-search-forward "^\\S-" nil t arg))
3947 (error "No next date after this line in this buffer")))
3948 (goto-char (match-beginning 0)))
3950 (defun org-agenda-previous-date-line (&optional arg)
3951 "Jump to the next line indicating a date in agenda buffer."
3953 (beginning-of-line 1)
3954 (if (not (re-search-backward "^\\S-" nil t arg))
3955 (error "No previous date before this line in this buffer")))
3957 ;; Initialize the highlight
3958 (defvar org-hl (funcall (if org-xemacs-p 'make-extent 'make-overlay) 1 1))
3959 (funcall (if org-xemacs-p 'set-extent-property 'overlay-put) org-hl
3962 (defun org-highlight (begin end &optional buffer)
3963 "Highlight a region with overlay."
3964 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
3965 org-hl begin end (or buffer (current-buffer))))
3967 (defun org-unhighlight ()
3968 "Detach overlay INDEX."
3969 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
3972 (defun org-agenda-follow-mode ()
3973 "Toggle follow mode in an agenda buffer."
3975 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
3976 (org-agenda-set-mode-name)
3977 (message "Follow mode is %s"
3978 (if org-agenda-follow-mode "on" "off")))
3980 (defun org-agenda-toggle-diary ()
3981 "Toggle follow mode in an agenda buffer."
3983 (setq org-agenda-include-diary (not org-agenda-include-diary))
3985 (org-agenda-set-mode-name)
3986 (message "Diary inclusion turned %s"
3987 (if org-agenda-include-diary "on" "off")))
3989 (defun org-agenda-toggle-time-grid ()
3990 "Toggle follow mode in an agenda buffer."
3992 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
3994 (org-agenda-set-mode-name)
3995 (message "Time-grid turned %s"
3996 (if org-agenda-use-time-grid "on" "off")))
3998 (defun org-agenda-set-mode-name ()
3999 "Set the mode name to indicate all the small mode settings."
4001 (concat "Org-Agenda"
4002 (if (equal org-agenda-ndays 1) " Day" "")
4003 (if (equal org-agenda-ndays 7) " Week" "")
4004 (if org-agenda-follow-mode " Follow" "")
4005 (if org-agenda-include-diary " Diary" "")
4006 (if org-agenda-use-time-grid " Grid" "")))
4007 (force-mode-line-update))
4009 (defun org-agenda-post-command-hook ()
4010 (and (eolp) (not (bolp)) (backward-char 1))
4011 (if (and org-agenda-follow-mode
4012 (get-text-property (point) 'org-marker))
4015 (defvar org-disable-diary nil) ;Dynamically-scoped param.
4017 (defun org-get-entries-from-diary (date)
4018 "Get the (Emacs Calendar) diary entries for DATE."
4019 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
4020 (diary-display-hook '(fancy-diary-display))
4021 (list-diary-entries-hook
4022 (cons 'org-diary-default-entry list-diary-entries-hook))
4024 (org-disable-diary t))
4026 (save-window-excursion
4027 (list-diary-entries date 1)))
4028 (if (not (get-buffer fancy-diary-buffer))
4030 (with-current-buffer fancy-diary-buffer
4031 (setq buffer-read-only nil)
4032 (if (= (point-max) 1)
4035 ;; Omit the date and other unnecessary stuff
4036 (org-agenda-cleanup-fancy-diary)
4037 ;; Add prefix to each line and extend the text properties
4038 (if (= (point-max) 1)
4040 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
4041 (set-buffer-modified-p nil)
4042 (kill-buffer fancy-diary-buffer)))
4044 (setq entries (org-split-string entries "\n"))
4048 (setq x (org-format-agenda-item "" x "Diary" 'time))
4049 ;; Extend the text properties to the beginning of the line
4050 (add-text-properties
4052 (text-properties-at (1- (length x)) x)
4057 (defun org-agenda-cleanup-fancy-diary ()
4058 "Remove unwanted stuff in buffer created by fancy-diary-display.
4059 This gets rid of the date, the underline under the date, and
4060 the dummy entry installed by `org-mode' to ensure non-empty diary for each
4061 date. Itt also removes lines that contain only whitespace."
4062 (goto-char (point-min))
4063 (if (looking-at ".*?:[ \t]*")
4066 (re-search-forward "\n=+$" nil t)
4068 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
4069 (re-search-forward "\n=+$" nil t)
4070 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
4071 (goto-char (point-min))
4072 (while (re-search-forward "^ +\n" nil t)
4074 (goto-char (point-min))
4075 (if (re-search-forward "^Org-mode dummy\n?" nil t)
4076 (replace-match "")))
4078 ;; Advise the add-to-diary-list function to allow org to jump to
4079 ;; diary entries. Wrapped into eval-after-load to avoid loading
4080 ;; advice unnecessarily
4081 (eval-after-load "diary-lib"
4082 '(defadvice add-to-diary-list (before org-mark-diary-entry activate)
4083 "Make the position visible."
4084 (if (and org-disable-diary ;; called from org-agenda
4087 (add-text-properties
4089 (list 'mouse-face 'highlight
4090 'keymap org-agenda-keymap
4093 "mouse-2 or RET jump to diary file %s"
4094 (abbreviate-file-name (buffer-file-name)))
4095 'org-agenda-diary-link t
4096 'org-marker (org-agenda-new-marker (point-at-bol)))
4099 (defun org-diary-default-entry ()
4100 "Add a dummy entry to the diary.
4101 Needed to avoid empty dates which mess up holiday display."
4102 ;; Catch the error if dealing with the new add-to-diary-alist
4104 (add-to-diary-list original-date "Org-mode dummy" "")
4106 (add-to-diary-list original-date "Org-mode dummy" "" nil))))
4108 (defun org-add-file (&optional file)
4109 "Add current file to the list of files in variable `org-agenda-files'.
4110 These are the files which are being checked for agenda entries.
4111 Optional argument FILE means, use this file instead of the current.
4112 It is possible (but not recommended) to add this function to the
4116 (let* ((file (or file (buffer-file-name)
4118 (error "Buffer is not visiting a file")
4119 (throw 'exit nil))))
4120 (true-file (file-truename file))
4121 (afile (abbreviate-file-name file))
4122 (present (delq nil (mapcar
4124 (equal true-file (file-truename x)))
4125 org-agenda-files))))
4128 (setq org-agenda-files
4129 (cons afile org-agenda-files))
4130 ;; Make sure custom.el does not end up with Org-mode
4131 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
4132 (customize-save-variable 'org-agenda-files org-agenda-files))
4133 (org-install-agenda-files-menu)
4134 (message "Added file: %s" afile))
4135 (message "File was already in list: %s" afile)))))
4137 (defun org-remove-file (&optional file)
4138 "Remove current file from the list of files in variable `org-agenda-files'.
4139 These are the files which are being checked for agenda entries.
4140 Optional argument FILE means, use this file instead of the current."
4142 (let* ((file (or file (buffer-file-name)))
4143 (true-file (file-truename file))
4144 (afile (abbreviate-file-name file))
4145 (files (delq nil (mapcar
4147 (if (equal true-file
4150 org-agenda-files))))
4151 (if (not (= (length files) (length org-agenda-files)))
4153 (setq org-agenda-files files)
4154 (customize-save-variable 'org-agenda-files org-agenda-files)
4155 (org-install-agenda-files-menu)
4156 (message "Removed file: %s" afile))
4157 (message "File was not in list: %s" afile))))
4159 (defun org-file-menu-entry (file)
4160 (vector file (list 'find-file file) t))
4162 (defun org-get-all-dates (beg end &optional no-ranges force-today)
4163 "Return a list of all relevant day numbers from BEG to END buffer positions.
4164 If NO-RANGES is non-nil, include only the start and end dates of a range,
4165 not every single day in the range. If FORCE-TODAY is non-nil, make
4166 sure that TODAY is included in the list."
4167 (let (dates date day day1 day2 ts1 ts2)
4169 (setq dates (list (time-to-days (current-time)))))
4172 (while (re-search-forward org-ts-regexp end t)
4173 (setq day (time-to-days (org-time-string-to-time
4174 (substring (match-string 1) 0 10))))
4175 (or (memq day dates) (push day dates)))
4178 (while (re-search-forward org-tr-regexp end t)
4179 (setq ts1 (substring (match-string 1) 0 10)
4180 ts2 (substring (match-string 2) 0 10)
4181 day1 (time-to-days (org-time-string-to-time ts1))
4182 day2 (time-to-days (org-time-string-to-time ts2)))
4183 (while (< (setq day1 (1+ day1)) day2)
4184 (or (memq day1 dates) (push day1 dates)))))
4188 (defun org-diary (&rest args)
4189 "Return diary information from org-files.
4190 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
4191 It accesses org files and extracts information from those files to be
4192 listed in the diary. The function accepts arguments specifying what
4193 items should be listed. The following arguments are allowed:
4195 :timestamp List the headlines of items containing a date stamp or
4196 date range matching the selected date. Deadlines will
4197 also be listed, on the expiration day.
4199 :deadline List any deadlines past due, or due within
4200 `org-deadline-warning-days'. The listing occurs only
4201 in the diary for *today*, not at any other date. If
4202 an entry is marked DONE, it is no longer listed.
4204 :scheduled List all items which are scheduled for the given date.
4205 The diary for *today* also contains items which were
4206 scheduled earlier and are not yet marked DONE.
4208 :todo List all TODO items from the org-file. This may be a
4209 long list - so this is not turned on by default.
4210 Like deadlines, these entries only show up in the
4211 diary for *today*, not at any other date.
4213 The call in the diary file should look like this:
4215 &%%(org-diary) ~/path/to/some/orgfile.org
4217 Use a separate line for each org file to check. Or, if you omit the file name,
4218 all files listed in `org-agenda-files' will be checked automatically:
4222 If you don't give any arguments (as in the example above), the default
4223 arguments (:deadline :scheduled :timestamp) are used. So the example above may
4226 &%%(org-diary :deadline :timestamp :scheduled)
4228 The function expects the lisp variables `entry' and `date' to be provided
4229 by the caller, because this is how the calendar works. Don't use this
4230 function from a program - use `org-agenda-get-day-entries' instead."
4231 (org-agenda-maybe-reset-markers)
4232 (org-compile-prefix-format org-agenda-prefix-format)
4233 (setq args (or args '(:deadline :scheduled :timestamp)))
4234 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
4238 ;; If this is called during org-agenda, don't return any entries to
4239 ;; the calendar. Org Agenda will list these entries itself.
4240 (if org-disable-diary (setq files nil))
4241 (while (setq file (pop files))
4242 (setq rtn (apply 'org-agenda-get-day-entries file date args))
4243 (setq results (append results rtn)))
4244 (concat (org-finalize-agenda-entries results) "\n")))
4246 (defun org-agenda-get-day-entries (file date &rest args)
4247 "Does the work for `org-diary' and `org-agenda'.
4248 FILE is the path to a file to be checked for entries. DATE is date like
4249 the one returned by `calendar-current-date'. ARGS are symbols indicating
4250 which kind of entries should be extracted. For details about these, see
4251 the documentation of `org-diary'."
4252 (setq args (or args '(:deadline :scheduled :timestamp)))
4253 (let* ((org-startup-with-deadline-check nil)
4254 (org-startup-folded nil)
4255 (buffer (if (file-exists-p file)
4256 (org-get-agenda-file-buffer file)
4257 (error "No such file %s" file)))
4260 ;; If file does not exist, make sure an error message ends up in diary
4261 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
4262 (with-current-buffer buffer
4263 (unless (eq major-mode 'org-mode)
4264 (error "Agenda file %s is not in `org-mode'" file))
4265 (let ((case-fold-search nil))
4268 (if org-respect-restriction
4269 (if (org-region-active-p)
4270 ;; Respect a region to restrict search
4271 (narrow-to-region (region-beginning) (region-end)))
4272 ;; If we work for the calendar or many files,
4273 ;; get rid of any restriction
4275 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
4276 (while (setq arg (pop args))
4278 ((and (eq arg :todo)
4279 (equal date (calendar-current-date)))
4280 (setq rtn (org-agenda-get-todos))
4281 (setq results (append results rtn)))
4282 ((eq arg :timestamp)
4283 (setq rtn (org-agenda-get-blocks))
4284 (setq results (append results rtn))
4285 (setq rtn (org-agenda-get-timestamps))
4286 (setq results (append results rtn)))
4287 ((eq arg :scheduled)
4288 (setq rtn (org-agenda-get-scheduled))
4289 (setq results (append results rtn)))
4290 ((and (eq arg :deadline)
4291 (equal date (calendar-current-date)))
4292 (setq rtn (org-agenda-get-deadlines))
4293 (setq results (append results rtn))))))))
4296 (defun org-entry-is-done-p ()
4297 "Is the current entry marked DONE?"
4299 (and (re-search-backward "[\r\n]\\*" nil t)
4300 (looking-at org-nl-done-regexp))))
4302 (defun org-at-date-range-p ()
4303 "Is the cursor inside a date range?"
4307 (let ((pos (point)))
4308 (skip-chars-backward "^<\r\n")
4309 (skip-chars-backward "<")
4310 (and (looking-at org-tr-regexp)
4311 (>= (match-end 0) pos)
4313 (skip-chars-backward "^<\r\n")
4314 (skip-chars-backward "<")
4315 (and (looking-at org-tr-regexp)
4316 (>= (match-end 0) pos)
4320 (defun org-agenda-get-todos ()
4321 "Return the TODO information for agenda display."
4322 (let* ((props (list 'face nil
4323 'done-face 'org-done
4324 'mouse-face 'highlight
4325 'keymap org-agenda-keymap
4327 (format "mouse-2 or RET jump to org file %s"
4328 (abbreviate-file-name (buffer-file-name)))))
4329 (regexp (concat "[\n\r]\\*+ *\\(" org-not-done-regexp
4333 (goto-char (point-min))
4334 (while (re-search-forward regexp nil t)
4335 (goto-char (match-beginning 1))
4336 (setq marker (org-agenda-new-marker (point-at-bol))
4337 txt (org-format-agenda-item "" (match-string 1))
4339 (+ (org-get-priority txt)
4340 (if org-todo-kwd-priority-p
4341 (- org-todo-kwd-max-priority -2
4343 (member (match-string 2) org-todo-keywords)))
4345 (add-text-properties
4346 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
4351 (goto-char (match-end 1)))
4354 (defconst org-agenda-no-heading-message
4355 "No heading for this item in buffer or region")
4357 (defun org-agenda-get-timestamps ()
4358 "Return the date stamp information for agenda display."
4359 (let* ((props (list 'face nil
4360 'mouse-face 'highlight
4361 'keymap org-agenda-keymap
4363 (format "mouse-2 or RET jump to org file %s"
4364 (abbreviate-file-name (buffer-file-name)))))
4365 (regexp (regexp-quote
4368 (car org-time-stamp-formats)
4369 (apply 'encode-time ; DATE bound by calendar
4370 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
4372 marker hdmarker deadlinep scheduledp donep tmp priority
4374 (goto-char (point-min))
4375 (while (re-search-forward regexp nil t)
4376 (if (not (save-match-data (org-at-date-range-p)))
4378 (setq marker (org-agenda-new-marker (match-beginning 0))
4379 tmp (buffer-substring (max (point-min)
4380 (- (match-beginning 0)
4381 org-ds-keyword-length))
4382 (match-beginning 0))
4383 timestr (buffer-substring (match-beginning 0) (point-at-eol))
4384 deadlinep (string-match org-deadline-regexp tmp)
4385 scheduledp (string-match org-scheduled-regexp tmp)
4386 donep (org-entry-is-done-p))
4387 (if (string-match ">" timestr)
4388 ;; substring should only run to end of time stamp
4389 (setq timestr (substring timestr 0 (match-end 0))))
4391 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4393 (goto-char (match-end 1))
4394 (setq hdmarker (org-agenda-new-marker))
4395 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4396 (setq txt (org-format-agenda-item
4398 (if deadlinep "Deadline: " "")
4399 (if scheduledp "Scheduled: " ""))
4400 (match-string 1) nil timestr)))
4401 (setq txt org-agenda-no-heading-message))
4402 (setq priority (org-get-priority txt))
4403 (add-text-properties
4404 0 (length txt) (append (list 'org-marker marker
4405 'org-hd-marker hdmarker) props)
4408 (add-text-properties
4411 (if donep 'org-done 'org-warning)
4412 'undone-face 'org-warning
4413 'done-face 'org-done
4414 'priority (+ 100 priority))
4417 (add-text-properties
4419 (list 'face 'org-scheduled-today
4420 'undone-face 'org-scheduled-today
4421 'done-face 'org-done
4422 priority (+ 99 priority))
4424 (add-text-properties
4426 (list 'priority priority) txt)))
4428 (outline-next-heading))))
4431 (defun org-agenda-get-deadlines ()
4432 "Return the deadline information for agenda display."
4433 (let* ((wdays org-deadline-warning-days)
4434 (props (list 'mouse-face 'highlight
4435 'keymap org-agenda-keymap
4437 (format "mouse-2 or RET jump to org file %s"
4438 (abbreviate-file-name (buffer-file-name)))))
4439 (regexp org-deadline-time-regexp)
4440 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4441 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4444 (goto-char (point-min))
4445 (while (re-search-forward regexp nil t)
4446 (setq pos (1- (match-beginning 1))
4448 (org-time-string-to-time (match-string 1)))
4450 ;; When to show a deadline in the calendar:
4451 ;; If the expiration is within wdays warning time.
4452 ;; Past-due deadlines are only shown on the current date
4453 (if (and (< diff wdays) todayp (not (= diff 0)))
4455 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4457 (goto-char (match-end 0))
4458 (setq pos1 (match-end 1))
4459 (setq head (buffer-substring-no-properties
4461 (progn (skip-chars-forward "^\r\n")
4463 (if (string-match org-looking-at-done-regexp head)
4465 (setq txt (org-format-agenda-item
4466 (format "In %3d d.: " diff) head))))
4467 (setq txt org-agenda-no-heading-message))
4469 (add-text-properties
4472 (list 'org-marker (org-agenda-new-marker pos)
4473 'org-hd-marker (org-agenda-new-marker pos1)
4474 'priority (+ (- 10 diff) (org-get-priority txt))
4475 'face (cond ((<= diff 0) 'org-warning)
4476 ((<= diff 5) 'org-scheduled-previously)
4479 ((<= diff 0) 'org-warning)
4480 ((<= diff 5) 'org-scheduled-previously)
4482 'done-face 'org-done)
4488 (defun org-agenda-get-scheduled ()
4489 "Return the scheduled information for agenda display."
4490 (let* ((props (list 'face 'org-scheduled-previously
4491 'undone-face 'org-scheduled-previously
4492 'done-face 'org-done
4493 'mouse-face 'highlight
4494 'keymap org-agenda-keymap
4496 (format "mouse-2 or RET jump to org file %s"
4497 (abbreviate-file-name (buffer-file-name)))))
4498 (regexp org-scheduled-time-regexp)
4499 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
4500 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
4503 (goto-char (point-min))
4504 (while (re-search-forward regexp nil t)
4505 (setq pos (1- (match-beginning 1))
4507 (org-time-string-to-time (match-string 1)))
4509 ;; When to show a scheduled item in the calendar:
4510 ;; If it is on or past the date.
4511 (if (and (< diff 0) todayp)
4513 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
4515 (goto-char (match-end 0))
4516 (setq pos1 (match-end 1))
4517 (setq head (buffer-substring-no-properties
4519 (progn (skip-chars-forward "^\r\n") (point))))
4520 (if (string-match org-looking-at-done-regexp head)
4522 (setq txt (org-format-agenda-item
4523 (format "Sched.%2dx: " (- 1 diff)) head))))
4524 (setq txt org-agenda-no-heading-message))
4526 (add-text-properties
4528 (append (list 'org-marker (org-agenda-new-marker pos)
4529 'org-hd-marker (org-agenda-new-marker pos1)
4530 'priority (+ (- 5 diff) (org-get-priority txt)))
4535 (defun org-agenda-get-blocks ()
4536 "Return the date-range information for agenda display."
4537 (let* ((props (list 'face nil
4538 'mouse-face 'highlight
4539 'keymap org-agenda-keymap
4541 (format "mouse-2 or RET jump to org file %s"
4542 (abbreviate-file-name (buffer-file-name)))))
4543 (regexp org-tr-regexp)
4544 (d0 (calendar-absolute-from-gregorian date))
4545 marker hdmarker ee txt d1 d2 s1 s2 timestr)
4546 (goto-char (point-min))
4547 (while (re-search-forward regexp nil t)
4548 (setq timestr (match-string 0)
4551 d1 (time-to-days (org-time-string-to-time s1))
4552 d2 (time-to-days (org-time-string-to-time s2)))
4553 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
4554 ;; Only allow days between the limits, because the normal
4555 ;; date stamps will catch the limits.
4557 (setq marker (org-agenda-new-marker (point)))
4558 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
4560 (setq hdmarker (org-agenda-new-marker (match-end 1)))
4561 (goto-char (match-end 1))
4562 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
4563 (setq txt (org-format-agenda-item
4564 (format (if (= d1 d2) "" "(%d/%d): ")
4565 (1+ (- d0 d1)) (1+ (- d2 d1)))
4566 (match-string 1) nil (if (= d0 d1) timestr))))
4567 (setq txt org-agenda-no-heading-message))
4568 (add-text-properties
4569 0 (length txt) (append (list 'org-marker marker
4570 'org-hd-marker hdmarker
4571 'priority (org-get-priority txt))
4575 (outline-next-heading))
4576 ;; Sort the entries by expiration date.
4581 (defconst org-plain-time-of-day-regexp
4584 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4587 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
4589 "Regular expression to match a plain time or time range.
4590 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
4591 groups carry important information:
4593 1 the first time, range or not
4594 8 the second time, if it is a range.")
4596 (defconst org-stamp-time-of-day-regexp
4598 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
4599 "\\([012][0-9]:[0-5][0-9]\\)>"
4601 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
4602 "Regular expression to match a timestamp time or time range.
4603 After a match, the following groups carry important information:
4605 1 date plus weekday, for backreferencing to make sure both times on same day
4606 2 the first time, range or not
4607 4 the second time, if it is a range.")
4609 (defvar org-prefix-has-time nil
4610 "A flag, set by `org-compile-prefix-format'.
4611 The flag is set if the currently compiled format contains a `%t'.")
4613 (defun org-format-agenda-item (extra txt &optional category dotime noprefix)
4614 "Format TXT to be inserted into the agenda buffer.
4615 In particular, it adds the prefix and corresponding text properties. EXTRA
4616 must be a string and replaces the `%s' specifier in the prefix format.
4617 CATEGORY (string, symbol or nil) may be used to overule the default
4618 category taken from local variable or file name. It will replace the `%c'
4619 specifier in the format. DOTIME, when non-nil, indicates that a
4620 time-of-day should be extracted from TXT for sorting of this entry, and for
4621 the `%t' specifier in the format. When DOTIME is a string, this string is
4622 searched for a time before TXT is. NOPREFIX is a flag and indicates that
4623 only the correctly processes TXT should be returned - this is used by
4624 `org-agenda-change-all-lines'."
4626 ;; Diary entries sometimes have extra whitespace at the beginning
4627 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
4628 (let* ((category (or category
4630 (if (buffer-file-name)
4631 (file-name-sans-extension
4632 (file-name-nondirectory (buffer-file-name)))
4634 time ;; needed for the eval of the prefix format
4635 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
4636 (time-of-day (and dotime (org-get-time-of-day ts)))
4637 stamp plain s0 s1 s2 rtn)
4638 (when (and dotime time-of-day org-prefix-has-time)
4639 ;; Extract starting and ending time and move them to prefix
4640 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
4641 (setq plain (string-match org-plain-time-of-day-regexp ts)))
4642 (setq s0 (match-string 0 ts)
4643 s1 (match-string (if plain 1 2) ts)
4644 s2 (match-string (if plain 8 4) ts))
4646 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
4647 ;; them, we might want to remove them there to avoid duplication.
4648 ;; The user can turn this off with a variable.
4649 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
4650 (string-match (concat (regexp-quote s0) " *") txt)
4651 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
4652 (= (match-beginning 0) 0)
4654 (setq txt (replace-match "" nil nil txt))))
4655 ;; Normalize the time(s) to 24 hour
4656 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
4657 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
4659 ;; Create the final string
4662 ;; Prepare the variables needed in the eval of the compiled format
4663 (setq time (cond (s2 (concat s1 "-" s2))
4664 (s1 (concat s1 "......"))
4667 category (if (symbolp category) (symbol-name category) category))
4668 ;; Evaluate the compiled format
4669 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
4671 ;; And finally add the text properties
4672 (add-text-properties
4673 0 (length rtn) (list 'category (downcase category)
4674 'prefix-length (- (length rtn) (length txt))
4675 'time-of-day time-of-day
4680 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
4682 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
4683 ((and todayp (member 'today (car org-agenda-time-grid))))
4684 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
4685 ((member 'weekly (car org-agenda-time-grid)))
4686 (t (throw 'exit list)))
4687 (let* ((have (delq nil (mapcar
4688 (lambda (x) (get-text-property 1 'time-of-day x))
4690 (string (nth 1 org-agenda-time-grid))
4691 (gridtimes (nth 2 org-agenda-time-grid))
4692 (req (car org-agenda-time-grid))
4693 (remove (member 'remove-match req))
4695 (if (and (member 'require-timed req) (not have))
4696 ;; don't show empty grid
4698 (while (setq time (pop gridtimes))
4699 (unless (and remove (member time have))
4700 (setq time (int-to-string time))
4701 (push (org-format-agenda-item
4702 nil string "" ;; FIXME: put a category?
4703 (concat (substring time 0 -2) ":" (substring time -2)))
4706 1 (length (car new)) 'face 'org-time-grid (car new))))
4707 (if (member 'time-up org-agenda-sorting-strategy)
4709 (append list new)))))
4711 (defun org-compile-prefix-format (format)
4712 "Compile the prefix format into a Lisp form that can be evaluated.
4713 The resulting form is returned and stored in the variable
4714 `org-prefix-format-compiled'."
4715 (setq org-prefix-has-time nil)
4716 (let ((start 0) varform vars var (s format) c f opt)
4717 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
4719 (setq var (cdr (assoc (match-string 4 s)
4720 '(("c" . category) ("t" . time) ("s" . extra))))
4721 c (or (match-string 3 s) "")
4722 opt (match-beginning 1)
4723 start (1+ (match-beginning 0)))
4724 (if (equal var 'time) (setq org-prefix-has-time t))
4725 (setq f (concat "%" (match-string 2 s) "s"))
4728 `(if (equal "" ,var)
4730 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
4731 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
4732 (setq s (replace-match "%s" t nil s))
4733 (push varform vars))
4734 (setq vars (nreverse vars))
4735 (setq org-prefix-format-compiled `(format ,s ,@vars))))
4737 (defun org-get-time-of-day (s &optional string)
4738 "Check string S for a time of day.
4739 If found, return it as a military time number between 0 and 2400.
4740 If not found, return nil.
4741 The optional STRING argument forces conversion into a 5 character wide string
4747 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
4749 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
4750 (let* ((t0 (+ (* 100
4751 (+ (string-to-number (match-string 1 s))
4752 (if (and (match-beginning 4)
4753 (equal (downcase (match-string 4 s)) "pm"))
4755 (if (match-beginning 3)
4756 (string-to-number (match-string 3 s))
4758 (t1 (concat " " (int-to-string t0))))
4759 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
4761 (defun org-finalize-agenda-entries (list)
4762 "Sort and concatenate the agenda items."
4763 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
4765 (defsubst org-cmp-priority (a b)
4766 "Compare the priorities of string a and b."
4767 (let ((pa (or (get-text-property 1 'priority a) 0))
4768 (pb (or (get-text-property 1 'priority b) 0)))
4769 (cond ((> pa pb) +1)
4773 (defsubst org-cmp-category (a b)
4774 "Compare the string values of categories of strings a and b."
4775 (let ((ca (or (get-text-property 1 'category a) ""))
4776 (cb (or (get-text-property 1 'category b) "")))
4777 (cond ((string-lessp ca cb) -1)
4778 ((string-lessp cb ca) +1)
4781 (defsubst org-cmp-time (a b)
4782 "Compare the time-of-day values of strings a and b."
4783 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
4784 (ta (or (get-text-property 1 'time-of-day a) def))
4785 (tb (or (get-text-property 1 'time-of-day b) def)))
4786 (cond ((< ta tb) -1)
4790 (defun org-entries-lessp (a b)
4791 "Predicate for sorting agenda entries."
4792 ;; The following variables will be used when the form is evaluated.
4793 (let* ((time-up (org-cmp-time a b))
4794 (time-down (if time-up (- time-up) nil))
4795 (priority-up (org-cmp-priority a b))
4796 (priority-down (if priority-up (- priority-up) nil))
4797 (category-up (org-cmp-category a b))
4798 (category-down (if category-up (- category-up) nil))
4799 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
4801 (eval (cons 'or org-agenda-sorting-strategy))
4802 '((-1 . t) (1 . nil) (nil . nil))))))
4804 (defun org-agenda-show-priority ()
4805 "Show the priority of the current item.
4806 This priority is composed of the main priority given with the [#A] cookies,
4807 and by additional input from the age of a schedules or deadline entry."
4809 (let* ((pri (get-text-property (point-at-bol) 'priority)))
4810 (message "Priority is %d" (if pri pri -1000))))
4812 (defun org-agenda-goto (&optional highlight)
4813 "Go to the Org-mode file which contains the item at point."
4815 (let* ((marker (or (get-text-property (point) 'org-marker)
4816 (org-agenda-error)))
4817 (buffer (marker-buffer marker))
4818 (pos (marker-position marker)))
4819 (switch-to-buffer-other-window buffer)
4822 (when (eq major-mode 'org-mode)
4823 (org-show-hidden-entry)
4825 (and (outline-next-heading)
4826 (org-flag-heading nil)))) ; show the next heading
4827 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
4829 (defun org-agenda-switch-to ()
4830 "Go to the Org-mode file which contains the item at point."
4832 (let* ((marker (or (get-text-property (point) 'org-marker)
4833 (org-agenda-error)))
4834 (buffer (marker-buffer marker))
4835 (pos (marker-position marker)))
4836 (switch-to-buffer buffer)
4837 (delete-other-windows)
4840 (when (eq major-mode 'org-mode)
4841 (org-show-hidden-entry)
4843 (and (outline-next-heading)
4844 (org-flag-heading nil)))))) ; show the next heading
4846 (defun org-agenda-goto-mouse (ev)
4847 "Go to the Org-mode file which contains the item at the mouse click."
4849 (mouse-set-point ev)
4852 (defun org-agenda-show ()
4853 "Display the Org-mode file which contains the item at point."
4855 (let ((win (selected-window)))
4857 (select-window win)))
4859 (defun org-agenda-recenter (arg)
4860 "Display the Org-mode file which contains the item at point and recenter."
4862 (let ((win (selected-window)))
4865 (select-window win)))
4867 (defun org-agenda-show-mouse (ev)
4868 "Display the Org-mode file which contains the item at the mouse click."
4870 (mouse-set-point ev)
4873 (defun org-agenda-check-no-diary ()
4874 "Check if the entry is a diary link and abort if yes."
4875 (if (get-text-property (point) 'org-agenda-diary-link)
4876 (org-agenda-error)))
4878 (defun org-agenda-error ()
4879 (error "Command not allowed in this line"))
4881 (defvar org-last-heading-marker (make-marker)
4882 "Marker pointing to the headline that last changed its TODO state
4883 by a remote command from the agenda.")
4885 (defun org-agenda-todo ()
4886 "Cycle TODO state of line at point, also in Org-mode file.
4887 This changes the line at point, all other lines in the agenda referring to
4888 the same tree node, and the headline of the tree node in the Org-mode file."
4890 (org-agenda-check-no-diary)
4891 (let* ((col (current-column))
4892 (marker (or (get-text-property (point) 'org-marker)
4893 (org-agenda-error)))
4894 (buffer (marker-buffer marker))
4895 (pos (marker-position marker))
4896 (hdmarker (get-text-property (point) 'org-hd-marker))
4897 (buffer-read-only nil)
4899 (with-current-buffer buffer
4902 (org-show-hidden-entry)
4904 (and (outline-next-heading)
4905 (org-flag-heading nil))) ; show the next heading
4908 (setq newhead (org-get-heading))
4910 (org-back-to-heading)
4911 (move-marker org-last-heading-marker (point))))
4912 (beginning-of-line 1)
4914 (org-agenda-change-all-lines newhead hdmarker 'fixface))
4915 (move-to-column col)))
4917 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
4918 "Change all lines in the agenda buffer which match hdmarker.
4919 The new content of the line will be NEWHEAD (as modified by
4920 `org-format-agenda-item'). HDMARKER is checked with
4921 `equal' against all `org-hd-marker' text properties in the file.
4922 If FIXFACE is non-nil, the face of each item is modified acording to
4923 the new TODO state."
4924 (let* (props m pl undone-face done-face finish new dotime)
4925 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
4927 (goto-char (point-max))
4928 (beginning-of-line 1)
4930 (setq finish (bobp))
4931 (when (and (setq m (get-text-property (point) 'org-hd-marker))
4933 (setq props (text-properties-at (point))
4934 dotime (get-text-property (point) 'dotime)
4935 new (org-format-agenda-item "x" newhead "x" dotime 'noprefix)
4936 pl (get-text-property (point) 'prefix-length)
4937 undone-face (get-text-property (point) 'undone-face)
4938 done-face (get-text-property (point) 'done-face))
4940 (if (looking-at ".*")
4942 (replace-match new t t)
4943 (beginning-of-line 1)
4944 (add-text-properties (point-at-bol) (point-at-eol) props)
4946 (add-text-properties
4947 (point-at-bol) (point-at-eol)
4949 (if org-last-todo-state-is-todo
4950 undone-face done-face))))
4951 (beginning-of-line 1))
4952 (error "Line update did not work")))
4953 (beginning-of-line 0)))))
4955 (defun org-agenda-priority-up ()
4956 "Increase the priority of line at point, also in Org-mode file."
4958 (org-agenda-priority 'up))
4960 (defun org-agenda-priority-down ()
4961 "Decrease the priority of line at point, also in Org-mode file."
4963 (org-agenda-priority 'down))
4965 (defun org-agenda-priority (&optional force-direction)
4966 "Set the priority of line at point, also in Org-mode file.
4967 This changes the line at point, all other lines in the agenda referring to
4968 the same tree node, and the headline of the tree node in the Org-mode file."
4970 (org-agenda-check-no-diary)
4971 (let* ((marker (or (get-text-property (point) 'org-marker)
4972 (org-agenda-error)))
4973 (buffer (marker-buffer marker))
4974 (pos (marker-position marker))
4975 (hdmarker (get-text-property (point) 'org-hd-marker))
4976 (buffer-read-only nil)
4978 (with-current-buffer buffer
4981 (org-show-hidden-entry)
4983 (and (outline-next-heading)
4984 (org-flag-heading nil))) ; show the next heading
4985 (funcall 'org-priority force-direction)
4987 (setq newhead (org-get-heading)))
4988 (org-agenda-change-all-lines newhead hdmarker)
4989 (beginning-of-line 1)))
4991 (defun org-agenda-date-later (arg &optional what)
4992 "Change the date of this item to one day later."
4994 (org-agenda-check-no-diary)
4995 (let* ((marker (or (get-text-property (point) 'org-marker)
4996 (org-agenda-error)))
4997 (buffer (marker-buffer marker))
4998 (pos (marker-position marker)))
4999 (with-current-buffer buffer
5002 (if (not (org-at-timestamp-p))
5003 (error "Cannot find time stamp"))
5004 (org-timestamp-change arg (or what 'day))
5005 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5007 (defun org-agenda-date-earlier (arg &optional what)
5008 "Change the date of this item to one day earlier."
5010 (org-agenda-date-later (- arg) what))
5012 (defun org-agenda-date-prompt (arg)
5013 "Change the date of this item. Date is prompted for, with default today.
5014 The prefix ARG is passed to the `org-time-stamp' command and can therefore
5015 be used to request time specification in the time stamp."
5017 (org-agenda-check-no-diary)
5018 (let* ((marker (or (get-text-property (point) 'org-marker)
5019 (org-agenda-error)))
5020 (buffer (marker-buffer marker))
5021 (pos (marker-position marker)))
5022 (with-current-buffer buffer
5025 (if (not (org-at-timestamp-p))
5026 (error "Cannot find time stamp"))
5027 (org-time-stamp arg)
5028 (message "Time stamp changed to %s" org-last-changed-timestamp))))
5030 (defun org-get-heading ()
5031 "Return the heading of the current entry, without the stars."
5033 (if (and (re-search-backward "[\r\n]\\*" nil t)
5034 (looking-at "[\r\n]\\*+[ \t]+\\(.*\\)"))
5038 (defun org-agenda-diary-entry ()
5039 "Make a diary entry, like the `i' command from the calendar.
5040 All the standard commands work: block, weekly etc"
5042 (require 'diary-lib)
5044 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
5045 (read-char-exclusive)))
5046 (cmd (cdr (assoc char
5047 '((?d . insert-diary-entry)
5048 (?w . insert-weekly-diary-entry)
5049 (?m . insert-monthly-diary-entry)
5050 (?y . insert-yearly-diary-entry)
5051 (?a . insert-anniversary-diary-entry)
5052 (?b . insert-block-diary-entry)
5053 (?c . insert-cyclic-diary-entry)))))
5054 (oldf (symbol-function 'calendar-cursor-to-date))
5056 (mark (or (mark t) (point))))
5058 (error "No command associated with <%c>" char))
5059 (unless (and (get-text-property point 'day)
5060 (or (not (equal ?b char))
5061 (get-text-property mark 'day)))
5062 (error "Don't know which date to use for diary entry"))
5063 ;; We implement this by hacking the `calendar-cursor-to-date' function
5064 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
5065 (let ((calendar-mark-ring
5066 (list (calendar-gregorian-from-absolute
5067 (or (get-text-property mark 'day)
5068 (get-text-property point 'day))))))
5071 (fset 'calendar-cursor-to-date
5072 (lambda (&optional error)
5073 (calendar-gregorian-from-absolute
5074 (get-text-property point 'day))))
5075 (call-interactively cmd))
5076 (fset 'calendar-cursor-to-date oldf)))))
5079 (defun org-agenda-execute-calendar-command (cmd)
5080 "Execute a calendar command from the agenda, with the date associated to
5081 the cursor position."
5082 (require 'diary-lib)
5083 (unless (get-text-property (point) 'day)
5084 (error "Don't know which date to use for calendar command"))
5085 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
5087 (date (calendar-gregorian-from-absolute
5088 (get-text-property point 'day)))
5089 (displayed-day (extract-calendar-day date))
5090 (displayed-month (extract-calendar-month date))
5091 (displayed-year (extract-calendar-year date)))
5094 (fset 'calendar-cursor-to-date
5095 (lambda (&optional error)
5096 (calendar-gregorian-from-absolute
5097 (get-text-property point 'day))))
5098 (call-interactively cmd))
5099 (fset 'calendar-cursor-to-date oldf))))
5101 (defun org-agenda-phases-of-moon ()
5102 "Display the phases of the moon for the 3 months around the cursor date."
5104 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
5106 (defun org-agenda-holidays ()
5107 "Display the holidays for the 3 months around the cursor date."
5109 (org-agenda-execute-calendar-command 'list-calendar-holidays))
5111 (defun org-agenda-sunrise-sunset (arg)
5112 "Display sunrise and sunset for the cursor date.
5113 Latitude and longitude can be specified with the variables
5114 `calendar-latitude' and `calendar-longitude'. When called with prefix
5115 argument, latitude and longitude will be prompted for."
5117 (let ((calendar-longitude (if arg nil calendar-longitude))
5118 (calendar-latitude (if arg nil calendar-latitude))
5119 (calendar-location-name
5120 (if arg "the given coordinates" calendar-location-name)))
5121 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
5123 (defun org-agenda-goto-calendar ()
5124 "Open the Emacs calendar with the date at the cursor."
5126 (let* ((day (or (get-text-property (point) 'day)
5127 (error "Don't know which date to open in calendar")))
5128 (date (calendar-gregorian-from-absolute day)))
5130 (calendar-goto-date date)))
5132 (defun org-calendar-goto-agenda ()
5133 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
5134 This is a command that has to be installed in `calendar-mode-map'."
5136 (org-agenda nil (calendar-absolute-from-gregorian
5137 (calendar-cursor-to-date))))
5139 (defun org-agenda-convert-date ()
5141 (let ((day (get-text-property (point) 'day))
5144 (error "Don't know which date to convert"))
5145 (setq date (calendar-gregorian-from-absolute day))
5147 "Gregorian: " (calendar-date-string date) "\n"
5148 "ISO: " (calendar-iso-date-string date) "\n"
5149 "Day of Yr: " (calendar-day-of-year-string date) "\n"
5150 "Julian: " (calendar-julian-date-string date) "\n"
5151 "Astron. JD: " (calendar-astro-date-string date)
5152 " (Julian date number at noon UTC)\n"
5153 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
5154 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
5155 "French: " (calendar-french-date-string date) "\n"
5156 "Mayan: " (calendar-mayan-date-string date) "\n"
5157 "Coptic: " (calendar-coptic-date-string date) "\n"
5158 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
5159 "Persian: " (calendar-persian-date-string date) "\n"
5160 "Chinese: " (calendar-chinese-date-string date) "\n"))
5161 (with-output-to-temp-buffer "*Dates*"
5163 (fit-window-to-buffer (get-buffer-window "*Dates*"))))
5167 (defun org-find-file-at-mouse (ev)
5168 "Open file link or URL at mouse."
5170 (mouse-set-point ev)
5171 (org-open-at-point 'in-emacs))
5173 (defun org-open-at-mouse (ev)
5174 "Open file link or URL at mouse."
5176 (mouse-set-point ev)
5177 (org-open-at-point))
5179 (defun org-open-at-point (&optional in-emacs)
5180 "Open link at or after point.
5181 If there is no link at point, this function will search forward up to
5182 the end of the current subtree.
5183 Normally, files will be opened by an appropriate application. If the
5184 optional argument IN-EMACS is non-nil, Emacs will visit the file."
5186 (if (org-at-timestamp-p)
5187 (org-agenda nil (time-to-days (org-time-string-to-time
5188 (substring (match-string 1) 0 10)))
5190 (let (type path line (pos (point)))
5192 (skip-chars-backward
5193 (concat (if org-allow-space-in-links "^" "^ ")
5194 org-non-link-chars))
5195 (if (re-search-forward
5199 (progn (outline-end-of-subtree) (max pos (point)))
5200 (error (end-of-line 1) (point))))
5202 (setq type (match-string 1)
5203 path (match-string 2)))
5205 (error "No link found"))
5206 ;; Remove any trailing spaces in path
5207 (if (string-match " +\\'" path)
5208 (setq path (replace-match "" t t path)))
5212 ((string= type "file")
5213 (if (string-match ":\\([0-9]+\\)\\'" path)
5214 (setq line (string-to-number (match-string 1 path))
5215 path (substring path 0 (match-beginning 0))))
5216 (org-open-file path in-emacs line))
5218 ((string= type "news")
5219 (org-follow-gnus-link path))
5221 ((string= type "bbdb")
5222 (org-follow-bbdb-link path))
5224 ((string= type "gnus")
5225 (let (group article)
5226 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5227 (error "Error in Gnus link"))
5228 (setq group (match-string 1 path)
5229 article (match-string 3 path))
5230 (org-follow-gnus-link group article)))
5232 ((string= type "vm")
5233 (let (folder article)
5234 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5235 (error "Error in VM link"))
5236 (setq folder (match-string 1 path)
5237 article (match-string 3 path))
5238 ;; in-emacs is the prefix arg, will be interpreted as read-only
5239 (org-follow-vm-link folder article in-emacs)))
5241 ((string= type "wl")
5242 (let (folder article)
5243 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5244 (error "Error in Wanderlust link"))
5245 (setq folder (match-string 1 path)
5246 article (match-string 3 path))
5247 (org-follow-wl-link folder article)))
5249 ((string= type "rmail")
5250 (let (folder article)
5251 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
5252 (error "Error in RMAIL link"))
5253 (setq folder (match-string 1 path)
5254 article (match-string 3 path))
5255 (org-follow-rmail-link folder article)))
5257 ((string= type "shell")
5259 (while (string-match "@{" cmd)
5260 (setq cmd (replace-match "<" t t cmd)))
5261 (while (string-match "@}" cmd)
5262 (setq cmd (replace-match ">" t t cmd)))
5263 (if (or (not org-confirm-shell-links)
5264 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
5269 (browse-url-at-point)))))))
5271 (defun org-follow-bbdb-link (name)
5272 "Follow a BBDB link to NAME."
5274 (let ((inhibit-redisplay t))
5276 ;; Exact match on name
5277 (bbdb-name (concat "\\`" name "\\'") nil)
5278 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5279 ;; Exact match on name
5280 (bbdb-company (concat "\\`" name "\\'") nil)
5281 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5282 ;; Partial match on name
5283 (bbdb-name name nil)
5284 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5285 ;; Partial match on company
5286 (bbdb-company name nil)
5287 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
5288 ;; General match including network address and notes
5290 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
5291 (delete-window (get-buffer-window "*BBDB*"))
5292 (error "No matching BBDB record")))))
5294 (defun org-follow-gnus-link (&optional group article)
5295 "Follow a Gnus link to GROUP and ARTICLE."
5297 (funcall (cdr (assq 'gnus org-link-frame-setup)))
5298 (if group (gnus-fetch-group group))
5300 (or (gnus-summary-goto-article article nil 'force)
5301 (if (fboundp 'gnus-summary-insert-cached-articles)
5303 (gnus-summary-insert-cached-articles)
5304 (gnus-summary-goto-article article nil 'force))
5305 (message "Message could not be found.")))))
5307 (defun org-follow-vm-link (&optional folder article readonly)
5308 "Follow a VM link to FOLDER and ARTICLE."
5310 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
5311 ;; ange-ftp or efs or tramp access
5312 (let ((user (or (match-string 1 folder) (user-login-name)))
5313 (host (match-string 2 folder))
5314 (file (match-string 3 folder)))
5317 ;; use tramp to access the file
5319 (setq folder (format "[%s@%s]%s" user host file))
5320 (setq folder (format "/%s@%s:%s" user host file))))
5322 ;; use ange-ftp or efs
5323 (require (if org-xemacs-p 'efs 'ange-ftp))
5324 (setq folder (format "/%s@%s:%s" user host file))))))
5326 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
5329 (vm-select-folder-buffer)
5331 (let ((case-fold-search t))
5332 (goto-char (point-min))
5333 (if (not (re-search-forward
5334 (concat "^" "message-id: *" (regexp-quote article))))
5335 (error "Could not find the specified message in this folder"))
5338 (vm-beginning-of-message)
5341 (defun org-follow-wl-link (folder article)
5342 "Follow a Wanderlust link to FOLDER and ARTICLE."
5343 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
5344 (if article (wl-summary-jump-to-msg-by-message-id article))
5345 (wl-summary-redisplay))
5347 (defun org-follow-rmail-link (folder article)
5348 "Follow an RMAIL link to FOLDER and ARTICLE."
5349 (let (message-number)
5351 (save-window-excursion
5352 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5353 (setq message-number
5356 (goto-char (point-max))
5357 (if (re-search-backward
5358 (concat "^Message-ID:\\s-+" (regexp-quote
5361 (rmail-what-message))))))
5364 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
5365 (rmail-show-message message-number)
5367 (error "Message not found"))))
5369 (defun org-open-file (path &optional in-emacs line)
5370 "Open the file at PATH.
5371 First, this expands any special file name abbreviations. Then the
5372 configuration variable `org-file-apps' is checked if it contains an
5373 entry for this file type, and if yes, the corresponding command is launched.
5374 If no application is found, Emacs simply visits the file.
5375 With optional argument IN-EMACS, Emacs will visit the file.
5376 If the file does not exist, an error is thrown."
5377 (let* ((file (convert-standard-filename (org-expand-file-name path)))
5378 (dfile (downcase file))
5380 (if (and (not (file-exists-p file))
5381 (not org-open-non-existing-files))
5382 (error "No such file: %s" file))
5383 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
5384 (setq ext (match-string 1 dfile))
5385 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
5386 (setq ext (match-string 1 dfile))))
5387 (setq apps (append org-file-apps (org-default-apps)))
5390 (setq cmd (or (cdr (assoc ext apps))
5391 (cdr (assoc t apps)))))
5393 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
5394 (setq cmd (format cmd (concat "\"" file "\"")))
5395 (save-window-excursion
5396 (shell-command (concat cmd " & &"))))
5399 (funcall (cdr (assq 'file org-link-frame-setup)) file)
5400 (if line (goto-line line)))
5403 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))))
5405 (defun org-default-apps ()
5406 "Return the default applications for this operating system."
5408 ((eq system-type 'darwin)
5409 org-file-apps-defaults-macosx)
5410 ((eq system-type 'windows-nt)
5411 org-file-apps-defaults-windowsnt)
5412 (t org-file-apps-defaults-gnu)))
5414 (defun org-expand-file-name (path)
5415 "Replace special path abbreviations and expand the file name."
5416 (expand-file-name path))
5419 (defvar org-insert-link-history nil
5420 "Minibuffer history for links inserted with `org-insert-link'.")
5422 (defvar org-stored-links nil
5423 "Contains the links stored with `org-store-link'.")
5426 (defun org-store-link (arg)
5427 "\\<org-mode-map>Store an org-link to the current location.
5428 This link can later be inserted into an org-buffer with
5429 \\[org-insert-link].
5430 For some link types, a prefix arg is interpreted:
5431 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
5432 For file links, arg negates `org-line-numbers-in-file-links'."
5437 ((eq major-mode 'bbdb-mode)
5438 (setq cpltxt (concat
5440 (or (bbdb-record-name (bbdb-current-record))
5441 (bbdb-record-company (bbdb-current-record))))
5442 link (org-make-link cpltxt)))
5444 ((eq major-mode 'calendar-mode)
5445 (let ((cd (calendar-cursor-to-date)))
5448 (car org-time-stamp-formats)
5450 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
5453 ((or (eq major-mode 'vm-summary-mode)
5454 (eq major-mode 'vm-presentation-mode))
5455 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
5456 (vm-follow-summary-cursor)
5458 (vm-select-folder-buffer)
5459 (let* ((message (car vm-message-pointer))
5460 (folder (buffer-file-name))
5461 (subject (vm-su-subject message))
5462 (author (vm-su-full-name message))
5463 (message-id (vm-su-message-id message)))
5464 (setq folder (abbreviate-file-name folder))
5465 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
5467 (setq folder (replace-match "" t t folder)))
5468 (setq cpltxt (concat author " on: " subject))
5469 (setq link (concat cpltxt "\n "
5471 "vm:" folder "#" message-id))))))
5473 ((eq major-mode 'wl-summary-mode)
5474 (let* ((msgnum (wl-summary-message-number))
5475 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
5476 msgnum 'message-id))
5477 (wl-message-entity (elmo-msgdb-overview-get-entity
5478 msgnum (wl-summary-buffer-msgdb)))
5479 (author (wl-summary-line-from)) ; FIXME: how to get author name?
5480 (subject "???")) ; FIXME: How to get subject of email?
5481 (setq cpltxt (concat author " on: " subject))
5482 (setq link (concat cpltxt "\n "
5484 "wl:" wl-summary-buffer-folder-name
5487 ((eq major-mode 'rmail-mode)
5490 (rmail-narrow-to-non-pruned-header)
5491 (let ((folder (buffer-file-name))
5492 (message-id (mail-fetch-field "message-id"))
5493 (author (mail-fetch-field "from"))
5494 (subject (mail-fetch-field "subject")))
5495 (setq cpltxt (concat author " on: " subject))
5496 (setq link (concat cpltxt "\n "
5498 "rmail:" folder "#" message-id)))))))
5500 ((eq major-mode 'gnus-group-mode)
5501 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
5502 (gnus-group-group-name)) ; version
5503 ((fboundp 'gnus-group-name)
5506 (setq cpltxt (concat
5507 (if (org-xor arg org-usenet-links-prefer-google)
5508 "http://groups.google.com/groups?group="
5511 link (org-make-link cpltxt))))
5513 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
5514 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
5515 (gnus-summary-beginning-of-article)
5516 (let* ((group (car gnus-article-current))
5517 (article (cdr gnus-article-current))
5518 (header (gnus-summary-article-header article))
5519 (author (mail-header-from header))
5520 (message-id (mail-header-id header))
5521 (date (mail-header-date header))
5522 (subject (gnus-summary-subject-string)))
5523 (setq cpltxt (concat author " on: " subject))
5524 (if (org-xor arg org-usenet-links-prefer-google)
5528 (format "http://groups.google.com/groups?as_umsgid=%s"
5529 (org-fixup-message-id-for-http message-id))))
5530 (setq link (concat cpltxt "\n"
5533 "#" (number-to-string article)))))))
5535 ((eq major-mode 'w3-mode)
5536 (setq cpltxt (url-view-url t)
5537 link (org-make-link cpltxt)))
5538 ((eq major-mode 'w3m-mode)
5539 (setq cpltxt w3m-current-url
5540 link (org-make-link cpltxt)))
5543 ;; Just link to this file here.
5544 (setq cpltxt (concat "file:"
5545 (abbreviate-file-name (buffer-file-name))))
5546 ;; Add the line number?
5547 (if (org-xor org-line-numbers-in-file-links arg)
5551 (+ (if (bolp) 1 0) (count-lines
5552 (point-min) (point)))))))
5553 (setq link (org-make-link cpltxt)))
5556 (error "Cannot link to a buffer which is not visiting a file"))
5558 (t (setq link nil)))
5560 (if (and (interactive-p) link)
5562 (setq org-stored-links
5563 (cons (cons (or cpltxt link) link) org-stored-links))
5564 (message "Stored: %s" (or cpltxt link)))
5567 (defun org-make-link (&rest strings)
5568 "Concatenate STRINGS, format resulting string with `org-link-format'."
5569 (format org-link-format (apply 'concat strings)))
5571 (defun org-xor (a b)
5575 (defun org-get-header (header)
5576 "Find a header field in the current buffer."
5578 (goto-char (point-min))
5579 (let ((case-fold-search t) s)
5582 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
5583 (setq s (match-string 1)))
5584 (while (string-match "\"" s)
5585 (setq s (replace-match "" t t s)))
5586 (if (string-match "[<(].*" s)
5587 (setq s (replace-match "" t t s))))
5588 ((eq header 'message-id)
5589 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
5590 (setq s (match-string 1))))
5591 ((eq header 'subject)
5592 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
5593 (setq s (match-string 1)))))
5594 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
5595 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
5599 (defun org-fixup-message-id-for-http (s)
5600 "Replace special characters in a message id, so it can be used in an http query."
5601 (while (string-match "<" s)
5602 (setq s (replace-match "%3C" t t s)))
5603 (while (string-match ">" s)
5604 (setq s (replace-match "%3E" t t s)))
5605 (while (string-match "@" s)
5606 (setq s (replace-match "%40" t t s)))
5609 (defun org-insert-link (&optional complete-file)
5610 "Insert a link. At the prompt, enter the link.
5612 Completion can be used to select a link previously stored with
5613 `org-store-link'. When the empty string is entered (i.e. if you just
5614 press RET at the prompt), the link defaults to the most recently
5615 stored link. As SPC triggers completion in the minibuffer, you need to
5616 use M-SPC or C-q SPC to force the insertion of a space character.
5618 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
5619 selected using completion. The path to the file will be relative to
5620 the current directory if the file is in the current directory or a
5621 subdirectory. Otherwise, the link will be the absolute path as
5622 completed in the minibuffer (i.e. normally ~/path/to/file).
5624 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
5625 is in the current directory or below."
5627 (let ((link (if complete-file
5628 (read-file-name "File: ")
5630 "Link: " org-stored-links nil nil nil
5631 org-insert-link-history
5632 (or (car (car org-stored-links))))))
5634 (if (or (not link) (equal link ""))
5635 (error "No links available"))
5637 (let ((pwd (file-name-as-directory (expand-file-name "."))))
5639 ((equal complete-file '(16))
5642 "file:" (abbreviate-file-name (expand-file-name link)))))
5643 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
5644 (expand-file-name link))
5647 "file:" (match-string 1 (expand-file-name link)))))
5648 (t (insert (org-make-link "file:" link)))))
5649 (setq linktxt (cdr (assoc link org-stored-links)))
5650 (if (not org-keep-stored-link-after-insertion)
5651 (setq org-stored-links (delq (assoc link org-stored-links)
5653 (if (not linktxt) (setq link (org-make-link link)))
5654 (let ((lines (org-split-string (or linktxt link) "\n")))
5655 (insert (car lines))
5656 (setq matched (string-match org-link-regexp (car lines)))
5657 (setq lines (cdr lines))
5661 (beginning-of-line 0)
5662 (looking-at "[ \t]+\\S-"))
5664 (setq matched (or matched
5665 (string-match org-link-regexp (car lines))))
5666 (insert (car lines))
5667 (setq lines (cdr lines))))
5669 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
5671 ;;; Hooks for remember.el
5673 (defun org-remember-annotation ()
5674 "Return a link to the current location as an annotation for remember.el.
5675 If you are using Org-mode files as target for data storage with
5676 remember.el, then the annotations should include a link compatible with the
5677 conventions in Org-mode. This function returns such a link."
5678 (org-store-link nil))
5680 (defconst org-remember-help
5681 "Select a destination location for the note.
5682 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
5683 RET at beg-of-buf -> Append to file as level 2 headline
5684 RET on headline -> Store as sublevel entry to current headline
5685 <left>/<right> -> before/after current headline, same headings level")
5688 (defun org-remember-handler ()
5689 "Store stuff from remember.el into an org file.
5690 First prompts for an org file. If the user just presses return, the value
5691 of `org-default-notes-file' is used.
5692 Then the command offers the headings tree of the selected file in order to
5693 file the text at a specific location.
5694 You can either immediately press RET to get the note appended to the
5695 file. Or you can use vertical cursor motion and visibility cycling (TAB) to
5696 find a better place. Then press RET or <left> or <right> in insert the note.
5698 Key Cursor position Note gets inserted
5699 -----------------------------------------------------------------------------
5700 RET buffer-start as level 2 heading at end of file
5701 RET on headline as sublevel of the heading at cursor
5702 RET no heading at cursor position, level taken from context.
5703 Or use prefix arg to specify level manually.
5704 <left> on headline as same level, before current heading
5705 <right> on headline as same level, after current heading
5707 So the fastest way to store the note is to press RET RET to append it to
5708 the default file. This way your current train of thought is not
5709 interrupted, in accordance with the principles of remember.el. But with
5710 little extra effort, you can push it directly to the correct location.
5712 Before being stored away, the function ensures that the text has a
5713 headline, i.e. a first line that starts with a \"*\". If not, a headline
5714 is constructed from the current date and some additional data.
5716 If the variable `org-adapt-indentation' is non-nil, the entire text is
5717 also indented so that it starts in the same column as the headline
5718 \(i.e. after the stars).
5720 See also the variable `org-reverse-note-order'."
5722 (let* ((txt (buffer-substring (point-min) (point-max)))
5723 (fastp current-prefix-arg)
5724 (file (if fastp org-default-notes-file (org-get-org-file)))
5725 (visiting (find-buffer-visiting file))
5726 (org-startup-with-deadline-check nil)
5727 (org-startup-folded nil)
5728 spos level indent reversed)
5729 ;; Modify text so that it becomes a nice subtree which can be inserted
5730 ;; into an org tree.
5731 (let* ((lines (split-string txt "\n"))
5733 (lines (cdr lines)))
5734 (if (string-match "^\\*+" first)
5735 ;; Is already a headline
5736 (setq indent (make-string (- (match-end 0) (match-beginning 0)
5738 ;; We need to add a headline: Use time and first buffer line
5739 (setq lines (cons first lines)
5740 first (concat "* " (current-time-string)
5741 " (" (remember-buffer-desc) ")")
5743 (if org-adapt-indentation
5744 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
5745 (setq txt (concat first "\n"
5746 (mapconcat 'identity lines "\n"))))
5749 (find-file-noselect file))
5750 (with-current-buffer (get-file-buffer file)
5751 (setq reversed (org-notes-order-reversed-p))
5755 ;; Ask the User for a location
5756 (setq spos (if fastp 1 (org-get-location
5758 org-remember-help)))
5759 (if (not spos) (throw 'quit nil)) ; return nil to show we did
5760 ; not handle this note
5763 ;; Put it at the start or end, as level 2
5766 (goto-char (if reversed (point-min) (point-max)))
5767 (if (not (bolp)) (newline))
5768 (org-paste-subtree (or current-prefix-arg 2) txt)))
5769 ((and (org-on-heading-p nil) (not current-prefix-arg))
5770 ;; Put it below this entry, at the beg/end of the subtree
5771 (org-back-to-heading)
5772 (setq level (outline-level))
5774 (outline-end-of-heading)
5775 (outline-end-of-subtree))
5776 (if (not (bolp)) (newline))
5777 (beginning-of-line 1)
5778 (org-paste-subtree (1+ level) txt))
5780 ;; Put it right there, with automatic level determined by
5781 ;; org-paste-subtree or from prefix arg
5782 (org-paste-subtree current-prefix-arg txt)))
5783 (when remember-save-after-remembering
5785 (if (not visiting) (kill-buffer (current-buffer)))))))))
5786 t) ;; return t to indicate that we took care of this note.
5788 (defun org-get-org-file ()
5789 "Read a filename, with default directory `org-directory'."
5790 (let ((default (or org-default-notes-file remember-data-file)))
5791 (read-file-name (format "File name [%s]: " default)
5792 (file-name-as-directory org-directory)
5795 (defun org-notes-order-reversed-p ()
5796 "Check if the current file should receive notes in reversed order."
5798 ((not org-reverse-note-order) nil)
5799 ((eq t org-reverse-note-order) t)
5800 ((not (listp org-reverse-note-order)) nil)
5802 (let ((all org-reverse-note-order)
5804 (while (setq entry (pop all))
5805 (if (string-match (car entry) (buffer-file-name))
5806 (throw 'exit (cdr entry))))
5811 ;; Watch out: Here we are talking about two different kind of tables.
5812 ;; Most of the code is for the tables created with the Org-mode table editor.
5813 ;; Sometimes, we talk about tables created and edited with the table.el
5814 ;; Emacs package. We call the former org-type tables, and the latter
5815 ;; table.el-type tables.
5818 (defun org-before-change-function (beg end)
5819 "Every change indicates that a table might need an update."
5820 (setq org-table-may-need-update t))
5822 (defconst org-table-line-regexp "^[ \t]*|"
5823 "Detects an org-type table line.")
5824 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
5825 "Detects an org-type table line.")
5826 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
5827 "Detects a table line marked for automatic recalculation.")
5828 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
5829 "Detects a table line marked for automatic recalculation.")
5830 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
5831 "Detects a table line marked for automatic recalculation.")
5832 (defconst org-table-hline-regexp "^[ \t]*|-"
5833 "Detects an org-type table hline.")
5834 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
5835 "Detects a table-type table hline.")
5836 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
5837 "Detects an org-type or table-type table.")
5838 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
5839 "Searching from within a table (any type) this finds the first line
5840 outside the table.")
5841 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
5842 "Searching from within a table (any type) this finds the first line
5843 outside the table.")
5845 (defun org-table-create-with-table.el ()
5846 "Use the table.el package to insert a new table.
5847 If there is already a table at point, convert between Org-mode tables
5848 and table.el tables."
5852 ((org-at-table.el-p)
5853 (if (y-or-n-p "Convert table to Org-mode table? ")
5854 (org-table-convert)))
5856 (if (y-or-n-p "Convert table to table.el table? ")
5857 (org-table-convert)))
5858 (t (call-interactively 'table-insert))))
5860 (defun org-table-create (&optional size)
5861 "Query for a size and insert a table skeleton.
5862 SIZE is a string Columns x Rows like for example \"3x2\"."
5865 (setq size (read-string
5866 (concat "Table size Columns x Rows [e.g. "
5867 org-table-default-size "]: ")
5868 "" nil org-table-default-size)))
5870 (let* ((pos (point))
5871 (indent (make-string (current-column) ?\ ))
5872 (split (org-split-string size " *x *"))
5873 (rows (string-to-number (nth 1 split)))
5874 (columns (string-to-number (car split)))
5875 (line (concat (apply 'concat indent "|" (make-list columns " |"))
5877 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
5878 (point-at-bol) (point)))
5879 (beginning-of-line 1)
5881 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
5882 (dotimes (i rows) (insert line))
5885 ;; Insert a hline after the first row.
5892 (defun org-table-convert-region (beg0 end0 nspace)
5893 "Convert region to a table.
5894 The region goes from BEG0 to END0, but these borders will be moved
5895 slightly, to make sure a beginning of line in the first line is included.
5896 When NSPACE is non-nil, it indicates the minimum number of spaces that
5897 separate columns (default: just one space)"
5898 (let* ((beg (min beg0 end0))
5899 (end (max beg0 end0))
5903 (beginning-of-line 1)
5904 (setq beg (move-marker (make-marker) (point)))
5906 (if (bolp) (backward-char 1) (end-of-line 1))
5907 (setq end (move-marker (make-marker) (point)))
5908 ;; Lets see if this is tab-separated material. If every nonempty line
5909 ;; contains a tab, we will assume that it is tab-separated material
5913 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
5914 (if nspace (setq tabsep nil))
5917 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
5918 (max 1 (prefix-numeric-value nspace)))))
5920 (while (re-search-forward re end t)
5921 (replace-match "|" t t))
5926 (defun org-table-import (file arg)
5927 "Import FILE as a table.
5928 The file is assumed to be tab-separated. Such files can be produced by most
5929 spreadsheet and database applications. If no tabs (at least one per line)
5930 are found, lines will be split on whitespace into fields."
5931 (interactive "f\nP")
5932 (or (bolp) (newline))
5935 (insert-file-contents file)
5936 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
5938 (defun org-table-export ()
5939 "Export table as a tab-separated file.
5940 Such a file can be imported into a spreadsheet program like Excel."
5942 (let* ((beg (org-table-begin))
5943 (end (org-table-end))
5944 (table (buffer-substring beg end))
5945 (file (read-file-name "Export table to: "))
5947 (unless (or (not (file-exists-p file))
5948 (y-or-n-p (format "Overwrite file %s? " file)))
5950 (with-current-buffer (find-file-noselect file)
5951 (setq buf (current-buffer))
5955 (goto-char (point-min))
5956 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
5957 (replace-match "" t t)
5959 (goto-char (point-min))
5960 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
5961 (replace-match "" t t)
5962 (goto-char (min (1+ (point)) (point-max))))
5963 (goto-char (point-min))
5964 (while (re-search-forward "^-[-+]*$" nil t)
5966 (if (looking-at "\n")
5968 (goto-char (point-min))
5969 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
5970 (replace-match "\t" t t))
5974 (defvar org-table-aligned-begin-marker (make-marker)
5975 "Marker at the beginning of the table last aligned.
5976 Used to check if cursor still is in that table, to minimize realignment.")
5977 (defvar org-table-aligned-end-marker (make-marker)
5978 "Marker at the end of the table last aligned.
5979 Used to check if cursor still is in that table, to minimize realignment.")
5980 (defvar org-table-last-alignment nil
5981 "List of flags for flushright alignment, from the last re-alignment.
5982 This is being used to correctly align a single field after TAB or RET.")
5983 ;; FIXME: The following is currently not used.
5984 (defvar org-table-last-column-widths nil
5985 "List of max width of fields in each column.
5986 This is being used to correctly align a single field after TAB or RET.")
5988 (defvar org-last-recalc-line nil)
5990 (defun org-table-align ()
5991 "Align the table at point by aligning all vertical bars."
5993 ;; (message "align") (sit-for 2)
5996 (beg (org-table-begin))
5997 (end (org-table-end))
5998 ;; Current cursor position
5999 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6000 (colpos (org-table-current-column))
6001 (winstart (window-start))
6002 text lines (new "") lengths l typenums ty fields maxfields i
6004 (indent "") cnt frac
6006 (spaces (if (org-in-invisibility-spec-p '(org-table))
6007 org-table-spaces-around-invisible-separators
6008 org-table-spaces-around-separators))
6012 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
6014 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
6017 ;; (message "Aligning table...")
6019 (setq lines (org-split-string
6020 (buffer-substring-no-properties beg end) "\n"))
6021 ;; Store the indentation of the first line
6022 (if (string-match "^ *" (car lines))
6023 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
6025 (setq lines (mapcar (lambda (l)
6026 (if (string-match "^ *|-" l)
6028 (if (string-match "[ \t]+$" l)
6029 (substring l 0 (match-beginning 0))
6032 ;; Get the data fields
6033 (setq fields (mapcar
6035 (org-split-string l " *| *"))
6036 (delq nil (copy-sequence lines))))
6037 ;; How many fields in the longest line?
6039 (setq maxfields (apply 'max (mapcar 'length fields)))
6041 (kill-region beg end)
6042 (org-table-create org-table-default-size)
6043 (error "Empty table - created default table")))
6044 ;; A list of empty string to fill any short rows on output
6045 (setq emptystrings (make-list maxfields ""))
6046 ;; Get the maximum length of a field and the most common datatype
6049 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
6050 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
6052 (push (apply 'max 1 (mapcar 'length column)) lengths)
6053 ;; compute the fraction stepwise, ignoring empty fields
6054 (setq cnt 0 frac 0.0)
6059 (setq frac ( / (+ (* frac cnt)
6060 (if (string-match org-table-number-regexp x) 1 0))
6061 (setq cnt (1+ cnt))))))
6063 (push (>= frac org-table-number-fraction) typenums))
6064 (setq lengths (nreverse lengths)
6065 typenums (nreverse typenums))
6066 (setq org-table-last-alignment typenums
6067 org-table-last-column-widths lengths)
6068 ;; Compute the formats needed for output of the table
6069 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
6070 (while (setq l (pop lengths))
6071 (setq ty (if (pop typenums) "" "-")) ; number types flushright
6072 (setq rfmt (concat rfmt (format rfmt1 ty l))
6073 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
6074 (setq rfmt (concat rfmt "\n")
6075 hfmt (concat (substring hfmt 0 -1) "|\n"))
6076 ;; Produce the new table
6078 ;; (setq l (pop lines))
6080 ;; (setq new (concat new (apply 'format rfmt
6081 ;; (append (pop fields) emptystrings))))
6082 ;; (setq new (concat new hfmt))))
6083 (setq new (mapconcat
6085 (if l (apply 'format rfmt
6086 (append (pop fields) emptystrings))
6089 ;; Replace the old one
6090 (delete-region beg end)
6091 (move-marker end nil)
6092 (move-marker org-table-aligned-begin-marker (point))
6094 (move-marker org-table-aligned-end-marker (point))
6095 ;; Try to move to the old location (approximately)
6097 (set-window-start (selected-window) winstart 'noforce)
6098 (org-table-goto-column colpos)
6099 (setq org-table-may-need-update nil)
6100 (if (org-in-invisibility-spec-p '(org-table))
6101 (org-table-add-invisible-to-vertical-lines))
6104 (defun org-table-begin (&optional table-type)
6105 "Find the beginning of the table and return its position.
6106 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
6108 (if (not (re-search-backward
6109 (if table-type org-table-any-border-regexp
6110 org-table-border-regexp)
6112 (error "Can't find beginning of table")
6113 (goto-char (match-beginning 0))
6114 (beginning-of-line 2)
6117 (defun org-table-end (&optional table-type)
6118 "Find the end of the table and return its position.
6119 With argument TABLE-TYPE, go to the end of a table.el-type table."
6121 (if (not (re-search-forward
6122 (if table-type org-table-any-border-regexp
6123 org-table-border-regexp)
6125 (goto-char (point-max))
6126 (goto-char (match-beginning 0)))
6129 (defun org-table-justify-field-maybe (&optional new)
6130 "Justify the current field, text to left, number to right.
6131 Optional argument NEW may specify text to replace the current field content."
6133 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
6134 ((org-at-table-hline-p)
6135 ;; FIXME: I used to enforce realign here, but I think this is not needed.
6136 ;; (setq org-table-may-need-update t)
6139 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
6141 (< (point) org-table-aligned-begin-marker)
6142 (>= (point) org-table-aligned-end-marker)))
6143 ;; This is not the same table, force a full re-align
6144 (setq org-table-may-need-update t))
6145 (t ;; realign the current field, based on previous full realign
6146 (let* ((pos (point)) s
6147 (col (org-table-current-column))
6148 (num (nth (1- col) org-table-last-alignment))
6151 (skip-chars-backward "^|\n")
6152 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
6154 (setq s (match-string 1)
6156 l (max 1 (- (match-end 0) (match-beginning 0) 3))
6157 e (not (= (match-beginning 2) (match-end 2))))
6158 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
6159 l (if e "|" (setq org-table-may-need-update t) ""))
6162 (if (<= (length new) l)
6163 (setq n (format f new t t)) ;; FIXME: why t t?????
6164 (setq n (concat new "|") org-table-may-need-update t)))
6166 (let (org-table-may-need-update)
6167 (replace-match n))))
6168 (setq org-table-may-need-update t))
6169 (goto-char pos))))))
6171 (defun org-table-next-field ()
6172 "Go to the next field in the current table.
6173 Before doing so, re-align the table if necessary."
6175 (org-table-maybe-eval-formula)
6176 (org-table-maybe-recalculate-line)
6177 (if (and org-table-automatic-realign
6178 org-table-may-need-update)
6180 (if (org-at-table-hline-p)
6184 (re-search-forward "|" (org-table-end))
6185 (if (looking-at "[ \t]*$")
6186 (re-search-forward "|" (org-table-end)))
6187 (if (looking-at "-")
6189 (beginning-of-line 0)
6190 (org-table-insert-row 'below))
6191 (if (looking-at " ") (forward-char 1))))
6193 (org-table-insert-row 'below))))
6195 (defun org-table-previous-field ()
6196 "Go to the previous field in the table.
6197 Before doing so, re-align the table if necessary."
6199 (org-table-justify-field-maybe)
6200 (org-table-maybe-recalculate-line)
6201 (if (and org-table-automatic-realign
6202 org-table-may-need-update)
6204 (if (org-at-table-hline-p)
6206 (re-search-backward "|" (org-table-begin))
6207 (re-search-backward "|" (org-table-begin))
6208 (while (looking-at "|\\(-\\|[ \t]*$\\)")
6209 (re-search-backward "|" (org-table-begin)))
6210 (if (looking-at "| ?")
6211 (goto-char (match-end 0))))
6213 (defun org-table-next-row ()
6214 "Go to the next row (same column) in the current table.
6215 Before doing so, re-align the table if necessary."
6217 (org-table-maybe-eval-formula)
6218 (org-table-maybe-recalculate-line)
6219 (if (or (looking-at "[ \t]*$")
6220 (save-excursion (skip-chars-backward " \t") (bolp)))
6222 (if (and org-table-automatic-realign
6223 org-table-may-need-update)
6225 (let ((col (org-table-current-column)))
6226 (beginning-of-line 2)
6227 (if (or (not (org-at-table-p))
6228 (org-at-table-hline-p))
6230 (beginning-of-line 0)
6231 (org-table-insert-row 'below)))
6232 (org-table-goto-column col)
6233 (skip-chars-backward "^|\n\r")
6234 (if (looking-at " ") (forward-char 1)))))
6236 (defun org-table-copy-down (n)
6237 "Copy a field down in the current column.
6238 If the field at the cursor is empty, copy into it the content of the nearest
6239 non-empty field above. With argument N, use the Nth non-empty field.
6240 If the current field is not empty, it is copied down to the next row, and
6241 the cursor is moved with it. Therefore, repeating this command causes the
6242 column to be filled row-by-row.
6243 If the variable `org-table-copy-increment' is non-nil and the field is an
6244 integer, it will be incremented while copying."
6246 (let* ((colpos (org-table-current-column))
6247 (field (org-table-get-field))
6248 (non-empty (string-match "[^ \t]" field))
6249 (beg (org-table-begin))
6251 (org-table-check-inside-data-field)
6254 (setq txt (org-trim field))
6255 (org-table-next-row)
6256 (org-table-blank-field))
6260 (while (progn (beginning-of-line 1)
6261 (re-search-backward org-table-dataline-regexp
6263 (org-table-goto-column colpos t)
6264 (if (and (looking-at
6265 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
6266 (= (setq n (1- n)) 0))
6267 (throw 'exit (match-string 1))))))))
6270 (if (and org-table-copy-increment
6271 (string-match "^[0-9]+$" txt))
6272 (setq txt (format "%d" (+ (string-to-int txt) 1))))
6274 (org-table-maybe-recalculate-line)
6276 (error "No non-empty field found"))))
6278 (defun org-table-check-inside-data-field ()
6279 "Is point inside a table data field?
6280 I.e. not on a hline or before the first or after the last column?"
6281 (if (or (not (org-at-table-p))
6282 (= (org-table-current-column) 0)
6283 (org-at-table-hline-p)
6284 (looking-at "[ \t]*$"))
6285 (error "Not in table data field")))
6287 (defvar org-table-clip nil
6288 "Clipboard for table regions.")
6290 (defun org-table-blank-field ()
6291 "Blank the current table field or active region."
6293 (org-table-check-inside-data-field)
6294 (if (and (interactive-p) (org-region-active-p))
6295 (let (org-table-clip)
6296 (org-table-cut-region (region-beginning) (region-end)))
6297 (skip-chars-backward "^|")
6299 (if (looking-at "|[^|\n]+")
6300 (let* ((pos (match-beginning 0))
6301 (match (match-string 0))
6302 (len (length match)))
6303 (replace-match (concat "|" (make-string (1- len) ?\ )))
6304 (goto-char (+ 2 pos))
6305 (substring match 1)))))
6307 (defun org-table-get-field (&optional n replace)
6308 "Return the value of the field in column N of current row.
6309 N defaults to current field.
6310 If REPLACE is a string, replace field with this value. The return value
6311 is always the old value."
6312 (and n (org-table-goto-column n))
6313 (skip-chars-backward "^|\n")
6315 (if (looking-at "|[^|\r\n]*")
6316 (let* ((pos (match-beginning 0))
6317 (val (buffer-substring (1+ pos) (match-end 0))))
6319 (replace-match (concat "|" replace)))
6320 (goto-char (min (point-at-eol) (+ 2 pos)))
6322 (forward-char 1) ""))
6324 (defun org-table-current-column ()
6325 "Find out which column we are in.
6326 When called interactively, column is also displayed in echo area."
6328 (if (interactive-p) (org-table-check-inside-data-field))
6330 (let ((cnt 0) (pos (point)))
6331 (beginning-of-line 1)
6332 (while (search-forward "|" pos t)
6333 (setq cnt (1+ cnt)))
6334 (if (interactive-p) (message "This is table column %d" cnt))
6337 (defun org-table-goto-column (n &optional on-delim force)
6338 "Move the cursor to the Nth column in the current table line.
6339 With optional argument ON-DELIM, stop with point before the left delimiter
6341 If there are less than N fields, just go to after the last delimiter.
6342 However, when FORCE is non-nil, create new columns if necessary."
6343 (let ((pos (point-at-eol)))
6344 (beginning-of-line 1)
6346 (while (and (> (setq n (1- n)) -1)
6347 (or (search-forward "|" pos t)
6349 (progn (end-of-line 1)
6350 (skip-chars-backward "^|")
6352 ; (backward-char 2) t)))))
6353 (when (and force (not (looking-at ".*|")))
6354 (save-excursion (end-of-line 1) (insert " | ")))
6357 (if (looking-at " ") (forward-char 1))))))
6359 (defun org-at-table-p (&optional table-type)
6360 "Return t if the cursor is inside an org-type table.
6361 If TABLE-TYPE is non-nil, also chack for table.el-type tables."
6362 (if org-enable-table-editor
6364 (beginning-of-line 1)
6365 (looking-at (if table-type org-table-any-line-regexp
6366 org-table-line-regexp)))
6369 (defun org-table-recognize-table.el ()
6370 "If there is a table.el table nearby, recognize it and move into it."
6371 (if org-table-tab-recognizes-table.el
6372 (if (org-at-table.el-p)
6374 (beginning-of-line 1)
6375 (if (looking-at org-table-dataline-regexp)
6377 (if (looking-at org-table1-hline-regexp)
6379 (beginning-of-line 2)
6380 (if (looking-at org-table-any-border-regexp)
6381 (beginning-of-line -1)))))
6382 (if (re-search-forward "|" (org-table-end t) t)
6385 (if (table--at-cell-p (point))
6387 (message "recognizing table.el table...")
6388 (table-recognize-table)
6389 (message "recognizing table.el table...done")))
6390 (error "This should not happen..."))
6395 (defun org-at-table.el-p ()
6396 "Return t if the cursor is inside a table.el-type table."
6398 (if (org-at-table-p 'any)
6400 (goto-char (org-table-begin 'any))
6401 (looking-at org-table1-hline-regexp))
6404 (defun org-at-table-hline-p ()
6405 "Return t if the cursor is inside a hline in a table."
6406 (if org-enable-table-editor
6408 (beginning-of-line 1)
6409 (looking-at org-table-hline-regexp))
6412 (defun org-table-insert-column ()
6413 "Insert a new column into the table."
6415 (if (not (org-at-table-p))
6416 (error "Not at a table"))
6417 (org-table-find-dataline)
6418 (let* ((col (max 1 (org-table-current-column)))
6419 (beg (org-table-begin))
6420 (end (org-table-end))
6421 ;; Current cursor position
6422 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6425 (while (< (point) end)
6426 (if (org-at-table-hline-p)
6428 (org-table-goto-column col t)
6430 (beginning-of-line 2))
6431 (move-marker end nil)
6433 (org-table-goto-column colpos)
6435 (org-table-modify-formulas 'insert col)))
6437 (defun org-table-find-dataline ()
6438 "Find a dataline in the current table, which is needed for column commands."
6439 (if (and (org-at-table-p)
6440 (not (org-at-table-hline-p)))
6442 (let ((col (current-column))
6443 (end (org-table-end)))
6444 (move-to-column col)
6445 (while (and (< (point) end)
6446 (or (not (= (current-column) col))
6447 (org-at-table-hline-p)))
6448 (beginning-of-line 2)
6449 (move-to-column col))
6450 (if (and (org-at-table-p)
6451 (not (org-at-table-hline-p)))
6454 "Please position cursor in a data line for column operations")))))
6456 (defun org-table-delete-column ()
6457 "Delete a column into the table."
6459 (if (not (org-at-table-p))
6460 (error "Not at a table"))
6461 (org-table-find-dataline)
6462 (org-table-check-inside-data-field)
6463 (let* ((col (org-table-current-column))
6464 (beg (org-table-begin))
6465 (end (org-table-end))
6466 ;; Current cursor position
6467 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6470 (while (< (point) end)
6471 (if (org-at-table-hline-p)
6473 (org-table-goto-column col t)
6474 (and (looking-at "|[^|\n]+|")
6475 (replace-match "|")))
6476 (beginning-of-line 2))
6477 (move-marker end nil)
6479 (org-table-goto-column colpos)
6481 (org-table-modify-formulas 'remove col)))
6483 (defun org-table-move-column-right ()
6484 "Move column to the right."
6486 (org-table-move-column nil))
6487 (defun org-table-move-column-left ()
6488 "Move column to the left."
6490 (org-table-move-column 'left))
6492 (defun org-table-move-column (&optional left)
6493 "Move the current column to the right. With arg LEFT, move to the left."
6495 (if (not (org-at-table-p))
6496 (error "Not at a table"))
6497 (org-table-find-dataline)
6498 (org-table-check-inside-data-field)
6499 (let* ((col (org-table-current-column))
6500 (col1 (if left (1- col) col))
6501 (beg (org-table-begin))
6502 (end (org-table-end))
6503 ;; Current cursor position
6504 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
6505 (colpos (if left (1- col) (1+ col))))
6506 (if (and left (= col 1))
6507 (error "Cannot move column further left"))
6508 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
6509 (error "Cannot move column further right"))
6511 (while (< (point) end)
6512 (if (org-at-table-hline-p)
6514 (org-table-goto-column col1 t)
6515 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
6516 (replace-match "|\\2|\\1|")))
6517 (beginning-of-line 2))
6518 (move-marker end nil)
6520 (org-table-goto-column colpos)
6522 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
6524 (defun org-table-move-row-down ()
6525 "move table row down."
6527 (org-table-move-row nil))
6528 (defun org-table-move-row-up ()
6529 "move table row up."
6531 (org-table-move-row 'up))
6533 (defun org-table-move-row (&optional up)
6534 "Move the current table line down. With arg UP, move it up."
6536 (let ((col (current-column))
6540 (beginning-of-line tonew)
6541 (if (not (org-at-table-p))
6544 (error "Cannot move row further")))
6546 (beginning-of-line 1)
6548 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
6549 (delete-region (point) (1+ (point-at-eol)))
6550 (beginning-of-line tonew)
6552 (beginning-of-line 0)
6553 (move-to-column col)))
6555 (defun org-table-insert-row (&optional arg)
6556 "Insert a new row above the current line into the table.
6557 With prefix ARG, insert below the current line."
6559 (if (not (org-at-table-p))
6560 (error "Not at a table"))
6561 (let* ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6563 (if (string-match "^[ \t]*|-" line)
6564 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
6565 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
6566 ;; Fix the first field if necessary
6567 (setq new (concat new))
6568 (if (string-match "^[ \t]*| *[#$] *|" line)
6569 (setq new (replace-match (match-string 0 line) t t new)))
6570 (beginning-of-line (if arg 2 1))
6571 (let (org-table-may-need-update)
6572 (insert-before-markers new)
6573 (insert-before-markers "\n"))
6574 (beginning-of-line 0)
6575 (re-search-forward "| ?" (point-at-eol) t)
6576 (and org-table-may-need-update (org-table-align))))
6578 (defun org-table-insert-hline (&optional arg)
6579 "Insert a horizontal-line below the current line into the table.
6580 With prefix ARG, insert above the current line."
6582 (if (not (org-at-table-p))
6583 (error "Not at a table"))
6584 (let ((line (buffer-substring-no-properties (point-at-bol) (point-at-eol)))
6585 (col (current-column))
6587 (if (string-match "^[ \t]*|-" line)
6589 (mapcar (lambda (x) (if (member x '(?| ?+))
6590 (prog1 (if start ?+ ?|) (setq start t))
6594 (mapcar (lambda (x) (if (equal x ?|)
6595 (prog1 (if start ?+ ?|) (setq start t))
6598 (beginning-of-line (if arg 1 2))
6599 (apply 'insert line)
6600 (if (equal (char-before (point)) ?+)
6601 (progn (backward-delete-char 1) (insert "|")))
6603 (beginning-of-line 0)
6604 (move-to-column col)))
6606 (defun org-table-kill-row ()
6607 "Delete the current row or horizontal line from the table."
6609 (if (not (org-at-table-p))
6610 (error "Not at a table"))
6611 (let ((col (current-column)))
6612 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
6613 (if (not (org-at-table-p)) (beginning-of-line 0))
6614 (move-to-column col)))
6617 (defun org-table-cut-region (beg end)
6618 "Copy region in table to the clipboard and blank all relevant fields."
6620 (org-table-copy-region beg end 'cut))
6622 (defun org-table-copy-region (beg end &optional cut)
6623 "Copy rectangular region in table to clipboard.
6624 A special clipboard is used which can only be accessed
6625 with `org-table-paste-rectangle'"
6627 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
6629 (rpl (if cut " " nil)))
6631 (org-table-check-inside-data-field)
6632 (setq l01 (count-lines (point-min) (point))
6633 c01 (org-table-current-column))
6635 (org-table-check-inside-data-field)
6636 (setq l02 (count-lines (point-min) (point))
6637 c02 (org-table-current-column))
6638 (setq l1 (min l01 l02) l2 (max l01 l02)
6639 c1 (min c01 c02) c2 (max c01 c02))
6643 (if (> l1 l2) (throw 'exit t))
6645 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
6646 (setq cols nil ic1 c1 ic2 c2)
6647 (while (< ic1 (1+ ic2))
6648 (push (org-table-get-field ic1 rpl) cols)
6649 (setq ic1 (1+ ic1)))
6650 (push (nreverse cols) region)
6651 (setq l1 (1+ l1)))))
6652 (setq org-table-clip (nreverse region))
6653 (if cut (org-table-align))
6656 (defun org-table-paste-rectangle ()
6657 "Paste a rectangular region into a table.
6658 The upper right corner ends up in the current field. All involved fields
6659 will be overwritten. If the rectangle does not fit into the present table,
6660 the table is enlarged as needed. The process ignores horizontal separator
6663 (unless (and org-table-clip (listp org-table-clip))
6664 (error "First cut/copy a region to paste!"))
6665 (org-table-check-inside-data-field)
6666 (let* ((clip org-table-clip)
6667 (line (count-lines (point-min) (point)))
6668 (col (org-table-current-column))
6669 (org-enable-table-editor t)
6670 (org-table-automatic-realign nil)
6672 (while (setq cols (pop clip))
6673 (while (org-at-table-hline-p) (beginning-of-line 2))
6674 (if (not (org-at-table-p))
6675 (progn (end-of-line 0) (org-table-next-field)))
6677 (while (setq field (pop cols))
6678 (org-table-goto-column c nil 'force)
6679 (org-table-get-field nil field)
6681 (beginning-of-line 2))
6683 (org-table-goto-column col)
6686 (defun org-table-convert ()
6687 "Convert from `org-mode' table to table.el and back.
6688 Obviously, this only works within limits. When an Org-mode table is
6689 converted to table.el, all horizontal separator lines get lost, because
6690 table.el uses these as cell boundaries and has no notion of horizontal lines.
6691 A table.el table can be converted to an Org-mode table only if it does not
6692 do row or column spanning. Multiline cells will become multiple cells.
6693 Beware, Org-mode does not test if the table can be successfully converted - it
6694 blindly applies a recipe that works for simple tables."
6697 (if (org-at-table.el-p)
6698 ;; convert to Org-mode table
6699 (let ((beg (move-marker (make-marker) (org-table-begin t)))
6700 (end (move-marker (make-marker) (org-table-end t))))
6701 (table-unrecognize-region beg end)
6703 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
6706 (if (org-at-table-p)
6707 ;; convert to table.el table
6708 (let ((beg (move-marker (make-marker) (org-table-begin)))
6709 (end (move-marker (make-marker) (org-table-end))))
6710 ;; first, get rid of all horizontal lines
6712 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
6714 ;; insert a hline before first
6716 (org-table-insert-hline 'above)
6717 ;; insert a hline after each line
6718 (while (progn (beginning-of-line 2) (< (point) end))
6719 (org-table-insert-hline))
6721 (setq end (move-marker end (org-table-end)))
6722 ;; replace "+" at beginning and ending of hlines
6723 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
6724 (replace-match "\\1+-"))
6726 (while (re-search-forward "-|[ \t]*$" end t)
6727 (replace-match "-+"))
6730 (defun org-table-wrap-region (arg)
6731 "Wrap several fields in a column like a paragraph.
6732 This is useful if you'd like to spread the contents of a field over several
6733 lines, in order to keep the table compact.
6735 If there is an active region, and both point and mark are in the same column,
6736 the text in the column is wrapped to minimum width for the given number of
6737 lines. Generally, this makes the table more compact. A prefix ARG may be
6738 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
6739 formats the selected text to two lines. If the region was longer than 2
6740 lines, the remaining lines remain empty. A negative prefix argument reduces
6741 the current number of lines by that amount. The wrapped text is pasted back
6742 into the table. If you formatted it to more lines than it was before, fields
6743 further down in the table get overwritten - so you might need to make space in
6746 If there is no region, the current field is split at the cursor position and
6747 the text fragment to the right of the cursor is prepended to the field one
6750 If there is no region, but you specify a prefix ARG, the current field gets
6751 blank, and the content is appended to the field above."
6753 (org-table-check-inside-data-field)
6754 (if (org-region-active-p)
6755 ;; There is a region: fill as a paragraph
6756 (let ((beg (region-beginning))
6758 (org-table-cut-region (region-beginning) (region-end))
6759 (if (> (length (car org-table-clip)) 1)
6760 (error "Region must be limited to single column"))
6761 (setq nlines (if arg
6763 (+ (length org-table-clip) arg)
6765 (length org-table-clip)))
6766 (setq org-table-clip
6767 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
6770 (org-table-paste-rectangle))
6771 ;; No region, split the current field at point
6773 ;; combine with field above
6774 (let ((s (org-table-blank-field))
6775 (col (org-table-current-column)))
6776 (beginning-of-line 0)
6777 (while (org-at-table-hline-p) (beginning-of-line 0))
6778 (org-table-goto-column col)
6779 (skip-chars-forward "^|")
6780 (skip-chars-backward " ")
6781 (insert " " (org-trim s))
6784 (when (looking-at "\\([^|]+\\)+|")
6785 (let ((s (match-string 1)))
6786 (replace-match " |")
6787 (goto-char (match-beginning 0))
6788 (org-table-next-row)
6789 (insert (org-trim s) " ")
6790 (org-table-align))))))
6793 "Remove whitespace at beginning and end of string."
6794 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
6795 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
6798 (defun org-wrap (string &optional width lines)
6799 "Wrap string to either a number of lines, or a width in characters.
6800 If WIDTH is non-nil, the string is wrapped to that width, however many lines
6801 that costs. If there is a word longer than WIDTH, the text is actually
6802 wrapped to the length of that word.
6803 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
6804 many lines, whatever width that takes.
6805 The return value is a list of lines, without newlines at the end."
6806 (let* ((words (org-split-string string "[ \t\n]+"))
6807 (maxword (apply 'max (mapcar 'length words)))
6810 (org-do-wrap words (max maxword width)))
6813 (setq ll (org-do-wrap words maxword))
6814 (if (<= (length ll) lines)
6817 (while (> (length ll) lines)
6819 (setq ll (org-do-wrap words w)))
6821 (t (error "Cannot wrap this")))))
6824 (defun org-do-wrap (words width)
6825 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
6828 (setq line (pop words))
6829 (while (and words (< (+ (length line) (length (car words))) width))
6830 (setq line (concat line " " (pop words))))
6831 (setq lines (push line lines)))
6834 ;; FIXME: I think I can make this more efficient
6835 (defun org-split-string (string &optional separators)
6836 "Splits STRING into substrings at SEPARATORS.
6837 No empty strings are returned if there are matches at the beginning
6839 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
6843 (while (and (string-match rexp string
6845 (= start (match-beginning 0))
6846 (< start (length string)))
6848 (< (match-beginning 0) (length string)))
6850 (or (eq (match-beginning 0) 0)
6851 (and (eq (match-beginning 0) (match-end 0))
6852 (eq (match-beginning 0) start))
6854 (cons (substring string start (match-beginning 0))
6856 (setq start (match-end 0)))
6857 (or (eq start (length string))
6859 (cons (substring string start)
6863 (defun org-table-add-invisible-to-vertical-lines ()
6864 "Add an `invisible' property to vertical lines of current table."
6866 (let* ((beg (org-table-begin))
6867 (end (org-table-end))
6871 (while (< (point) end)
6872 (setq end1 (point-at-eol))
6873 (if (looking-at org-table-dataline-regexp)
6874 (while (re-search-forward "|" end1 t)
6875 (add-text-properties (1- (point)) (point)
6876 '(invisible org-table)))
6877 (while (re-search-forward "[+|]" end1 t)
6878 (add-text-properties (1- (point)) (point)
6879 '(invisible org-table))))
6880 (beginning-of-line 2)))))
6882 (defun org-table-toggle-vline-visibility (&optional arg)
6883 "Toggle the visibility of table vertical lines.
6884 The effect is immediate and on all tables in the file.
6885 With prefix ARG, make lines invisible when ARG is positive, make lines
6886 visible when ARG is not positive"
6889 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
6890 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
6891 (t (if (org-in-invisibility-spec-p '(org-table))
6894 (if (eq action 'off)
6896 (org-remove-from-invisibility-spec '(org-table))
6897 (org-table-map-tables 'org-table-align)
6898 (message "Vertical table lines visible")
6899 (if (org-at-table-p)
6901 (org-add-to-invisibility-spec '(org-table))
6902 (org-table-map-tables 'org-table-align)
6903 (message "Vertical table lines invisible"))
6904 (redraw-frame (selected-frame))))
6906 (defun org-table-map-tables (function)
6907 "Apply FUNCTION to the start of all tables in the buffer."
6911 (goto-char (point-min))
6912 (while (re-search-forward org-table-any-line-regexp nil t)
6913 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
6914 (beginning-of-line 1)
6915 (if (looking-at org-table-line-regexp)
6916 (save-excursion (funcall function)))
6917 (re-search-forward org-table-any-border-regexp nil 1)))))
6919 (defun org-table-sum (&optional beg end nlast)
6920 "Sum numbers in region of current table column.
6921 The result will be displayed in the echo area, and will be available
6922 as kill to be inserted with \\[yank].
6924 If there is an active region, it is interpreted as a rectangle and all
6925 numbers in that rectangle will be summed. If there is no active
6926 region and point is located in a table column, sum all numbers in that
6929 If at least one number looks like a time HH:MM or HH:MM:SS, all other
6930 numbers are assumed to be times as well (in decimal hours) and the
6931 numbers are added as such.
6933 If NLAST is a number, only the NLAST fields will actually be summed."
6936 (let (col (timecnt 0) diff h m s org-table-clip)
6938 ((and beg end)) ; beg and end given explicitly
6939 ((org-region-active-p)
6940 (setq beg (region-beginning) end (region-end)))
6942 (setq col (org-table-current-column))
6943 (goto-char (org-table-begin))
6944 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
6945 (error "No table data"))
6946 (org-table-goto-column col)
6947 ;not needed? (skip-chars-backward "^|")
6949 (goto-char (org-table-end))
6950 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
6951 (error "No table data"))
6952 (org-table-goto-column col)
6953 ;not needed? (skip-chars-forward "^|")
6954 (setq end (point))))
6955 (let* ((items (apply 'append (org-table-copy-region beg end)))
6956 (items1 (cond ((not nlast) items)
6957 ((>= nlast (length items)) items)
6958 (t (setq items (reverse items))
6959 (setcdr (nthcdr (1- nlast) items) nil)
6961 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
6963 (res (apply '+ numbers))
6964 (sres (if (= timecnt 0)
6966 (setq diff (* 3600 res)
6967 h (floor (/ diff 3600)) diff (mod diff 3600)
6968 m (floor (/ diff 60)) diff (mod diff 60)
6970 (format "%d:%02d:%02d" h m s))))
6973 (message (substitute-command-keys
6974 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
6975 (length numbers) sres))))
6978 (defun org-table-get-number-for-summing (s)
6980 (if (string-match "^ *|? *" s)
6981 (setq s (replace-match "" nil nil s)))
6982 (if (string-match " *|? *$" s)
6983 (setq s (replace-match "" nil nil s)))
6984 (setq n (string-to-number s))
6986 ((and (string-match "0" s)
6987 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
6988 ((string-match "\\`[ \t]+\\'" s) nil)
6989 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
6990 (let ((h (string-to-number (or (match-string 1 s) "0")))
6991 (m (string-to-number (or (match-string 2 s) "0")))
6992 (s (string-to-number (or (match-string 4 s) "0"))))
6993 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
6994 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
6998 (defun org-table-get-vertical-vector (desc &optional tbeg col)
6999 "Get a calc vector from a column, according to descriptor DESC.
7000 Optional arguments TBEG and COL can give the beginning of the table
7001 and the current column, to avoid unnecessary parsing."
7003 (or tbeg (setq tbeg (org-table-begin)))
7004 (or col (setq col (org-table-current-column)))
7005 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
7007 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
7008 (setq n1 (- (match-end 1) (match-beginning 1)))
7009 (if (match-beginning 3)
7010 (setq n2 (- (match-end 2) (match-beginning 3))))
7011 (setq n (if n2 (max n1 n2) n1))
7012 (setq n1 (if n2 (min n1 n2)))
7014 (while (and (> nn 0)
7015 (re-search-backward org-table-hline-regexp tbeg t))
7016 (push (org-current-line) hline-list)
7018 (setq hline-list (nreverse hline-list))
7019 (goto-line (nth (1- n) hline-list))
7020 (when (re-search-forward org-table-dataline-regexp)
7021 (org-table-goto-column col)
7023 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
7024 (when (re-search-backward org-table-dataline-regexp)
7025 (org-table-goto-column col)
7027 (setq l (apply 'append (org-table-copy-region beg end)))
7028 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
7029 (if (equal x "") "0" x))
7031 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
7032 (setq n1 (string-to-number (match-string 1 desc))
7033 n2 (string-to-number (match-string 2 desc)))
7034 (beginning-of-line 1)
7036 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
7037 (org-table-goto-column col)
7038 (setq beg (point))))
7039 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
7040 (org-table-goto-column col)
7042 (setq l (apply 'append (org-table-copy-region beg end)))
7043 (concat "[" (mapconcat
7044 (lambda (x) (setq x (org-trim x))
7045 (if (equal x "") "0" x))
7047 ((string-match "\\([0-9]+\\)" desc)
7048 (beginning-of-line 1)
7049 (when (re-search-backward org-table-dataline-regexp tbeg t
7050 (string-to-number (match-string 0 desc)))
7051 (org-table-goto-column col)
7052 (org-trim (org-table-get-field))))))))
7054 (defvar org-table-formula-history nil)
7056 (defvar org-table-column-names nil
7057 "Alist with column names, derived from the `!' line.")
7058 (defvar org-table-column-name-regexp nil
7059 "Regular expression matching the current column names.")
7060 (defvar org-table-local-parameters nil
7061 "Alist with parameter names, derived from the `$' line.")
7062 (defvar org-table-named-field-locations nil
7063 "Alist with locations of named fields.")
7065 (defun org-table-get-formula (&optional equation named)
7066 "Read a formula from the minibuffer, offer stored formula as default."
7067 (let* ((name (car (rassoc (list (org-current-line)
7068 (org-table-current-column))
7069 org-table-named-field-locations)))
7072 (error "Not in a named field"))
7073 (int-to-string (org-table-current-column))))
7074 (dummy (and name (not named)
7075 (not (y-or-n-p "Replace named-field formula with column equation? " ))
7077 (org-table-may-need-update nil)
7078 (stored-list (org-table-get-stored-formulas))
7079 (stored (cdr (assoc scol stored-list)))
7081 ((and stored equation (string-match "^ *= *$" equation))
7086 (format "%s formula $%s=" (if named "Field" "Column") scol)
7087 (or stored "") 'org-table-formula-history
7091 (when (not (string-match "\\S-" eq))
7093 (setq stored-list (delq (assoc scol stored-list) stored-list))
7094 (org-table-store-formulas stored-list)
7095 (error "Formula removed"))
7096 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
7097 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
7098 (if (and name (not named))
7099 ;; We set the column equation, delete the named one.
7100 (setq stored-list (delq (assoc name stored-list) stored-list)
7103 (setcdr (assoc scol stored-list) eq)
7104 (setq stored-list (cons (cons scol eq) stored-list)))
7105 (if (or mustsave (not (equal stored eq)))
7106 (org-table-store-formulas stored-list))
7109 (defun org-table-store-formulas (alist)
7110 "Store the list of formulas below the current table."
7111 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
7113 (goto-char (org-table-end))
7114 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
7115 (delete-region (point) (match-end 0)))
7117 (mapconcat (lambda (x)
7118 (concat "$" (car x) "=" (cdr x)))
7122 (defun org-table-get-stored-formulas ()
7123 "Return an alist with the t=stored formulas directly after current table."
7125 (let (scol eq eq-alist strings string seen)
7127 (goto-char (org-table-end))
7128 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
7129 (setq strings (org-split-string (match-string 2) " *:: *"))
7130 (while (setq string (pop strings))
7131 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
7132 (setq scol (match-string 1 string)
7133 eq (match-string 2 string)
7134 eq-alist (cons (cons scol eq) eq-alist))
7135 (if (member scol seen)
7136 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
7137 (push scol seen))))))
7138 (nreverse eq-alist)))
7140 (defun org-table-modify-formulas (action &rest columns)
7141 "Modify the formulas stored below the current table.
7142 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
7143 expected, for the other action only a single column number is needed."
7144 (let ((list (org-table-get-stored-formulas))
7145 (nmax (length (org-split-string
7146 (buffer-substring (point-at-bol) (point-at-eol))
7148 col col1 col2 scol si sc1 sc2)
7150 ((null list)) ; No action needed if there are no stored formulas
7151 ((eq action 'remove)
7152 (setq col (car columns)
7153 scol (int-to-string col))
7154 (org-table-replace-in-formulas list scol "INVALID")
7155 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
7156 (loop for i from (1+ col) upto nmax by 1 do
7157 (setq si (int-to-string i))
7158 (org-table-replace-in-formulas list si (int-to-string (1- i)))
7159 (if (assoc si list) (setcar (assoc si list)
7160 (int-to-string (1- i))))))
7161 ((eq action 'insert)
7162 (setq col (car columns))
7163 (loop for i from nmax downto col by 1 do
7164 (setq si (int-to-string i))
7165 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
7166 (if (assoc si list) (setcar (assoc si list)
7167 (int-to-string (1+ i))))))
7169 (setq col1 (car columns) col2 (nth 1 columns)
7170 sc1 (int-to-string col1) sc2 (int-to-string col2))
7171 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
7172 (org-table-replace-in-formulas list sc1 "ZqZ")
7173 (org-table-replace-in-formulas list sc2 sc1)
7174 (org-table-replace-in-formulas list "ZqZ" sc2)
7175 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
7176 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
7177 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
7178 (t (error "Invalid action in `org-table-modify-formulas'")))
7179 (if list (org-table-store-formulas list))))
7181 (defun org-table-replace-in-formulas (list s1 s2)
7183 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
7184 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
7185 re (concat (regexp-quote s1) "\\>"))
7186 (while (setq elt (pop list))
7188 (while (string-match re s)
7189 (setq s (replace-match s2 t t s)))
7192 (defun org-table-get-specials ()
7193 "Get the column nmaes and local parameters for this table."
7195 (let ((beg (org-table-begin)) (end (org-table-end))
7196 names name fields fields1 field cnt c v line col)
7197 (setq org-table-column-names nil
7198 org-table-local-parameters nil
7199 org-table-named-field-locations nil)
7201 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
7202 (setq names (org-split-string (match-string 1) " *| *")
7204 (while (setq name (pop names))
7206 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
7207 (push (cons name (int-to-string cnt)) org-table-column-names))))
7208 (setq org-table-column-names (nreverse org-table-column-names))
7209 (setq org-table-column-name-regexp
7210 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
7212 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
7213 (setq fields (org-split-string (match-string 1) " *| *"))
7214 (while (setq field (pop fields))
7215 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
7216 (push (cons (match-string 1 field) (match-string 2 field))
7217 org-table-local-parameters))))
7219 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
7220 (setq c (match-string 1)
7221 fields (org-split-string (match-string 2) " *| *"))
7223 (beginning-of-line (if (equal c "_") 2 0))
7224 (setq line (org-current-line) col 1)
7225 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
7226 (setq fields1 (org-split-string (match-string 1) " *| *"))))
7227 (while (and fields1 (setq field (pop fields)))
7228 (setq v (pop fields1) col (1+ col))
7229 (when (and (stringp field) (stringp v)
7230 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
7231 (push (cons field v) org-table-local-parameters)
7232 (push (list field line col) org-table-named-field-locations)))))))
7234 (defun org-this-word ()
7235 ;; Get the current word
7237 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
7238 (end (progn (skip-chars-forward "^ \t\n") (point))))
7239 (buffer-substring-no-properties beg end))))
7241 (defun org-table-maybe-eval-formula ()
7242 "Check if the current field starts with \"=\" or \":=\".
7243 If yes, store the formula and apply it."
7244 ;; We already know we are in a table. Get field will only return a formula
7245 ;; when appropriate. It might return a separator line, but no problem.
7246 (when org-table-formula-evaluate-inline
7247 (let* ((field (org-trim (or (org-table-get-field) "")))
7249 (when (string-match "^:?=\\(.+\\)" field)
7250 (setq named (equal (string-to-char field) ?:)
7251 eq (match-string 1 field))
7252 (if (fboundp 'calc-eval)
7253 (org-table-eval-formula (if named '(4) nil) eq))))))
7255 (defvar org-recalc-commands nil
7256 "List of commands triggering the reccalculation of a line.
7257 Will be filled automatically during use.")
7259 (defvar org-recalc-marks
7260 '((" " . "Unmarked: no special line, no automatic recalculation")
7261 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
7262 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
7263 ("!" . "Column name definition line. Reference in formula as $name.")
7264 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
7265 ("_" . "Names for values in row below this one.")
7266 ("^" . "Names for values in row above this one.")))
7268 (defun org-table-rotate-recalc-marks (&optional newchar)
7269 "Rotate the recalculation mark in the first column.
7270 If in any row, the first field is not consistent with a mark,
7271 insert a new column for the makers.
7272 When there is an active region, change all the lines in the region,
7273 after prompting for the marking character.
7274 After each change, a message will be displayed indication the meaning
7277 (unless (org-at-table-p) (error "Not at a table"))
7278 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
7279 (beg (org-table-begin))
7280 (end (org-table-end))
7281 (l (org-current-line))
7282 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
7283 (l2 (if (org-region-active-p) (org-current-line (region-end))))
7287 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
7288 (col (org-table-current-column))
7289 (forcenew (car (assoc newchar org-recalc-marks)))
7292 (message "Change region to what mark? Type # * ! $ or SPC: ")
7293 (setq newchar (char-to-string (read-char-exclusive))
7294 forcenew (car (assoc newchar org-recalc-marks))))
7295 (if (and newchar (not forcenew))
7296 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
7298 (if l1 (goto-line l1))
7300 (beginning-of-line 1)
7301 (unless (looking-at org-table-dataline-regexp)
7302 (error "Not at a table data line")))
7304 (org-table-goto-column 1)
7305 (org-table-insert-column)
7306 (org-table-goto-column (1+ col)))
7307 (setq epos (point-at-eol))
7309 (beginning-of-line 1)
7310 (org-table-get-field
7311 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
7313 (setq new (or forcenew
7314 (cadr (member (match-string 1) marks))))
7320 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
7321 (and (looking-at org-table-dataline-regexp)
7322 (org-table-get-field 1 (concat " " new " "))))
7324 (if (not (= epos (point-at-eol))) (org-table-align))
7326 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
7328 (defun org-table-maybe-recalculate-line ()
7329 "Recompute the current line if marked for it, and if we haven't just done it."
7331 (and org-table-allow-automatic-line-recalculation
7332 (not (and (memq last-command org-recalc-commands)
7333 (equal org-last-recalc-line (org-current-line))))
7334 (save-excursion (beginning-of-line 1)
7335 (looking-at org-table-auto-recalculate-regexp))
7336 (fboundp 'calc-eval)
7337 (org-table-recalculate) t))
7339 (defvar org-table-formula-debug nil
7340 "Non-nil means, debug table formulas.
7341 When nil, simply write \"#ERROR\" in corrupted fields.")
7344 (defsubst org-set-calc-mode (var &optional value)
7346 (setq var (assoc var '(("D" calc-angle-mode deg)
7347 ("R" calc-angle-mode rad)
7348 ("F" calc-prefer-frac t)
7349 ("S" calc-symbolic-mode t)))
7350 value (nth 2 var) var (nth 1 var)))
7351 (if (memq var modes)
7352 (setcar (cdr (memq var modes)) value)
7353 (cons var (cons value modes)))
7356 (defun org-table-eval-formula (&optional arg equation
7357 suppress-align suppress-const
7359 "Replace the table field value at the cursor by the result of a calculation.
7361 This function makes use of Dave Gillespie's calc package, in my view the
7362 most exciting program ever written for GNU Emacs. So you need to have calc
7363 installed in order to use this function.
7365 In a table, this command replaces the value in the current field with the
7366 result of a formula. It also installes the formula as the \"current\" column
7367 formula, by storing it in a special line below the table. When called
7368 with a `C-u' prefix, the current field must ba a named field, and the
7369 formula is installed as valid in only this specific field.
7371 When called, the command first prompts for a formula, which is read in
7372 the minibuffer. Previously entered formulas are available through the
7373 history list, and the last used formula is offered as a default.
7374 These stored formulas are adapted correctly when moving, inserting, or
7375 deleting columns with the corresponding commands.
7377 The formula can be any algebraic expression understood by the calc package.
7378 For details, see the Org-mode manual.
7380 This function can also be called from Lisp programs and offers
7381 additional Arguments: EQUATION can be the formula to apply. If this
7382 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
7383 used to speed-up recursive calls by by-passing unnecessary aligns.
7384 SUPPRESS-CONST suppresses the interpretation of constants in the
7385 formula, assuming that this has been done already outside the fuction.
7386 SUPPRESS-STORE means the formula should not be stored, either because
7387 it is already stored, or because it is a modified equation that should
7388 not overwrite the stored one."
7391 (org-table-check-inside-data-field)
7392 (org-table-get-specials)
7394 (ndown (if (integerp arg) arg 1))
7395 (org-table-automatic-realign nil)
7396 (case-fold-search nil)
7398 (formula (if (and equation suppress-store)
7400 (org-table-get-formula equation (equal arg '(4)))))
7401 (n0 (org-table-current-column))
7402 (modes (copy-sequence org-calc-default-modes))
7403 n form fmt x ev orig c)
7404 ;; Parse the format string. Since we have a lot of modes, this is
7405 ;; a lot of work. However, I think calc still uses most of the time.
7406 (if (string-match ";" formula)
7407 (let ((tmp (org-split-string formula ";")))
7408 (setq formula (car tmp)
7409 fmt (concat (cdr (assoc "%" org-table-local-parameters))
7411 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
7412 (setq c (string-to-char (match-string 1 fmt))
7413 n (string-to-number (or (match-string 1 fmt) "")))
7414 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
7415 (setq modes (org-set-calc-mode
7417 (list (cdr (assoc c '((?n. float) (?f. fix)
7418 (?s. sci) (?e. eng))))
7420 (setq fmt (replace-match "" t t fmt)))
7421 (while (string-match "[DRFS]" fmt)
7422 (setq modes (org-set-calc-mode (match-string 0 fmt)))
7423 (setq fmt (replace-match "" t t fmt)))
7424 (unless (string-match "\\S-" fmt)
7426 (if (and (not suppress-const) org-table-formula-use-constants)
7427 (setq formula (org-table-formula-substitute-names formula)))
7428 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
7430 (setq fields (org-split-string
7432 (point-at-bol) (point-at-eol)) " *| *"))
7433 (if org-table-formula-numbers-only
7434 (setq fields (mapcar
7435 (lambda (x) (number-to-string (string-to-number x)))
7437 (setq ndown (1- ndown))
7438 (setq form (copy-sequence formula))
7439 ;; Insert the references to fields in same row
7440 (while (string-match "\\$\\([0-9]+\\)?" form)
7441 (setq n (if (match-beginning 1)
7442 (string-to-int (match-string 1 form))
7444 x (nth (1- n) fields))
7445 (unless x (error "Invalid field specifier \"%s\""
7446 (match-string 0 form)))
7447 (if (equal x "") (setq x "0"))
7448 (setq form (replace-match (concat "(" x ")") t t form)))
7449 ;; Insert ranges in current column
7450 (while (string-match "\\&[-I0-9]+" form)
7451 (setq form (replace-match
7453 (org-table-get-vertical-vector (match-string 0 form)
7456 (setq ev (calc-eval (cons form modes)
7457 (if org-table-formula-numbers-only 'num)))
7459 (when org-table-formula-debug
7460 (with-output-to-temp-buffer "*Help*"
7461 (princ (format "Substitution history of formula
7464 $1-> %s\n" orig formula form))
7466 (princ (format " %s^\nError: %s"
7467 (make-string (car ev) ?\-) (nth 1 ev)))
7468 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
7470 (if fmt (format fmt (string-to-number ev)) ev)))))
7471 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
7472 (unless (and (interactive-p) (not ndown))
7473 (unless (let (inhibit-redisplay)
7474 (y-or-n-p "Debugging Formula. Continue to next? "))
7477 (delete-window (get-buffer-window "*Help*"))
7479 (if (listp ev) (setq fmt nil ev "#ERROR"))
7480 (org-table-justify-field-maybe
7481 (if fmt (format fmt (string-to-number ev)) ev))
7482 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
7483 (call-interactively 'org-return)
7485 (and down (org-table-maybe-recalculate-line))
7486 (or suppress-align (and org-table-may-need-update
7487 (org-table-align)))))
7489 (defun org-table-recalculate (&optional all noalign)
7490 "Recalculate the current table line by applying all stored formulas."
7492 (or (memq this-command org-recalc-commands)
7493 (setq org-recalc-commands (cons this-command org-recalc-commands)))
7494 (unless (org-at-table-p) (error "Not at a table"))
7495 (org-table-get-specials)
7496 (let* ((eqlist (sort (org-table-get-stored-formulas)
7497 (lambda (a b) (string< (car a) (car b)))))
7498 (inhibit-redisplay t)
7499 (line-re org-table-dataline-regexp)
7500 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
7501 (thiscol (org-table-current-column))
7502 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
7503 ;; Insert constants in all formulas
7506 (setcdr x (org-table-formula-substitute-names (cdr x)))
7509 ;; Split the equation list
7510 (while (setq eq (pop eqlist))
7511 (if (<= (string-to-char (car eq)) ?9)
7514 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
7517 (setq end (move-marker (make-marker) (1+ (org-table-end))))
7518 (goto-char (setq beg (org-table-begin)))
7519 (if (re-search-forward org-table-calculate-mark-regexp end t)
7520 ;; This is a table with marked lines, only compute selected lines
7521 (setq line-re org-table-recalculate-regexp)
7522 ;; Move forward to the first non-header line
7523 (if (and (re-search-forward org-table-dataline-regexp end t)
7524 (re-search-forward org-table-hline-regexp end t)
7525 (re-search-forward org-table-dataline-regexp end t))
7526 (setq beg (match-beginning 0))
7527 nil))) ;; just leave beg where it is
7528 (setq beg (point-at-bol)
7529 end (move-marker (make-marker) (1+ (point-at-eol)))))
7531 (and all (message "Re-applying formulas to full table..."))
7532 (while (re-search-forward line-re end t)
7533 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
7534 ;; Unprotected line, recalculate
7535 (and all (message "Re-applying formulas to full table...(line %d)"
7536 (setq cnt (1+ cnt))))
7537 (setq org-last-recalc-line (org-current-line))
7539 (while (setq entry (pop eql))
7540 (goto-line org-last-recalc-line)
7541 (org-table-goto-column (string-to-int (car entry)) nil 'force)
7542 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
7543 (goto-line thisline)
7544 (org-table-goto-column thiscol)
7545 (or noalign (and org-table-may-need-update (org-table-align))
7546 (and all (message "Re-applying formulas to %d lines...done" cnt)))
7547 ;; Now do the names fields
7548 (while (setq eq (pop eqlname))
7550 a (assoc name org-table-named-field-locations))
7552 (message "Re-applying formula to named field: %s" name)
7553 (goto-line (nth 1 a))
7554 (org-table-goto-column (nth 2 a))
7555 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
7556 ;; back to initial position
7557 (goto-line thisline)
7558 (org-table-goto-column thiscol)
7559 (or noalign (and org-table-may-need-update (org-table-align))
7560 (and all (message "Re-applying formulas...done")))))
7562 (defun org-table-formula-substitute-names (f)
7563 "Replace $const with values in string F."
7564 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
7565 ;; First, check for column names
7566 (while (setq start (string-match org-table-column-name-regexp f start))
7567 (setq start (1+ start))
7568 (setq a (assoc (match-string 1 f) org-table-column-names))
7569 (setq f (replace-match (concat "$" (cdr a)) t t f)))
7570 ;; Expand ranges to vectors
7571 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
7572 (setq n1 (string-to-number (match-string 1 f))
7573 n2 (string-to-number (match-string 2 f))
7574 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
7575 s (concat "[($" (number-to-string (1- nn1)) ")"))
7576 (loop for i from nn1 upto nn2 do
7577 (setq s (concat s ",($" (int-to-string i) ")")))
7578 (setq s (concat s "]"))
7579 (if (< n2 n1) (setq s (concat "rev(" s ")")))
7580 (setq f (replace-match s t t f)))
7581 ;; Parameters and constants
7583 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
7584 (setq start (1+ start))
7585 (if (setq a (save-match-data
7586 (org-table-get-constant (match-string 1 f))))
7587 (setq f (replace-match (concat "(" a ")") t t f))))
7588 (if org-table-formula-debug
7589 (put-text-property 0 (length f) :orig-formula f1 f))
7592 (defun org-table-get-constant (const)
7593 "Find the value for a parameter or constant in a formula.
7594 Parameters get priority."
7595 (or (cdr (assoc const org-table-local-parameters))
7596 (cdr (assoc const org-table-formula-constants))
7597 (and (fboundp 'constants-get) (constants-get const))
7600 (defvar org-edit-formulas-map (make-sparse-keymap))
7601 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
7602 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
7603 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
7606 (defvar org-window-configuration)
7608 (defun org-table-edit-formulas ()
7609 "Edit the formulas of the current table in a separate buffer."
7611 (unless (org-at-table-p)
7612 (error "Not at a table"))
7613 (org-table-get-specials)
7614 (let ((eql (org-table-get-stored-formulas))
7615 (pos (move-marker (make-marker) (point)))
7616 (wc (current-window-configuration))
7618 (switch-to-buffer-other-window "*Edit Formulas*")
7621 (set (make-local-variable 'org-pos) pos)
7622 (set (make-local-variable 'org-window-configuration) wc)
7623 (use-local-map org-edit-formulas-map)
7624 (setq s "# Edit formulas and finish with `C-c C-c'.
7625 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
7626 # Use `C-c ?' to get information about $name at point.
7627 # To cancel editing, press `C-c C-q'.\n")
7628 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7630 (while (setq entry (pop eql))
7631 (when (setq loc (assoc (car entry) org-table-named-field-locations))
7632 (setq s (format "# Named formula, referring to column %d in line %d\n"
7633 (nth 2 loc) (nth 1 loc)))
7634 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
7636 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
7637 (remove-text-properties 0 (length s) '(face nil) s)
7639 (goto-char (point-min))
7640 (message "Edit formulas and finish with `C-c C-c'.")))
7642 (defun org-show-variable ()
7643 "Show the location/value of the $ expression at point."
7645 (let (var (pos org-pos) (win (selected-window)) e)
7647 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
7648 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
7649 (setq var (match-string 1))
7650 (error "No variable at point")))
7652 ((setq e (assoc var org-table-named-field-locations))
7653 (switch-to-buffer-other-window (marker-buffer pos))
7654 (goto-line (nth 1 e))
7655 (org-table-goto-column (nth 2 e))
7657 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
7658 ((setq e (assoc var org-table-column-names))
7659 (switch-to-buffer-other-window (marker-buffer pos))
7661 (goto-char (org-table-begin))
7662 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
7665 (goto-char (match-beginning 1))
7666 (message "Named column (column %s)" (cdr e)))
7667 (error "Column name not found"))
7668 (select-window win))
7669 ((string-match "^[0-9]$" var)
7671 (switch-to-buffer-other-window (marker-buffer pos))
7673 (goto-char (org-table-begin))
7675 (if (re-search-forward org-table-dataline-regexp
7678 (goto-char (match-beginning 0))
7679 (org-table-goto-column (string-to-number var))
7680 (message "Column %s" var))
7681 (error "Column name not found"))
7682 (select-window win))
7683 ((setq e (assoc var org-table-local-parameters))
7684 (switch-to-buffer-other-window (marker-buffer pos))
7686 (goto-char (org-table-begin))
7687 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
7689 (goto-char (match-beginning 1))
7690 (message "Local parameter."))
7691 (error "Parameter not found"))
7692 (select-window win))
7695 ((setq e (assoc var org-table-formula-constants))
7696 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
7697 ((setq e (and (fboundp 'constants-get) (constants-get var)))
7698 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
7699 (t (error "Undefined name $%s" var)))))))
7701 (defun org-finish-edit-formulas (&optional arg)
7702 "Parse the buffer for formula definitions and install them.
7703 With prefix ARG, apply the new formulas to the table."
7705 (let ((pos org-pos) eql)
7706 (goto-char (point-min))
7707 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
7708 (push (cons (match-string 1) (match-string 2)) eql))
7709 (set-window-configuration org-window-configuration)
7710 (select-window (get-buffer-window (marker-buffer pos)))
7712 (unless (org-at-table-p)
7713 (error "Lost table position - cannot install formulae"))
7714 (org-table-store-formulas eql)
7715 (move-marker pos nil)
7716 (kill-buffer "*Edit Formulas*")
7718 (org-table-recalculate 'all)
7719 (message "New formulas installed - press C-u C-c C-c to apply."))))
7721 (defun org-abort-edit-formulas ()
7722 "Abort editing formulas, without installing the changes."
7724 (let ((pos org-pos))
7725 (set-window-configuration org-window-configuration)
7726 (select-window (get-buffer-window (marker-buffer pos)))
7728 (message "Formula editing aborted without installing changes")))
7730 ;;; The orgtbl minor mode
7732 ;; Define a minor mode which can be used in other modes in order to
7733 ;; integrate the org-mode table editor.
7735 ;; This is really a hack, because the org-mode table editor uses several
7736 ;; keys which normally belong to the major mode, for example the TAB and
7737 ;; RET keys. Here is how it works: The minor mode defines all the keys
7738 ;; necessary to operate the table editor, but wraps the commands into a
7739 ;; function which tests if the cursor is currently inside a table. If that
7740 ;; is the case, the table editor command is executed. However, when any of
7741 ;; those keys is used outside a table, the function uses `key-binding' to
7742 ;; look up if the key has an associated command in another currently active
7743 ;; keymap (minor modes, major mode, global), and executes that command.
7744 ;; There might be problems if any of the keys used by the table editor is
7745 ;; otherwise used as a prefix key.
7747 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7748 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7749 ;; addresses this by checking explicitly for both bindings.
7751 ;; The optimized version (see variable `orgtbl-optimized') takes over
7752 ;; all keys which are bound to `self-insert-command' in the *global map*.
7753 ;; Some modes bind other commands to simple characters, for example
7754 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
7755 ;; active, this binding is ignored inside tables and replaced with a
7756 ;; modified self-insert.
7758 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
7759 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
7760 In the optimized version, the table editor takes over all simple keys that
7761 normally just insert a character. In tables, the characters are inserted
7762 in a way to minimize disturbing the table structure (i.e. in overwrite mode
7763 for empty fields). Outside tables, the correct binding of the keys is
7766 The default for this option is t if the optimized version is also used in
7767 Org-mode. See the variable `org-enable-table-editor' for details. Changing
7768 this variable requires a restart of Emacs to become effective."
7772 (defvar orgtbl-mode nil
7773 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
7774 table editor in arbitrary modes.")
7775 (make-variable-buffer-local 'orgtbl-mode)
7777 (defvar orgtbl-mode-map (make-sparse-keymap)
7778 "Keymap for `orgtbl-mode'.")
7781 (defun turn-on-orgtbl ()
7782 "Unconditionally turn on `orgtbl-mode'."
7786 (defun orgtbl-mode (&optional arg)
7787 "The `org-mode' table editor as a minor mode for use in other modes."
7789 (if (eq major-mode 'org-mode)
7790 ;; Exit without error, in case some hook functions calls this
7791 ;; by accident in org-mode.
7792 (message "Orgtbl-mode is not useful in org-mode, command ignored")
7794 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
7797 (and (orgtbl-setup) (defun orgtbl-setup () nil))
7798 ;; Make sure we are first in minor-mode-map-alist
7799 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
7800 (and c (setq minor-mode-map-alist
7801 (cons c (delq c minor-mode-map-alist)))))
7802 (set (make-local-variable (quote org-table-may-need-update)) t)
7803 (make-local-hook (quote before-change-functions))
7804 (add-hook 'before-change-functions 'org-before-change-function
7806 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
7807 auto-fill-inhibit-regexp)
7808 (set (make-local-variable 'auto-fill-inhibit-regexp)
7809 (if auto-fill-inhibit-regexp
7810 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
7812 (easy-menu-add orgtbl-mode-menu)
7813 (run-hooks 'orgtbl-mode-hook))
7814 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
7815 (remove-hook 'before-change-functions 'org-before-change-function t)
7816 (easy-menu-remove orgtbl-mode-menu)
7817 (force-mode-line-update 'all))))
7819 ;; Install it as a minor mode.
7820 (put 'orgtbl-mode :included t)
7821 (put 'orgtbl-mode :menu-tag "Org Table Mode")
7822 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
7824 (defun orgtbl-make-binding (fun n &rest keys)
7825 "Create a function for binding in the table minor mode.
7826 FUN is the command to call inside a table. N is used to create a unique
7827 command name. KEYS are keys that should be checked in for a command
7828 to execute outside of tables."
7831 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
7833 (concat "In tables, run `" (symbol-name fun) "'.\n"
7834 "Outside of tables, run the binding of `"
7835 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7840 (list 'call-interactively (list 'quote fun))
7841 (list 'let '(orgtbl-mode)
7842 (list 'call-interactively
7845 (list 'key-binding k))
7847 '('orgtbl-error))))))))
7849 (defun orgtbl-error ()
7850 "Error when there is no default binding for a table key."
7852 (error "This key is has no function outside tables"))
7854 (defun orgtbl-setup ()
7855 "Setup orgtbl keymaps."
7859 '([(meta shift left)] org-table-delete-column)
7860 '([(meta left)] org-table-move-column-left)
7861 '([(meta right)] org-table-move-column-right)
7862 '([(meta shift right)] org-table-insert-column)
7863 '([(meta shift up)] org-table-kill-row)
7864 '([(meta shift down)] org-table-insert-row)
7865 '([(meta up)] org-table-move-row-up)
7866 '([(meta down)] org-table-move-row-down)
7867 '("\C-c\C-w" org-table-cut-region)
7868 '("\C-c\M-w" org-table-copy-region)
7869 '("\C-c\C-y" org-table-paste-rectangle)
7870 '("\C-c-" org-table-insert-hline)
7871 '([(shift tab)] org-table-previous-field)
7872 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7873 '("\C-m" org-table-next-row)
7874 (list (org-key 'S-return) 'org-table-copy-down)
7875 '([(meta return)] org-table-wrap-region)
7876 '("\C-c\C-q" org-table-wrap-region)
7877 '("\C-c?" org-table-current-column)
7878 '("\C-c " org-table-blank-field)
7879 '("\C-c+" org-table-sum)
7880 '("\C-c|" org-table-toggle-vline-visibility)
7881 '("\C-c=" org-table-eval-formula)
7882 '("\C-c'" org-table-edit-formulas)
7883 '("\C-c*" org-table-recalculate)
7884 '([(control ?#)] org-table-rotate-recalc-marks)))
7886 (while (setq elt (pop bindings))
7887 (setq nfunc (1+ nfunc))
7890 cmd (orgtbl-make-binding fun nfunc key))
7891 (define-key orgtbl-mode-map key cmd))
7892 ;; Special treatment needed for TAB and RET
7893 (define-key orgtbl-mode-map [(return)]
7894 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
7895 (define-key orgtbl-mode-map "\C-m"
7896 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
7897 (define-key orgtbl-mode-map [(tab)]
7898 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
7899 (define-key orgtbl-mode-map "\C-i"
7900 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
7901 (when orgtbl-optimized
7902 ;; If the user wants maximum table support, we need to hijack
7903 ;; some standard editing functions
7904 (substitute-key-definition 'self-insert-command 'orgtbl-self-insert-command
7905 orgtbl-mode-map global-map)
7906 (substitute-key-definition 'delete-char 'orgtbl-delete-char
7907 orgtbl-mode-map global-map)
7908 (substitute-key-definition 'delete-backward-char 'orgtbl-delete-backward-char
7909 orgtbl-mode-map global-map)
7910 (define-key org-mode-map "|" 'self-insert-command))
7911 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
7913 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
7914 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
7915 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
7916 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
7918 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
7919 ["Copy Field from Above"
7920 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
7923 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
7924 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
7925 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
7926 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
7928 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
7929 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
7930 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
7931 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
7933 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
7935 ["Copy Rectangle" org-copy-special :active (org-at-table-p) :keys "C-c M-w"]
7936 ["Cut Rectangle" org-cut-special :active (org-at-table-p) :keys "C-c C-w"]
7937 ["Paste Rectangle" org-paste-special :active (org-at-table-p) :keys "C-c C-y"]
7938 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p) :keys "C-c C-q"])
7940 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
7941 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
7942 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
7943 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
7944 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
7945 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
7946 ["Sum Column/Rectangle" org-table-sum
7947 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
7948 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
7950 (setq org-table-formula-debug (not org-table-formula-debug))
7951 :style toggle :selected org-table-formula-debug]
7955 (defun orgtbl-tab ()
7956 "Justification and field motion for `orgtbl-mode'."
7958 (org-table-justify-field-maybe)
7959 (org-table-next-field))
7961 (defun orgtbl-ret ()
7962 "Justification and field motion for `orgtbl-mode'."
7964 (org-table-justify-field-maybe)
7965 (org-table-next-row))
7967 (defun orgtbl-self-insert-command (N)
7968 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
7969 If the cursor is in a table looking at whitespace, the whitespace is
7970 overwritten, and the table is not marked as requiring realignment."
7972 (if (and (org-at-table-p)
7974 (looking-at "[^|\n]* +|"))
7975 (let (org-table-may-need-update)
7976 (goto-char (1- (match-end 0)))
7977 (delete-backward-char 1)
7978 (goto-char (match-beginning 0))
7979 (self-insert-command N))
7980 (setq org-table-may-need-update t)
7982 (call-interactively (key-binding (vector last-input-event))))))
7984 (defun orgtbl-delete-backward-char (N)
7985 "Like `delete-backward-char', insert whitespace at field end in tables.
7986 When deleting backwards, in tables this function will insert whitespace in
7987 front of the next \"|\" separator, to keep the table aligned. The table will
7988 still be marked for re-alignment, because a narrow field may lead to a
7989 reduced column width."
7991 (if (and (org-at-table-p)
7993 (string-match "|" (buffer-substring (point-at-bol) (point)))
7994 (looking-at ".*?|"))
7995 (let ((pos (point)))
7996 (backward-delete-char N)
7997 (skip-chars-forward "^|")
7999 (goto-char (1- pos)))
8000 (delete-backward-char N)))
8002 (defun orgtbl-delete-char (N)
8003 "Like `delete-char', but insert whitespace at field end in tables.
8004 When deleting characters, in tables this function will insert whitespace in
8005 front of the next \"|\" separator, to keep the table aligned. The table
8006 will still be marked for re-alignment, because a narrow field may lead to
8007 a reduced column width."
8009 (if (and (org-at-table-p)
8011 (not (= (char-after) ?|))
8013 (if (looking-at ".*?|")
8014 (let ((pos (point)))
8015 (replace-match (concat
8016 (substring (match-string 0) 1 -1)
8023 (defconst org-level-max 20)
8025 (defun org-export-find-first-heading-line (list)
8026 "Remove all lines from LIST which are before the first headline."
8027 (let ((orig-list list)
8028 (re (concat "^" outline-regexp)))
8030 (not (string-match re (car list))))
8032 (or list orig-list)))
8034 (defun org-skip-comments (lines)
8035 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
8036 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
8037 (re2 "^\\(\\*+\\)[ \t\n\r]")
8039 (while (setq line (pop lines))
8041 ((and (string-match re1 line)
8042 (setq level (- (match-end 1) (match-beginning 1))))
8043 ;; Beginning of a COMMENT subtree. Skip it.
8044 (while (and (setq line (pop lines))
8045 (or (not (string-match re2 line))
8046 (> (- (match-end 1) (match-beginning 1)) level))))
8047 (setq lines (cons line lines)))
8048 ((string-match "^#" line)
8049 ;; an ordinary comment line
8051 (t (setq rtn (cons line rtn)))))
8056 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
8057 "Characters for underlining headings in ASCII export.")
8059 (defconst org-html-entities
8099 ("Aring") ("AA"."Å")
8188 ("varepsilon"."ε")
8201 ("sigmaf") ("varsigma"."ς")
8209 ("thetasym") ("vartheta"."ϑ")
8212 ("bull") ("bullet"."•")
8213 ("hellip") ("dots"."…")
8223 ("larr") ("leftarrow"."←") ("gets"."←")
8224 ("uarr") ("uparrow"."↑")
8225 ("rarr") ("to"."→") ("rightarrow"."→")
8226 ("darr")("downarrow"."↓")
8227 ("harr") ("leftrightarrow"."↔")
8228 ("crarr") ("hookleftarrow"."↵") ; has round hook, not quite CR
8229 ("lArr") ("Leftarrow"."⇐")
8230 ("uArr") ("Uparrow"."⇑")
8231 ("rArr") ("Rightarrow"."⇒")
8232 ("dArr") ("Downarrow"."⇓")
8233 ("hArr") ("Leftrightarrow"."⇔")
8235 ("part") ("partial"."∂")
8236 ("exist") ("exists"."∃")
8237 ("empty") ("emptyset"."∅")
8239 ("isin") ("in"."∈")
8245 ("lowast") ("ast"."∗")
8247 ("prop") ("proptp"."∝")
8248 ("infin") ("infty"."∞")
8249 ("ang") ("angle"."∠")
8250 ("and") ("vee"."∧")
8251 ("or") ("wedge"."∨")
8257 ("cong") ("simeq"."≅")
8258 ("asymp")("approx"."≈")
8259 ("ne") ("neq"."≠")
8263 ("sub") ("subset"."⊂")
8264 ("sup") ("supset"."⊃")
8271 ("sdot") ("cdot"."⋅")
8278 ("loz") ("Diamond"."◊")
8279 ("spades") ("spadesuit"."♠")
8280 ("clubs") ("clubsuit"."♣")
8281 ("hearts") ("diamondsuit"."♥")
8282 ("diams") ("diamondsuit"."♦")
8349 "Entities for TeX->HTML translation.
8350 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
8351 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
8352 In that case, \"\\ent\" will be translated to \"&other;\".
8353 The list contains HTML entities for Latin-1, Greek and other symbols.
8354 It is supplemented by a number of commonly used TeX macros with appropriate
8355 translations. There is currently no way for users to extend this.")
8357 (defvar org-last-level nil) ; dynamically scoped variable
8359 (defun org-export-as-ascii (arg)
8360 "Export the outline as a pretty ASCII file.
8361 If there is an active region, export only the region.
8362 The prefix ARG specifies how many levels of the outline should become
8363 underlined headlines. The default is 3."
8365 (setq-default org-todo-line-regexp org-todo-line-regexp)
8368 (if (org-region-active-p) (region-beginning) (point-min))
8369 (if (org-region-active-p) (region-end) (point-max))))
8370 (lines (org-export-find-first-heading-line
8371 (org-skip-comments (org-split-string region "[\r\n]"))))
8372 (org-startup-with-deadline-check nil)
8375 (case-fold-search nil)
8376 (filename (concat (file-name-sans-extension (buffer-file-name))
8378 (buffer (find-file-noselect filename))
8379 (levels-open (make-vector org-level-max nil))
8380 (date (format-time-string "%Y/%m/%d" (current-time)))
8381 (time (format-time-string "%X" (current-time)))
8382 (author user-full-name)
8383 (title (buffer-name))
8385 (email user-mail-address)
8386 (language org-export-default-language)
8391 (setq org-last-level 1)
8392 (org-init-section-numbers)
8394 (find-file-noselect filename)
8396 ;; Search for the export key lines
8397 (org-parse-key-lines)
8399 (setq lang-words (or (assoc language org-export-language-setup)
8400 (assoc "en" org-export-language-setup)))
8401 (if org-export-ascii-show-new-buffer
8402 (switch-to-buffer-other-window buffer)
8403 (set-buffer buffer))
8406 (if options (org-parse-export-options options))
8407 (setq umax (if arg (prefix-numeric-value arg)
8408 org-export-headline-levels))
8411 (if title (org-insert-centered title ?=))
8413 (if (or author email)
8414 (insert (concat (nth 1 lang-words) ": " (or author "")
8415 (if email (concat " <" email ">") "")
8418 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
8419 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
8423 (if org-export-with-toc
8425 (insert (nth 3 lang-words) "\n"
8426 (make-string (length (nth 3 lang-words)) ?=) "\n")
8427 (mapcar '(lambda (line)
8428 (if (string-match org-todo-line-regexp
8430 ;; This is a headline
8432 (setq level (- (match-end 1) (match-beginning 1))
8433 txt (match-string 3 line)
8435 (or (and (match-beginning 2)
8436 (not (equal (match-string 2 line)
8440 (org-search-todo-below
8441 line lines level))))
8442 (setq txt (org-html-expand-for-ascii txt))
8444 (if org-export-with-section-numbers
8445 (setq txt (concat (org-section-number level)
8450 (make-string (* (1- level) 4) ?\ )
8451 (format (if todo "%s (*)\n" "%s\n") txt))
8452 (setq org-last-level level))
8456 (org-init-section-numbers)
8457 (while (setq line (pop lines))
8458 ;; Remove the quoted HTML tags.
8459 (setq line (org-html-expand-for-ascii line))
8461 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8463 (setq level (- (match-end 1) (match-beginning 1))
8464 txt (match-string 2 line))
8465 (org-ascii-level-start level txt umax))
8466 (t (insert line "\n"))))
8469 (goto-char (point-min))))
8471 (defun org-search-todo-below (line lines level)
8472 "Search the subtree below LINE for any TODO entries."
8473 (let ((rest (cdr (memq line lines)))
8474 (re org-todo-line-regexp)
8477 (while (setq line (pop rest))
8478 (if (string-match re line)
8480 (setq lv (- (match-end 1) (match-beginning 1))
8481 todo (and (match-beginning 2)
8482 (not (equal (match-string 2 line)
8485 (if (<= lv level) (throw 'exit nil))
8486 (if todo (throw 'exit t))))))))
8488 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
8489 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
8490 (defun org-html-expand-for-ascii (line)
8491 "Handle quoted HTML for ASCII export."
8492 (if org-export-html-expand
8493 (while (string-match "@<[^<>\n]*>" line)
8494 ;; We just remove the tags for now.
8495 (setq line (replace-match "" nil nil line))))
8498 (defun org-insert-centered (s &optional underline)
8499 "Insert the string S centered and underline it with character UNDERLINE."
8500 (let ((ind (max (/ (- 80 (length s)) 2) 0)))
8501 (insert (make-string ind ?\ ) s "\n")
8503 (insert (make-string ind ?\ )
8504 (make-string (length s) underline)
8507 (defun org-ascii-level-start (level title umax)
8508 "Insert a new level in ASCII export."
8511 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
8512 (if (or (not (equal (char-before) ?\n))
8513 (not (equal (char-before (1- (point))) ?\n)))
8515 (setq char (nth (- umax level) (reverse org-ascii-underline)))
8516 (if org-export-with-section-numbers
8517 (setq title (concat (org-section-number level) " " title)))
8518 (insert title "\n" (make-string (string-width title) char) "\n"))))
8520 (defun org-export-copy-visible ()
8521 "Copy the visible part of the buffer to another buffer, for printing.
8522 Also removes the first line of the buffer if it specifies a mode,
8523 and all options lines."
8525 (let* ((filename (concat (file-name-sans-extension (buffer-file-name))
8527 (buffer (find-file-noselect filename))
8529 (org-make-options-regexp
8530 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
8532 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
8533 (if org-noutline-p "\\(\n\\|$\\)" "")))
8535 (with-current-buffer buffer
8539 (setq s (goto-char (point-min)))
8540 (while (not (= (point) (point-max)))
8541 (goto-char (org-find-invisible))
8542 (append-to-buffer buffer s (point))
8543 (setq s (goto-char (org-find-visible)))))
8544 (switch-to-buffer-other-window buffer)
8546 (goto-char (point-min))
8547 (if (looking-at ".*-\\*- mode:.*\n")
8549 (while (re-search-forward ore nil t)
8551 (goto-char (point-min))))
8553 (defun org-find-visible ()
8554 (if (featurep 'noutline)
8556 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8557 (get-char-property s 'invisible)))
8559 (skip-chars-forward "^\n")
8561 (defun org-find-invisible ()
8562 (if (featurep 'noutline)
8564 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
8565 (not (get-char-property s 'invisible))))
8567 (skip-chars-forward "^\r")
8572 (defun org-get-current-options ()
8573 "Return a string with current options as keyword options.
8574 Does include HTML export options as well as TODO and CATEGORY stuff."
8580 #+TEXT: Some descriptive text to be emitted. Several lines OK.
8581 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
8588 (buffer-name) (user-full-name) user-mail-address org-export-default-language
8589 org-export-headline-levels
8590 org-export-with-section-numbers
8592 org-export-preserve-breaks
8593 org-export-html-expand
8594 org-export-with-fixed-width
8595 org-export-with-tables
8596 org-export-with-sub-superscripts
8597 org-export-with-emphasize
8598 org-export-with-TeX-macros
8599 (file-name-nondirectory (buffer-file-name))
8600 (if (equal org-todo-interpretation 'sequence)
8601 (mapconcat 'identity org-todo-keywords " ")
8602 "TODO FEEDBACK VERIFY DONE")
8603 (if (equal org-todo-interpretation 'type)
8604 (mapconcat 'identity org-todo-keywords " ")
8605 "Me Jason Marie DONE")
8606 (cdr (assoc org-startup-folded
8607 '((nil . "nofold")(t . "fold")(content . "content"))))
8608 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
8609 org-archive-location
8612 (defun org-insert-export-options-template ()
8613 "Insert into the buffer a template with information for exporting."
8615 (if (not (bolp)) (newline))
8616 (let ((s (org-get-current-options)))
8617 (and (string-match "#\\+CATEGORY" s)
8618 (setq s (substring s 0 (match-beginning 0))))
8621 (defun org-toggle-fixed-width-section (arg)
8622 "Toggle the fixed-width indicator at the beginning of lines in the region.
8623 If there is no active region, only acts on the current line.
8624 If the first non-white character in the first line of the region is a
8625 vertical bar \"|\", then the command removes the bar from all lines in
8626 the region. If the first character is not a bar, the command adds a
8627 bar to all lines, in the column given by the beginning of the region.
8629 If there is a numerical prefix ARG, create ARG new lines starting with \"|\"."
8632 (regionp (org-region-active-p))
8633 (beg (if regionp (region-beginning) (point)))
8634 (end (if regionp (region-end)))
8635 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
8636 (re "[ \t]*\\(:\\)")
8640 (setq cc (current-column))
8641 (beginning-of-line 1)
8642 (setq off (looking-at re))
8644 (setq nlines (1- nlines))
8645 (beginning-of-line 1)
8648 (move-to-column cc t)
8651 ((and off (looking-at re))
8652 (replace-match "" t t nil 1))
8653 ((not off) (move-to-column cc t) (insert ":")))
8654 (forward-line 1)))))
8656 (defun org-export-as-html-and-open (arg)
8657 "Export the outline as HTML and immediately open it with a browser.
8658 If there is an active region, export only the region.
8659 The prefix ARG specifies how many levels of the outline should become
8660 headlines. The default is 3. Lower levels will become bulleted lists."
8662 (org-export-as-html arg 'hidden)
8663 (org-open-file (buffer-file-name)))
8665 (defun org-export-as-html-batch ()
8666 "Call `org-export-as-html', may be used in batch processing as
8668 --load=$HOME/lib/emacs/org.el
8669 --eval \"(setq org-export-headline-levels 2)\"
8670 --visit=MyFile --funcall org-export-as-html-batch"
8671 (org-export-as-html org-export-headline-levels 'hidden))
8673 (defun org-export-as-html (arg &optional hidden)
8674 "Export the outline as a pretty HTML file.
8675 If there is an active region, export only the region.
8676 The prefix ARG specifies how many levels of the outline should become
8677 headlines. The default is 3. Lower levels will become bulleted lists."
8679 (setq-default org-todo-line-regexp org-todo-line-regexp)
8680 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
8681 (setq-default org-done-string org-done-string)
8682 (let* ((region-p (org-region-active-p))
8685 (if region-p (region-beginning) (point-min))
8686 (if region-p (region-end) (point-max))))
8688 (org-skip-comments (org-split-string region "[\r\n]")))
8689 (lines (org-export-find-first-heading-line all_lines))
8690 (level 0) (line "") (origline "") txt todo
8692 (filename (concat (file-name-sans-extension (buffer-file-name))
8694 (buffer (find-file-noselect filename))
8695 (levels-open (make-vector org-level-max nil))
8696 (date (format-time-string "%Y/%m/%d" (current-time)))
8697 (time (format-time-string "%X" (current-time)))
8698 (author user-full-name)
8699 (title (buffer-name))
8701 (email user-mail-address)
8702 (language org-export-default-language)
8708 table-buffer table-orig-buffer
8710 (message "Exporting...")
8712 (setq org-last-level 1)
8713 (org-init-section-numbers)
8715 ;; Search for the export key lines
8716 (org-parse-key-lines)
8717 (setq lang-words (or (assoc language org-export-language-setup)
8718 (assoc "en" org-export-language-setup)))
8720 ;; Switch to the output buffer
8721 (if (or hidden (not org-export-html-show-new-buffer))
8723 (switch-to-buffer-other-window buffer))
8726 (let ((case-fold-search nil))
8727 (if options (org-parse-export-options options))
8728 (setq umax (if arg (prefix-numeric-value arg)
8729 org-export-headline-levels))
8733 "<html lang=\"%s\"><head>
8735 <meta http-equiv=\"Content-Type\" content=\"text/html\">
8736 <meta name=generator content=\"Org-mode\">
8737 <meta name=generated content=\"%s %s\">
8738 <meta name=author content=\"%s\">
8741 language (org-html-expand title) date time author))
8742 (if title (insert (concat "<H1 align=\"center\">"
8743 (org-html-expand title) "</H1>\n")))
8744 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
8745 (if email (insert (concat "<a href=\"mailto:" email "\"><"
8746 email "></a>\n")))
8747 (if (or author email) (insert "<br>\n"))
8748 (if (and date time) (insert (concat (nth 2 lang-words) ": "
8749 date " " time "<br>\n")))
8750 (if text (insert (concat "<p>\n" (org-html-expand text))))
8751 (if org-export-with-toc
8753 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
8755 (mapcar '(lambda (line)
8756 (if (string-match org-todo-line-regexp line)
8757 ;; This is a headline
8759 (setq level (- (match-end 1) (match-beginning 1))
8760 txt (save-match-data
8762 (match-string 3 line)))
8764 (or (and (match-beginning 2)
8765 (not (equal (match-string 2 line)
8769 (org-search-todo-below
8770 line lines level))))
8771 (if org-export-with-section-numbers
8772 (setq txt (concat (org-section-number level)
8776 (setq head-count (+ head-count 1))
8777 (if (> level org-last-level)
8779 (setq cnt (- level org-last-level))
8780 (while (>= (setq cnt (1- cnt)) 0)
8783 (if (< level org-last-level)
8785 (setq cnt (- org-last-level level))
8786 (while (>= (setq cnt (1- cnt)) 0)
8792 "<li><a href=\"#sec-%d\"><span style='color:red'>%s</span></a></li>\n"
8793 "<li><a href=\"#sec-%d\">%s</a></li>\n")
8795 (setq org-last-level level))
8798 (while (> org-last-level 0)
8799 (setq org-last-level (1- org-last-level))
8803 (org-init-section-numbers)
8804 (while (setq line (pop lines) origline line)
8805 ;; Protect the links
8807 (while (string-match org-link-maybe-angles-regexp line start)
8808 (setq start (match-end 0))
8809 (setq line (replace-match
8810 (concat "\000" (match-string 1 line) "\000")
8813 ;; replace "<" and ">" by "<" and ">"
8814 ;; handle @<..> HTML tags (replace "@>..<" by "<..>")
8815 (setq line (org-html-expand line))
8818 (if (and org-export-with-fixed-width
8819 (string-match "^[ \t]*:\\(.*\\)" line))
8821 (let ((l (match-string 1 line)))
8822 (while (string-match " " l)
8823 (setq l (replace-match " " t t l)))
8824 (insert "\n<span style='font-family:Courier'>"
8827 (not (string-match "^[ \t]+\\(:.*\\)"
8831 (while (string-match org-protected-link-regexp line start)
8832 (setq start (- (match-end 0) 2))
8833 (setq type (match-string 1 line))
8835 ((member type '("http" "https" "ftp" "mailto" "news"))
8837 (setq line (replace-match
8838 ; "<a href=\"\\1:\\2\"><\\1:\\2></a>"
8839 "<a href=\"\\1:\\2\">\\1:\\2</a>"
8841 ((string= type "file")
8843 (let* ((filename (match-string 2 line))
8844 (abs-p (file-name-absolute-p filename))
8845 (thefile (if abs-p (expand-file-name filename) filename))
8846 (thefile (save-match-data
8847 (if (string-match ":[0-9]+$" thefile)
8848 (replace-match "" t t thefile)
8852 (string-match (org-image-file-name-regexp) thefile))))
8853 (setq line (replace-match
8854 (if (and org-export-html-inline-images
8856 (concat "<img src=\"" thefile "\"/>")
8857 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
8860 ((member type '("bbdb" "vm" "wl" "rmail" "gnus" "shell"))
8861 (setq line (replace-match
8862 "<i><\\1:\\2></i>" nil nil line)))))
8865 (if (and (string-match org-todo-line-regexp line)
8866 (match-beginning 2))
8867 (if (equal (match-string 2 line) org-done-string)
8868 (setq line (replace-match
8869 "<span style='color:green'>\\2</span>"
8871 (setq line (replace-match "<span style='color:red'>\\2</span>"
8875 (if (string-match org-deadline-line-regexp line)
8877 (if (save-match-data
8878 (string-match "<a href"
8879 (substring line 0 (match-beginning 0))))
8880 nil ; Don't do the replacement - it is inside a link
8881 (setq line (replace-match "<span style='color:red'>\\&</span>"
8885 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
8886 ;; This is a headline
8887 (setq level (- (match-end 1) (match-beginning 1))
8888 txt (match-string 2 line))
8889 (if (<= level umax) (setq head-count (+ head-count 1)))
8890 (org-html-level-start level txt umax
8891 (and org-export-with-toc (<= level umax))
8894 ((and org-export-with-tables
8895 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
8896 (if (not table-open)
8898 (setq table-open t table-buffer nil table-orig-buffer nil))
8900 (setq table-buffer (cons line table-buffer)
8901 table-orig-buffer (cons origline table-orig-buffer))
8902 (when (or (not lines)
8903 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
8905 (setq table-open nil
8906 table-buffer (nreverse table-buffer)
8907 table-orig-buffer (nreverse table-orig-buffer))
8908 (insert (org-format-table-html table-buffer table-orig-buffer))))
8911 ;; Lines starting with "-", and empty lines make new paragraph.
8912 ;; FIXME: Should we add + and *?
8913 (if (string-match "^ *-\\|^[ \t]*$" line) (insert "<p>"))
8914 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
8916 (if org-export-html-with-timestamp
8917 (insert org-export-html-html-helper-timestamp))
8918 (insert "</body>\n</html>\n")
8921 (goto-char (point-min)))))
8923 (defun org-format-table-html (lines olines)
8924 "Find out which HTML converter to use and return the HTML code."
8925 (if (string-match "^[ \t]*|" (car lines))
8926 ;; A normal org table
8927 (org-format-org-table-html lines)
8928 ;; Table made by table.el - test for spanning
8929 (let* ((hlines (delq nil (mapcar
8931 (if (string-match "^[ \t]*\\+-" x) x
8934 (first (car hlines))
8935 (ll (and (string-match "\\S-+" first)
8936 (match-string 0 first)))
8937 (re (concat "^[ \t]*" (regexp-quote ll)))
8938 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
8940 (if (and (not spanning)
8941 (not org-export-prefer-native-exporter-for-tables))
8942 ;; We can use my own converter with HTML conversions
8943 (org-format-table-table-html lines)
8944 ;; Need to use the code generator in table.el, with the original text.
8945 (org-format-table-table-html-using-table-generate-source olines)))))
8947 (defun org-format-org-table-html (lines)
8948 "Format a table into html."
8949 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
8950 (setq lines (nreverse lines))
8951 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
8952 (setq lines (nreverse lines))
8953 (let ((head (and org-export-highlight-first-table-line
8955 (lambda (x) (string-match "^[ \t]*|-" x))
8958 (setq html (concat org-export-html-table-tag "\n"))
8959 (while (setq line (pop lines))
8961 (if (string-match "^[ \t]*|-" line)
8963 (setq head nil) ;; head ends here, first time around
8965 (throw 'next-line t)))
8966 ;; Break the line into fields
8967 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
8971 (mapconcat (lambda (x)
8973 (concat "<th>" x "</th>")
8974 (concat "<td valign=\"top\">" x "</td>")))
8977 (setq html (concat html "</table>\n"))
8980 (defun org-fake-empty-table-line (line)
8981 "Replace everything except \"|\" with spaces."
8982 (let ((i (length line))
8983 (newstr (copy-sequence line)))
8986 (if (not (eq (aref newstr i) ?|))
8987 (aset newstr i ?\ )))
8990 (defun org-format-table-table-html (lines)
8991 "Format a table generated by table.el into html.
8992 This conversion does *not* use `table-generate-source' from table.el.
8993 This has the advantage that Org-mode's HTML conversions can be used.
8994 But it has the disadvantage, that no cell- or row-spanning is allowed."
8995 (let (line field-buffer
8996 (head org-export-highlight-first-table-line)
8998 (setq html (concat org-export-html-table-tag "\n"))
8999 (while (setq line (pop lines))
9000 (setq empty " ")
9002 (if (string-match "^[ \t]*\\+-" line)
9011 (if (equal x "") (setq x empty))
9013 (concat "<th valign=\"top\">" x
9015 (concat "<td valign=\"top\">" x
9020 (setq field-buffer nil)))
9022 (throw 'next-line t)))
9023 ;; Break the line into fields and store the fields
9024 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
9026 (setq field-buffer (mapcar
9028 (concat x "<br>" (pop fields)))
9030 (setq field-buffer fields))))
9031 (setq html (concat html "</table>\n"))
9034 (defun org-format-table-table-html-using-table-generate-source (lines)
9035 "Format a table into html, using `table-generate-source' from table.el.
9036 This has the advantage that cell- or row-spanning is allowed.
9037 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
9039 (with-current-buffer (get-buffer-create " org-tmp1 ")
9041 (insert (mapconcat 'identity lines "\n"))
9042 (goto-char (point-min))
9043 (if (not (re-search-forward "|[^+]" nil t))
9044 (error "Error processing table"))
9045 (table-recognize-table)
9046 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
9047 (table-generate-source 'html " org-tmp2 ")
9048 (set-buffer " org-tmp2 ")
9049 (buffer-substring (point-min) (point-max))))
9051 (defun org-html-expand (string)
9052 "Prepare STRING for HTML export. Applies all active conversions."
9053 ;; First check if there is a link in the line - if yes, apply conversions
9054 ;; only before the start of the link.
9055 (let* ((m (string-match org-link-regexp string))
9056 (s (if m (substring string 0 m) string))
9057 (r (if m (substring string m) "")))
9058 ;; convert < to < and > to >
9059 (while (string-match "<" s)
9060 (setq s (replace-match "<" t t s)))
9061 (while (string-match ">" s)
9062 (setq s (replace-match ">" t t s)))
9063 (if org-export-html-expand
9064 (while (string-match "@<\\([^&]*\\)>" s)
9065 (setq s (replace-match "<\\1>" nil nil s))))
9066 (if org-export-with-emphasize
9067 (setq s (org-export-html-convert-emphasize s)))
9068 (if org-export-with-sub-superscripts
9069 (setq s (org-export-html-convert-sub-super s)))
9070 (if org-export-with-TeX-macros
9071 (let ((start 0) wd ass)
9072 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
9073 (setq wd (match-string 1 s))
9074 (if (setq ass (assoc wd org-html-entities))
9075 (setq s (replace-match (or (cdr ass)
9076 (concat "&" (car ass) ";"))
9078 (setq start (+ start (length wd)))))))
9081 (defun org-create-multibrace-regexp (left right n)
9082 "Create a regular expression which will match a balanced sexp.
9083 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
9084 as single character strings.
9085 The regexp returned will match the entire expression including the
9086 delimiters. It will also define a single group which contains the
9087 match except for the outermost delimiters. The maximum depth of
9088 stacked delimiters is N. Escaping delimiters is not possible."
9089 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
9092 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
9095 re (concat re or next)
9096 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
9097 (concat left "\\(" re "\\)" right)))
9099 (defvar org-match-substring-regexp
9101 "\\([^\\]\\)\\([_^]\\)\\("
9102 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
9104 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
9106 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
9107 "The regular expression matching a sub- or superscript.")
9109 (defun org-export-html-convert-sub-super (string)
9110 "Convert sub- and superscripts in STRING to HTML."
9112 (while (string-match org-match-substring-regexp string)
9113 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
9114 (setq c (or (match-string 8 string)
9115 (match-string 6 string)
9116 (match-string 5 string)))
9117 (setq string (replace-match
9118 (concat (match-string 1 string)
9119 "<" key ">" c "</" key ">")
9121 (while (string-match "\\\\\\([_^]\\)" string)
9122 (setq string (replace-match (match-string 1 string) t t string))))
9125 (defun org-export-html-convert-emphasize (string)
9126 (while (string-match
9127 "\\(\\s-\\|^\\)\\(\\*\\([a-zA-Z]+\\)\\*\\)\\([^a-zA-Z*]\\|$\\)"
9129 (setq string (replace-match
9130 (concat "<b>" (match-string 3 string) "</b>")
9132 (while (string-match
9133 "\\(\\s-\\|^\\)\\(/\\([a-zA-Z]+\\)/\\)\\([^a-zA-Z*]\\|$\\)"
9135 (setq string (replace-match
9136 (concat "<i>" (match-string 3 string) "</i>")
9138 (while (string-match
9139 "\\(\\s-\\|^\\)\\(_\\([a-zA-Z]+\\)_\\)\\([^a-zA-Z*]\\|$\\)"
9141 (setq string (replace-match
9142 (concat "<u>" (match-string 3 string) "</u>")
9146 (defun org-parse-key-lines ()
9147 "Find the special key lines with the information for exporters."
9150 (let ((re (org-make-options-regexp
9151 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
9153 (while (re-search-forward re nil t)
9154 (setq key (match-string 1))
9155 (cond ((string-equal key "TITLE")
9156 (setq title (match-string 2)))
9157 ((string-equal key "AUTHOR")
9158 (setq author (match-string 2)))
9159 ((string-equal key "EMAIL")
9160 (setq email (match-string 2)))
9161 ((string-equal key "LANGUAGE")
9162 (setq language (match-string 2)))
9163 ((string-equal key "TEXT")
9164 (setq text (concat text "\n" (match-string 2))))
9165 ((string-equal key "OPTIONS")
9166 (setq options (match-string 2))))))))
9168 (defun org-parse-export-options (s)
9169 "Parse the export options line."
9170 (let ((op '(("H" . org-export-headline-levels)
9171 ("num" . org-export-with-section-numbers)
9172 ("toc" . org-export-with-toc)
9173 ("\\n" . org-export-preserve-breaks)
9174 ("@" . org-export-html-expand)
9175 (":" . org-export-with-fixed-width)
9176 ("|" . org-export-with-tables)
9177 ("^" . org-export-with-sub-superscripts)
9178 ("*" . org-export-with-emphasize)
9179 ("TeX" . org-export-with-TeX-macros)))
9181 (while (setq o (pop op))
9182 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
9184 (set (make-local-variable (cdr o))
9185 (car (read-from-string (match-string 1 s))))))))
9187 (defun org-html-level-start (level title umax with-toc head-count)
9188 "Insert a new level in HTML export."
9189 (let ((l (1+ (max level umax))))
9190 (while (<= l org-level-max)
9191 (if (aref levels-open (1- l))
9193 (org-html-level-close l)
9194 (aset levels-open (1- l) nil)))
9198 (if (aref levels-open (1- level))
9199 (insert "<li>" title "<p>\n")
9200 (aset levels-open (1- level) t)
9201 (insert "<ul><li>" title "<p>\n")))
9202 (if org-export-with-section-numbers
9203 (setq title (concat (org-section-number level) " " title)))
9204 (setq level (+ level 1))
9206 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
9207 level head-count title level))
9208 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
9210 (defun org-html-level-close (&rest args)
9211 "Terminate one level in HTML export."
9215 ;; Variable holding the vector with section numbers
9216 (defvar org-section-numbers (make-vector org-level-max 0))
9218 (defun org-init-section-numbers ()
9219 "Initialize the vector for the section numbers."
9221 (numbers (nreverse (org-split-string "" "\\.")))
9222 (depth (1- (length org-section-numbers)))
9223 (i depth) number-string)
9226 (aset org-section-numbers i 0)
9227 (setq number-string (or (car numbers) "0"))
9228 (if (string-match "\\`[A-Z]\\'" number-string)
9229 (aset org-section-numbers i
9230 (- (string-to-char number-string) ?A -1))
9231 (aset org-section-numbers i (string-to-int number-string)))
9235 (defun org-section-number (&optional level)
9236 "Return a string with the current section number.
9237 When LEVEL is non-nil, increase section numbers on that level."
9238 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
9241 (aset org-section-numbers
9242 level (1+ (aref org-section-numbers level))))
9243 (setq idx (1+ level))
9244 (while (<= idx depth)
9246 (aset org-section-numbers idx 0))
9247 (setq idx (1+ idx))))
9249 (while (<= idx depth)
9250 (setq n (aref org-section-numbers idx))
9251 (setq string (concat string (if (not (string= string "")) "." "")
9253 (setq idx (1+ idx)))
9255 (if (string-match "\\`\\([@0]\\.\\)+" string)
9256 (setq string (replace-match "" nil nil string)))
9257 (if (string-match "\\(\\.0\\)+\\'" string)
9258 (setq string (replace-match "" nil nil string))))
9264 ;; - Bindings in Org-mode map are currently
9265 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
9266 ;; abcd fgh j lmnopqrstuvwxyz ? #$ -+*/= [] ; |,.<>~ \t necessary bindings
9267 ;; e (?) useful from outline-mode
9268 ;; i k @ expendable from outline-mode
9269 ;; 0123456789 ! %^& ()_{} " `' free
9271 (define-key org-mode-map "\C-i" 'org-cycle)
9272 (define-key org-mode-map [(meta tab)] 'org-complete)
9273 (define-key org-mode-map "\M-\C-i" 'org-complete)
9274 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
9275 (define-key org-mode-map [(meta left)] 'org-metaleft)
9276 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
9277 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
9278 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
9279 (define-key org-mode-map [(meta right)] 'org-metaright)
9280 (define-key org-mode-map [(meta up)] 'org-metaup)
9281 (define-key org-mode-map [(meta down)] 'org-metadown)
9282 ;(define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-subtree)
9283 ;(define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-subtree)
9284 ;(define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-subtree)
9285 (define-key org-mode-map "\C-c\C-h\C-w" 'org-cut-special)
9286 (define-key org-mode-map "\C-c\C-h\M-w" 'org-copy-special)
9287 (define-key org-mode-map "\C-c\C-h\C-y" 'org-paste-special)
9288 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
9289 (define-key org-mode-map "\C-c\C-j" 'org-goto)
9290 (define-key org-mode-map "\C-c\C-t" 'org-todo)
9291 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
9292 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
9293 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
9294 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
9295 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
9296 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
9297 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
9298 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
9299 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
9300 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
9301 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
9302 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
9303 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
9304 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
9305 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
9306 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
9307 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
9308 (define-key org-mode-map "\C-c[" 'org-add-file)
9309 (define-key org-mode-map "\C-c]" 'org-remove-file)
9310 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
9311 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
9312 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
9313 (define-key org-mode-map (org-key 'S-left) 'org-timestamp-down-day)
9314 (define-key org-mode-map (org-key 'S-right) 'org-timestamp-up-day)
9315 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
9316 ;; The following line is necessary for German keyboards under Suse GNU/Linux
9317 (unless org-xemacs-p
9318 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
9319 (define-key org-mode-map [(shift tab)] 'org-shifttab)
9320 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
9321 (define-key org-mode-map "\C-m" 'org-return)
9322 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
9323 (define-key org-mode-map [(meta return)] 'org-meta-return)
9324 (define-key org-mode-map "\C-c?" 'org-table-current-column)
9325 (define-key org-mode-map "\C-c " 'org-table-blank-field)
9326 (define-key org-mode-map "\C-c+" 'org-table-sum)
9327 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
9328 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
9329 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
9330 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
9331 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
9332 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
9333 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
9334 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
9335 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
9336 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
9337 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
9338 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
9339 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
9340 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
9341 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
9342 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
9343 (define-key org-mode-map "\C-c\C-x\C-h" 'org-export-as-html-and-open)
9345 (defsubst org-table-p () (org-at-table-p))
9347 (defun org-self-insert-command (N)
9348 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
9349 If the cursor is in a table looking at whitespace, the whitespace is
9350 overwritten, and the table is not marked as requiring realignment."
9352 (if (and (org-table-p)
9354 (looking-at "[^|\n]* +|"))
9355 (let (org-table-may-need-update)
9356 (goto-char (1- (match-end 0)))
9357 (delete-backward-char 1)
9358 (goto-char (match-beginning 0))
9359 (self-insert-command N))
9360 (setq org-table-may-need-update t)
9361 (self-insert-command N)))
9364 ;; The following two functions might still be optimized to trigger
9365 ;; re-alignment less frequently.
9367 (defun org-delete-backward-char (N)
9368 "Like `delete-backward-char', insert whitespace at field end in tables.
9369 When deleting backwards, in tables this function will insert whitespace in
9370 front of the next \"|\" separator, to keep the table aligned. The table will
9371 still be marked for re-alignment, because a narrow field may lead to a
9372 reduced column width."
9374 (if (and (org-table-p)
9376 (string-match "|" (buffer-substring (point-at-bol) (point)))
9377 (looking-at ".*?|"))
9378 (let ((pos (point)))
9379 (backward-delete-char N)
9380 (skip-chars-forward "^|")
9382 (goto-char (1- pos)))
9383 (backward-delete-char N)))
9385 (defun org-delete-char (N)
9386 "Like `delete-char', but insert whitespace at field end in tables.
9387 When deleting characters, in tables this function will insert whitespace in
9388 front of the next \"|\" separator, to keep the table aligned. The table
9389 will still be marked for re-alignment, because a narrow field may lead to
9390 a reduced column width."
9392 (if (and (org-table-p)
9394 (not (= (char-after) ?|))
9396 (if (looking-at ".*?|")
9397 (let ((pos (point)))
9398 (replace-match (concat
9399 (substring (match-string 0) 1 -1)
9404 ;; How to do this: Measure non-white length of current string
9405 ;; If equal to column width, we should realign.
9407 (when (eq org-enable-table-editor 'optimized)
9408 ;; If the user wants maximum table support, we need to hijack
9409 ;; some standard editing functions
9410 (substitute-key-definition 'self-insert-command 'org-self-insert-command
9411 org-mode-map global-map)
9412 (substitute-key-definition 'delete-char 'org-delete-char
9413 org-mode-map global-map)
9414 (substitute-key-definition 'delete-backward-char 'org-delete-backward-char
9415 org-mode-map global-map)
9416 (define-key org-mode-map "|" 'self-insert-command))
9418 (defun org-shiftcursor-error ()
9419 "Throw an error because Shift-Cursor command was applied in wrong context."
9420 (error "This command is only active in tables and on headlines"))
9422 (defun org-shifttab ()
9423 "Call `(org-cycle t)' or `org-table-previous-field'."
9426 ((org-at-table-p) (org-table-previous-field))
9427 (t (org-cycle '(4)))))
9429 (defun org-shiftmetaleft ()
9430 "Call `org-promote-subtree' or `org-table-delete-column'."
9433 ((org-at-table-p) (org-table-delete-column))
9434 ((org-on-heading-p) (org-promote-subtree))
9435 (t (org-shiftcursor-error))))
9437 (defun org-shiftmetaright ()
9438 "Call `org-demote-subtree' or `org-table-insert-column'."
9441 ((org-at-table-p) (org-table-insert-column))
9442 ((org-on-heading-p) (org-demote-subtree))
9443 (t (org-shiftcursor-error))))
9445 (defun org-shiftmetaup (&optional arg)
9446 "Call `org-move-subtree-up' or `org-table-kill-row'."
9449 ((org-at-table-p) (org-table-kill-row))
9450 ((org-on-heading-p) (org-move-subtree-up arg))
9451 (t (org-shiftcursor-error))))
9452 (defun org-shiftmetadown (&optional arg)
9453 "Call `org-move-subtree-down' or `org-table-insert-row'."
9456 ((org-at-table-p) (org-table-insert-row arg))
9457 ((org-on-heading-p) (org-move-subtree-down arg))
9458 (t (org-shiftcursor-error))))
9460 (defun org-metaleft (&optional arg)
9461 "Call `org-do-promote' or `org-table-move-column' to left."
9464 ((org-at-table-p) (org-table-move-column 'left))
9465 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
9466 (t (backward-word (prefix-numeric-value arg)))))
9468 (defun org-metaright (&optional arg)
9469 "Call `org-do-demote' or `org-table-move-column' to right."
9472 ((org-at-table-p) (org-table-move-column nil))
9473 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
9474 (t (forward-word (prefix-numeric-value arg)))))
9476 (defun org-metaup (&optional arg)
9477 "Call `org-move-subtree-up' or `org-table-move-row' up."
9480 ((org-at-table-p) (org-table-move-row 'up))
9481 ((org-on-heading-p) (org-move-subtree-up arg))
9482 (t (org-shiftcursor-error))))
9484 (defun org-metadown (&optional arg)
9485 "Call `org-move-subtree-down' or `org-table-move-row' down."
9488 ((org-at-table-p) (org-table-move-row nil))
9489 ((org-on-heading-p) (org-move-subtree-down arg))
9490 (t (org-shiftcursor-error))))
9492 (defun org-shiftup (&optional arg)
9493 "Call `org-timestamp-up' or `org-priority-up'."
9496 ((org-at-timestamp-p) (org-timestamp-up arg))
9497 (t (org-priority-up))))
9499 (defun org-shiftdown (&optional arg)
9500 "Call `org-timestamp-down' or `org-priority-down'."
9503 ((org-at-timestamp-p) (org-timestamp-down arg))
9504 (t (org-priority-down))))
9506 (defun org-copy-special ()
9507 "Call either `org-table-copy' or `org-copy-subtree'."
9510 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
9512 (defun org-cut-special ()
9513 "Call either `org-table-copy' or `org-cut-subtree'."
9516 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
9518 (defun org-paste-special (arg)
9519 "Call either `org-table-paste-rectangle' or `org-paste-subtree'."
9521 (if (org-at-table-p)
9522 (org-table-paste-rectangle)
9523 (org-paste-subtree arg)))
9525 (defun org-ctrl-c-ctrl-c (&optional arg)
9526 "Call realign table, or recognize a table.el table, or update keywords.
9527 When the cursor is inside a table created by the table.el package,
9528 activate that table. Otherwise, if the cursor is at a normal table
9529 created with org.el, re-align that table. This command works even if
9530 the automatic table editor has been turned off.
9531 If the cursor is in one of the special #+KEYWORD lines, this triggers
9532 scanning the buffer for these lines and updating the information."
9534 (let ((org-enable-table-editor t))
9536 ((org-at-table.el-p)
9538 (beginning-of-line 1)
9539 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
9540 (table-recognize-table))
9542 (org-table-maybe-eval-formula)
9544 (org-table-recalculate t)
9545 (org-table-maybe-recalculate-line))
9547 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
9549 ((equal (match-string 1) "TBLFM")
9550 ;; Recalculate the table before this line
9552 (beginning-of-line 1)
9553 (skip-chars-backward " \r\n\t")
9554 (if (org-at-table-p) (org-table-recalculate t))))
9556 (let ((org-inhibit-startup t)) (org-mode)))))
9557 ((org-region-active-p)
9558 (org-table-convert-region (region-beginning) (region-end) arg))
9559 ((and (region-beginning) (region-end))
9560 (if (y-or-n-p "Convert inactive region to table? ")
9561 (org-table-convert-region (region-beginning) (region-end) arg)
9563 (t (error "No table at point, and no region to make one")))))
9565 (defun org-return ()
9566 "Call `org-table-next-row' or `newline'."
9570 (org-table-justify-field-maybe)
9571 (org-table-next-row))
9574 (defun org-meta-return (&optional arg)
9575 "Call `org-insert-heading' or `org-table-wrap-region'."
9579 (org-table-wrap-region arg))
9580 (t (org-insert-heading))))
9584 ;; Define the Org-mode menus
9585 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
9587 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
9588 ["Next Field" org-cycle (org-at-table-p)]
9589 ["Previous Field" org-shifttab (org-at-table-p)]
9590 ["Next Row" org-return (org-at-table-p)]
9592 ["Blank Field" org-table-blank-field (org-at-table-p)]
9593 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
9596 ["Move Column Left" org-metaleft (org-at-table-p)]
9597 ["Move Column Right" org-metaright (org-at-table-p)]
9598 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
9599 ["Insert Column" org-shiftmetaright (org-at-table-p)])
9601 ["Move Row Up" org-metaup (org-at-table-p)]
9602 ["Move Row Down" org-metadown (org-at-table-p)]
9603 ["Delete Row" org-shiftmetaup (org-at-table-p)]
9604 ["Insert Row" org-shiftmetadown (org-at-table-p)]
9606 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
9608 ["Copy Rectangle" org-copy-special (org-at-table-p)]
9609 ["Cut Rectangle" org-cut-special (org-at-table-p)]
9610 ["Paste Rectangle" org-paste-special (org-at-table-p)]
9611 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
9614 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
9615 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
9616 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
9618 ["Recalculate line" org-table-recalculate (org-at-table-p)]
9619 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
9620 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
9622 ["Sum Column/Rectangle" org-table-sum
9623 (or (org-at-table-p) (org-region-active-p))]
9624 ["Which Column?" org-table-current-column (org-at-table-p)])
9626 (setq org-table-formula-debug (not org-table-formula-debug))
9627 :style toggle :selected org-table-formula-debug]
9629 ["Invisible Vlines" org-table-toggle-vline-visibility
9630 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
9632 ["Create" org-table-create (and (not (org-at-table-p))
9633 org-enable-table-editor)]
9634 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
9635 ["Import from File" org-table-import (not (org-at-table-p))]
9636 ["Export to File" org-table-export (org-at-table-p)]
9638 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
9640 (easy-menu-define org-org-menu org-mode-map "Org menu"
9642 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
9643 ["Sparse Tree" org-occur t]
9644 ["Show All" show-all t]
9646 ["New Heading" org-insert-heading t]
9647 ("Navigate Headings"
9648 ["Up" outline-up-heading t]
9649 ["Next" outline-next-visible-heading t]
9650 ["Previous" outline-previous-visible-heading t]
9651 ["Next Same Level" outline-forward-same-level t]
9652 ["Previous Same Level" outline-backward-same-level t]
9654 ["Jump" org-goto t])
9656 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
9657 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
9659 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
9660 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
9661 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
9663 ["Promote Heading" org-metaleft (not (org-at-table-p))]
9664 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
9665 ["Demote Heading" org-metaright (not (org-at-table-p))]
9666 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
9668 ["Archive Subtree" org-archive-subtree t])
9671 ["TODO/DONE/-" org-todo t]
9672 ["Show TODO Tree" org-show-todo-tree t]
9674 ["Set Priority" org-priority t]
9675 ["Priority Up" org-shiftup t]
9676 ["Priority Down" org-shiftdown t])
9677 ("Dates and Scheduling"
9678 ["Timestamp" org-time-stamp t]
9680 ["1 Day Later" org-timestamp-up-day t]
9681 ["1 Day Earlier" org-timestamp-down-day t]
9682 ["1 ... Later" org-shiftup t]
9683 ["1 ... Earlier" org-shiftdown t])
9684 ["Compute Time Range" org-evaluate-time-range t]
9685 ["Schedule Item" org-schedule t]
9686 ["Deadline" org-deadline t]
9688 ["Goto Calendar" org-goto-calendar t]
9689 ["Date from Calendar" org-date-from-calendar t])
9692 ["Show TODO Tree this File" org-show-todo-tree t]
9693 ["Check Deadlines this File" org-check-deadlines t]
9694 ["Timeline Current File" org-timeline t]
9696 ["Agenda" org-agenda t])
9697 ("File List for Agenda")
9700 ["Store Link (Global)" org-store-link t]
9701 ["Insert Link" org-insert-link t]
9702 ["Follow Link" org-open-at-point t])
9705 ["ASCII" org-export-as-ascii t]
9706 ["Extract Visible Text" org-export-copy-visible t]
9707 ["HTML" org-export-as-html t]
9708 ["HTML and Open" org-export-as-html-and-open t]
9709 ; ["OPML" org-export-as-opml nil]
9711 ["Option Template" org-insert-export-options-template t]
9712 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
9715 ["Show Version" org-version t]
9716 ["Info Documentation" org-info t])
9718 ["Browse Org Group" org-customize t]
9720 ["Build Full Customize Menu" org-create-customize-menu
9721 (fboundp 'customize-menu-create)])
9724 (defun org-info (&optional node)
9725 "Read documentation for Org-mode in the info system.
9726 With optional NODE, go directly to that node."
9729 (Info-goto-node (format "(org)%s" (or node ""))))
9731 (defun org-install-agenda-files-menu ()
9733 '("Org") "File List for Agenda"
9736 ["Edit File List" (customize-variable 'org-agenda-files) t]
9737 ["Add Current File to List" org-add-file t]
9738 ["Remove Current File from List" org-remove-file t]
9740 (mapcar 'org-file-menu-entry org-agenda-files))))
9744 (defun org-customize ()
9745 "Call the customize function with org as argument."
9747 (customize-browse 'org))
9749 (defun org-create-customize-menu ()
9750 "Create a full customization menu for Org-mode, insert it into the menu."
9752 (if (fboundp 'customize-menu-create)
9755 '("Org") "Customize"
9756 `(["Browse Org group" org-customize t]
9758 ,(customize-menu-create 'org)
9759 ["Set" Custom-set t]
9760 ["Save" Custom-save t]
9761 ["Reset to Current" Custom-reset-current t]
9762 ["Reset to Saved" Custom-reset-saved t]
9763 ["Reset to Standard Settings" Custom-reset-standard t]))
9764 (message "\"Org\"-menu now contains full customization menu"))
9765 (error "Cannot expand menu (outdated version of cus-edit.el)")))
9767 ;;; Miscellaneous stuff
9769 (defun org-move-line-down (arg)
9770 "Move the current line down. With prefix argument, move it past ARG lines."
9772 (let ((col (current-column))
9774 (beginning-of-line 1) (setq beg (point))
9775 (beginning-of-line 2) (setq end (point))
9776 (beginning-of-line (+ 1 arg))
9777 (setq pos (move-marker (make-marker) (point)))
9778 (insert (delete-and-extract-region beg end))
9780 (move-to-column col)))
9782 (defun org-move-line-up (arg)
9783 "Move the current line up. With prefix argument, move it past ARG lines."
9785 (let ((col (current-column))
9787 (beginning-of-line 1) (setq beg (point))
9788 (beginning-of-line 2) (setq end (point))
9789 (beginning-of-line (- arg))
9790 (setq pos (move-marker (make-marker) (point)))
9791 (insert (delete-and-extract-region beg end))
9793 (move-to-column col)))
9795 ;; Functions needed for Emacs/XEmacs region compatibility
9797 (defun org-region-active-p ()
9798 "Is `transient-mark-mode' on and the region active?
9799 Works on both Emacs and XEmacs."
9800 (if org-ignore-region
9803 (and zmacs-regions (region-active-p))
9804 (and transient-mark-mode mark-active))))
9806 (defun org-add-to-invisibility-spec (arg)
9807 "Add elements to `buffer-invisibility-spec'.
9808 See documentation for `buffer-invisibility-spec' for the kind of elements
9811 ((fboundp 'add-to-invisibility-spec)
9812 (add-to-invisibility-spec arg))
9813 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
9814 (setq buffer-invisibility-spec (list arg)))
9816 (setq buffer-invisibility-spec
9817 (cons arg buffer-invisibility-spec)))))
9819 (defun org-remove-from-invisibility-spec (arg)
9820 "Remove elements from `buffer-invisibility-spec'."
9821 (if (fboundp 'remove-from-invisibility-spec)
9822 (remove-from-invisibility-spec arg)
9823 (if (consp buffer-invisibility-spec)
9824 (setq buffer-invisibility-spec
9825 (delete arg buffer-invisibility-spec)))))
9827 (defun org-in-invisibility-spec-p (arg)
9828 "Is ARG a member of `buffer-invisibility-spec'?."
9829 (if (consp buffer-invisibility-spec)
9830 (member arg buffer-invisibility-spec)
9833 (defun org-image-file-name-regexp ()
9834 "Return regexp matching the file names of images."
9835 (if (fboundp 'image-file-name-regexp)
9836 (image-file-name-regexp)
9837 (let ((image-file-name-extensions
9838 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
9839 "xbm" "xpm" "pbm" "pgm" "ppm")))
9841 (regexp-opt (nconc (mapcar 'upcase
9842 image-file-name-extensions)
9843 image-file-name-extensions)
9847 ;; Functions needed for compatibility with old outline.el
9849 ;; The following functions capture almost the entire compatibility code
9850 ;; between the different versions of outline-mode. The only other place
9851 ;; where this is important are the font-lock-keywords. Search for
9852 ;; `org-noutline-p' to find it.
9854 ;; C-a should go to the beginning of a *visible* line, also in the
9855 ;; new outline.el. I guess this should be patched into Emacs?
9856 (defun org-beginning-of-line ()
9857 "Go to the beginning of the current line. If that is invisible, continue
9858 to a visible line beginning. This makes the function of C-a more intuitive."
9860 (beginning-of-line 1)
9864 (if (org-invisible-p)
9865 (while (and (not (bobp)) (org-invisible-p))
9867 (beginning-of-line 1))
9869 (when org-noutline-p
9870 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
9872 (defun org-invisible-p ()
9873 "Check if point is at a character currently not visible."
9875 ;; Early versions of noutline don't have `outline-invisible-p'.
9876 (if (fboundp 'outline-invisible-p)
9877 (outline-invisible-p)
9878 (get-char-property (point) 'invisible))
9880 (skip-chars-backward "^\r\n")
9881 (equal (char-before) ?\r))))
9883 (defun org-back-to-heading (&optional invisible-ok)
9884 "Move to previous heading line, or beg of this line if it's a heading.
9885 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
9887 (outline-back-to-heading invisible-ok)
9888 (if (looking-at outline-regexp)
9890 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
9894 (progn (goto-char (match-end 1))
9895 (looking-at outline-regexp)))
9896 (error "Before first heading")))))
9898 (defun org-on-heading-p (&optional invisible-ok)
9899 "Return t if point is on a (visible) heading line.
9900 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
9902 (outline-on-heading-p 'invisible-ok)
9904 (skip-chars-backward "^\n\r")
9905 (and (looking-at outline-regexp)
9908 (equal (char-before) ?\n))))))
9910 (defun org-up-heading-all (arg)
9911 "Move to the heading line of which the present line is a subheading.
9912 This function considers both visible and invisible heading lines.
9913 With argument, move up ARG levels."
9915 (if (fboundp 'outline-up-heading-all)
9916 (outline-up-heading-all arg) ; emacs 21 version of outline.el
9917 (outline-up-heading arg t)) ; emacs 22 version of outline.el
9918 (org-back-to-heading t)
9919 (looking-at outline-regexp)
9920 (if (<= (- (match-end 0) (match-beginning 0)) arg)
9921 (error "Cannot move up %d levels" arg)
9923 (concat "[\n\r]" (regexp-quote
9924 (make-string (- (match-end 0) (match-beginning 0) arg)
9929 (defun org-show-hidden-entry ()
9930 "Show an entry where even the heading is hidden."
9932 (if (not org-noutline-p)
9934 (org-back-to-heading t)
9935 (org-flag-heading nil)))
9938 (defun org-check-occur-regexp (regexp)
9939 "If REGEXP starts with \"^\", modify it to check for \\r as well.
9940 Of course, only for the old outline mode."
9943 (if (string-match "^\\^" regexp)
9944 (concat "[\n\r]" (substring regexp 1))
9947 (defun org-flag-heading (flag &optional entry)
9948 "Flag the current heading. FLAG non-nil means make invisible.
9949 When ENTRY is non-nil, show the entire entry."
9951 (org-back-to-heading t)
9952 (if (not org-noutline-p)
9953 ;; Make the current headline visible
9954 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
9955 ;; Check if we should show the entire entry
9959 (save-excursion ;; FIXME: Is this the fix for points in the -|
9960 ;; middle of text? |
9961 (and (outline-next-heading) ;; |
9962 (org-flag-heading nil)))) ; show the next heading _|
9963 (outline-flag-region (max 1 (1- (point)))
9964 (save-excursion (outline-end-of-heading) (point))
9967 (if flag ?\r ?\n))))))
9969 (defun org-show-subtree ()
9970 "Show everything after this heading at deeper levels."
9971 (outline-flag-region
9974 (outline-end-of-subtree) (outline-next-heading) (point))
9975 (if org-noutline-p nil ?\n)))
9977 (defun org-show-entry ()
9978 "Show the body directly following this heading.
9979 Show the heading too, if it is currently invisible."
9982 (org-back-to-heading t)
9983 (outline-flag-region
9986 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
9987 (or (match-beginning 1) (point-max)))
9988 (if org-noutline-p nil ?\n))))
9991 (defun org-make-options-regexp (kwds)
9992 "Make a regular expression for keyword lines."
9994 (if org-noutline-p "^" "[\n\r]")
9996 (mapconcat 'regexp-quote kwds "\\|")
9998 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
10000 ;; Advise the bookmark-jump function to make jump position visible
10001 ;; Wrapped into eval-after-load to avoid loading advice unnecessarily
10002 (eval-after-load "bookmark"
10003 '(defadvice bookmark-jump (after org-make-visible activate)
10004 "Make the position visible."
10005 (and (eq major-mode 'org-mode)
10007 (org-show-hierarchy-above))))
10013 (run-hooks 'org-load-hook)
10015 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
10016 ;;; org.el ends here