version 4.12a
[org-mode/org-tableheadings.git] / org.el
blob3aba8c55fe2d68acffcd40a8176668bef40040e9
1 ;;; org.el --- Outline-based notes management and organize
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <dominik at science dot uva dot nl>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://www.astro.uva.nl/~dominik/Tools/org/
8 ;; Version: 4.12
9 ;;
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)
15 ;; any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
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.
44 ;; Installation
45 ;; ------------
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
72 ;; name is.
74 ;; Documentation
75 ;; -------------
76 ;; The documentation of Org-mode can be found in the TeXInfo file. The
77 ;; distribution also contains a PDF version of it. At the homepage of
78 ;; Org-mode, you can read the same text online as HTML. There is also an
79 ;; excellent reference card made by Philip Rooke. This card can be found
80 ;; in the etc/ directory of Emacs 22.
82 ;; Changes since version 4.00:
83 ;; ---------------------------
84 ;; Version 4.12
85 ;; - Templates for remember buffer. Note that the remember setup changes.
86 ;; To set up templates, see `org-remember-templates'.
87 ;; - The time in new time stamps can be rounded, see new option
88 ;; `org-time-stamp-rounding-minutes'.
89 ;; - Bug fixes (there are *always* more bugs).
91 ;; Version 4.10
92 ;; - Bug fixes.
94 ;; Version 4.09
95 ;; - Bug fixes.
96 ;; - Small improvements to font-lock support.
97 ;; - MHE support finalized.
99 ;; Version 4.08
100 ;; - Bug fixes.
101 ;; - Improved MHE support
103 ;; Version 4.07
104 ;; - Bug fixes.
105 ;; - Leading stars in headlines can be hidden, so make the outline look
106 ;; cleaner.
107 ;; - Mouse-1 can be used to follow links.
109 ;; Version 4.06
110 ;; - HTML exporter treats targeted internal links.
111 ;; - Bug fixes.
113 ;; Version 4.05
114 ;; - Changes to internal link system (thanks to David Wainberg for ideas).
115 ;; - in-file links: [[Search String]] instead of <file:::Search String>
116 ;; - automatic links to "radio targets".
117 ;; - CamelCase not longer active by default, configure org-activate-camels
118 ;; if you want to turn it back on.
119 ;; - After following a link, `C-c &' jumps back to it.
120 ;; - MH-E link support (thanks to Thomas Baumann).
121 ;; - Special table lines are no longer exported.
122 ;; - Bug fixes and minor improvements.
124 ;; Version 4.04
125 ;; - Cleanup tags display in agenda.
126 ;; - Bug fixes.
128 ;; Version 4.03
129 ;; - Table alignment fixed for use with wide characters.
130 ;; - `C-c -' leaves cursor in current table line.
131 ;; - The current TAG can be incorporated into the agenda prefix.
132 ;; See option `org-agenda-prefix-format' for details.
134 ;; Version 4.02
135 ;; - Minor bug fixes and improvements around tag searches.
136 ;; - XEmacs compatibility fixes.
138 ;; Version 4.01
139 ;; - Tags can also be set remotely from agenda buffer.
140 ;; - Boolean logic for tag searches.
141 ;; - Additional agenda commands can be configured through the variable
142 ;; `org-agenda-custom-commands'.
143 ;; - Minor bug fixes.
145 ;;; Code:
147 (eval-when-compile (require 'cl) (require 'calendar))
148 (require 'outline)
149 (require 'time-date)
150 (require 'easymenu)
152 (defvar calc-embedded-close-formula) ; defined by the calc package
153 (defvar calc-embedded-open-formula) ; defined by the calc package
154 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
156 ;;; Customization variables
158 (defvar org-version "4.12"
159 "The version number of the file org.el.")
160 (defun org-version ()
161 (interactive)
162 (message "Org-mode version %s" org-version))
164 ;; The following two constants are for compatibility with different Emacs
165 ;; versions (Emacs versus XEmacs) and with different versions of outline.el.
166 ;; The compatibility code in org.el is based on these two constants.
167 (defconst org-xemacs-p (featurep 'xemacs)
168 "Are we running XEmacs?")
169 (defconst org-noutline-p (featurep 'noutline)
170 "Are we using the new outline mode?")
172 (defgroup org nil
173 "Outline-based notes management and organizer."
174 :tag "Org"
175 :group 'outlines
176 :group 'hypermedia
177 :group 'calendar)
179 (defgroup org-startup nil
180 "Options concerning startup of Org-mode."
181 :tag "Org Startup"
182 :group 'org)
184 (defcustom org-CUA-compatible nil
185 "Non-nil means use alternative key bindings for S-<cursor movement>.
186 Org-mode used S-<cursor movement> for changing timestamps and priorities.
187 S-<cursor movement> is also used for example by `CUA-mode' to select text.
188 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
189 alternative bindings. Setting this variable to t will replace the following
190 keys both in Org-mode and in the Org-agenda buffer.
192 S-RET -> C-S-RET
193 S-up -> M-p
194 S-down -> M-n
195 S-left -> M--
196 S-right -> M-+
198 If you do not like the alternative keys, take a look at the variable
199 `org-disputed-keys'.
201 This option is only relevant at load-time of Org-mode. Changing it requires
202 a restart of Emacs to become effective."
203 :group 'org-startup
204 :type 'boolean)
206 (defvar org-disputed-keys
207 '((S-up [(shift up)] [(meta ?p)])
208 (S-down [(shift down)] [(meta ?n)])
209 (S-left [(shift left)] [(meta ?-)])
210 (S-right [(shift right)] [(meta ?+)])
211 (S-return [(shift return)] [(control shift return)]))
212 "Keys for which Org-mode and other modes compete.
213 This is an alist, cars are symbols for lookup, 1st element is the default key,
214 second element will be used when `org-CUA-compatible' is t.")
216 (defun org-key (key)
217 "Select a key according to `org-CUA-compatible'."
218 (nth (if org-CUA-compatible 2 1)
219 (or (assq key org-disputed-keys)
220 (error "Invalid Key %s in `org-key'" key))))
222 (defcustom org-startup-folded t
223 "Non-nil means, entering Org-mode will switch to OVERVIEW.
224 This can also be configured on a per-file basis by adding one of
225 the following lines anywhere in the buffer:
227 #+STARTUP: fold
228 #+STARTUP: nofold
229 #+STARTUP: content"
230 :group 'org-startup
231 :type '(choice
232 (const :tag "nofold: show all" nil)
233 (const :tag "fold: overview" t)
234 (const :tag "content: all headlines" content)))
236 (defcustom org-startup-truncated t
237 "Non-nil means, entering Org-mode will set `truncate-lines'.
238 This is useful since some lines containing links can be very long and
239 uninteresting. Also tables look terrible when wrapped."
240 :group 'org-startup
241 :type 'boolean)
243 (defcustom org-startup-with-deadline-check nil
244 "Non-nil means, entering Org-mode will run the deadline check.
245 This means, if you start editing an org file, you will get an
246 immediate reminder of any due deadlines.
247 This can also be configured on a per-file basis by adding one of
248 the following lines anywhere in the buffer:
250 #+STARTUP: dlcheck
251 #+STARTUP: nodlcheck"
252 :group 'org-startup
253 :type 'boolean)
255 (defcustom org-insert-mode-line-in-empty-file nil
256 "Non-nil means insert the first line setting Org-mode in empty files.
257 When the function `org-mode' is called interactively in an empty file, this
258 normally means that the file name does not automatically trigger Org-mode.
259 To ensure that the file will always be in Org-mode in the future, a
260 line enforcing Org-mode will be inserted into the buffer, if this option
261 has been set."
262 :group 'org-startup
263 :type 'boolean)
265 (defgroup org-keywords nil
266 "Options concerning TODO items in Org-mode."
267 :tag "Org Keywords"
268 :group 'org)
270 (defcustom org-todo-keywords '("TODO" "DONE")
271 "List of TODO entry keywords.
272 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
273 considered to mean that the entry is \"done\". All the other mean that
274 action is required, and will make the entry show up in todo lists, diaries
275 etc.
276 The command \\[org-todo] cycles an entry through these states, and an
277 additional state where no keyword is present. For details about this
278 cycling, see also the variable `org-todo-interpretation'
279 Changes become only effective after restarting Emacs."
280 :group 'org-keywords
281 :type '(repeat (string :tag "Keyword")))
283 (defcustom org-todo-interpretation 'sequence
284 "Controls how TODO keywords are interpreted.
285 \\<org-mode-map>Possible values are `sequence' and `type'.
286 This variable is only relevant if `org-todo-keywords' contains more than two
287 states. There are two ways how these keywords can be used:
289 - As a sequence in the process of working on a TODO item, for example
290 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
291 org-todo-interpretation 'sequence)
293 - As different types of TODO items, for example
294 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
295 org-todo-interpretation 'type)
297 When the states are interpreted as a sequence, \\[org-todo] always cycles
298 to the next state, in order to walk through all different states. So with
299 \\[org-todo], you turn an empty entry into the state TODO. When you started
300 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
301 later to VERIFY and finally to DONE.
303 When the states are interpreted as types, \\[org-todo] still cycles through
304 when it is called several times in direct succession, in order to initially
305 select the type. However, if not called immediately after a previous
306 \\[org-todo], it switches from each type directly to DONE. So with the
307 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
308 RELAXED. If you later return to this entry and press \\[org-todo] again,
309 RELAXED will not be changed REMIND, but directly to DONE.
311 You can create a large number of types. To initially select a
312 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
313 type with completion. Of course, you can also type the keyword
314 directly into the buffer. M-TAB completes TODO keywords at the
315 beginning of a headline."
316 :group 'org-keywords
317 :type '(choice (const sequence)
318 (const type)))
320 (defcustom org-default-priority ?B
321 "The default priority of TODO items.
322 This is the priority an item get if no explicit priority is given."
323 :group 'org-keywords
324 :type 'character)
326 (defcustom org-lowest-priority ?C
327 "The lowest priority of TODO items. A character like ?A, ?B etc."
328 :group 'org-keywords
329 :type 'character)
331 (defcustom org-deadline-string "DEADLINE:"
332 "String to mark deadline entries.
333 A deadline is this string, followed by a time stamp. Should be a word,
334 terminated by a colon. You can insert a schedule keyword and
335 a timestamp with \\[org-deadline].
336 Changes become only effective after restarting Emacs."
337 :group 'org-keywords
338 :type 'string)
340 (defcustom org-scheduled-string "SCHEDULED:"
341 "String to mark scheduled TODO entries.
342 A schedule is this string, followed by a time stamp. Should be a word,
343 terminated by a colon. You can insert a schedule keyword and
344 a timestamp with \\[org-schedule].
345 Changes become only effective after restarting Emacs."
346 :group 'org-keywords
347 :type 'string)
349 (defcustom org-closed-string "CLOSED:"
350 "String used as the prefix for timestamps logging closing a TODO entry."
351 :group 'org-keywords
352 :type 'string)
354 (defcustom org-comment-string "COMMENT"
355 "Entries starting with this keyword will never be exported.
356 An entry can be toggled between COMMENT and normal with
357 \\[org-toggle-comment].
358 Changes become only effective after restarting Emacs."
359 :group 'org-keywords
360 :type 'string)
362 (defcustom org-quote-string "QUOTE"
363 "Entries starting with this keyword will be exported in fixed-width font.
364 Quoting applies only to the text in the entry following the headline, and does
365 not extend beyond the next headline, even if that is lower level.
366 An entry can be toggled between QUOTE and normal with
367 \\[org-toggle-fixed-width-section]."
368 :group 'org-keywords
369 :type 'string)
371 (defcustom org-after-todo-state-change-hook nil
372 "Hook which is run after the state of a TODO item was changed.
373 The new state (a string with a TODO keyword, or nil) is available in the
374 Lisp variable `state'."
375 :group 'org-keywords
376 :type 'hook)
378 ;; Variables for pre-computed regular expressions, all buffer local
379 (defvar org-todo-kwd-priority-p nil
380 "Do TODO items have priorities?")
381 (make-variable-buffer-local 'org-todo-kwd-priority-p)
382 (defvar org-todo-kwd-max-priority nil
383 "Maximum priority of TODO items.")
384 (make-variable-buffer-local 'org-todo-kwd-max-priority)
385 (defvar org-ds-keyword-length 12
386 "Maximum length of the Deadline and SCHEDULED keywords.")
387 (make-variable-buffer-local 'org-ds-keyword-length)
388 (defvar org-done-string nil
389 "The last string in `org-todo-keywords', indicating an item is DONE.")
390 (make-variable-buffer-local 'org-done-string)
391 (defvar org-todo-regexp nil
392 "Matches any of the TODO state keywords.")
393 (make-variable-buffer-local 'org-todo-regexp)
394 (defvar org-not-done-regexp nil
395 "Matches any of the TODO state keywords except the last one.")
396 (make-variable-buffer-local 'org-not-done-regexp)
397 (defvar org-todo-line-regexp nil
398 "Matches a headline and puts TODO state into group 2 if present.")
399 (make-variable-buffer-local 'org-todo-line-regexp)
400 (defvar org-nl-done-regexp nil
401 "Matches newline followed by a headline with the DONE keyword.")
402 (make-variable-buffer-local 'org-nl-done-regexp)
403 (defvar org-looking-at-done-regexp nil
404 "Matches the DONE keyword a point.")
405 (make-variable-buffer-local 'org-looking-at-done-regexp)
406 (defvar org-deadline-regexp nil
407 "Matches the DEADLINE keyword.")
408 (make-variable-buffer-local 'org-deadline-regexp)
409 (defvar org-deadline-time-regexp nil
410 "Matches the DEADLINE keyword together with a time stamp.")
411 (make-variable-buffer-local 'org-deadline-time-regexp)
412 (defvar org-deadline-line-regexp nil
413 "Matches the DEADLINE keyword and the rest of the line.")
414 (make-variable-buffer-local 'org-deadline-line-regexp)
415 (defvar org-scheduled-regexp nil
416 "Matches the SCHEDULED keyword.")
417 (make-variable-buffer-local 'org-scheduled-regexp)
418 (defvar org-scheduled-time-regexp nil
419 "Matches the SCHEDULED keyword together with a time stamp.")
420 (make-variable-buffer-local 'org-scheduled-time-regexp)
422 (defvar org-category nil
423 "Variable used by org files to set a category for agenda display.
424 Such files should use a file variable to set it, for example
426 -*- mode: org; org-category: \"ELisp\"
428 or contain a special line
430 #+CATEGORY: ELisp
432 If the file does not specify a category, then file's base name
433 is used instead.")
434 (make-variable-buffer-local 'org-category)
436 (defgroup org-time nil
437 "Options concerning time stamps and deadlines in Org-mode."
438 :tag "Org Time"
439 :group 'org)
441 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
442 "Formats for `format-time-string' which are used for time stamps.
443 It is not recommended to change this constant.")
445 (defcustom org-time-stamp-rounding-minutes 0
446 "Number of minutes to round time stamps to upon insertion.
447 When zero, insert the time unmodified. Useful rounding numbers
448 should be factors of 60, so for example 5, 10, 15.
449 When this is not zero, you can still force an exact time-stamp by using
450 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
451 :group 'org-time
452 :type 'integer)
454 (defcustom org-deadline-warning-days 30
455 "No. of days before expiration during which a deadline becomes active.
456 This variable governs the display in the org file."
457 :group 'org-time
458 :type 'number)
460 (defcustom org-popup-calendar-for-date-prompt t
461 "Non-nil means, pop up a calendar when prompting for a date.
462 In the calendar, the date can be selected with mouse-1. However, the
463 minibuffer will also be active, and you can simply enter the date as well.
464 When nil, only the minibuffer will be available."
465 :group 'org-time
466 :type 'boolean)
468 (defcustom org-calendar-follow-timestamp-change t
469 "Non-nil means, make the calendar window follow timestamp changes.
470 When a timestamp is modified and the calendar window is visible, it will be
471 moved to the new date."
472 :group 'org-time
473 :type 'boolean)
475 (defcustom org-log-done nil
476 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
477 When the state of an entry is changed from nothing to TODO, remove a previous
478 closing date."
479 :group 'org-time
480 :type 'boolean)
482 (defgroup org-agenda nil
483 "Options concerning agenda display Org-mode."
484 :tag "Org Agenda"
485 :group 'org)
487 (defcustom org-agenda-files nil
488 "A list of org files for agenda/diary display.
489 Entries are added to this list with \\[org-agenda-file-to-front] and removed with
490 \\[org-remove-file]. You can also use customize to edit the list."
491 :group 'org-agenda
492 :type '(repeat file))
494 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
495 "Custom commands for the agenda.
496 These commands will be offered on the splash screen displayed by the
497 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
499 key The key (a single char as a string) to be associated with the command.
500 type The command type, any of the following symbols:
501 todo Entries with a specific TODO keyword, in all agenda files.
502 tags Tags match in all agenda files.
503 todo-tree Sparse tree of specific TODO keyword in *current* file.
504 tags-tree Sparse tree with all tags matches in *current* file.
505 occur-tree Occur sparse tree for current file.
506 match What to search for:
507 - a single keyword for TODO keyword searches
508 - a tags match expression for tags searches
509 - a regular expression for occur searches"
510 :group 'org-agenda
511 :type '(repeat
512 (list (string :tag "Key")
513 (choice :tag "Type"
514 (const :tag "Tags search in all agenda files" tags)
515 (const :tag "TODO keyword search in all agenda files" todo)
516 (const :tag "Tags sparse tree in current buffer" tags-tree)
517 (const :tag "TODO keyword tree in current buffer" todo-tree)
518 (const :tag "Occur tree in current buffer" occur-tree))
519 (string :tag "Match"))))
521 (defcustom org-select-timeline-window t
522 "Non-nil means, after creating a timeline, move cursor into Timeline window.
523 When nil, cursor will remain in the current window."
524 :group 'org-agenda
525 :type 'boolean)
527 (defcustom org-select-agenda-window t
528 "Non-nil means, after creating an agenda, move cursor into Agenda window.
529 When nil, cursor will remain in the current window."
530 :group 'org-agenda
531 :type 'boolean)
533 (defcustom org-fit-agenda-window t
534 "Non-nil means, change window size of agenda to fit content."
535 :group 'org-agenda
536 :type 'boolean)
538 (defcustom org-agenda-show-all-dates t
539 "Non-nil means, `org-agenda' shows every day in the selected range.
540 When nil, only the days which actually have entries are shown."
541 :group 'org-agenda
542 :type 'boolean)
544 ;; FIXME: First day of month works only for current month because it would
545 ;; require a variable ndays treatment.
546 (defcustom org-agenda-start-on-weekday 1
547 "Non-nil means, start the overview always on the specified weekday.
548 0 Denotes Sunday, 1 denotes Monday etc.
549 When nil, always start on the current day."
550 :group 'org-agenda
551 :type '(choice (const :tag "Today" nil)
552 (const :tag "First day of month" t)
553 (number :tag "Weekday No.")))
555 (defcustom org-agenda-ndays 7
556 "Number of days to include in overview display."
557 :group 'org-agenda
558 :type 'number)
560 (defcustom org-agenda-include-all-todo t
561 "Non-nil means, the agenda will always contain all TODO entries.
562 When nil, date-less entries will only be shown if `org-agenda' is called
563 with a prefix argument.
564 When non-nil, the TODO entries will be listed at the top of the agenda, before
565 the entries for specific days."
566 :group 'org-agenda
567 :type 'boolean)
569 (defcustom org-agenda-include-diary nil
570 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
571 :group 'org-agenda
572 :type 'boolean)
574 (defcustom org-calendar-to-agenda-key [?c]
575 "The key to be installed in `calendar-mode-map' for switching to the agenda.
576 The command `org-calendar-goto-agenda' will be bound to this key. The
577 default is the character `c' because then `c' can be used to switch back and
578 forth between agenda and calendar."
579 :group 'org-agenda
580 :type 'sexp)
582 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
583 "Sorting structure for the agenda items of a single day.
584 This is a list of symbols which will be used in sequence to determine
585 if an entry should be listed before another entry. The following
586 symbols are recognized:
588 time-up Put entries with time-of-day indications first, early first
589 time-down Put entries with time-of-day indications first, late first
590 category-keep Keep the default order of categories, corresponding to the
591 sequence in `org-agenda-files'.
592 category-up Sort alphabetically by category, A-Z.
593 category-down Sort alphabetically by category, Z-A.
594 priority-up Sort numerically by priority, high priority last.
595 priority-down Sort numerically by priority, high priority first.
597 The different possibilities will be tried in sequence, and testing stops
598 if one comparison returns a \"not-equal\". For example, the default
599 '(time-up category-keep priority-down)
600 means: Pull out all entries having a specified time of day and sort them,
601 in order to make a time schedule for the current day the first thing in the
602 agenda listing for the day. Of the entries without a time indication, keep
603 the grouped in categories, don't sort the categories, but keep them in
604 the sequence given in `org-agenda-files'. Within each category sort by
605 priority.
607 Leaving out `category-keep' would mean that items will be sorted across
608 categories by priority."
609 :group 'org-agenda
610 :type '(repeat
611 (choice
612 (const time-up)
613 (const time-down)
614 (const category-keep)
615 (const category-up)
616 (const category-down)
617 (const priority-up)
618 (const priority-down))))
620 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
621 "Format specification for the prefix of items in the agenda buffer.
622 This format works similar to a printf format, with the following meaning:
624 %c the category of the item, \"Diary\" for entries from the diary, or
625 as given by the CATEGORY keyword or derived from the file name.
626 %T the first tag of the item.
627 %t the time-of-day specification if one applies to the entry, in the
628 format HH:MM
629 %s Scheduling/Deadline information, a short string
631 All specifiers work basically like the standard `%s' of printf, but may
632 contain two additional characters: A question mark just after the `%' and
633 a whitespace/punctuation character just before the final letter.
635 If the first character after `%' is a question mark, the entire field
636 will only be included if the corresponding value applies to the
637 current entry. This is useful for fields which should have fixed
638 width when present, but zero width when absent. For example,
639 \"%?-12t\" will result in a 12 character time field if a time of the
640 day is specified, but will completely disappear in entries which do
641 not contain a time.
643 If there is punctuation or whitespace character just before the final
644 format letter, this character will be appended to the field value if
645 the value is not empty. For example, the format \"%-12:c\" leads to
646 \"Diary: \" if the category is \"Diary\". If the category were be
647 empty, no additional colon would be interted.
649 The default value of this option is \" %-12:c%?-12t% s\", meaning:
650 - Indent the line with two space characters
651 - Give the category in a 12 chars wide field, padded with whitespace on
652 the right (because of `-'). Append a colon if there is a category
653 (because of `:').
654 - If there is a time-of-day, put it into a 12 chars wide field. If no
655 time, don't put in an empty field, just skip it (because of '?').
656 - Finally, put the scheduling information and append a whitespace.
658 As another example, if you don't want the time-of-day of entries in
659 the prefix, you could use:
661 (setq org-agenda-prefix-format \" %-11:c% s\")
663 See also the variables `org-agenda-remove-times-when-in-prefix' and
664 `org-agenda-remove-tags-when-in-prefix'."
665 :type 'string
666 :group 'org-agenda)
668 (defcustom org-timeline-prefix-format " % s"
669 "Like `org-agenda-prefix-format', but for the timeline of a single file."
670 :type 'string
671 :group 'org-agenda)
673 (defvar org-prefix-format-compiled nil
674 "The compiled version of the most recently used prefix format.
675 Depending on which command was used last, this may be the compiled version
676 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
678 (defcustom org-agenda-use-time-grid t
679 "Non-nil means, show a time grid in the agenda schedule.
680 A time grid is a set of lines for specific times (like every two hours between
681 8:00 and 20:00). The items scheduled for a day at specific times are
682 sorted in between these lines.
683 For details about when the grid will be shown, and what it will look like, see
684 the variable `org-agenda-time-grid'."
685 :group 'org-agenda
686 :type 'boolean)
688 (defcustom org-agenda-time-grid
689 '((daily today require-timed)
690 "----------------"
691 (800 1000 1200 1400 1600 1800 2000))
693 "The settings for time grid for agenda display.
694 This is a list of three items. The first item is again a list. It contains
695 symbols specifying conditions when the grid should be displayed:
697 daily if the agenda shows a single day
698 weekly if the agenda shows an entire week
699 today show grid on current date, independent of daily/weekly display
700 require-timed show grid only if at least on item has a time specification
702 The second item is a string which will be places behing the grid time.
704 The third item is a list of integers, indicating the times that should have
705 a grid line."
706 :group 'org-agenda
707 :type
708 '(list
709 (set :greedy t :tag "Grid Display Options"
710 (const :tag "Show grid in single day agenda display" daily)
711 (const :tag "Show grid in weekly agenda display" weekly)
712 (const :tag "Always show grid for today" today)
713 (const :tag "Show grid only if any timed entries are present"
714 require-timed)
715 (const :tag "Skip grid times already present in an entry"
716 remove-match))
717 (string :tag "Grid String")
718 (repeat :tag "Grid Times" (integer :tag "Time"))))
720 (defcustom org-agenda-remove-times-when-in-prefix t
721 "Non-nil means, remove duplicate time specifications in agenda items.
722 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
723 time-of-day specification in a headline or diary entry is extracted and
724 placed into the prefix. If this option is non-nil, the original specification
725 \(a timestamp or -range, or just a plain time(range) specification like
726 11:30-4pm) will be removed for agenda display. This makes the agenda less
727 cluttered.
728 The option can be t or nil. It may also be the symbol `beg', indicating
729 that the time should only be removed what it is located at the beginning of
730 the headline/diary entry."
731 :group 'org-agenda
732 :type '(choice
733 (const :tag "Always" t)
734 (const :tag "Never" nil)
735 (const :tag "When at beginning of entry" beg)))
737 (defcustom org-sort-agenda-notime-is-late t
738 "Non-nil means, items without time are considered late.
739 This is only relevant for sorting. When t, items which have no explicit
740 time like 15:30 will be considered as 24:01, i.e. later than any items which
741 do have a time. When nil, the default time is before 0:00. You can use this
742 option to decide if the schedule for today should come before or after timeless
743 agenda entries."
744 :group 'org-agenda
745 :type 'boolean)
747 (defcustom org-agenda-remove-tags-when-in-prefix nil
748 "Non-nil means, the tags from copy of headline in agenda.
749 When this is the symbol `prefix', only remove tags when
750 `org-agenda-prefix-format' contains a `%T' specifier."
751 :group 'org-agenda
752 :type '(choice
753 (const :tag "Always" t)
754 (const :tag "Never" nil)
755 (const :tag "When prefix format contains %T" prefix)))
757 (defgroup org-structure nil
758 "Options concerning structure editing in Org-mode."
759 :tag "Org Structure"
760 :group 'org)
762 (defcustom org-cycle-include-plain-lists nil
763 "Non-nil means, include plain lists into visibility cycling.
764 This means that during cycling, plain list items will *temporarily* be
765 interpreted as outline headlines with a level given by 1000+i where i is the
766 indentation of the bullet. In all other operations, plain list items are
767 not seen as headlines. For example, you cannot assign a TODO keyword to
768 such an item."
769 :group 'org-structure
770 :type 'boolean)
772 (defcustom org-cycle-emulate-tab t
773 "Where should `org-cycle' emulate TAB.
774 nil Never
775 white Only in completely white lines
776 t Everywhere except in headlines"
777 :group 'org-structure
778 :type '(choice (const :tag "Never" nil)
779 (const :tag "Only in completely white lines" white)
780 (const :tag "Everywhere except in headlines" t)
783 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
784 "Hook that is run after `org-cycle' has changed the buffer visibility.
785 The function(s) in this hook must accept a single argument which indicates
786 the new state that was set by the most recent `org-cycle' command. The
787 argument is a symbol. After a global state change, it can have the values
788 `overview', `content', or `all'. After a local state change, it can have
789 the values `folded', `children', or `subtree'."
790 :group 'org-structure
791 :type 'hook)
793 (defcustom org-highlight-sparse-tree-matches t
794 "Non-nil means, highlight all matches that define a sparse tree.
795 The highlights will automatically disappear the next time the buffer is
796 changed by an edit command."
797 :group 'org-structure
798 :type 'boolean)
800 (defcustom org-show-hierarchy-above t
801 "Non-nil means, show full hierarchy when showing a spot in the tree.
802 Turning this off makes sparse trees more compact, but also less clear."
803 :group 'org-structure
804 :type 'boolean)
806 (defcustom org-show-following-heading t
807 "Non-nil means, show heading following match in `org-occur'.
808 When doing an `org-occur' it is useful to show the headline which
809 follows the match, even if they do not match the regexp. This makes it
810 easier to edit directly inside the sparse tree. However, if you use
811 `org-occur' mainly as an overview, the following headlines are
812 unnecessary clutter."
813 :group 'org-structure
814 :type 'boolean)
816 (defcustom org-occur-hook '(org-first-headline-recenter)
817 "Hook that is run after `org-occur' has constructed a sparse tree.
818 This can be used to recenter the window to show as much of the structure
819 as possible."
820 :group 'org-structure
821 :type 'hook)
823 (defcustom org-odd-levels-only nil
824 "Non-nil means, skip even levels and only use odd levels for the outline.
825 This has the effect that two stars are being added/taken away in
826 promotion/demotion commands. It also influences how levels are
827 handled by the exporters.
828 Changing it requires restart of `font-lock-mode' to become effective
829 for fontification also in regions already fontified."
830 :group 'org-structure
831 :group 'org-font-lock
832 :type 'boolean)
834 (defcustom org-adapt-indentation t
835 "Non-nil means, adapt indentation when promoting and demoting.
836 When this is set and the *entire* text in an entry is indented, the
837 indentation is increased by one space in a demotion command, and
838 decreased by one in a promotion command. If any line in the entry
839 body starts at column 0, indentation is not changed at all."
840 :group 'org-structure
841 :type 'boolean)
843 (defcustom org-plain-list-ordered-item-terminator t
844 "The character that makes a line with leading number an ordered list item.
845 Valid values are ?. and ?\). To get both terminators, use t. While
846 ?. may look nicer, it creates the danger that a line with leading
847 number may be incorrectly interpreted as an item. ?\) therefore is
848 the safe choice."
849 :group 'org-structure
850 :type '(choice (const :tag "dot like in \"2.\"" ?.)
851 (const :tag "paren like in \"2)\"" ?\))
852 (const :tab "both" t)))
854 (defcustom org-auto-renumber-ordered-lists t
855 "Non-nil means, automatically renumber ordered plain lists.
856 Renumbering happens when the sequence have been changed with
857 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
858 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
859 :group 'org-structure
860 :type 'boolean)
862 (defcustom org-enable-fixed-width-editor t
863 "Non-nil means, lines starting with \":\" are treated as fixed-width.
864 This currently only means, they are never auto-wrapped.
865 When nil, such lines will be treated like ordinary lines.
866 See also the QUOTE keyword."
867 :group 'org-structure
868 :type 'boolean)
870 (defcustom org-archive-location "%s_archive::"
871 "The location where subtrees should be archived.
872 This string consists of two parts, separated by a double-colon.
874 The first part is a file name - when omitted, archiving happens in the same
875 file. %s will be replaced by the current file name (without directory part).
876 Archiving to a different file is useful to keep archived entries from
877 contributing to the Org-mode Agenda.
879 The part after the double colon is a headline. The archived entries will be
880 filed under that headline. When omitted, the subtrees are simply filed away
881 at the end of the file, as top-level entries.
883 Here are a few examples:
884 \"%s_archive::\"
885 If the current file is Projects.org, archive in file
886 Projects.org_archive, as top-level trees. This is the default.
888 \"::* Archived Tasks\"
889 Archive in the current file, under the top-level headline
890 \"* Archived Tasks\".
892 \"~/org/archive.org::\"
893 Archive in file ~/org/archive.org (absolute path), as top-level trees.
895 \"basement::** Finished Tasks\"
896 Archive in file ./basement (relative path), as level 3 trees
897 below the level 2 heading \"** Finished Tasks\".
899 You may set this option on a per-file basis by adding to the buffer a
900 line like
902 #+ARCHIVE: basement::** Finished Tasks"
903 :group 'org-structure
904 :type 'string)
906 (defcustom org-archive-mark-done t
907 "Non-nil means, mark archived entries as DONE."
908 :group 'org-structure
909 :type 'boolean)
911 (defcustom org-archive-stamp-time t
912 "Non-nil means, add a time stamp to archived entries.
913 The time stamp will be added directly after the TODO state keyword in the
914 first line, so it is probably best to use this in combinations with
915 `org-archive-mark-done'."
916 :group 'org-structure
917 :type 'boolean)
919 (defgroup org-tags nil
920 "Options concerning startup of Org-mode."
921 :tag "Org Tags"
922 :group 'org)
924 (defcustom org-tags-column 48
925 "The column to which tags should be indented in a headline.
926 If this number is positive, it specifies the column. If it is negative,
927 it means that the tags should be flushright to that column. For example,
928 -79 works well for a normal 80 character screen."
929 :group 'org-tags
930 :type 'integer)
932 (defcustom org-auto-align-tags t
933 "Non-nil means, realign tags after pro/demotion of TODO state change.
934 These operations change the length of a headline and therefore shift
935 the tags around. With this options turned on, after each such operation
936 the tags are again aligned to `org-tags-column'."
937 :group 'org-tags
938 :type 'boolean)
940 (defcustom org-use-tag-inheritance t
941 "Non-nil means, tags in levels apply also for sublevels.
942 When nil, only the tags directly given in a specific line apply there.
943 If you turn off this option, you very likely want to turn on the
944 companion option `org-tags-match-list-sublevels'."
945 :group 'org-tags
946 :type 'boolean)
948 (defcustom org-tags-match-list-sublevels nil
949 "Non-nil means list also sublevels of headlines matching tag search.
950 Because of tag inheritance (see variable `org-use-tag-inheritance'),
951 the sublevels of a headline matching a tag search often also match
952 the same search. Listing all of them can create very long lists.
953 Setting this variable to nil causes subtrees to be skipped.
954 This option is off by default, because inheritance in on. If you turn
955 inheritance off, you very likely want to turn this option on.
957 As a special case, if the tag search is restricted to TODO items, the
958 value of this variable is ignored and sublevels are always checked, to
959 make sure all corresponding TODO items find their way into the list."
960 :group 'org-tags
961 :type 'boolean)
963 (defvar org-tags-history nil
964 "History of minibuffer reads for tags.")
965 (defvar org-last-tags-completion-table nil
966 "The last used completion table for tags.")
968 (defgroup org-link nil
969 "Options concerning links in Org-mode."
970 :tag "Org Link"
971 :group 'org)
973 (defcustom org-tab-follows-link nil
974 "Non-nil means, on links TAB will follow the link.
975 Needs to be set before org.el is loaded."
976 :group 'org-link
977 :type 'boolean)
979 (defcustom org-return-follows-link nil
980 "Non-nil means, on links RET will follow the link.
981 Needs to be set before org.el is loaded."
982 :group 'org-link
983 :type 'boolean)
985 (defcustom org-mark-ring-length 4
986 "Number of different positions to be recorded in the ring
987 Changing this requires a restart of Emacs to work correctly."
988 :group 'org-link
989 :type 'interger)
991 (defcustom org-link-format "<%s>"
992 "Default format for linkes in the buffer.
993 This is a format string for printf, %s will be replaced by the link text.
994 If you want to make sure that your link is always properly terminated,
995 include angle brackets into this format, like \"<%s>\". Some people also
996 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
997 :group 'org-link
998 :type '(choice
999 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
1000 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
1001 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
1002 (string :tag "Other" :value "<%s>")))
1004 (defcustom org-allow-space-in-links t
1005 "Non-nil means, file names in links may contain space characters.
1006 When nil, it becomes possible to put several links into a line.
1007 Note that in tables, a link never extends accross fields, so in a table
1008 it is always possible to put several links into a line.
1009 Changing this variable requires a restart of Emacs of become effective."
1010 :group 'org-link
1011 :type 'boolean)
1013 (defcustom org-radio-targets t
1014 "Non-nil means activate text matching a link target.
1015 Radio targets are strings in triple angular brackets, like <<<My Target>>>.
1016 When this option is set, any occurrence of \"my target\" in normal text
1017 becomes a link."
1018 :group 'org-link
1019 :type 'boolean)
1021 (defcustom org-activate-camels nil
1022 "Non-nil means, treat words in CamelCase as in-file links.
1023 Changing this requires restart of Emacs to become effective."
1024 :group 'org-link
1025 :type 'boolean)
1027 (defcustom org-context-in-file-links t
1028 "Non-nil means, file links from `org-store-link' contain context.
1029 A search string will be added to the file name with :: as separator and
1030 used to find the context when the link is activated by the command
1031 `org-open-at-point'.
1032 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1033 negates this setting for the duration of the command."
1034 :group 'org-link
1035 :type 'boolean)
1037 (defcustom org-file-link-context-use-camel-case nil
1038 "Non-nil means, use CamelCase to store a search context in a file link.
1039 When nil, the search string simply consists of the words of the string."
1040 :group 'org-link
1041 :type 'boolean)
1043 (defcustom org-keep-stored-link-after-insertion nil
1044 "Non-nil means, keep link in list for entire session.
1046 The command `org-store-link' adds a link pointing to the current
1047 location to an internal list. These links accumulate during a session.
1048 The command `org-insert-link' can be used to insert links into any
1049 Org-mode file (offering completion for all stored links). When this
1050 option is nil, every link which has been inserted once using \\[org-insert-link]
1051 will be removed from the list, to make completing the unused links
1052 more efficient."
1053 :group 'org-link
1054 :type 'boolean)
1056 (defcustom org-link-frame-setup
1057 '((vm . vm-visit-folder-other-frame)
1058 (gnus . gnus-other-frame)
1059 (file . find-file-other-window))
1060 "Setup the frame configuration for following links.
1061 When following a link with Emacs, it may often be useful to display
1062 this link in another window or frame. This variable can be used to
1063 set this up for the different types of links.
1064 For VM, use any of
1065 `vm-visit-folder'
1066 `vm-visit-folder-other-frame'
1067 For Gnus, use any of
1068 `gnus'
1069 `gnus-other-frame'
1070 For FILE, use any of
1071 `find-file'
1072 `find-file-other-window'
1073 `find-file-other-frame'
1074 For the calendar, use the variable `calendar-setup'.
1075 For BBDB, it is currently only possible to display the matches in
1076 another window."
1077 :group 'org-link
1078 :type '(list
1079 (cons (const vm)
1080 (choice
1081 (const vm-visit-folder)
1082 (const vm-visit-folder-other-window)
1083 (const vm-visit-folder-other-frame)))
1084 (cons (const gnus)
1085 (choice
1086 (const gnus)
1087 (const gnus-other-frame)))
1088 (cons (const file)
1089 (choice
1090 (const find-file)
1091 (const find-file-other-window)
1092 (const find-file-other-frame)))))
1094 (defcustom org-usenet-links-prefer-google nil
1095 "Non-nil means, `org-store-link' will create web links to Google groups.
1096 When nil, Gnus will be used for such links.
1097 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1098 negates this setting for the duration of the command."
1099 :group 'org-link
1100 :type 'boolean)
1102 (defcustom org-open-non-existing-files nil
1103 "Non-nil means, `org-open-file' will open non-existing file.
1104 When nil, an error will be generated."
1105 :group 'org-link
1106 :type 'boolean)
1108 (defcustom org-confirm-shell-links t
1109 "Non-nil means, ask for confirmation before executing shell links.
1110 The default is true, to keep new users from shooting into their own foot."
1111 :group 'org-link
1112 :type 'boolean)
1114 (defconst org-file-apps-defaults-gnu
1115 '((t . mailcap))
1116 "Default file applications on a UNIX or GNU/Linux system.
1117 See `org-file-apps'.")
1119 (defconst org-file-apps-defaults-macosx
1120 '((t . "open %s")
1121 ("ps" . "gv %s")
1122 ("ps.gz" . "gv %s")
1123 ("eps" . "gv %s")
1124 ("eps.gz" . "gv %s")
1125 ("dvi" . "xdvi %s")
1126 ("fig" . "xfig %s"))
1127 "Default file applications on a MacOS X system.
1128 The system \"open\" is known as a default, but we use X11 applications
1129 for some files for which the OS does not have a good default.
1130 See `org-file-apps'.")
1132 (defconst org-file-apps-defaults-windowsnt
1133 '((t . (w32-shell-execute "open" file)))
1134 "Default file applications on a Windows NT system.
1135 The system \"open\" is used for most files.
1136 See `org-file-apps'.")
1138 (defcustom org-file-apps
1140 ("txt" . emacs)
1141 ("tex" . emacs)
1142 ("ltx" . emacs)
1143 ("org" . emacs)
1144 ("el" . emacs)
1146 "External applications for opening `file:path' items in a document.
1147 Org-mode uses system defaults for different file types, but
1148 you can use this variable to set the application for a given file
1149 extension. The entries in this list are cons cells with a file extension
1150 and the corresponding command. Possible values for the command are:
1151 `emacs' The file will be visited by the current Emacs process.
1152 `default' Use the default application for this file type.
1153 string A command to be executed by a shell; %s will be replaced
1154 by the path to the file.
1155 sexp A Lisp form which will be evaluated. The file path will
1156 be available in the Lisp variable `file'.
1157 For more examples, see the system specific constants
1158 `org-file-apps-defaults-macosx'
1159 `org-file-apps-defaults-windowsnt'
1160 `org-file-apps-defaults-gnu'."
1161 :group 'org-link
1162 :type '(repeat
1163 (cons (choice :value ""
1164 (string :tag "Extension")
1165 (const :tag "Default for unrecognized files" t)
1166 (const :tag "Links to a directory" directory))
1167 (choice :value ""
1168 (const :tag "Visit with Emacs" emacs)
1169 (const :tag "Use system default" default)
1170 (string :tag "Command")
1171 (sexp :tag "Lisp form")))))
1173 (defcustom org-mhe-search-all-folders nil
1174 "Non-nil means, that the search for the mh-message will be extended to
1175 all folders if the message cannot be found in the folder given in the link.
1176 Searching all folders is very effective with one of the search engines
1177 supported by MH-E, but will be slow with pick."
1178 :group 'org-link
1179 :type 'boolean)
1181 (defgroup org-remember nil
1182 "Options concerning interaction with remember.el."
1183 :tag "Org Remember"
1184 :group 'org)
1186 (defcustom org-directory "~/org"
1187 "Directory with org files.
1188 This directory will be used as default to prompt for org files.
1189 Used by the hooks for remember.el."
1190 :group 'org-remember
1191 :type 'directory)
1193 (defcustom org-default-notes-file "~/.notes"
1194 "Default target for storing notes.
1195 Used by the hooks for remember.el. This can be a string, or nil to mean
1196 the value of `remember-data-file'."
1197 :group 'org-remember
1198 :type '(choice
1199 (const :tag "Default from remember-data-file" nil)
1200 file))
1202 (defcustom org-remember-templates nil
1203 "Templates for the creation of remember buffers.
1204 When nil, just let remember make the buffer.
1205 When not nil, this is a list of 3-element lists. In each entry, the first
1206 element is a character, a unique key to select this template.
1207 The second element is the template. The third element is optional and can
1208 specify a destination file for remember items created with this template.
1209 The default file is given by `org-default-notes-file'.
1211 The template specifies the structure of the remember buffer. It should have
1212 a first line starting with a star, to act as the org-mode headline.
1213 Furthermore, the following %-escapes will be replaced with content:
1214 %t time stamp, date only
1215 %T time stamp with date and time
1216 %u inactive time stamp, date only
1217 %U inactive time stamp with date and time
1218 %n user name
1219 %a annotation, normally the link created with org-store-link
1220 %i initial content, the region when remember is called with C-u.
1221 If %i is indented, the entire inserted text will be indented as well.
1222 %? This will be removed, and the cursor placed at this position."
1223 :group 'org-remember
1224 :type '(repeat :tag "enabled"
1225 (list :value (?a "\n" nil)
1226 (character :tag "Selection Key")
1227 (string :tag "Template")
1228 (file :tag "Destination file (optional)"))))
1230 (defcustom org-reverse-note-order nil
1231 "Non-nil means, store new notes at the beginning of a file or entry.
1232 When nil, new notes will be filed to the end of a file or entry."
1233 :group 'org-remember
1234 :type '(choice
1235 (const :tag "Reverse always" t)
1236 (const :tag "Reverse never" nil)
1237 (repeat :tag "By file name regexp"
1238 (cons regexp boolean))))
1240 (defgroup org-table nil
1241 "Options concerning tables in Org-mode."
1242 :tag "Org Table"
1243 :group 'org)
1245 (defcustom org-enable-table-editor 'optimized
1246 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1247 When nil, such lines will be treated like ordinary lines.
1249 When equal to the symbol `optimized', the table editor will be optimized to
1250 do the following:
1251 - Use automatic overwrite mode in front of whitespace in table fields.
1252 This make the structure of the table stay in tact as long as the edited
1253 field does not exceed the column width.
1254 - Minimize the number of realigns. Normally, the table is aligned each time
1255 TAB or RET are pressed to move to another field. With optimization this
1256 happens only if changes to a field might have changed the column width.
1257 Optimization requires replacing the functions `self-insert-command',
1258 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1259 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1260 very good at guessing when a re-align will be necessary, but you can always
1261 force one with \\[org-ctrl-c-ctrl-c].
1263 If you would like to use the optimized version in Org-mode, but the
1264 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1266 This variable can be used to turn on and off the table editor during a session,
1267 but in order to toggle optimization, a restart is required.
1269 See also the variable `org-table-auto-blank-field'."
1270 :group 'org-table
1271 :type '(choice
1272 (const :tag "off" nil)
1273 (const :tag "on" t)
1274 (const :tag "on, optimized" optimized)))
1276 ;; FIXME: We could have a third option which makes it jump only over the first
1277 ;; hline in a table.
1278 (defcustom org-table-tab-jumps-over-hlines t
1279 "Non-nil means, tab in the last column of a table with jump over a hline.
1280 If a horizontal separator line is following the current line,
1281 `org-table-next-field' can either create a new row before that line, or jump
1282 over the line. When this option is nil, a new line will be created before
1283 this line."
1284 :group 'org-table
1285 :type 'boolean)
1287 (defcustom org-table-auto-blank-field t
1288 "Non-nil means, automatically blank table field when starting to type into it.
1289 This only happens when typing immediately after a field motion
1290 command (TAB, S-TAB or RET).
1291 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1292 :group 'org-table
1293 :type 'boolean)
1295 (defcustom org-table-default-size "5x2"
1296 "The default size for newly created tables, Columns x Rows."
1297 :group 'org-table
1298 :type 'string)
1300 (defcustom org-table-automatic-realign t
1301 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1302 When nil, aligning is only done with \\[org-table-align], or after column
1303 removal/insertion."
1304 :group 'org-table
1305 :type 'boolean)
1307 (defcustom org-table-spaces-around-separators '(1 . 1)
1308 "The number of spaces to be placed before and after separators."
1309 :group 'org-table
1310 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1312 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1313 "The number of spaces to be placed before and after separators.
1314 This option applies when the column separators have been made invisible."
1315 :group 'org-table
1316 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1318 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1319 "Regular expression for recognizing numbers in table columns.
1320 If a table column contains mostly numbers, it will be aligned to the
1321 right. If not, it will be aligned to the left.
1323 The default value of this option is a regular expression which allows
1324 anything which looks remotely like a number as used in scientific
1325 context. For example, all of the following will be considered a
1326 number:
1327 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1329 Other options offered by the customize interface are more restrictive."
1330 :group 'org-table
1331 :type '(choice
1332 (const :tag "Positive Integers"
1333 "^[0-9]+$")
1334 (const :tag "Integers"
1335 "^[-+]?[0-9]+$")
1336 (const :tag "Floating Point Numbers"
1337 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1338 (const :tag "Floating Point Number or Integer"
1339 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1340 (const :tag "Exponential, Floating point, Integer"
1341 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1342 (const :tag "Very General Number-Like"
1343 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1344 (string :tag "Regexp:")))
1346 (defcustom org-table-number-fraction 0.5
1347 "Fraction of numbers in a column required to make the column align right.
1348 In a column all non-white fields are considered. If at least this
1349 fraction of fields is matched by `org-table-number-fraction',
1350 alignment to the right border applies."
1351 :group 'org-table
1352 :type 'number)
1354 (defcustom org-export-highlight-first-table-line t
1355 "Non-nil means, highlight the first table line.
1356 In HTML export, this means use <th> instead of <td>.
1357 In tables created with table.el, this applies to the first table line.
1358 In Org-mode tables, all lines before the first horizontal separator
1359 line will be formatted with <th> tags."
1360 :group 'org-table
1361 :type 'boolean)
1363 (defcustom org-table-tab-recognizes-table.el t
1364 "Non-nil means, TAB will automatically notice a table.el table.
1365 When it sees such a table, it moves point into it and - if necessary -
1366 calls `table-recognize-table'."
1367 :group 'org-table
1368 :type 'boolean)
1370 (defgroup org-table-calculation nil
1371 "Options concerning tables in Org-mode."
1372 :tag "Org Table Calculation"
1373 :group 'org)
1375 (defcustom org-table-copy-increment t
1376 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1377 :group 'org-table-calculation
1378 :type 'boolean)
1380 (defcustom org-calc-default-modes
1381 '(calc-internal-prec 12
1382 calc-float-format (float 5)
1383 calc-angle-mode deg
1384 calc-prefer-frac nil
1385 calc-symbolic-mode nil
1386 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1387 calc-display-working-message t
1389 "List with Calc mode settings for use in calc-eval for table formulas.
1390 The list must contain alternating symbols (Calc modes variables and values).
1391 Don't remove any of the default settings, just change the values. Org-mode
1392 relies on the variables to be present in the list."
1393 :group 'org-table-calculation
1394 :type 'plist)
1396 (defcustom org-table-formula-evaluate-inline t
1397 "Non-nil means, TAB and RET evaluate a formula in current table field.
1398 If the current field starts with an equal sign, it is assumed to be a formula
1399 which should be evaluated as described in the manual and in the documentation
1400 string of the command `org-table-eval-formula'. This feature requires the
1401 Emacs calc package.
1402 When this variable is nil, formula calculation is only available through
1403 the command \\[org-table-eval-formula]."
1404 :group 'org-table-calculation
1405 :type 'boolean)
1408 (defcustom org-table-formula-use-constants t
1409 "Non-nil means, interpret constants in formulas in tables.
1410 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1411 by the value given in `org-table-formula-constants', or by a value obtained
1412 from the `constants.el' package."
1413 :group 'org-table-calculation
1414 :type 'boolean)
1416 (defcustom org-table-formula-constants nil
1417 "Alist with constant names and values, for use in table formulas.
1418 The car of each element is a name of a constant, without the `$' before it.
1419 The cdr is the value as a string. For example, if you'd like to use the
1420 speed of light in a formula, you would configure
1422 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1424 and then use it in an equation like `$1*$c'."
1425 :group 'org-table-calculation
1426 :type '(repeat
1427 (cons (string :tag "name")
1428 (string :tag "value"))))
1430 (defcustom org-table-formula-numbers-only nil
1431 "Non-nil means, calculate only with numbers in table formulas.
1432 Then all input fields will be converted to a number, and the result
1433 must also be a number. When nil, calc's full potential is available
1434 in table calculations, including symbolics etc."
1435 :group 'org-table-calculation
1436 :type 'boolean)
1438 (defcustom org-table-allow-automatic-line-recalculation t
1439 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1440 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1441 :group 'org-table-calculation
1442 :type 'boolean)
1444 (defgroup org-export nil
1445 "Options for exporting org-listings."
1446 :tag "Org Export"
1447 :group 'org)
1449 (defcustom org-export-language-setup
1450 '(("en" "Author" "Date" "Table of Contents")
1451 ("da" "Ophavsmand" "Dato" "Indhold")
1452 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1453 ("es" "Autor" "Fecha" "\xccndice")
1454 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1455 ("it" "Autore" "Data" "Indice")
1456 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1457 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1458 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1459 "Terms used in export text, translated to different languages.
1460 Use the variable `org-export-default-language' to set the language,
1461 or use the +OPTION lines for a per-file setting."
1462 :group 'org-export
1463 :type '(repeat
1464 (list
1465 (string :tag "HTML language tag")
1466 (string :tag "Author")
1467 (string :tag "Date")
1468 (string :tag "Table of Contents"))))
1470 (defcustom org-export-default-language "en"
1471 "The default language of HTML export, as a string.
1472 This should have an association in `org-export-language-setup'."
1473 :group 'org-export
1474 :type 'string)
1476 (defcustom org-export-html-style
1477 "<style type=\"text/css\">
1478 html {
1479 font-family: Times, serif;
1480 font-size: 12pt;
1482 .title { text-align: center; }
1483 .todo, .deadline { color: red; }
1484 .done { color: green; }
1485 .target { background-color: lavender; }
1486 pre {
1487 border: 1pt solid #AEBDCC;
1488 background-color: #F3F5F7;
1489 padding: 5pt;
1490 font-family: courier, monospace;
1492 table { border-collapse: collapse; }
1493 td, th {
1494 vertical-align: top;
1495 border: 1pt solid #ADB9CC;
1497 </style>"
1498 "The default style specification for exported HTML files.
1499 Since there are different ways of setting style information, this variable
1500 needs to contain the full HTML structure to provide a style, including the
1501 surrounding HTML tags. The style specifications should include definitions
1502 for new classes todo, done, title, and deadline. For example, legal values
1503 would be:
1505 <style type=\"text/css\">
1506 p { font-weight: normal; color: gray; }
1507 h1 { color: black; }
1508 .title { text-align: center; }
1509 .todo, .deadline { color: red; }
1510 .done { color: green; }
1511 </style>
1513 or, if you want to keep the style in a file,
1515 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1517 As the value of this option simply gets inserted into the HTML <head> header,
1518 you can \"misuse\" it to add arbitrary text to the header."
1519 :group 'org-export
1520 :type 'string)
1522 (defcustom org-export-headline-levels 3
1523 "The last level which is still exported as a headline.
1524 Inferior levels will produce itemize lists when exported.
1525 Note that a numeric prefix argument to an exporter function overrides
1526 this setting.
1528 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1529 :group 'org-export
1530 :type 'number)
1532 (defcustom org-export-with-section-numbers t
1533 "Non-nil means, add section numbers to headlines when exporting.
1535 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1536 :group 'org-export
1537 :type 'boolean)
1539 (defcustom org-export-with-toc t
1540 "Non-nil means, create a table of contents in exported files.
1541 The TOC contains headlines with levels up to`org-export-headline-levels'.
1543 Headlines which contain any TODO items will be marked with \"(*)\" in
1544 ASCII export, and with red color in HTML output.
1546 In HTML output, the TOC will be clickable.
1548 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1549 :group 'org-export
1550 :type 'boolean)
1552 (defcustom org-export-plain-list-max-depth 20
1553 "Maximum depth of hand-formatted lists in HTML export.
1555 Org-mode parses hand-formatted enumeration and bullet lists and
1556 transforms them to HTML open export. Different indentation of the
1557 bullet or number indicates different list nesting levels. To avoid
1558 confusion, only a single level is allowed by default. When this is
1559 larger than 1, deeper indentation leads to deeper list nesting. For
1560 example, the default value of 3 allows the following list to be
1561 formatted correctly in HTML:
1563 * Fruit
1564 - Apple
1565 - Banana
1566 1. from Africa
1567 2. from South America
1568 - Pineapple
1569 * Bread
1570 * Dairy products"
1571 :group 'org-export
1572 :type 'integer)
1574 (defcustom org-export-preserve-breaks nil
1575 "Non-nil means, preserve all line breaks when exporting.
1576 Normally, in HTML output paragraphs will be reformatted. In ASCII
1577 export, line breaks will always be preserved, regardless of this variable.
1579 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1580 :group 'org-export
1581 :type 'boolean)
1583 (defcustom org-export-html-inline-images t
1584 "Non-nil means, inline images into exported HTML pages.
1585 The link will still be to the original location of the image file.
1586 So if you are moving the page, lets say to your public HTML site,
1587 you will have to move the image and maybe change the link."
1588 :group 'org-export
1589 :type 'boolean)
1591 (defcustom org-export-html-expand t
1592 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1593 When nil, these tags will be exported as plain text and therefore
1594 not be interpreted by a browser.
1596 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1597 :group 'org-export
1598 :type 'boolean)
1600 (defcustom org-export-with-fixed-width t
1601 "Non-nil means, lines starting with \":\" will be in fixed width font.
1602 This can be used to have pre-formatted text, fragments of code etc. For
1603 example:
1604 : ;; Some Lisp examples
1605 : (while (defc cnt)
1606 : (ding))
1607 will be looking just like this in also HTML. In ASCII export, this option
1608 has no effect.
1610 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1611 :group 'org-export
1612 :type 'boolean)
1614 (defcustom org-export-with-tables t
1615 "If non-nil, lines starting with \"|\" define a table.
1616 For example:
1618 | Name | Address | Birthday |
1619 |-------------+----------+-----------|
1620 | Arthur Dent | England | 29.2.2100 |
1622 In ASCII export, this option has no effect.
1624 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1625 :group 'org-export
1626 :type 'boolean)
1628 (defcustom org-export-table-remove-special-lines t
1629 "Remove special lines and marking characters in calculating tables.
1630 This removes the special marking character column from tables that are set
1631 up for spreadsheet calculations. It also removes the entire lines
1632 marked with `!', `_', or `^'. The lines with `$' are kept, because
1633 the values of constants may be useful to have."
1634 :group 'org-export
1635 :type 'boolean)
1637 (defcustom org-export-prefer-native-exporter-for-tables nil
1638 "Non-nil means, always export tables created with table.el natively.
1639 Natively means, use the HTML code generator in table.el.
1640 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1641 the table does not use row- or column-spanning). This has the
1642 advantage, that the automatic HTML conversions for math symbols and
1643 sub/superscripts can be applied. Org-mode's HTML generator is also
1644 much faster."
1645 :group 'org-export
1646 :type 'boolean)
1648 (defcustom org-export-html-table-tag
1649 "<table border=1 cellspacing=0 cellpadding=6>"
1650 "The HTML tag used to start a table.
1651 This must be a <table> tag, but you may change the options like
1652 borders and spacing."
1653 :group 'org-export
1654 :type 'string)
1656 (defcustom org-export-with-emphasize t
1657 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1658 If the export target supports emphasizing text, the word will be
1659 typeset in bold, italic, or underlined, respectively. Works only for
1660 single words, but you can say: I *really* *mean* *this*.
1661 In ASCII export, this option has no effect.
1663 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1664 :group 'org-export
1665 :type 'boolean)
1667 (defcustom org-match-sexp-depth 3
1668 "Number of stacked braces for sub/superscript matching.
1669 This has to be set before loading org.el to be effective."
1670 :group 'org-export
1671 :type 'integer)
1673 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1674 (defcustom org-export-with-sub-superscripts t
1675 "Non-nil means, interpret \"_\" and \"^\" for export.
1676 When this option is turned on, you can use TeX-like syntax for sub- and
1677 superscripts. Several characters after \"_\" or \"^\" will be
1678 considered as a single item - so grouping with {} is normally not
1679 needed. For example, the following things will be parsed as single
1680 sub- or superscripts.
1682 10^24 or 10^tau several digits will be considered 1 item.
1683 10^-12 or 10^-tau a leading sign with digits or a word
1684 x^2-y^3 will be read as x^2 - y^3, because items are
1685 terminated by almost any nonword/nondigit char.
1686 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1688 Still, ambiguity is possible - so when in doubt use {} to enclose the
1689 sub/superscript.
1690 In ASCII export, this option has no effect.
1692 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1693 :group 'org-export
1694 :type 'boolean)
1696 (defcustom org-export-with-TeX-macros t
1697 "Non-nil means, interpret simple TeX-like macros when exporting.
1698 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1699 No only real TeX macros will work here, but the standard HTML entities
1700 for math can be used as macro names as well. For a list of supported
1701 names in HTML export, see the constant `org-html-entities'.
1702 In ASCII export, this option has no effect.
1704 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1705 :group 'org-export
1706 :type 'boolean)
1708 (defcustom org-export-html-with-timestamp nil
1709 "If non-nil, write `org-export-html-html-helper-timestamp'
1710 into the exported HTML text. Otherwise, the buffer will just be saved
1711 to a file."
1712 :group 'org-export
1713 :type 'boolean)
1715 (defcustom org-export-html-html-helper-timestamp
1716 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1717 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1718 :group 'org-export
1719 :type 'string)
1721 (defcustom org-export-ascii-show-new-buffer t
1722 "Non-nil means, popup buffer containing the exported ASCII text.
1723 Otherwise the buffer will just be saved to a file and stay hidden."
1724 :group 'org-export
1725 :type 'boolean)
1727 (defcustom org-export-html-show-new-buffer nil
1728 "Non-nil means, popup buffer containing the exported html text.
1729 Otherwise, the buffer will just be saved to a file and stay hidden."
1730 :group 'org-export
1731 :type 'boolean)
1733 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1734 "The file name for the iCalendar file covering all agenda files.
1735 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1736 :group 'org-export
1737 :type 'file)
1739 (defcustom org-icalendar-include-todo nil
1740 "Non-nil means, export to iCalendar files should also cover TODO items."
1741 :group 'org-export
1742 :type 'boolean)
1744 (defcustom org-icalendar-combined-name "OrgMode"
1745 "Calendar name for the combined iCalendar representing all agenda files."
1746 :group 'org-export
1747 :type 'string)
1749 (defgroup org-font-lock nil
1750 "Faces and settings for highlighting in Org-mode."
1751 :tag "Org Font Lock"
1752 :group 'org)
1754 (defcustom org-level-color-stars-only nil
1755 "Non-nil means fontify only the stars in each headline.
1756 When nil, the entire headline is fontified.
1757 Changing it requires restart of `font-lock-mode' to become effective
1758 also in regions already fontified."
1759 :group 'org-font-lock
1760 :type 'boolean)
1762 (defcustom org-hide-leading-stars nil
1763 "Non-nil means, hide the first N-1 stars in a headline.
1764 This works by using the face `org-hide' for these stars. This
1765 face is white for a light background, and black for a dark
1766 background. You may have to customize the face `org-hide' to
1767 make this work.
1768 Changing it requires restart of `font-lock-mode' to become effective
1769 also in regions already fontified."
1770 :group 'org-font-lock
1771 :type 'boolean)
1773 (defcustom org-fontify-done-headline nil
1774 "Non-nil means, change the face of a headline if it is marked DONE.
1775 Normally, only the TODO/DONE keyword indicates the state of a headline.
1776 When this is non-nil, the headline after the keyword is set to the
1777 `org-headline-done' as an additional indication."
1778 :group 'org-font-lock
1779 :type 'boolean)
1781 (defcustom org-fontify-emphasized-text t
1782 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
1783 Changing this variable requires a restart of Emacs to take effect."
1784 :group 'org-font-lock
1785 :type 'boolean)
1787 (defface org-hide
1789 (((type tty) (class color)) (:foreground "white"))
1790 (((class color) (background light)) (:foreground "white"))
1791 (((class color) (background dark)) (:foreground "black"))
1792 ; (((class color) (backgro6und light)) (:foreground "grey90"))
1793 ; (((class color) (background dark)) (:foreground "grey10"))
1794 (t (:inverse-video nil)))
1795 "Face used for level 1 headlines."
1796 :group 'org-font-lock)
1798 (defface org-level-1 ;; font-lock-function-name-face
1799 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1800 (((class color) (background light)) (:foreground "Blue"))
1801 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1802 (t (:inverse-video t :bold t)))
1803 "Face used for level 1 headlines."
1804 :group 'org-font-lock)
1806 (defface org-level-2 ;; font-lock-variable-name-face
1807 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1808 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1809 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1810 (t (:bold t :italic t)))
1811 "Face used for level 2 headlines."
1812 :group 'org-font-lock)
1814 (defface org-level-3 ;; font-lock-keyword-face
1815 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1816 (((class color) (background light)) (:foreground "Purple"))
1817 (((class color) (background dark)) (:foreground "Cyan"))
1818 (t (:bold t)))
1819 "Face used for level 3 headlines."
1820 :group 'org-font-lock)
1822 (defface org-level-4 ;; font-lock-comment-face
1823 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1824 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1825 (((class color) (background light)) (:foreground "Firebrick"))
1826 (((class color) (background dark)) (:foreground "chocolate1"))
1827 (t (:bold t :italic t)))
1828 "Face used for level 4 headlines."
1829 :group 'org-font-lock)
1831 (defface org-level-5 ;; font-lock-type-face
1832 '((((type tty) (class color)) (:foreground "green"))
1833 (((class color) (background light)) (:foreground "ForestGreen"))
1834 (((class color) (background dark)) (:foreground "PaleGreen"))
1835 (t (:bold t :underline t)))
1836 "Face used for level 5 headlines."
1837 :group 'org-font-lock)
1839 (defface org-level-6 ;; font-lock-constant-face
1840 '((((type tty) (class color)) (:foreground "magenta"))
1841 (((class color) (background light)) (:foreground "CadetBlue"))
1842 (((class color) (background dark)) (:foreground "Aquamarine"))
1843 (t (:bold t :underline t)))
1844 "Face used for level 6 headlines."
1845 :group 'org-font-lock)
1847 (defface org-level-7 ;; font-lock-builtin-face
1848 '((((type tty) (class color)) (:foreground "blue" :weight light))
1849 (((class color) (background light)) (:foreground "Orchid"))
1850 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1851 (t (:bold t)))
1852 "Face used for level 7 headlines."
1853 :group 'org-font-lock)
1855 (defface org-level-8 ;; font-lock-string-face
1856 '((((type tty) (class color)) (:foreground "green"))
1857 (((class color) (background light)) (:foreground "RosyBrown"))
1858 (((class color) (background dark)) (:foreground "LightSalmon"))
1859 (t (:italic t)))
1860 "Face used for level 8 headlines."
1861 :group 'org-font-lock)
1863 (defface org-special-keyword ;; font-lock-string-face
1864 '((((type tty) (class color)) (:foreground "green"))
1865 (((class color) (background light)) (:foreground "RosyBrown"))
1866 (((class color) (background dark)) (:foreground "LightSalmon"))
1867 (t (:italic t)))
1868 "Face used for special keywords."
1869 :group 'org-font-lock)
1871 (defface org-warning ;; font-lock-warning-face
1872 '((((type tty) (class color)) (:foreground "red"))
1873 (((class color) (background light)) (:foreground "Red" :bold t))
1874 (((class color) (background dark)) (:foreground "Red1" :bold t))
1875 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1876 (t (:inverse-video t :bold t)))
1877 "Face for deadlines and TODO keywords."
1878 :group 'org-font-lock)
1880 (defface org-headline-done ;; font-lock-string-face
1881 '((((type tty) (class color)) (:foreground "green"))
1882 (((class color) (background light)) (:foreground "RosyBrown"))
1883 (((class color) (background dark)) (:foreground "LightSalmon"))
1884 (t (:italic t)))
1885 "Face used to indicate that a headline is DONE. See also the variable
1886 `org-fontify-done-headline'."
1887 :group 'org-font-lock)
1889 ;; Inheritance does not yet work for xemacs. So we just copy...
1891 (defface org-deadline-announce
1892 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1893 (((class color) (background light)) (:foreground "Blue"))
1894 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1895 (t (:inverse-video t :bold t)))
1896 "Face for upcoming deadlines."
1897 :group 'org-font-lock)
1899 (defface org-scheduled-today
1900 '((((type tty) (class color)) (:foreground "green"))
1901 (((class color) (background light)) (:foreground "DarkGreen"))
1902 (((class color) (background dark)) (:foreground "PaleGreen"))
1903 (t (:bold t :underline t)))
1904 "Face for items scheduled for a certain day."
1905 :group 'org-font-lock)
1907 (defface org-scheduled-previously
1908 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1909 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1910 (((class color) (background light)) (:foreground "Firebrick"))
1911 (((class color) (background dark)) (:foreground "chocolate1"))
1912 (t (:bold t :italic t)))
1913 "Face for items scheduled previously, and not yet done."
1914 :group 'org-font-lock)
1916 (defface org-formula
1917 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1918 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1919 (((class color) (background light)) (:foreground "Firebrick"))
1920 (((class color) (background dark)) (:foreground "chocolate1"))
1921 (t (:bold t :italic t)))
1922 "Face for formulas."
1923 :group 'org-font-lock)
1925 (defface org-link
1926 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1927 (((class color) (background light)) (:foreground "Purple"))
1928 (((class color) (background dark)) (:foreground "Cyan"))
1929 (t (:bold t)))
1930 "Face for links."
1931 :group 'org-font-lock)
1933 (defface org-tag
1934 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1935 (((class color) (background light)) (:foreground "Purple" :weight bold))
1936 (((class color) (background dark)) (:foreground "Cyan" :weight bold))
1937 (t (:bold t)))
1938 "Face for tags."
1939 :group 'org-font-lock)
1941 (defface org-done ;; font-lock-type-face
1942 '((((type tty) (class color)) (:foreground "green"))
1943 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1944 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1945 (t (:bold t :underline t)))
1946 "Face used for DONE."
1947 :group 'org-font-lock)
1949 (defface org-table ;; font-lock-function-name-face
1950 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1951 (((class color) (background light)) (:foreground "Blue"))
1952 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1953 (t (:inverse-video t :bold t)))
1954 "Face used for tables."
1955 :group 'org-font-lock)
1957 (defface org-time-grid ;; font-lock-variable-name-face
1958 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1959 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1960 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1961 (t (:bold t :italic t)))
1962 "Face used for time grids."
1963 :group 'org-font-lock)
1965 (defvar org-level-faces
1966 '(org-level-1 org-level-2 org-level-3 org-level-4
1967 org-level-5 org-level-6 org-level-7 org-level-8
1969 (defvar org-n-levels (length org-level-faces))
1971 (defun org-set-regexps-and-options ()
1972 "Precompute regular expressions for current buffer."
1973 (when (eq major-mode 'org-mode)
1974 (let ((re (org-make-options-regexp
1975 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1976 "STARTUP" "ARCHIVE")))
1977 (splitre "[ \t]+")
1978 kwds int key value cat arch)
1979 (save-excursion
1980 (save-restriction
1981 (widen)
1982 (goto-char (point-min))
1983 (while (re-search-forward re nil t)
1984 (setq key (match-string 1) value (match-string 2))
1985 (cond
1986 ((equal key "CATEGORY")
1987 (if (string-match "[ \t]+$" value)
1988 (setq value (replace-match "" t t value)))
1989 (setq cat (intern value)))
1990 ((equal key "SEQ_TODO")
1991 (setq int 'sequence
1992 kwds (append kwds (org-split-string value splitre))))
1993 ((equal key "PRI_TODO")
1994 (setq int 'priority
1995 kwds (append kwds (org-split-string value splitre))))
1996 ((equal key "TYP_TODO")
1997 (setq int 'type
1998 kwds (append kwds (org-split-string value splitre))))
1999 ((equal key "STARTUP")
2000 (let ((opts (org-split-string value splitre))
2001 (set '(("fold" org-startup-folded t)
2002 ("nofold" org-startup-folded nil)
2003 ("content" org-startup-folded content)
2004 ("hidestars" org-hide-leading-stars t)
2005 ("showstars" org-hide-leading-stars nil)
2006 ("odd" org-odd-levels-only t)
2007 ("oddeven" org-odd-levels-only nil)
2008 ("dlcheck" org-startup-with-deadline-check t)
2009 ("nodlcheck" org-startup-with-deadline-check nil)))
2010 l var val)
2011 (while (setq l (assoc (pop opts) set))
2012 (setq var (nth 1 l) val (nth 2 l))
2013 (set (make-local-variable var) val))))
2014 ((equal key "ARCHIVE")
2015 (string-match " *$" value)
2016 (setq arch (replace-match "" t t value))
2017 (remove-text-properties 0 (length arch)
2018 '(face t fontified t) arch)))
2020 (and cat (set (make-local-variable 'org-category) cat))
2021 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2022 (and arch (set (make-local-variable 'org-archive-location) arch))
2023 (and int (set (make-local-variable 'org-todo-interpretation) int)))
2024 ;; Compute the regular expressions and other local variables
2025 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2026 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2027 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2028 (length org-scheduled-string)))
2029 org-done-string
2030 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2031 org-todo-regexp
2032 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2033 "\\|") "\\)\\>")
2034 org-not-done-regexp
2035 (concat "\\<\\("
2036 (mapconcat 'regexp-quote
2037 (nreverse (cdr (reverse org-todo-keywords)))
2038 "\\|")
2039 "\\)\\>")
2040 org-todo-line-regexp
2041 (concat "^\\(\\*+\\)[ \t]*\\("
2042 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2043 "\\)? *\\(.*\\)")
2044 org-nl-done-regexp
2045 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2046 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2047 org-deadline-regexp (concat "\\<" org-deadline-string)
2048 org-deadline-time-regexp
2049 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2050 org-deadline-line-regexp
2051 (concat "\\<\\(" org-deadline-string "\\).*")
2052 org-scheduled-regexp
2053 (concat "\\<" org-scheduled-string)
2054 org-scheduled-time-regexp
2055 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
2056 (org-set-font-lock-defaults)))
2058 ;; Tell the compiler about dynamically scoped variables,
2059 ;; and variables from other packages
2060 (defvar zmacs-regions) ; XEmacs regions
2061 (defvar original-date) ; dynamically scoped in calendar
2062 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2063 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2064 (defvar org-html-entities) ; defined later in this file
2065 (defvar org-goto-start-pos) ; dynamically scoped parameter
2066 (defvar org-time-was-given) ; dynamically scoped parameter
2067 (defvar org-ts-what) ; dynamically scoped parameter
2068 (defvar mark-active) ; Emacs only, not available in XEmacs.
2069 (defvar timecnt) ; dynamically scoped parameter
2070 (defvar levels-open) ; dynamically scoped parameter
2071 (defvar title) ; dynamically scoped parameter
2072 (defvar author) ; dynamically scoped parameter
2073 (defvar email) ; dynamically scoped parameter
2074 (defvar text) ; dynamically scoped parameter
2075 (defvar entry) ; dynamically scoped parameter
2076 (defvar date) ; dynamically scoped parameter
2077 (defvar language) ; dynamically scoped parameter
2078 (defvar options) ; dynamically scoped parameter
2079 (defvar ans1) ; dynamically scoped parameter
2080 (defvar ans2) ; dynamically scoped parameter
2081 (defvar starting-day) ; local variable
2082 (defvar include-all-loc) ; local variable
2083 (defvar vm-message-pointer) ; from vm
2084 (defvar vm-folder-directory) ; from vm
2085 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2086 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2087 (defvar gnus-group-name) ; from gnus
2088 (defvar gnus-article-current) ; from gnus
2089 (defvar w3m-current-url) ; from w3m
2090 (defvar mh-progs) ; from MH-E
2091 (defvar mh-current-folder) ; from MH-E
2092 (defvar mh-show-folder-buffer) ; from MH-E
2093 (defvar mh-index-folder) ; from MH-E
2094 (defvar mh-searcher) ; from MH-E
2095 (defvar org-selected-point) ; dynamically scoped parameter
2096 (defvar calendar-mode-map) ; from calendar.el
2097 (defvar last-arg) ; local variable
2098 (defvar remember-save-after-remembering) ; from remember.el
2099 (defvar remember-data-file) ; from remember.el
2100 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2101 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2103 ;;; Define the mode
2105 (defvar org-mode-map (copy-keymap outline-mode-map)
2106 "Keymap for Org-mode.")
2108 (defvar org-struct-menu) ; defined later in this file
2109 (defvar org-org-menu) ; defined later in this file
2110 (defvar org-tbl-menu) ; defined later in this file
2112 ;; We use a before-change function to check if a table might need
2113 ;; an update.
2114 (defvar org-table-may-need-update t
2115 "Indicates that a table might need an update.
2116 This variable is set by `org-before-change-function'.
2117 `org-table-align' sets it back to nil.")
2118 (defvar org-mode-hook nil)
2119 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2120 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2123 ;;;###autoload
2124 (define-derived-mode org-mode outline-mode "Org"
2125 "Outline-based notes management and organizer, alias
2126 \"Carsten's outline-mode for keeping track of everything.\"
2128 Org-mode develops organizational tasks around a NOTES file which
2129 contains information about projects as plain text. Org-mode is
2130 implemented on top of outline-mode, which is ideal to keep the content
2131 of large files well structured. It supports ToDo items, deadlines and
2132 time stamps, which magically appear in the diary listing of the Emacs
2133 calendar. Tables are easily created with a built-in table editor.
2134 Plain text URL-like links connect to websites, emails (VM), Usenet
2135 messages (Gnus), BBDB entries, and any files related to the project.
2136 For printing and sharing of notes, an Org-mode file (or a part of it)
2137 can be exported as a structured ASCII or HTML file.
2139 The following commands are available:
2141 \\{org-mode-map}"
2142 (easy-menu-add org-org-menu)
2143 (easy-menu-add org-tbl-menu)
2144 (org-install-agenda-files-menu)
2145 (setq outline-regexp "\\*+")
2146 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2147 (setq outline-level 'org-outline-level)
2148 (if org-startup-truncated (setq truncate-lines t))
2149 (org-set-regexps-and-options)
2150 (set (make-local-variable 'font-lock-unfontify-region-function)
2151 'org-unfontify-region)
2152 ;; Activate before-change-function
2153 (set (make-local-variable 'org-table-may-need-update) t)
2154 (org-add-hook 'before-change-functions 'org-before-change-function nil
2155 'local)
2156 ;; Paragraphs and auto-filling
2157 (org-set-autofill-regexps)
2158 (org-update-radio-target-regexp)
2159 ;; Settings for Calc embedded mode
2160 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2161 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2162 (if (and org-insert-mode-line-in-empty-file
2163 (interactive-p)
2164 (= (point-min) (point-max)))
2165 (insert " -*- mode: org -*-\n\n"))
2167 ;; Get rid of Outline menus, they are not needed
2168 ;; Need to do this here because define-derived-mode sets up
2169 ;; the keymap so late.
2170 (if org-xemacs-p
2171 (progn
2172 (delete-menu-item '("Headings"))
2173 (delete-menu-item '("Show"))
2174 (delete-menu-item '("Hide"))
2175 (set-menubar-dirty-flag))
2176 (define-key org-mode-map [menu-bar headings] 'undefined)
2177 (define-key org-mode-map [menu-bar hide] 'undefined)
2178 (define-key org-mode-map [menu-bar show] 'undefined))
2180 (unless org-inhibit-startup
2181 (if org-startup-with-deadline-check
2182 (call-interactively 'org-check-deadlines)
2183 (cond
2184 ((eq org-startup-folded t)
2185 (org-cycle '(4)))
2186 ((eq org-startup-folded 'content)
2187 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2188 (org-cycle '(4)) (org-cycle '(4))))))))
2190 (defsubst org-current-line (&optional pos)
2191 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2193 (defun org-current-time ()
2194 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2195 (if (> org-time-stamp-rounding-minutes 0)
2196 (let ((r org-time-stamp-rounding-minutes)
2197 (time (decode-time)))
2198 (apply 'encode-time
2199 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2200 (nthcdr 2 time))))
2201 (current-time)))
2203 ;; FIXME: Do we need to copy?
2204 (defun org-string-props (string &rest properties)
2205 "Add PROPERTIES to string."
2206 (add-text-properties 0 (length string) properties string)
2207 string)
2209 ;;; Font-Lock stuff
2211 (defvar org-mouse-map (make-sparse-keymap))
2212 (define-key org-mouse-map
2213 (if org-xemacs-p [button2] [mouse-2]) 'org-open-at-mouse)
2214 (define-key org-mouse-map
2215 (if org-xemacs-p [button3] [mouse-3]) 'org-find-file-at-mouse)
2216 (define-key org-mouse-map [follow-link] 'mouse-face)
2217 (when org-tab-follows-link
2218 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2219 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2220 (when org-return-follows-link
2221 (define-key org-mouse-map [(return)] 'org-open-at-point)
2222 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2224 (require 'font-lock)
2226 (defconst org-non-link-chars "\t\n\r|<>\000")
2227 (defconst org-link-regexp
2228 (if org-allow-space-in-links
2229 (concat
2230 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|mhe\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2231 (concat
2232 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|mhe\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2234 "Regular expression for matching links.")
2235 (defconst org-link-maybe-angles-regexp
2236 (concat "<?\\(" org-link-regexp "\\)>?")
2237 "Matches a link and optionally surrounding angle brackets.")
2238 (defconst org-protected-link-regexp
2239 (concat "\000" org-link-regexp "\000")
2240 "Matches a link and optionally surrounding angle brackets.")
2242 (defconst org-bracket-link-regexp
2243 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2244 "Matches a link in double brackets.")
2246 (defconst org-ts-lengths
2247 (cons (length (format-time-string (car org-time-stamp-formats)))
2248 (length (format-time-string (cdr org-time-stamp-formats))))
2249 "This holds the lengths of the two different time formats.")
2250 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2251 "Regular expression for fast time stamp matching.")
2252 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2253 "Regular expression for fast time stamp matching.")
2254 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2255 "Regular expression matching time strings for analysis.")
2256 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2257 "Regular expression matching time stamps, with groups.")
2258 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2259 "Regular expression matching a time stamp range.")
2260 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2261 org-ts-regexp "\\)?")
2262 "Regular expression matching a time stamp or time stamp range.")
2264 (defun org-activate-links (limit)
2265 "Run through the buffer and add overlays to links."
2266 (if (re-search-forward org-link-regexp limit t)
2267 (progn
2268 (add-text-properties (match-beginning 0) (match-end 0)
2269 (list 'mouse-face 'highlight
2270 'keymap org-mouse-map))
2271 t)))
2273 (defun org-activate-links2 (limit)
2274 "Run through the buffer and add overlays to links."
2275 (if (re-search-forward org-bracket-link-regexp limit t)
2276 (progn
2277 (add-text-properties (match-beginning 0) (match-end 0)
2278 (list 'mouse-face 'highlight
2279 'keymap org-mouse-map))
2280 t)))
2282 (defun org-activate-dates (limit)
2283 "Run through the buffer and add overlays to dates."
2284 (if (re-search-forward org-tsr-regexp limit t)
2285 (progn
2286 (add-text-properties (match-beginning 0) (match-end 0)
2287 (list 'mouse-face 'highlight
2288 'keymap org-mouse-map))
2289 t)))
2291 (defvar org-target-link-regexp nil
2292 "Regular expression matching radio targets in plain text.")
2293 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2294 "Regular expression matching a link target.")
2295 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2296 "Regular expression matching a link target.")
2298 (defun org-activate-target-links (limit)
2299 "Run through the buffer and add overlays to target matches."
2300 (when (and org-radio-targets org-target-link-regexp)
2301 (let ((case-fold-search t))
2302 (if (re-search-forward org-target-link-regexp limit t)
2303 (progn
2304 (add-text-properties (match-beginning 0) (match-end 0)
2305 (list 'mouse-face 'highlight
2306 'keymap org-mouse-map
2307 'org-linked-text t))
2308 t)))))
2310 (defun org-update-radio-target-regexp ()
2311 "Find all radio targets in this file and update the regular expression."
2312 (interactive)
2313 (when org-radio-targets
2314 (setq org-target-link-regexp
2315 (org-make-target-link-regexp (org-all-targets 'radio)))
2316 (font-lock-mode -1)
2317 (font-lock-mode 1)))
2319 (defun org-all-targets (&optional radio)
2320 "Return a list of all targets in this file.
2321 With optional argument RADIO, only find radio targets."
2322 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2323 rtn)
2324 (save-excursion
2325 (goto-char (point-min))
2326 (while (re-search-forward re nil t)
2327 (add-to-list 'rtn (downcase
2328 (if (fboundp 'match-string-no-properties)
2329 (match-string-no-properties 1)
2330 (match-string 1)))))
2331 rtn)))
2333 (defun org-make-target-link-regexp (targets)
2334 "Make regular expression matching all strings in TARGETS.
2335 The regular expression finds the targets also if there is a line break
2336 between words."
2337 (and targets
2338 (concat
2339 "\\<\\("
2340 (mapconcat
2341 (lambda (x)
2342 (while (string-match " +" x)
2343 (setq x (replace-match "\\s-+" t t x)))
2345 targets
2346 "\\|")
2347 "\\)\\>")))
2349 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2350 "Matches CamelCase words, possibly with a star before it.")
2352 (defun org-activate-camels (limit)
2353 "Run through the buffer and add overlays to dates."
2354 (if org-activate-camels
2355 (if (re-search-forward org-camel-regexp limit t)
2356 (progn
2357 (add-text-properties (match-beginning 0) (match-end 0)
2358 (list 'mouse-face 'highlight
2359 'keymap org-mouse-map))
2360 t))))
2362 (defun org-activate-tags (limit)
2363 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2364 (progn
2365 (add-text-properties (match-beginning 1) (match-end 1)
2366 (list 'mouse-face 'highlight
2367 'keymap org-mouse-map))
2368 t)))
2370 (defun org-font-lock-level ()
2371 (save-excursion
2372 (org-back-to-heading t)
2373 (- (match-end 0) (match-beginning 0))))
2375 (defun org-outline-level ()
2376 (save-excursion
2377 (looking-at outline-regexp)
2378 (if (match-beginning 1)
2379 (+ (org-get-string-indentation (match-string 1)) 1000)
2380 (- (match-end 0) (match-beginning 0)))))
2382 (defvar org-font-lock-keywords nil)
2384 (defun org-set-font-lock-defaults ()
2385 (let* ((em org-fontify-emphasized-text)
2386 (org-font-lock-extra-keywords
2387 (list
2388 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
2389 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
2390 '(org-activate-links (0 'org-link t))
2391 '(org-activate-links2 (0 'org-link t))
2392 '(org-activate-target-links (0 'org-link t))
2393 '(org-activate-dates (0 'org-link t))
2394 '(org-activate-camels (0 'org-link t))
2395 '(org-activate-tags (1 'org-tag t))
2396 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2397 '(1 'org-warning t))
2398 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2399 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2400 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2401 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2402 (if em '("\\(\\W\\|^\\)\\(\\*\\w+\\*\\)\\(\\W\\|$\\)" 2 'bold))
2403 (if em '("\\(\\W\\|^\\)\\(/\\w+/\\)\\(\\W\\|$\\)" 2 'italic))
2404 (if em '("\\(\\W\\|^\\)\\(_\\w+_\\)\\(\\W\\|$\\)" 2 'underline))
2405 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2406 "\\|" org-quote-string "\\)\\>")
2407 '(1 'org-special-keyword t))
2408 '("^#.*" (0 'font-lock-comment-face t))
2409 (if org-fontify-done-headline
2410 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2411 '(1 'org-done t) '(2 'org-headline-done t))
2412 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2413 '(1 'org-done t)))
2414 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2415 (1 'org-table t))
2416 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2417 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2418 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2420 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
2421 ;; Now set the full font-lock-keywords
2422 (set (make-local-variable 'org-font-lock-keywords)
2423 org-font-lock-extra-keywords)
2424 (set (make-local-variable 'font-lock-defaults)
2425 '(org-font-lock-keywords t nil nil backward-paragraph))
2426 (kill-local-variable 'font-lock-keywords) nil))
2428 (defvar org-m nil)
2429 (defvar org-l nil)
2430 (defvar org-f nil)
2431 (defun org-get-level-face (n)
2432 "Get the right face for match N in font-lock matching of healdines."
2433 (setq org-l (- (match-end 2) (match-beginning 1)))
2434 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
2435 (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
2436 (cond
2437 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
2438 ((eq n 2) org-f)
2439 (t (if org-level-color-stars-only nil org-f))))
2441 (defun org-unfontify-region (beg end &optional maybe_loudly)
2442 "Remove fontification and activation overlays from links."
2443 (font-lock-default-unfontify-region beg end)
2444 (let* ((buffer-undo-list t)
2445 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2446 (inhibit-modification-hooks t)
2447 deactivate-mark buffer-file-name buffer-file-truename)
2448 (remove-text-properties beg end
2449 '(mouse-face nil keymap nil org-linked-text nil))))
2451 ;;; Visibility cycling
2453 (defvar org-cycle-global-status nil)
2454 (defvar org-cycle-subtree-status nil)
2455 (defun org-cycle (&optional arg)
2456 "Visibility cycling for Org-mode.
2458 - When this function is called with a prefix argument, rotate the entire
2459 buffer through 3 states (global cycling)
2460 1. OVERVIEW: Show only top-level headlines.
2461 2. CONTENTS: Show all headlines of all levels, but no body text.
2462 3. SHOW ALL: Show everything.
2464 - When point is at the beginning of a headline, rotate the subtree started
2465 by this line through 3 different states (local cycling)
2466 1. FOLDED: Only the main headline is shown.
2467 2. CHILDREN: The main headline and the direct children are shown.
2468 From this state, you can move to one of the children
2469 and zoom in further.
2470 3. SUBTREE: Show the entire subtree, including body text.
2472 - When there is a numeric prefix, go up to a heading with level ARG, do
2473 a `show-subtree' and return to the previous cursor position. If ARG
2474 is negative, go up that many levels.
2476 - When point is not at the beginning of a headline, execute
2477 `indent-relative', like TAB normally does. See the option
2478 `org-cycle-emulate-tab' for details.
2480 - Special case: if point is the the beginning of the buffer and there is
2481 no headline in line 1, this function will act as if called with prefix arg."
2482 (interactive "P")
2484 (if (or (and (bobp) (not (looking-at outline-regexp)))
2485 (equal arg '(4)))
2486 ;; special case: use global cycling
2487 (setq arg t))
2489 (let ((outline-regexp
2490 (if org-cycle-include-plain-lists
2491 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2492 outline-regexp)))
2494 (cond
2496 ((org-at-table-p 'any)
2497 ;; Enter the table or move to the next field in the table
2498 (or (org-table-recognize-table.el)
2499 (progn
2500 (org-table-justify-field-maybe)
2501 (org-table-next-field))))
2503 ((eq arg t) ;; Global cycling
2505 (cond
2506 ((and (eq last-command this-command)
2507 (eq org-cycle-global-status 'overview))
2508 ;; We just created the overview - now do table of contents
2509 ;; This can be slow in very large buffers, so indicate action
2510 (message "CONTENTS...")
2511 (save-excursion
2512 ;; Visit all headings and show their offspring
2513 (goto-char (point-max))
2514 (catch 'exit
2515 (while (and (progn (condition-case nil
2516 (outline-previous-visible-heading 1)
2517 (error (goto-char (point-min))))
2519 (looking-at outline-regexp))
2520 (show-branches)
2521 (if (bobp) (throw 'exit nil))))
2522 (message "CONTENTS...done"))
2523 (setq org-cycle-global-status 'contents)
2524 (run-hook-with-args 'org-cycle-hook 'contents))
2526 ((and (eq last-command this-command)
2527 (eq org-cycle-global-status 'contents))
2528 ;; We just showed the table of contents - now show everything
2529 (show-all)
2530 (message "SHOW ALL")
2531 (setq org-cycle-global-status 'all)
2532 (run-hook-with-args 'org-cycle-hook 'all))
2535 ;; Default action: go to overview
2536 (hide-sublevels 1)
2537 (message "OVERVIEW")
2538 (setq org-cycle-global-status 'overview)
2539 (run-hook-with-args 'org-cycle-hook 'overview))))
2541 ((integerp arg)
2542 ;; Show-subtree, ARG levels up from here.
2543 (save-excursion
2544 (org-back-to-heading)
2545 (outline-up-heading (if (< arg 0) (- arg)
2546 (- (funcall outline-level) arg)))
2547 (org-show-subtree)))
2549 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2550 ;; At a heading: rotate between three different views
2551 (org-back-to-heading)
2552 (let ((goal-column 0) eoh eol eos)
2553 ;; First, some boundaries
2554 (save-excursion
2555 (org-back-to-heading)
2556 (save-excursion
2557 (beginning-of-line 2)
2558 (while (and (not (eobp)) ;; this is like `next-line'
2559 (get-char-property (1- (point)) 'invisible))
2560 (beginning-of-line 2)) (setq eol (point)))
2561 (outline-end-of-heading) (setq eoh (point))
2562 (org-end-of-subtree t) (setq eos (point))
2563 (outline-next-heading))
2564 ;; Find out what to do next and set `this-command'
2565 (cond
2566 ((= eos eoh)
2567 ;; Nothing is hidden behind this heading
2568 (message "EMPTY ENTRY")
2569 (setq org-cycle-subtree-status nil))
2570 ((>= eol eos)
2571 ;; Entire subtree is hidden in one line: open it
2572 (org-show-entry)
2573 (show-children)
2574 (message "CHILDREN")
2575 (setq org-cycle-subtree-status 'children)
2576 (run-hook-with-args 'org-cycle-hook 'children))
2577 ((and (eq last-command this-command)
2578 (eq org-cycle-subtree-status 'children))
2579 ;; We just showed the children, now show everything.
2580 (org-show-subtree)
2581 (message "SUBTREE")
2582 (setq org-cycle-subtree-status 'subtree)
2583 (run-hook-with-args 'org-cycle-hook 'subtree))
2585 ;; Default action: hide the subtree.
2586 (hide-subtree)
2587 (message "FOLDED")
2588 (setq org-cycle-subtree-status 'folded)
2589 (run-hook-with-args 'org-cycle-hook 'folded)))))
2591 ;; TAB emulation
2592 (buffer-read-only (org-back-to-heading))
2593 ((if (and (eq org-cycle-emulate-tab 'white)
2594 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2596 (eq org-cycle-emulate-tab t))
2597 (if (and (looking-at "[ \n\r\t]")
2598 (string-match "^[ \t]*$" (buffer-substring
2599 (point-at-bol) (point))))
2600 (progn
2601 (beginning-of-line 1)
2602 (and (looking-at "[ \t]+") (replace-match ""))))
2603 (indent-relative))
2605 (t (save-excursion
2606 (org-back-to-heading)
2607 (org-cycle))))))
2609 (defun org-optimize-window-after-visibility-change (state)
2610 "Adjust the window after a change in outline visibility.
2611 This function is the default value of the hook `org-cycle-hook'."
2612 (cond
2613 ((eq state 'overview) (org-first-headline-recenter 1))
2614 ((eq state 'content) nil)
2615 ((eq state 'all) nil)
2616 ((eq state 'folded) nil)
2617 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2618 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2620 (defun org-subtree-end-visible-p ()
2621 "Is the end of the current subtree visible?"
2622 (pos-visible-in-window-p
2623 (save-excursion (org-end-of-subtree t) (point))))
2625 (defun org-first-headline-recenter (&optional N)
2626 "Move cursor to the first headline and recenter the headline.
2627 Optional argument N means, put the headline into the Nth line of the window."
2628 (goto-char (point-min))
2629 (when (re-search-forward (concat "^" outline-regexp) nil t)
2630 (beginning-of-line)
2631 (recenter (prefix-numeric-value N))))
2633 (defvar org-goto-window-configuration nil)
2634 (defvar org-goto-marker nil)
2635 (defvar org-goto-map (make-sparse-keymap))
2636 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2637 (while (setq cmd (pop cmds))
2638 (substitute-key-definition cmd cmd org-goto-map global-map)))
2639 (define-key org-goto-map "\C-m" 'org-goto-ret)
2640 (define-key org-goto-map [(left)] 'org-goto-left)
2641 (define-key org-goto-map [(right)] 'org-goto-right)
2642 (define-key org-goto-map [(?q)] 'org-goto-quit)
2643 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2644 (define-key org-goto-map "\C-i" 'org-cycle)
2645 (define-key org-goto-map [(tab)] 'org-cycle)
2646 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2647 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2648 (define-key org-goto-map "n" 'outline-next-visible-heading)
2649 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2650 (define-key org-goto-map "f" 'outline-forward-same-level)
2651 (define-key org-goto-map "b" 'outline-backward-same-level)
2652 (define-key org-goto-map "u" 'outline-up-heading)
2653 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2654 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2655 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2656 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2657 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2658 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2659 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2661 (defconst org-goto-help
2662 "Select a location to jump to, press RET
2663 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2665 (defun org-goto ()
2666 "Go to a different location of the document, keeping current visibility.
2668 When you want to go to a different location in a document, the fastest way
2669 is often to fold the entire buffer and then dive into the tree. This
2670 method has the disadvantage, that the previous location will be folded,
2671 which may not be what you want.
2673 This command works around this by showing a copy of the current buffer in
2674 overview mode. You can dive into the tree in that copy, to find the
2675 location you want to reach. When pressing RET, the command returns to the
2676 original buffer in which the visibility is still unchanged. It then jumps
2677 to the new location, making it and the headline hierarchy above it visible."
2678 (interactive)
2679 (let* ((org-goto-start-pos (point))
2680 (selected-point
2681 (org-get-location (current-buffer) org-goto-help)))
2682 (if selected-point
2683 (progn
2684 (org-mark-ring-push org-goto-start-pos)
2685 (goto-char selected-point)
2686 (if (or (org-invisible-p) (org-invisible-p2))
2687 (org-show-hierarchy-above)))
2688 (error "Quit"))))
2690 (defun org-get-location (buf help)
2691 "Let the user select a location in the Org-mode buffer BUF.
2692 This function uses a recursive edit. It returns the selected position
2693 or nil."
2694 (let (org-selected-point)
2695 (save-excursion
2696 (save-window-excursion
2697 (delete-other-windows)
2698 (switch-to-buffer (get-buffer-create "*org-goto*"))
2699 (with-output-to-temp-buffer "*Help*"
2700 (princ help))
2701 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2702 (setq buffer-read-only nil)
2703 (erase-buffer)
2704 (insert-buffer-substring buf)
2705 (let ((org-startup-truncated t)
2706 (org-startup-folded t)
2707 (org-startup-with-deadline-check nil))
2708 (org-mode))
2709 (setq buffer-read-only t)
2710 (if (boundp 'org-goto-start-pos)
2711 (goto-char org-goto-start-pos)
2712 (goto-char (point-min)))
2713 (org-beginning-of-line)
2714 (message "Select location and press RET")
2715 ;; now we make sure that during selection, ony very few keys work
2716 ;; and that it is impossible to switch to another window.
2717 (let ((gm (current-global-map))
2718 (overriding-local-map org-goto-map))
2719 (unwind-protect
2720 (progn
2721 (use-global-map org-goto-map)
2722 (recursive-edit))
2723 (use-global-map gm)))))
2724 (kill-buffer "*org-goto*")
2725 org-selected-point))
2727 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2728 (defun org-goto-ret (&optional arg)
2729 "Finish `org-goto' by going to the new location."
2730 (interactive "P")
2731 (setq org-selected-point (point)
2732 current-prefix-arg arg)
2733 (throw 'exit nil))
2735 (defun org-goto-left ()
2736 "Finish `org-goto' by going to the new location."
2737 (interactive)
2738 (if (org-on-heading-p)
2739 (progn
2740 (beginning-of-line 1)
2741 (setq org-selected-point (point)
2742 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2743 (throw 'exit nil))
2744 (error "Not on a heading")))
2746 (defun org-goto-right ()
2747 "Finish `org-goto' by going to the new location."
2748 (interactive)
2749 (if (org-on-heading-p)
2750 (progn
2751 (outline-end-of-subtree)
2752 (or (eobp) (forward-char 1))
2753 (setq org-selected-point (point)
2754 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2755 (throw 'exit nil))
2756 (error "Not on a heading")))
2758 (defun org-goto-quit ()
2759 "Finish `org-goto' without cursor motion."
2760 (interactive)
2761 (setq org-selected-point nil)
2762 (throw 'exit nil))
2764 ;;; Promotion, Demotion, Inserting new headlines
2766 (defvar org-ignore-region nil
2767 "To temporarily disable the active region.")
2769 (defun org-insert-heading (&optional force-heading)
2770 "Insert a new heading or item with same depth at point."
2771 (interactive "P")
2772 (when (or force-heading (not (org-insert-item)))
2773 (let* ((head (save-excursion
2774 (condition-case nil
2775 (org-back-to-heading)
2776 (error (outline-next-heading)))
2777 (prog1 (match-string 0)
2778 (funcall outline-level)))))
2779 (unless (bolp) (newline))
2780 (insert head)
2781 (unless (eolp)
2782 (save-excursion (newline-and-indent)))
2783 (unless (equal (char-before) ?\ )
2784 (insert " "))
2785 (run-hooks 'org-insert-heading-hook))))
2787 (defun org-insert-item ()
2788 "Insert a new item at the current level.
2789 Return t when things worked, nil when we are not in an item."
2790 (when (save-excursion
2791 (condition-case nil
2792 (progn
2793 (org-beginning-of-item)
2794 (org-at-item-p)
2796 (error nil)))
2797 (unless (bolp) (newline))
2798 (insert (match-string 0))
2799 (org-maybe-renumber-ordered-list)
2802 (defun org-insert-todo-heading (arg)
2803 "Insert a new heading with the same level and TODO state as current heading.
2804 If the heading has no TODO state, or if the state is DONE, use the first
2805 state (TODO by default). Also with prefix arg, force first state."
2806 (interactive "P")
2807 (org-insert-heading)
2808 (save-excursion
2809 (org-back-to-heading)
2810 (outline-previous-heading)
2811 (looking-at org-todo-line-regexp))
2812 (if (or arg
2813 (not (match-beginning 2))
2814 (equal (match-string 2) org-done-string))
2815 (insert (car org-todo-keywords) " ")
2816 (insert (match-string 2) " ")))
2818 (defun org-promote-subtree ()
2819 "Promote the entire subtree.
2820 See also `org-promote'."
2821 (interactive)
2822 (save-excursion
2823 (org-map-tree 'org-promote)))
2825 (defun org-demote-subtree ()
2826 "Demote the entire subtree. See `org-demote'.
2827 See also `org-promote'."
2828 (interactive)
2829 (save-excursion
2830 (org-map-tree 'org-demote)))
2832 (defun org-do-promote ()
2833 "Promote the current heading higher up the tree.
2834 If the region is active in `transient-mark-mode', promote all headings
2835 in the region."
2836 (interactive)
2837 (save-excursion
2838 (if (org-region-active-p)
2839 (org-map-region 'org-promote (region-beginning) (region-end))
2840 (org-promote)))
2841 (org-fix-position-after-promote))
2843 (defun org-do-demote ()
2844 "Demote the current heading lower down the tree.
2845 If the region is active in `transient-mark-mode', demote all headings
2846 in the region."
2847 (interactive)
2848 (save-excursion
2849 (if (org-region-active-p)
2850 (org-map-region 'org-demote (region-beginning) (region-end))
2851 (org-demote)))
2852 (org-fix-position-after-promote))
2854 (defun org-fix-position-after-promote ()
2855 "Make sure that after pro/demotion cursor position is right."
2856 (and (equal (char-after) ?\ )
2857 (equal (char-before) ?*)
2858 (forward-char 1)))
2860 (defun org-get-legal-level (level change)
2861 "Rectify a level change under the influence of `org-odd-levels-only'
2862 LEVEL is a current level, CHANGE is by how much the level should be
2863 modified. Even if CHANGE is nil, LEVEL may be returned modified because
2864 even level numbers will become the next higher odd number."
2865 (if org-odd-levels-only
2866 (cond ((not change) (1+ (* 2 (/ level 2))))
2867 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
2868 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
2869 (max 1 (+ level change))))
2871 (defun org-promote ()
2872 "Promote the current heading higher up the tree.
2873 If the region is active in `transient-mark-mode', promote all headings
2874 in the region."
2875 (org-back-to-heading t)
2876 (let* ((level (save-match-data (funcall outline-level)))
2877 (up-head (make-string (org-get-legal-level level -1) ?*))
2878 (diff (abs (- level (length up-head)))))
2879 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2880 (replace-match up-head nil t)
2881 ;; Fixup tag positioning
2882 (and org-auto-align-tags (org-set-tags nil t))
2883 (if org-adapt-indentation
2884 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
2885 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
2887 (defun org-demote ()
2888 "Demote the current heading lower down the tree.
2889 If the region is active in `transient-mark-mode', demote all headings
2890 in the region."
2891 (org-back-to-heading t)
2892 (let* ((level (save-match-data (funcall outline-level)))
2893 (down-head (make-string (org-get-legal-level level 1) ?*))
2894 (diff (abs (- level (length down-head)))))
2895 (replace-match down-head nil t)
2896 ;; Fixup tag positioning
2897 (and org-auto-align-tags (org-set-tags nil t))
2898 (if org-adapt-indentation
2899 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
2901 (defun org-map-tree (fun)
2902 "Call FUN for every heading underneath the current one."
2903 (org-back-to-heading)
2904 (let ((level (funcall outline-level)))
2905 (save-excursion
2906 (funcall fun)
2907 (while (and (progn
2908 (outline-next-heading)
2909 (> (funcall outline-level) level))
2910 (not (eobp)))
2911 (funcall fun)))))
2913 (defun org-map-region (fun beg end)
2914 "Call FUN for every heading between BEG and END."
2915 (let ((org-ignore-region t))
2916 (save-excursion
2917 (setq end (copy-marker end))
2918 (goto-char beg)
2919 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2920 (< (point) end))
2921 (funcall fun))
2922 (while (and (progn
2923 (outline-next-heading)
2924 (< (point) end))
2925 (not (eobp)))
2926 (funcall fun)))))
2928 (defun org-fixup-indentation (from to prohibit)
2929 "Change the indentation in the current entry by re-replacing FROM with TO.
2930 However, if the regexp PROHIBIT matches at all, don't do anything.
2931 This is being used to change indentation along with the length of the
2932 heading marker. But if there are any lines which are not indented, nothing
2933 is changed at all."
2934 (save-excursion
2935 (let ((end (save-excursion (outline-next-heading)
2936 (point-marker))))
2937 (unless (save-excursion (re-search-forward prohibit end t))
2938 (while (re-search-forward from end t)
2939 (replace-match to)
2940 (beginning-of-line 2)))
2941 (move-marker end nil))))
2943 ;;; Vertical tree motion, cutting and pasting of subtrees
2945 (defun org-move-subtree-up (&optional arg)
2946 "Move the current subtree up past ARG headlines of the same level."
2947 (interactive "p")
2948 (org-move-subtree-down (- (prefix-numeric-value arg))))
2950 (defun org-move-subtree-down (&optional arg)
2951 "Move the current subtree down past ARG headlines of the same level."
2952 (interactive "p")
2953 (setq arg (prefix-numeric-value arg))
2954 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2955 'outline-get-last-sibling))
2956 (ins-point (make-marker))
2957 (cnt (abs arg))
2958 beg end txt folded)
2959 ;; Select the tree
2960 (org-back-to-heading)
2961 (setq beg (point))
2962 (save-match-data
2963 (save-excursion (outline-end-of-heading)
2964 (setq folded (org-invisible-p)))
2965 (outline-end-of-subtree))
2966 (outline-next-heading)
2967 (setq end (point))
2968 ;; Find insertion point, with error handling
2969 (goto-char beg)
2970 (while (> cnt 0)
2971 (or (and (funcall movfunc) (looking-at outline-regexp))
2972 (progn (goto-char beg)
2973 (error "Cannot move past superior level or buffer limit")))
2974 (setq cnt (1- cnt)))
2975 (if (> arg 0)
2976 ;; Moving forward - still need to move over subtree
2977 (progn (outline-end-of-subtree)
2978 (outline-next-heading)
2979 (if (not (or (looking-at (concat "^" outline-regexp))
2980 (bolp)))
2981 (newline))))
2982 (move-marker ins-point (point))
2983 (setq txt (buffer-substring beg end))
2984 (delete-region beg end)
2985 (insert txt)
2986 (goto-char ins-point)
2987 (if folded (hide-subtree))
2988 (move-marker ins-point nil)))
2990 (defvar org-subtree-clip ""
2991 "Clipboard for cut and paste of subtrees.
2992 This is actually only a copy of the kill, because we use the normal kill
2993 ring. We need it to check if the kill was created by `org-copy-subtree'.")
2995 (defvar org-subtree-clip-folded nil
2996 "Was the last copied subtree folded?
2997 This is used to fold the tree back after pasting.")
2999 (defun org-cut-subtree ()
3000 "Cut the current subtree into the clipboard.
3001 This is a short-hand for marking the subtree and then cutting it."
3002 (interactive)
3003 (org-copy-subtree 'cut))
3005 (defun org-copy-subtree (&optional cut)
3006 "Cut the current subtree into the clipboard.
3007 This is a short-hand for marking the subtree and then copying it.
3008 If CUT is non nil, actually cut the subtree."
3009 (interactive)
3010 (let (beg end folded)
3011 (org-back-to-heading)
3012 (setq beg (point))
3013 (save-match-data
3014 (save-excursion (outline-end-of-heading)
3015 (setq folded (org-invisible-p)))
3016 (outline-end-of-subtree))
3017 (if (equal (char-after) ?\n) (forward-char 1))
3018 (setq end (point))
3019 (goto-char beg)
3020 (when (> end beg)
3021 (setq org-subtree-clip-folded folded)
3022 (if cut (kill-region beg end) (copy-region-as-kill beg end))
3023 (setq org-subtree-clip (current-kill 0))
3024 (message "%s: Subtree with %d characters"
3025 (if cut "Cut" "Copied")
3026 (length org-subtree-clip)))))
3028 (defun org-paste-subtree (&optional level tree)
3029 "Paste the clipboard as a subtree, with modification of headline level.
3030 The entire subtree is promoted or demoted in order to match a new headline
3031 level. By default, the new level is derived from the visible headings
3032 before and after the insertion point, and taken to be the inferior headline
3033 level of the two. So if the previous visible heading is level 3 and the
3034 next is level 4 (or vice versa), level 4 will be used for insertion.
3035 This makes sure that the subtree remains an independent subtree and does
3036 not swallow low level entries.
3038 You can also force a different level, either by using a numeric prefix
3039 argument, or by inserting the heading marker by hand. For example, if the
3040 cursor is after \"*****\", then the tree will be shifted to level 5.
3042 If you want to insert the tree as is, just use \\[yank].
3044 If optional TREE is given, use this text instead of the kill ring."
3045 (interactive "P")
3046 (unless (org-kill-is-subtree-p tree)
3047 (error
3048 (substitute-command-keys
3049 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
3050 (let* ((txt (or tree (current-kill 0)))
3051 (^re (concat "^\\(" outline-regexp "\\)"))
3052 (re (concat "\\(" outline-regexp "\\)"))
3053 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3055 (old-level (if (string-match ^re txt)
3056 (- (match-end 0) (match-beginning 0))
3057 -1))
3058 (force-level (cond (level (prefix-numeric-value level))
3059 ((string-match
3060 ^re_ (buffer-substring (point-at-bol) (point)))
3061 (- (match-end 0) (match-beginning 0)))
3062 (t nil)))
3063 (previous-level (save-excursion
3064 (condition-case nil
3065 (progn
3066 (outline-previous-visible-heading 1)
3067 (if (looking-at re)
3068 (- (match-end 0) (match-beginning 0))
3070 (error 1))))
3071 (next-level (save-excursion
3072 (condition-case nil
3073 (progn
3074 (outline-next-visible-heading 1)
3075 (if (looking-at re)
3076 (- (match-end 0) (match-beginning 0))
3078 (error 1))))
3079 (new-level (or force-level (max previous-level next-level)))
3080 (shift (if (or (= old-level -1)
3081 (= new-level -1)
3082 (= old-level new-level))
3084 (- new-level old-level)))
3085 (shift1 shift)
3086 (delta (if (> shift 0) -1 1))
3087 (func (if (> shift 0) 'org-demote 'org-promote))
3088 (org-odd-levels-only nil)
3089 beg end)
3090 ;; Remove the forces level indicator
3091 (if force-level
3092 (delete-region (point-at-bol) (point)))
3093 ;; Make sure we start at the beginning of an empty line
3094 (if (not (bolp)) (insert "\n"))
3095 (if (not (looking-at "[ \t]*$"))
3096 (progn (insert "\n") (backward-char 1)))
3097 ;; Paste
3098 (setq beg (point))
3099 (insert txt)
3100 (setq end (point))
3101 (goto-char beg)
3102 ;; Shift if necessary
3103 (if (= shift 0)
3104 (message "Pasted at level %d, without shift" new-level)
3105 (save-restriction
3106 (narrow-to-region beg end)
3107 (while (not (= shift 0))
3108 (org-map-region func (point-min) (point-max))
3109 (setq shift (+ delta shift)))
3110 (goto-char (point-min))
3111 (message "Pasted at level %d, with shift by %d levels"
3112 new-level shift1)))
3113 (if (and (eq org-subtree-clip (current-kill 0))
3114 org-subtree-clip-folded)
3115 ;; The tree was folded before it was killed/copied
3116 (hide-subtree))))
3118 (defun org-kill-is-subtree-p (&optional txt)
3119 "Check if the current kill is an outline subtree, or a set of trees.
3120 Returns nil if kill does not start with a headline, or if the first
3121 headline level is not the largest headline level in the tree.
3122 So this will actually accept several entries of equal levels as well,
3123 which is OK for `org-paste-subtree'.
3124 If optional TXT is given, check this string instead of the current kill."
3125 (let* ((kill (or txt (current-kill 0) ""))
3126 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3127 (- (match-end 0) (match-beginning 0))))
3128 (re (concat "^" outline-regexp))
3129 (start 1))
3130 (if (not start-level)
3131 nil ;; does not even start with a heading
3132 (catch 'exit
3133 (while (setq start (string-match re kill (1+ start)))
3134 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3135 (throw 'exit nil)))
3136 t))))
3138 ;;; Plain list items
3140 (defun org-at-item-p ()
3141 "Is point in a line starting a hand-formatted item?"
3142 (let ((llt org-plain-list-ordered-item-terminator))
3143 (save-excursion
3144 (goto-char (point-at-bol))
3145 (looking-at
3146 (cond
3147 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3148 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3149 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3150 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3152 (defun org-get-indentation ()
3153 "Get the indentation of the current line, interpreting tabs."
3154 (save-excursion
3155 (beginning-of-line 1)
3156 (skip-chars-forward " \t")
3157 (current-column)))
3159 (defun org-beginning-of-item ()
3160 "Go to the beginning of the current hand-formatted item.
3161 If the cursor is not in an item, throw an error."
3162 (let ((pos (point))
3163 (limit (save-excursion (org-back-to-heading)
3164 (beginning-of-line 2) (point)))
3165 ind ind1)
3166 (if (org-at-item-p)
3167 (beginning-of-line 1)
3168 (beginning-of-line 1)
3169 (skip-chars-forward " \t")
3170 (setq ind (current-column))
3171 (if (catch 'exit
3172 (while t
3173 (beginning-of-line 0)
3174 (if (< (point) limit) (throw 'exit nil))
3175 (unless (looking-at " \t]*$")
3176 (skip-chars-forward " \t")
3177 (setq ind1 (current-column))
3178 (if (< ind1 ind)
3179 (throw 'exit (org-at-item-p))))))
3181 (goto-char pos)
3182 (error "Not in an item")))))
3184 (defun org-end-of-item ()
3185 "Go to the end of the current hand-formatted item.
3186 If the cursor is not in an item, throw an error."
3187 (let ((pos (point))
3188 (limit (save-excursion (outline-next-heading) (point)))
3189 (ind (save-excursion
3190 (org-beginning-of-item)
3191 (skip-chars-forward " \t")
3192 (current-column)))
3193 ind1)
3194 (if (catch 'exit
3195 (while t
3196 (beginning-of-line 2)
3197 (if (>= (point) limit) (throw 'exit t))
3198 (unless (looking-at "[ \t]*$")
3199 (skip-chars-forward " \t")
3200 (setq ind1 (current-column))
3201 (if (<= ind1 ind) (throw 'exit t)))))
3202 (beginning-of-line 1)
3203 (goto-char pos)
3204 (error "Not in an item"))))
3206 (defun org-move-item-down (arg)
3207 "Move the plain list item at point down, i.e. swap with following item.
3208 Subitems (items with larger indentation) are considered part of the item,
3209 so this really moves item trees."
3210 (interactive "p")
3211 (let (beg end ind ind1 (pos (point)) txt)
3212 (org-beginning-of-item)
3213 (setq beg (point))
3214 (setq ind (org-get-indentation))
3215 (org-end-of-item)
3216 (setq end (point))
3217 (setq ind1 (org-get-indentation))
3218 (if (and (org-at-item-p) (= ind ind1))
3219 (progn
3220 (org-end-of-item)
3221 (setq txt (buffer-substring beg end))
3222 (save-excursion
3223 (delete-region beg end))
3224 (setq pos (point))
3225 (insert txt)
3226 (goto-char pos)
3227 (org-maybe-renumber-ordered-list))
3228 (goto-char pos)
3229 (error "Cannot move this item further down"))))
3231 (defun org-move-item-up (arg)
3232 "Move the plain list item at point up, i.e. swap with previous item.
3233 Subitems (items with larger indentation) are considered part of the item,
3234 so this really moves item trees."
3235 (interactive "p")
3236 (let (beg end ind ind1 (pos (point)) txt)
3237 (org-beginning-of-item)
3238 (setq beg (point))
3239 (setq ind (org-get-indentation))
3240 (org-end-of-item)
3241 (setq end (point))
3242 (goto-char beg)
3243 (catch 'exit
3244 (while t
3245 (beginning-of-line 0)
3246 (if (looking-at "[ \t]*$")
3248 (if (<= (setq ind1 (org-get-indentation)) ind)
3249 (throw 'exit t)))))
3250 (condition-case nil
3251 (org-beginning-of-item)
3252 (error (goto-char beg)
3253 (error "Cannot move this item further up")))
3254 (setq ind1 (org-get-indentation))
3255 (if (and (org-at-item-p) (= ind ind1))
3256 (progn
3257 (setq txt (buffer-substring beg end))
3258 (save-excursion
3259 (delete-region beg end))
3260 (setq pos (point))
3261 (insert txt)
3262 (goto-char pos)
3263 (org-maybe-renumber-ordered-list))
3264 (goto-char pos)
3265 (error "Cannot move this item further up"))))
3267 (defun org-maybe-renumber-ordered-list ()
3268 "Renumber the ordered list at point if setup allows it.
3269 This tests the user option `org-auto-renumber-ordered-lists' before
3270 doing the renumbering."
3271 (and org-auto-renumber-ordered-lists
3272 (org-at-item-p)
3273 (match-beginning 3)
3274 (org-renumber-ordered-list 1)))
3276 (defun org-get-string-indentation (s)
3277 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3278 (let ((n -1) (i 0) (w tab-width) c)
3279 (catch 'exit
3280 (while (< (setq n (1+ n)) (length s))
3281 (setq c (aref s n))
3282 (cond ((= c ?\ ) (setq i (1+ i)))
3283 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3284 (t (throw 'exit t)))))
3287 (defun org-renumber-ordered-list (arg)
3288 "Renumber an ordered plain list.
3289 Cursor next to be in the first line of an item, the line that starts
3290 with something like \"1.\" or \"2)\"."
3291 (interactive "p")
3292 (unless (and (org-at-item-p)
3293 (match-beginning 3))
3294 (error "This is not an ordered list"))
3295 (let ((line (org-current-line))
3296 (col (current-column))
3297 (ind (org-get-string-indentation
3298 (buffer-substring (point-at-bol) (match-beginning 3))))
3299 ;; (term (substring (match-string 3) -1))
3300 ind1 (n (1- arg)))
3301 ;; find where this list begins
3302 (catch 'exit
3303 (while t
3304 (catch 'next
3305 (beginning-of-line 0)
3306 (if (looking-at "[ \t]*$") (throw 'next t))
3307 (skip-chars-forward " \t") (setq ind1 (current-column))
3308 (if (or (< ind1 ind)
3309 (and (= ind1 ind)
3310 (not (org-at-item-p))))
3311 (throw 'exit t)))))
3312 ;; Walk forward and replace these numbers
3313 (catch 'exit
3314 (while t
3315 (catch 'next
3316 (beginning-of-line 2)
3317 (if (eobp) (throw 'exit nil))
3318 (if (looking-at "[ \t]*$") (throw 'next nil))
3319 (skip-chars-forward " \t") (setq ind1 (current-column))
3320 (if (> ind1 ind) (throw 'next t))
3321 (if (< ind1 ind) (throw 'exit t))
3322 (if (not (org-at-item-p)) (throw 'exit nil))
3323 (if (not (match-beginning 3))
3324 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3325 (delete-region (match-beginning 3) (1- (match-end 3)))
3326 (goto-char (match-beginning 3))
3327 (insert (format "%d" (setq n (1+ n)))))))
3328 (goto-line line)
3329 (move-to-column col)))
3331 (defvar org-last-indent-begin-marker (make-marker))
3332 (defvar org-last-indent-end-marker (make-marker))
3334 (defun org-outdent-item (arg)
3335 "Outdent a local list item."
3336 (interactive "p")
3337 (org-indent-item (- arg)))
3339 (defun org-indent-item (arg)
3340 "Indent a local list item."
3341 (interactive "p")
3342 (unless (org-at-item-p)
3343 (error "Not on an item"))
3344 (let (beg end ind ind1)
3345 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3346 (setq beg org-last-indent-begin-marker
3347 end org-last-indent-end-marker)
3348 (org-beginning-of-item)
3349 (setq beg (move-marker org-last-indent-begin-marker (point)))
3350 (org-end-of-item)
3351 (setq end (move-marker org-last-indent-end-marker (point))))
3352 (goto-char beg)
3353 (skip-chars-forward " \t") (setq ind (current-column))
3354 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3355 (while (< (point) end)
3356 (beginning-of-line 1)
3357 (skip-chars-forward " \t") (setq ind1 (current-column))
3358 (delete-region (point-at-bol) (point))
3359 (indent-to-column (+ ind1 arg))
3360 (beginning-of-line 2))
3361 (goto-char beg)))
3363 ;;; Archiving
3365 (defun org-archive-subtree ()
3366 "Move the current subtree to the archive.
3367 The archive can be a certain top-level heading in the current file, or in
3368 a different file. The tree will be moved to that location, the subtree
3369 heading be marked DONE, and the current time will be added."
3370 (interactive)
3371 ;; Save all relevant TODO keyword-relatex variables
3372 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3373 (tr-org-todo-keywords org-todo-keywords)
3374 (tr-org-todo-interpretation org-todo-interpretation)
3375 (tr-org-done-string org-done-string)
3376 (tr-org-todo-regexp org-todo-regexp)
3377 (tr-org-todo-line-regexp org-todo-line-regexp)
3378 (this-buffer (current-buffer))
3379 file heading buffer level newfile-p)
3380 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3381 (progn
3382 (setq file (format (match-string 1 org-archive-location)
3383 (file-name-nondirectory buffer-file-name))
3384 heading (match-string 2 org-archive-location)))
3385 (error "Invalid `org-archive-location'"))
3386 (if (> (length file) 0)
3387 (setq newfile-p (not (file-exists-p file))
3388 buffer (find-file-noselect file))
3389 (setq buffer (current-buffer)))
3390 (unless buffer
3391 (error "Cannot access file \"%s\"" file))
3392 (if (and (> (length heading) 0)
3393 (string-match "^\\*+" heading))
3394 (setq level (match-end 0))
3395 (setq heading nil level 0))
3396 (save-excursion
3397 ;; We first only copy, in case something goes wrong
3398 ;; we need to protect this-command, to avoid kill-region sets it,
3399 ;; which would lead to duplication of subtrees
3400 (let (this-command) (org-copy-subtree))
3401 (set-buffer buffer)
3402 ;; Enforce org-mode for the archive buffer
3403 (if (not (eq major-mode 'org-mode))
3404 ;; Force the mode for future visits.
3405 (let ((org-insert-mode-line-in-empty-file t))
3406 (call-interactively 'org-mode)))
3407 (when newfile-p
3408 (goto-char (point-max))
3409 (insert (format "\nArchived entries from file %s\n\n"
3410 (buffer-file-name this-buffer))))
3411 ;; Force the TODO keywords of the original buffer
3412 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3413 (org-todo-keywords tr-org-todo-keywords)
3414 (org-todo-interpretation tr-org-todo-interpretation)
3415 (org-done-string tr-org-done-string)
3416 (org-todo-regexp tr-org-todo-regexp)
3417 (org-todo-line-regexp tr-org-todo-line-regexp))
3418 (goto-char (point-min))
3419 (if heading
3420 (progn
3421 (if (re-search-forward
3422 (concat "\\(^\\|\r\\)"
3423 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3424 nil t)
3425 (goto-char (match-end 0))
3426 ;; Heading not found, just insert it at the end
3427 (goto-char (point-max))
3428 (or (bolp) (insert "\n"))
3429 (insert "\n" heading "\n")
3430 (end-of-line 0))
3431 ;; Make the heading visible, and the following as well
3432 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3433 (if (re-search-forward
3434 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3435 nil t)
3436 (progn (goto-char (match-beginning 0)) (insert "\n")
3437 (beginning-of-line 0))
3438 (goto-char (point-max)) (insert "\n")))
3439 (goto-char (point-max)) (insert "\n"))
3440 ;; Paste
3441 (org-paste-subtree (1+ level))
3442 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3443 (if org-archive-mark-done
3444 (org-todo (length org-todo-keywords)))
3445 ;; Move cursor to right after the TODO keyword
3446 (when org-archive-stamp-time
3447 (beginning-of-line 1)
3448 (looking-at org-todo-line-regexp)
3449 (goto-char (or (match-end 2) (match-beginning 3)))
3450 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3451 (org-current-time))
3452 ")"))
3453 ;; Save the buffer, if it is not the same buffer.
3454 (if (not (eq this-buffer buffer)) (save-buffer))))
3455 ;; Here we are back in the original buffer. Everything seems to have
3456 ;; worked. So now cut the tree and finish up.
3457 (let (this-command) (org-cut-subtree))
3458 (if (looking-at "[ \t]*$") (kill-line))
3459 (message "Subtree archived %s"
3460 (if (eq this-buffer buffer)
3461 (concat "under heading: " heading)
3462 (concat "in file: " (abbreviate-file-name file))))))
3464 ;;; Completion
3466 (defun org-complete (&optional arg)
3467 "Perform completion on word at point.
3468 At the beginning of a headline, this completes TODO keywords as given in
3469 `org-todo-keywords'.
3470 If the current word is preceded by a backslash, completes the TeX symbols
3471 that are supported for HTML support.
3472 If the current word is preceded by \"#+\", completes special words for
3473 setting file options.
3474 At all other locations, this simply calls `ispell-complete-word'."
3475 (interactive "P")
3476 (catch 'exit
3477 (let* ((end (point))
3478 (beg1 (save-excursion
3479 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3480 (skip-chars-backward "a-zA-Z_@0-9")
3481 (point)))
3482 (beg (save-excursion
3483 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3484 (skip-chars-backward "a-zA-Z0-9_:$")
3485 (point)))
3486 (camel (equal (char-before beg) ?*))
3487 (tag (equal (char-before beg1) ?:))
3488 (texp (equal (char-before beg) ?\\))
3489 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3490 beg)
3491 "#+"))
3492 (completion-ignore-case opt)
3493 (type nil)
3494 (tbl nil)
3495 (table (cond
3496 (opt
3497 (setq type :opt)
3498 (mapcar (lambda (x)
3499 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3500 (cons (match-string 2 x) (match-string 1 x)))
3501 (org-split-string (org-get-current-options) "\n")))
3502 (texp
3503 (setq type :tex)
3504 org-html-entities)
3505 ((string-match "\\`\\*+[ \t]*\\'"
3506 (buffer-substring (point-at-bol) beg))
3507 (setq type :todo)
3508 (mapcar 'list org-todo-keywords))
3509 (camel
3510 (setq type :camel)
3511 (save-excursion
3512 (goto-char (point-min))
3513 (while (re-search-forward org-todo-line-regexp nil t)
3514 (push (list
3515 (if org-file-link-context-use-camel-case
3516 (org-make-org-heading-camel (match-string 3) t)
3517 (org-make-org-heading-search-string
3518 (match-string 3) t)))
3519 tbl)))
3520 tbl)
3521 (tag (setq type :tag beg beg1)
3522 (org-get-buffer-tags))
3523 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3524 (pattern (buffer-substring-no-properties beg end))
3525 (completion (try-completion pattern table)))
3526 (cond ((eq completion t)
3527 (if (equal type :opt)
3528 (insert (substring (cdr (assoc (upcase pattern) table))
3529 (length pattern)))))
3530 ((null completion)
3531 (message "Can't find completion for \"%s\"" pattern)
3532 (ding))
3533 ((not (string= pattern completion))
3534 (delete-region beg end)
3535 (if (string-match " +$" completion)
3536 (setq completion (replace-match "" t t completion)))
3537 (insert completion)
3538 (if (get-buffer-window "*Completions*")
3539 (delete-window (get-buffer-window "*Completions*")))
3540 (if (assoc completion table)
3541 (if (eq type :todo) (insert " ")
3542 (if (eq type :tag) (insert ":"))))
3543 (if (and (equal type :opt) (assoc completion table))
3544 (message "%s" (substitute-command-keys
3545 "Press \\[org-complete] again to insert example settings"))))
3547 (message "Making completion list...")
3548 (let ((list (sort (all-completions pattern table) 'string<)))
3549 (with-output-to-temp-buffer "*Completions*"
3550 (condition-case nil
3551 ;; Protection needed for XEmacs and emacs 21
3552 (display-completion-list list pattern)
3553 (error (display-completion-list list)))))
3554 (message "Making completion list...%s" "done"))))))
3556 ;;; Comments, TODO and DEADLINE
3558 (defun org-toggle-comment ()
3559 "Change the COMMENT state of an entry."
3560 (interactive)
3561 (save-excursion
3562 (org-back-to-heading)
3563 (if (looking-at (concat outline-regexp
3564 "\\( +\\<" org-comment-string "\\>\\)"))
3565 (replace-match "" t t nil 1)
3566 (if (looking-at outline-regexp)
3567 (progn
3568 (goto-char (match-end 0))
3569 (insert " " org-comment-string))))))
3571 (defvar org-last-todo-state-is-todo nil
3572 "This is non-nil when the last TODO state change led to a TODO state.
3573 If the last change removed the TODO tag or switched to DONE, then
3574 this is nil.")
3576 (defun org-todo (&optional arg)
3577 "Change the TODO state of an item.
3578 The state of an item is given by a keyword at the start of the heading,
3579 like
3580 *** TODO Write paper
3581 *** DONE Call mom
3583 The different keywords are specified in the variable `org-todo-keywords'.
3584 By default the available states are \"TODO\" and \"DONE\".
3585 So for this example: when the item starts with TODO, it is changed to DONE.
3586 When it starts with DONE, the DONE is removed. And when neither TODO nor
3587 DONE are present, add TODO at the beginning of the heading.
3589 With prefix arg, use completion to determine the new state. With numeric
3590 prefix arg, switch to that state."
3591 (interactive "P")
3592 (save-excursion
3593 (org-back-to-heading)
3594 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3595 (or (looking-at (concat " +" org-todo-regexp " *"))
3596 (looking-at " *"))
3597 (let* ((this (match-string 1))
3598 (completion-ignore-case t)
3599 (member (member this org-todo-keywords))
3600 (tail (cdr member))
3601 (state (cond
3602 ((equal arg '(4))
3603 ;; Read a state with completion
3604 (completing-read "State: " (mapcar (lambda(x) (list x))
3605 org-todo-keywords)
3606 nil t))
3607 ((eq arg 'right)
3608 (if this
3609 (if tail (car tail) nil)
3610 (car org-todo-keywords)))
3611 ((eq arg 'left)
3612 (if (equal member org-todo-keywords)
3614 (if this
3615 (nth (- (length org-todo-keywords) (length tail) 2)
3616 org-todo-keywords)
3617 org-done-string)))
3618 (arg
3619 ;; user requests a specific state
3620 (nth (1- (prefix-numeric-value arg))
3621 org-todo-keywords))
3622 ((null member) (car org-todo-keywords))
3623 ((null tail) nil) ;; -> first entry
3624 ((eq org-todo-interpretation 'sequence)
3625 (car tail))
3626 ((memq org-todo-interpretation '(type priority))
3627 (if (eq this-command last-command)
3628 (car tail)
3629 (if (> (length tail) 0) org-done-string nil)))
3630 (t nil)))
3631 (next (if state (concat " " state " ") " ")))
3632 (replace-match next t t)
3633 (setq org-last-todo-state-is-todo
3634 (not (equal state org-done-string)))
3635 (when org-log-done
3636 (if (equal state org-done-string)
3637 (org-log-done)
3638 (if (not this)
3639 (org-log-done t))))
3640 ;; Fixup tag positioning
3641 (and org-auto-align-tags (org-set-tags nil t))
3642 (run-hooks 'org-after-todo-state-change-hook)))
3643 ;; Fixup cursor location if close to the keyword
3644 (if (and (outline-on-heading-p)
3645 (not (bolp))
3646 (save-excursion (beginning-of-line 1)
3647 (looking-at org-todo-line-regexp))
3648 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3649 (progn
3650 (goto-char (or (match-end 2) (match-end 1)))
3651 (just-one-space))))
3653 (defun org-log-done (&optional undone)
3654 "Add a time stamp logging that a TODO entry has been closed.
3655 When UNDONE is non-nil, remove such a time stamp again."
3656 (interactive)
3657 (let (beg end col)
3658 (save-excursion
3659 (org-back-to-heading t)
3660 (setq beg (point))
3661 (looking-at (concat outline-regexp " *"))
3662 (goto-char (match-end 0))
3663 (setq col (current-column))
3664 (outline-next-heading)
3665 (setq end (point))
3666 (goto-char beg)
3667 (when (re-search-forward (concat
3668 "[\r\n]\\([ \t]*"
3669 (regexp-quote org-closed-string)
3670 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3671 (delete-region (match-beginning 1) (match-end 1)))
3672 (unless undone
3673 (org-back-to-heading t)
3674 (skip-chars-forward "^\n\r")
3675 (goto-char (min (1+ (point)) (point-max)))
3676 (when (not (member (char-before) '(?\r ?\n)))
3677 (insert "\n"))
3678 (indent-to col)
3679 (insert org-closed-string " "
3680 (format-time-string
3681 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3682 (org-current-time))
3683 "\n")))))
3685 (defun org-show-todo-tree (arg)
3686 "Make a compact tree which shows all headlines marked with TODO.
3687 The tree will show the lines where the regexp matches, and all higher
3688 headlines above the match.
3689 With \\[universal-argument] prefix, also show the DONE entries.
3690 With a numeric prefix N, construct a sparse tree for the Nth element
3691 of `org-todo-keywords'."
3692 (interactive "P")
3693 (let ((case-fold-search nil)
3694 (kwd-re
3695 (cond ((null arg) org-not-done-regexp)
3696 ((equal arg '(4)) org-todo-regexp)
3697 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3698 (regexp-quote (nth (1- (prefix-numeric-value arg))
3699 org-todo-keywords)))
3700 (t (error "Invalid prefix argument: %s" arg)))))
3701 (message "%d TODO entries found"
3702 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3704 (defun org-deadline ()
3705 "Insert the DEADLINE: string to make a deadline.
3706 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3707 to modify it to the correct date."
3708 (interactive)
3709 (insert
3710 org-deadline-string " "
3711 (format-time-string (car org-time-stamp-formats)
3712 (org-read-date nil 'to-time)))
3713 (message "%s" (substitute-command-keys
3714 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3716 (defun org-schedule ()
3717 "Insert the SCHEDULED: string to schedule a TODO item.
3718 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3719 to modify it to the correct date."
3720 (interactive)
3721 (insert
3722 org-scheduled-string " "
3723 (format-time-string (car org-time-stamp-formats)
3724 (org-read-date nil 'to-time)))
3725 (message "%s" (substitute-command-keys
3726 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3729 (defun org-occur (regexp &optional callback)
3730 "Make a compact tree which shows all matches of REGEXP.
3731 The tree will show the lines where the regexp matches, and all higher
3732 headlines above the match. It will also show the heading after the match,
3733 to make sure editing the matching entry is easy.
3734 If CALLBACK is non-nil, it is a function which is called to confirm
3735 that the match should indeed be shown."
3736 (interactive "sRegexp: ")
3737 (org-remove-occur-highlights nil nil t)
3738 (setq regexp (org-check-occur-regexp regexp))
3739 (let ((cnt 0))
3740 (save-excursion
3741 (goto-char (point-min))
3742 (hide-sublevels 1)
3743 (while (re-search-forward regexp nil t)
3744 (when (or (not callback)
3745 (save-match-data (funcall callback)))
3746 (setq cnt (1+ cnt))
3747 (org-highlight-new-match (match-beginning 0) (match-end 0))
3748 (org-show-hierarchy-above))))
3749 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
3750 nil 'local)
3751 (run-hooks 'org-occur-hook)
3752 (if (interactive-p)
3753 (message "%d match(es) for regexp %s" cnt regexp))
3754 cnt))
3756 (defun org-show-hierarchy-above ()
3757 "Make sure point and the headings hierarchy above is visible."
3758 (catch 'exit
3759 (if (org-on-heading-p t)
3760 (org-flag-heading nil) ; only show the heading
3761 (and (or (org-invisible-p) (org-invisible-p2))
3762 (org-show-hidden-entry))) ; show entire entry
3763 (save-excursion
3764 (and org-show-following-heading
3765 (outline-next-heading)
3766 (org-flag-heading nil))) ; show the next heading
3767 (when org-show-hierarchy-above
3768 (save-excursion ; show all higher headings
3769 (while (and (condition-case nil
3770 (progn (org-up-heading-all 1) t)
3771 (error nil))
3772 (not (bobp)))
3773 (org-flag-heading nil))))))
3775 ;; Overlay compatibility functions
3776 (defun org-make-overlay (beg end &optional buffer)
3777 (if org-xemacs-p (make-extent beg end buffer) (make-overlay beg end buffer)))
3778 (defun org-delete-overlay (ovl)
3779 (if org-xemacs-p (delete-extent ovl) (delete-overlay ovl)))
3780 (defun org-detatch-overlay (ovl)
3781 (if org-xemacs-p (detach-extent ovl) (delete-overlay ovl)))
3782 (defun org-move-overlay (ovl beg end &optional buffer)
3783 (if org-xemacs-p
3784 (set-extent-endpoints ovl beg end buffer)
3785 (move-overlay ovl beg end buffer)))
3786 (defun org-overlay-put (ovl prop value)
3787 (if org-xemacs-p
3788 (set-extent-property ovl prop value)
3789 (overlay-put ovl prop value)))
3791 (defvar org-occur-highlights nil)
3792 (defun org-highlight-new-match (beg end)
3793 "Highlight from BEG to END and mark the highlight is an occur headline."
3794 (let ((ov (org-make-overlay beg end)))
3795 (org-overlay-put ov 'face 'secondary-selection)
3796 (push ov org-occur-highlights)))
3798 (defun org-remove-occur-highlights (&optional beg end noremove)
3799 "Remove the occur highlights from the buffer.
3800 BEG and END are ignored. If NOREMOVE is nil, remove this function
3801 from the `before-change-functions' in the current buffer."
3802 (interactive)
3803 (mapc 'org-delete-overlay org-occur-highlights)
3804 (setq org-occur-highlights nil)
3805 (unless noremove
3806 (remove-hook 'before-change-functions
3807 'org-remove-occur-highlights 'local)))
3809 ;;; Priorities
3811 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3812 "Regular expression matching the priority indicator.")
3814 (defvar org-remove-priority-next-time nil)
3816 (defun org-priority-up ()
3817 "Increase the priority of the current item."
3818 (interactive)
3819 (org-priority 'up))
3821 (defun org-priority-down ()
3822 "Decrease the priority of the current item."
3823 (interactive)
3824 (org-priority 'down))
3826 (defun org-priority (&optional action)
3827 "Change the priority of an item by ARG.
3828 ACTION can be set, up, or down."
3829 (interactive)
3830 (setq action (or action 'set))
3831 (let (current new news have remove)
3832 (save-excursion
3833 (org-back-to-heading)
3834 (if (looking-at org-priority-regexp)
3835 (setq current (string-to-char (match-string 2))
3836 have t)
3837 (setq current org-default-priority))
3838 (cond
3839 ((eq action 'set)
3840 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3841 (setq new (read-char-exclusive))
3842 (cond ((equal new ?\ ) (setq remove t))
3843 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3844 (error "Priority must be between `%c' and `%c'"
3845 ?A org-lowest-priority))))
3846 ((eq action 'up)
3847 (setq new (1- current)))
3848 ((eq action 'down)
3849 (setq new (1+ current)))
3850 (t (error "Invalid action")))
3851 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3852 (setq news (format "%c" new))
3853 (if have
3854 (if remove
3855 (replace-match "" t t nil 1)
3856 (replace-match news t t nil 2))
3857 (if remove
3858 (error "No priority cookie found in line")
3859 (looking-at org-todo-line-regexp)
3860 (if (match-end 2)
3861 (progn
3862 (goto-char (match-end 2))
3863 (insert " [#" news "]"))
3864 (goto-char (match-beginning 3))
3865 (insert "[#" news "] ")))))
3866 (if remove
3867 (message "Priority removed")
3868 (message "Priority of current item set to %s" news))))
3871 (defun org-get-priority (s)
3872 "Find priority cookie and return priority."
3873 (save-match-data
3874 (if (not (string-match org-priority-regexp s))
3875 (* 1000 (- org-lowest-priority org-default-priority))
3876 (* 1000 (- org-lowest-priority
3877 (string-to-char (match-string 2 s)))))))
3879 ;;; Timestamps
3881 (defvar org-last-changed-timestamp nil)
3883 (defun org-time-stamp (arg)
3884 "Prompt for a date/time and insert a time stamp.
3885 If the user specifies a time like HH:MM, or if this command is called
3886 with a prefix argument, the time stamp will contain date and time.
3887 Otherwise, only the date will be included. All parts of a date not
3888 specified by the user will be filled in from the current date/time.
3889 So if you press just return without typing anything, the time stamp
3890 will represent the current date/time. If there is already a timestamp
3891 at the cursor, it will be modified."
3892 (interactive "P")
3893 (let ((fmt (if arg (cdr org-time-stamp-formats)
3894 (car org-time-stamp-formats)))
3895 (org-time-was-given nil)
3896 time)
3897 (cond
3898 ((and (org-at-timestamp-p)
3899 (eq last-command 'org-time-stamp)
3900 (eq this-command 'org-time-stamp))
3901 (insert "--")
3902 (setq time (let ((this-command this-command))
3903 (org-read-date arg 'totime)))
3904 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3905 (insert (format-time-string fmt time)))
3906 ((org-at-timestamp-p)
3907 (setq time (let ((this-command this-command))
3908 (org-read-date arg 'totime)))
3909 (and (org-at-timestamp-p) (replace-match
3910 (setq org-last-changed-timestamp
3911 (format-time-string fmt time))
3912 t t))
3913 (message "Timestamp updated"))
3915 (setq time (let ((this-command this-command))
3916 (org-read-date arg 'totime)))
3917 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3918 (insert (format-time-string fmt time))))))
3920 (defun org-time-stamp-inactive (&optional arg)
3921 "Insert an inactive time stamp.
3922 An inactive time stamp is enclosed in square brackets instead of angle
3923 brackets. It is inactive in the sense that it does not trigger agenda entries,
3924 does not link to the calendar and cannot be changed with the S-cursor keys.
3925 So these are more for recording a certain time/date."
3926 ;; FIXME: Would it be better not to ask for a date/time here?
3927 (interactive "P")
3928 (let ((fmt (if arg (cdr org-time-stamp-formats)
3929 (car org-time-stamp-formats)))
3930 (org-time-was-given nil)
3931 time)
3932 (setq time (org-read-date arg 'totime))
3933 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3934 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3935 (insert (format-time-string fmt time))))
3937 (defvar org-date-ovl (org-make-overlay 1 1))
3938 (org-overlay-put org-date-ovl 'face 'org-warning)
3939 (org-detatch-overlay org-date-ovl)
3941 ;;; FIXME: Make the function take "Fri" as "next friday"
3942 ;;; because these are mostly being used to record the current time.
3943 (defun org-read-date (&optional with-time to-time)
3944 "Read a date and make things smooth for the user.
3945 The prompt will suggest to enter an ISO date, but you can also enter anything
3946 which will at least partially be understood by `parse-time-string'.
3947 Unrecognized parts of the date will default to the current day, month, year,
3948 hour and minute. For example,
3949 3-2-5 --> 2003-02-05
3950 feb 15 --> currentyear-02-15
3951 sep 12 9 --> 2009-09-12
3952 12:45 --> today 12:45
3953 22 sept 0:34 --> currentyear-09-22 0:34
3954 12 --> currentyear-currentmonth-12
3955 etc.
3956 The function understands only English month and weekday abbreviations,
3957 but this can be configured with the variables `parse-time-months' and
3958 `parse-time-weekdays'.
3960 While prompting, a calendar is popped up - you can also select the
3961 date with the mouse (button 1). The calendar shows a period of three
3962 months. To scroll it to other months, use the keys `>' and `<'.
3963 If you don't like the calendar, turn it off with
3964 \(setq org-popup-calendar-for-date-prompt nil)
3966 With optional argument TO-TIME, the date will immediately be converted
3967 to an internal time.
3968 With an optional argument WITH-TIME, the prompt will suggest to also
3969 insert a time. Note that when WITH-TIME is not set, you can still
3970 enter a time, and this function will inform the calling routine about
3971 this change. The calling routine may then choose to change the format
3972 used to insert the time stamp into the buffer to include the time."
3973 (require 'parse-time)
3974 (let* ((org-time-stamp-rounding-minutes
3975 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
3976 (ct (org-current-time))
3977 (default-time
3978 ;; Default time is either today, or, when entering a range,
3979 ;; the range start.
3980 (if (save-excursion
3981 (re-search-backward
3982 (concat org-ts-regexp "--\\=")
3983 (- (point) 20) t))
3984 (apply
3985 'encode-time
3986 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3987 (parse-time-string (match-string 1))))
3988 ct))
3989 (calendar-move-hook nil)
3990 (view-diary-entries-initially nil)
3991 (timestr (format-time-string
3992 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
3993 (prompt (format "YYYY-MM-DD [%s]: " timestr))
3994 ans ans1 ans2
3995 second minute hour day month year tl)
3997 (if org-popup-calendar-for-date-prompt
3998 ;; Also show a calendar for date selection
3999 ;; Copied (with modifications) from planner.el by John Wiegley
4000 (save-excursion
4001 (save-window-excursion
4002 (calendar)
4003 (calendar-forward-day (- (time-to-days default-time)
4004 (calendar-absolute-from-gregorian
4005 (calendar-current-date))))
4006 (org-eval-in-calendar nil)
4007 (let* ((old-map (current-local-map))
4008 (map (copy-keymap calendar-mode-map))
4009 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
4010 (define-key map (kbd "RET") 'org-calendar-select)
4011 (define-key map (if org-xemacs-p [button1] [mouse-1])
4012 'org-calendar-select-mouse)
4013 (define-key map (if org-xemacs-p [button2] [mouse-2])
4014 'org-calendar-select-mouse)
4015 (define-key minibuffer-local-map [(meta shift left)]
4016 (lambda () (interactive)
4017 (org-eval-in-calendar '(calendar-backward-month 1))))
4018 (define-key minibuffer-local-map [(meta shift right)]
4019 (lambda () (interactive)
4020 (org-eval-in-calendar '(calendar-forward-month 1))))
4021 (define-key minibuffer-local-map [(shift up)]
4022 (lambda () (interactive)
4023 (org-eval-in-calendar '(calendar-backward-week 1))))
4024 (define-key minibuffer-local-map [(shift down)]
4025 (lambda () (interactive)
4026 (org-eval-in-calendar '(calendar-forward-week 1))))
4027 (define-key minibuffer-local-map [(shift left)]
4028 (lambda () (interactive)
4029 (org-eval-in-calendar '(calendar-backward-day 1))))
4030 (define-key minibuffer-local-map [(shift right)]
4031 (lambda () (interactive)
4032 (org-eval-in-calendar '(calendar-forward-day 1))))
4033 (define-key minibuffer-local-map ">"
4034 (lambda () (interactive)
4035 (org-eval-in-calendar '(scroll-calendar-left 1))))
4036 (define-key minibuffer-local-map "<"
4037 (lambda () (interactive)
4038 (org-eval-in-calendar '(scroll-calendar-right 1))))
4039 (unwind-protect
4040 (progn
4041 (use-local-map map)
4042 (setq ans (read-string prompt "" nil nil))
4043 (if (not (string-match "\\S-" ans)) (setq ans nil))
4044 (setq ans (or ans1 ans ans2)))
4045 (use-local-map old-map)))))
4046 ;; Naked prompt only
4047 (setq ans (read-string prompt "" nil timestr)))
4048 (org-detatch-overlay org-date-ovl)
4050 (if (string-match
4051 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
4052 (progn
4053 (setq year (if (match-end 2)
4054 (string-to-number (match-string 2 ans))
4055 (string-to-number (format-time-string "%Y")))
4056 month (string-to-number (match-string 3 ans))
4057 day (string-to-number (match-string 4 ans)))
4058 (if (< year 100) (setq year (+ 2000 year)))
4059 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
4060 t nil ans))))
4061 (setq tl (parse-time-string ans)
4062 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
4063 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
4064 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
4065 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
4066 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
4067 second (or (nth 0 tl) 0))
4068 (if (and (boundp 'org-time-was-given)
4069 (nth 2 tl))
4070 (setq org-time-was-given t))
4071 (if (< year 100) (setq year (+ 2000 year)))
4072 (if to-time
4073 (encode-time second minute hour day month year)
4074 (if (or (nth 1 tl) (nth 2 tl))
4075 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
4076 (format "%04d-%02d-%02d" year month day)))))
4078 (defun org-eval-in-calendar (form)
4079 "Eval FORM in the calendar window and return to current window.
4080 Also, store the cursor date in variable ans2."
4081 (let ((sw (selected-window)))
4082 (select-window (get-buffer-window "*Calendar*"))
4083 (eval form)
4084 (when (calendar-cursor-to-date)
4085 (let* ((date (calendar-cursor-to-date))
4086 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4087 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4088 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4089 (select-window sw)))
4091 (defun org-calendar-select ()
4092 "Return to `org-read-date' with the date currently selected.
4093 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4094 (interactive)
4095 (when (calendar-cursor-to-date)
4096 (let* ((date (calendar-cursor-to-date))
4097 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4098 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4099 (if (active-minibuffer-window) (exit-minibuffer))))
4101 (defun org-calendar-select-mouse (ev)
4102 "Return to `org-read-date' with the date currently selected.
4103 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4104 (interactive "e")
4105 (mouse-set-point ev)
4106 (when (calendar-cursor-to-date)
4107 (let* ((date (calendar-cursor-to-date))
4108 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4109 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4110 (if (active-minibuffer-window) (exit-minibuffer))))
4112 (defun org-check-deadlines (ndays)
4113 "Check if there are any deadlines due or past due.
4114 A deadline is considered due if it happens within `org-deadline-warning-days'
4115 days from today's date. If the deadline appears in an entry marked DONE,
4116 it is not shown. The prefix arg NDAYS can be used to test that many
4117 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4118 (interactive "P")
4119 (let* ((org-warn-days
4120 (cond
4121 ((equal ndays '(4)) 100000)
4122 (ndays (prefix-numeric-value ndays))
4123 (t org-deadline-warning-days)))
4124 (case-fold-search nil)
4125 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4126 (callback
4127 (lambda ()
4128 (and (let ((d1 (time-to-days (current-time)))
4129 (d2 (time-to-days
4130 (org-time-string-to-time (match-string 1)))))
4131 (< (- d2 d1) org-warn-days))
4132 (not (org-entry-is-done-p))))))
4133 (message "%d deadlines past-due or due within %d days"
4134 (org-occur regexp callback)
4135 org-warn-days)))
4137 (defun org-evaluate-time-range (&optional to-buffer)
4138 "Evaluate a time range by computing the difference between start and end.
4139 Normally the result is just printed in the echo area, but with prefix arg
4140 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4141 If the time range is actually in a table, the result is inserted into the
4142 next column.
4143 For time difference computation, a year is assumed to be exactly 365
4144 days in order to avoid rounding problems."
4145 (interactive "P")
4146 (save-excursion
4147 (unless (org-at-date-range-p)
4148 (goto-char (point-at-bol))
4149 (re-search-forward org-tr-regexp (point-at-eol) t))
4150 (if (not (org-at-date-range-p))
4151 (error "Not at a time-stamp range, and none found in current line")))
4152 (let* ((ts1 (match-string 1))
4153 (ts2 (match-string 2))
4154 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4155 (match-end (match-end 0))
4156 (time1 (org-time-string-to-time ts1))
4157 (time2 (org-time-string-to-time ts2))
4158 (t1 (time-to-seconds time1))
4159 (t2 (time-to-seconds time2))
4160 (diff (abs (- t2 t1)))
4161 (negative (< (- t2 t1) 0))
4162 ;; (ys (floor (* 365 24 60 60)))
4163 (ds (* 24 60 60))
4164 (hs (* 60 60))
4165 (fy "%dy %dd %02d:%02d")
4166 (fy1 "%dy %dd")
4167 (fd "%dd %02d:%02d")
4168 (fd1 "%dd")
4169 (fh "%02d:%02d")
4170 y d h m align)
4171 ;; FIXME: Should I re-introduce years, make year refer to same date?
4172 ;; This would be the only useful way to have years, actually.
4173 (if havetime
4174 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4176 d (floor (/ diff ds)) diff (mod diff ds)
4177 h (floor (/ diff hs)) diff (mod diff hs)
4178 m (floor (/ diff 60)))
4179 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4181 d (floor (+ (/ diff ds) 0.5))
4182 h 0 m 0))
4183 (if (not to-buffer)
4184 (message (org-make-tdiff-string y d h m))
4185 (when (org-at-table-p)
4186 (goto-char match-end)
4187 (setq align t)
4188 (and (looking-at " *|") (goto-char (match-end 0))))
4189 (if (looking-at
4190 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4191 (replace-match ""))
4192 (if negative (insert " -"))
4193 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4194 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4195 (insert " " (format fh h m))))
4196 (if align (org-table-align))
4197 (message "Time difference inserted"))))
4199 (defun org-make-tdiff-string (y d h m)
4200 (let ((fmt "")
4201 (l nil))
4202 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4203 l (push y l)))
4204 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4205 l (push d l)))
4206 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4207 l (push h l)))
4208 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4209 l (push m l)))
4210 (apply 'format fmt (nreverse l))))
4212 (defun org-time-string-to-time (s)
4213 (apply 'encode-time (org-parse-time-string s)))
4215 (defun org-parse-time-string (s &optional nodefault)
4216 "Parse the standard Org-mode time string.
4217 This should be a lot faster than the normal `parse-time-string'.
4218 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4219 hour and minute fields will be nil if not given."
4220 (if (string-match org-ts-regexp1 s)
4221 (list 0
4222 (if (or (match-beginning 8) (not nodefault))
4223 (string-to-number (or (match-string 8 s) "0")))
4224 (if (or (match-beginning 7) (not nodefault))
4225 (string-to-number (or (match-string 7 s) "0")))
4226 (string-to-number (match-string 4 s))
4227 (string-to-number (match-string 3 s))
4228 (string-to-number (match-string 2 s))
4229 nil nil nil)
4230 (make-list 9 0)))
4232 (defun org-timestamp-up (&optional arg)
4233 "Increase the date item at the cursor by one.
4234 If the cursor is on the year, change the year. If it is on the month or
4235 the day, change that.
4236 With prefix ARG, change by that many units."
4237 (interactive "p")
4238 (org-timestamp-change (prefix-numeric-value arg)))
4240 (defun org-timestamp-down (&optional arg)
4241 "Decrease the date item at the cursor by one.
4242 If the cursor is on the year, change the year. If it is on the month or
4243 the day, change that.
4244 With prefix ARG, change by that many units."
4245 (interactive "p")
4246 (org-timestamp-change (- (prefix-numeric-value arg))))
4248 (defun org-timestamp-up-day (&optional arg)
4249 "Increase the date in the time stamp by one day.
4250 With prefix ARG, change that many days."
4251 (interactive "p")
4252 (if (and (not (org-at-timestamp-p))
4253 (org-on-heading-p))
4254 (org-todo 'up)
4255 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4257 (defun org-timestamp-down-day (&optional arg)
4258 "Decrease the date in the time stamp by one day.
4259 With prefix ARG, change that many days."
4260 (interactive "p")
4261 (if (and (not (org-at-timestamp-p))
4262 (org-on-heading-p))
4263 (org-todo 'down)
4264 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4266 (defsubst org-pos-in-match-range (pos n)
4267 (and (match-beginning n)
4268 (<= (match-beginning n) pos)
4269 (>= (match-end n) pos)))
4271 (defun org-at-timestamp-p ()
4272 "Determine if the cursor is in or at a timestamp."
4273 (interactive)
4274 (let* ((tsr org-ts-regexp2)
4275 (pos (point))
4276 (ans (or (looking-at tsr)
4277 (save-excursion
4278 (skip-chars-backward "^<\n\r\t")
4279 (if (> (point) 1) (backward-char 1))
4280 (and (looking-at tsr)
4281 (> (- (match-end 0) pos) -1))))))
4282 (and (boundp 'org-ts-what)
4283 (setq org-ts-what
4284 (cond
4285 ((org-pos-in-match-range pos 2) 'year)
4286 ((org-pos-in-match-range pos 3) 'month)
4287 ((org-pos-in-match-range pos 7) 'hour)
4288 ((org-pos-in-match-range pos 8) 'minute)
4289 ((or (org-pos-in-match-range pos 4)
4290 (org-pos-in-match-range pos 5)) 'day)
4291 (t 'day))))
4292 ans))
4294 (defun org-timestamp-change (n &optional what)
4295 "Change the date in the time stamp at point.
4296 The date will be changed by N times WHAT. WHAT can be `day', `month',
4297 `year', `minute', `second'. If WHAT is not given, the cursor position
4298 in the timestamp determines what will be changed."
4299 (let ((fmt (car org-time-stamp-formats))
4300 org-ts-what
4301 (pos (point))
4302 ts time time0)
4303 (if (not (org-at-timestamp-p))
4304 (error "Not at a timestamp"))
4305 (setq org-ts-what (or what org-ts-what))
4306 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4307 (- (match-end 0) (match-beginning 0))))
4309 (cdr org-time-stamp-formats)
4310 (car org-time-stamp-formats)))
4311 (setq ts (match-string 0))
4312 (replace-match "")
4313 (setq time0 (org-parse-time-string ts))
4314 (setq time
4315 (apply 'encode-time
4316 (append
4317 (list (or (car time0) 0))
4318 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4319 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4320 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4321 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4322 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4323 (nthcdr 6 time0))))
4324 (if (eq what 'calendar)
4325 (let ((cal-date
4326 (save-excursion
4327 (save-match-data
4328 (set-buffer "*Calendar*")
4329 (calendar-cursor-to-date)))))
4330 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4331 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4332 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4333 (setcar time0 (or (car time0) 0))
4334 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4335 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4336 (setq time (apply 'encode-time time0))))
4337 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4338 (goto-char pos)
4339 ;; Try to recenter the calendar window, if any
4340 (if (and org-calendar-follow-timestamp-change
4341 (get-buffer-window "*Calendar*" t)
4342 (memq org-ts-what '(day month year)))
4343 (org-recenter-calendar (time-to-days time)))))
4345 (defun org-recenter-calendar (date)
4346 "If the calendar is visible, recenter it to DATE."
4347 (let* ((win (selected-window))
4348 (cwin (get-buffer-window "*Calendar*" t))
4349 (calendar-move-hook nil))
4350 (when cwin
4351 (select-window cwin)
4352 (calendar-goto-date (if (listp date) date
4353 (calendar-gregorian-from-absolute date)))
4354 (select-window win))))
4356 (defun org-goto-calendar (&optional arg)
4357 "Go to the Emacs calendar at the current date.
4358 If there is a time stamp in the current line, go to that date.
4359 A prefix ARG can be used to force the current date."
4360 (interactive "P")
4361 (let ((tsr org-ts-regexp) diff
4362 (calendar-move-hook nil)
4363 (view-diary-entries-initially nil))
4364 (if (or (org-at-timestamp-p)
4365 (save-excursion
4366 (beginning-of-line 1)
4367 (looking-at (concat ".*" tsr))))
4368 (let ((d1 (time-to-days (current-time)))
4369 (d2 (time-to-days
4370 (org-time-string-to-time (match-string 1)))))
4371 (setq diff (- d2 d1))))
4372 (calendar)
4373 (calendar-goto-today)
4374 (if (and diff (not arg)) (calendar-forward-day diff))))
4376 (defun org-date-from-calendar ()
4377 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4378 If there is already a time stamp at the cursor position, update it."
4379 (interactive)
4380 (org-timestamp-change 0 'calendar))
4382 ;;; Agenda, and Diary Integration
4384 ;;; Define the mode
4386 (defvar org-agenda-mode-map (make-sparse-keymap)
4387 "Keymap for `org-agenda-mode'.")
4389 (defvar org-agenda-menu) ; defined later in this file.
4390 (defvar org-agenda-follow-mode nil)
4391 (defvar org-agenda-show-log nil)
4392 (defvar org-agenda-buffer-name "*Org Agenda*")
4393 (defvar org-agenda-redo-command nil)
4394 (defvar org-agenda-mode-hook nil)
4395 (defvar org-agenda-type nil)
4396 (defvar org-agenda-force-single-file nil)
4398 ;;;###autoload
4399 (defun org-agenda-mode ()
4400 "Mode for time-sorted view on action items in Org-mode files.
4402 The following commands are available:
4404 \\{org-agenda-mode-map}"
4405 (interactive)
4406 (kill-all-local-variables)
4407 (setq major-mode 'org-agenda-mode)
4408 (setq mode-name "Org-Agenda")
4409 (use-local-map org-agenda-mode-map)
4410 (easy-menu-add org-agenda-menu)
4411 (if org-startup-truncated (setq truncate-lines t))
4412 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4413 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4414 (unless org-agenda-keep-modes
4415 (setq org-agenda-follow-mode nil
4416 org-agenda-show-log nil))
4417 (easy-menu-change
4418 '("Agenda") "Agenda Files"
4419 (append
4420 (list
4421 (vector
4422 (if (get 'org-agenda-files 'org-restrict)
4423 "Restricted to single file"
4424 "Edit File List")
4425 '(customize-variable 'org-agenda-files)
4426 (not (get 'org-agenda-files 'org-restrict)))
4427 "--")
4428 (mapcar 'org-file-menu-entry (org-agenda-files))))
4429 (org-agenda-set-mode-name)
4430 (apply
4431 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4432 (list 'org-agenda-mode-hook)))
4434 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4435 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
4436 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4437 (define-key org-agenda-mode-map " " 'org-agenda-show)
4438 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4439 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4440 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4441 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4442 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4443 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4444 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4445 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4446 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4447 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4448 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4449 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4451 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4452 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4453 (while l (define-key org-agenda-mode-map
4454 (int-to-string (pop l)) 'digit-argument)))
4456 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4457 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4458 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4459 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4460 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4461 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4462 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4463 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4464 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4465 (define-key org-agenda-mode-map "n" 'next-line)
4466 (define-key org-agenda-mode-map "p" 'previous-line)
4467 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4468 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4469 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4470 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4471 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4472 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4473 (eval-after-load "calendar"
4474 '(define-key calendar-mode-map org-calendar-to-agenda-key
4475 'org-calendar-goto-agenda))
4476 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4477 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4478 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4479 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4480 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4481 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4482 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4483 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4484 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4485 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4486 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4487 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4488 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4489 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4490 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4491 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4492 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4493 "Local keymap for agenda entries from Org-mode.")
4495 (define-key org-agenda-keymap
4496 (if org-xemacs-p [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4497 (define-key org-agenda-keymap
4498 (if org-xemacs-p [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4499 (define-key org-agenda-keymap [follow-link] 'mouse-face)
4500 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4501 '("Agenda"
4502 ("Agenda Files")
4503 "--"
4504 ["Show" org-agenda-show t]
4505 ["Go To (other window)" org-agenda-goto t]
4506 ["Go To (one window)" org-agenda-switch-to t]
4507 ["Follow Mode" org-agenda-follow-mode
4508 :style toggle :selected org-agenda-follow-mode :active t]
4509 "--"
4510 ["Cycle TODO" org-agenda-todo t]
4511 ("Tags"
4512 ["Show all Tags" org-agenda-show-tags t]
4513 ["Set Tags" org-agenda-set-tags t])
4514 ("Reschedule"
4515 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4516 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4517 "--"
4518 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4519 ("Priority"
4520 ["Set Priority" org-agenda-priority t]
4521 ["Increase Priority" org-agenda-priority-up t]
4522 ["Decrease Priority" org-agenda-priority-down t]
4523 ["Show Priority" org-agenda-show-priority t])
4524 "--"
4525 ;; ["New agenda command" org-agenda t]
4526 ["Rebuild buffer" org-agenda-redo t]
4527 "--"
4528 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4529 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4530 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4531 "--"
4532 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4533 :style radio :selected (equal org-agenda-ndays 1)]
4534 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4535 :style radio :selected (equal org-agenda-ndays 7)]
4536 "--"
4537 ["Show Logbook entries" org-agenda-log-mode
4538 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4539 ["Include Diary" org-agenda-toggle-diary
4540 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4541 ["Use Time Grid" org-agenda-toggle-time-grid
4542 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4543 "--"
4544 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4545 ("Calendar Commands"
4546 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4547 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4548 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4549 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4550 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4551 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4552 "--"
4553 ["Quit" org-agenda-quit t]
4554 ["Exit and Release Buffers" org-agenda-exit t]
4557 ;;;###autoload
4558 (defun org-agenda (arg)
4559 "Dispatch agenda commands to collect entries to the agenda buffer.
4560 Prompts for a character to select a command. Any prefix arg will be passed
4561 on to the selected command. The default selections are:
4563 a Call `org-agenda' to display the agenda for the current day or week.
4564 t Call `org-todo-list' to display the global todo list.
4565 T Call `org-todo-list' to display the global todo list, select only
4566 entries with a specific TODO keyword (the user gets a prompt).
4567 m Call `org-tags-view' to display headlines with tags matching
4568 a condition (the user is prompted for the condition).
4569 M Like `m', but select only TODO entries, no ordinary headlines.
4571 More commands can be added by configuring the variable
4572 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4573 searches can be pre-defined in this way.
4575 If the current buffer is in Org-mode and visiting a file, you can also
4576 first press `1' to indicate that the agenda should be temporarily (until the
4577 next use of \\[org-agenda]) restricted to the current file."
4578 (interactive "P")
4579 (catch 'exit
4580 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
4581 (custom org-agenda-custom-commands)
4582 c entry key type string)
4583 (put 'org-agenda-files 'org-restrict nil)
4584 (save-window-excursion
4585 (delete-other-windows)
4586 (switch-to-buffer-other-window " *Agenda Commands*")
4587 (erase-buffer)
4588 (insert
4589 "Press key for an agenda command:
4590 --------------------------------
4591 a Agenda for current week or day
4592 t List of all TODO entries T Entries with special TODO kwd
4593 m Match a TAGS query M Like m, but only TODO entries
4594 C Configure your own agenda commands")
4595 (while (setq entry (pop custom))
4596 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4597 (insert (format "\n%-4s%-14s: %s"
4599 (cond
4600 ((eq type 'tags) "Tags query")
4601 ((eq type 'todo) "TODO keyword")
4602 ((eq type 'tags-tree) "Tags tree")
4603 ((eq type 'todo-tree) "TODO kwd tree")
4604 ((eq type 'occur-tree) "Occur tree")
4605 (t "???"))
4606 (org-string-props string 'face 'org-link))))
4607 (goto-char (point-min))
4608 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4609 (message "Press key for agenda command%s"
4610 (if restrict-ok ", or [1] to restrict to current file" ""))
4611 (setq c (read-char-exclusive))
4612 (message "")
4613 (when (equal c ?1)
4614 (if restrict-ok
4615 (put 'org-agenda-files 'org-restrict (list buffer-file-name))
4616 (error "Cannot restrict agenda to current buffer"))
4617 (message "Press key for agenda command%s"
4618 (if restrict-ok " (restricted to current file)" ""))
4619 (setq c (read-char-exclusive))
4620 (message "")))
4621 (require 'calendar) ; FIXME: can we avoid this for some commands?
4622 ;; For example the todo list should not need it (but does...)
4623 (cond
4624 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4625 ((equal c ?a) (call-interactively 'org-agenda-list))
4626 ((equal c ?t) (call-interactively 'org-todo-list))
4627 ((equal c ?T)
4628 (setq current-prefix-arg (or arg '(4)))
4629 (call-interactively 'org-todo-list))
4630 ((equal c ?m) (call-interactively 'org-tags-view))
4631 ((equal c ?M)
4632 (setq current-prefix-arg (or arg '(4)))
4633 (call-interactively 'org-tags-view))
4634 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4635 (setq type (nth 1 entry) string (nth 2 entry))
4636 (cond
4637 ((eq type 'tags)
4638 (org-tags-view current-prefix-arg string))
4639 ((eq type 'todo)
4640 (org-todo-list string))
4641 ((eq type 'tags-tree)
4642 (org-check-for-org-mode)
4643 (org-tags-sparse-tree current-prefix-arg string))
4644 ((eq type 'todo-tree)
4645 (org-check-for-org-mode)
4646 (org-occur (concat "^" outline-regexp "[ \t]*"
4647 (regexp-quote string) "\\>")))
4648 ((eq type 'occur-tree)
4649 (org-check-for-org-mode)
4650 (org-occur string))
4651 (t (error "Invalid custom agenda command type %s" type))))
4652 (t (error "Invalid key"))))))
4654 (defun org-check-for-org-mode ()
4655 "Make sure current buffer is in org-mode. Error if not."
4656 (or (eq major-mode 'org-mode)
4657 (error "Cannot execute org-mode agenda command on buffer in %s."
4658 major-mode)))
4660 (defun org-fit-agenda-window ()
4661 "Fit the window to the buffer size."
4662 (and org-fit-agenda-window
4663 (fboundp 'fit-window-to-buffer)
4664 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4665 (/ (frame-height) 2))))
4667 (defun org-agenda-files ()
4668 "Get the list of agenda files."
4669 (or (get 'org-agenda-files 'org-restrict)
4670 org-agenda-files))
4672 (defvar org-agenda-markers nil
4673 "List of all currently active markers created by `org-agenda'.")
4674 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4675 "Creation time of the last agenda marker.")
4677 (defun org-agenda-new-marker (&optional pos)
4678 "Return a new agenda marker.
4679 Org-mode keeps a list of these markers and resets them when they are
4680 no longer in use."
4681 (let ((m (copy-marker (or pos (point)))))
4682 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4683 (push m org-agenda-markers)
4686 (defun org-agenda-maybe-reset-markers (&optional force)
4687 "Reset markers created by `org-agenda'. But only if they are old enough."
4688 (if (or force
4689 (> (- (time-to-seconds (current-time))
4690 org-agenda-last-marker-time)
4692 (while org-agenda-markers
4693 (move-marker (pop org-agenda-markers) nil))))
4695 (defvar org-agenda-new-buffers nil
4696 "Buffers created to visit agenda files.")
4698 (defun org-get-agenda-file-buffer (file)
4699 "Get a buffer visiting FILE. If the buffer needs to be created, add
4700 it to the list of buffers which might be released later."
4701 (let ((buf (find-buffer-visiting file)))
4702 (if buf
4703 buf ; just return it
4704 ;; Make a new buffer and remember it
4705 (setq buf (find-file-noselect file))
4706 (if buf (push buf org-agenda-new-buffers))
4707 buf)))
4709 (defun org-release-buffers (blist)
4710 "Release all buffers in list, asking the user for confirmation when needed.
4711 When a buffer is unmodified, it is just killed. When modified, it is saved
4712 \(if the user agrees) and then killed."
4713 (let (buf file)
4714 (while (setq buf (pop blist))
4715 (setq file (buffer-file-name buf))
4716 (when (and (buffer-modified-p buf)
4717 file
4718 (y-or-n-p (format "Save file %s? " file)))
4719 (with-current-buffer buf (save-buffer)))
4720 (kill-buffer buf))))
4722 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4724 (defun org-timeline (&optional include-all keep-modes)
4725 "Show a time-sorted view of the entries in the current org file.
4726 Only entries with a time stamp of today or later will be listed. With
4727 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4728 under the current date.
4729 If the buffer contains an active region, only check the region for
4730 dates."
4731 (interactive "P")
4732 (require 'calendar)
4733 (org-agenda-maybe-reset-markers 'force)
4734 (org-compile-prefix-format org-timeline-prefix-format)
4735 (let* ((dopast t)
4736 (dotodo include-all)
4737 (doclosed org-agenda-show-log)
4738 (org-agenda-keep-modes keep-modes)
4739 (entry buffer-file-name)
4740 (org-agenda-files (list buffer-file-name))
4741 (date (calendar-current-date))
4742 (win (selected-window))
4743 (pos1 (point))
4744 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4745 (end (if (org-region-active-p) (region-end) (point-max)))
4746 (day-numbers (org-get-all-dates beg end 'no-ranges
4747 t doclosed)) ; always include today
4748 (today (time-to-days (current-time)))
4749 (org-respect-restriction t)
4750 (past t)
4751 args
4752 s e rtn d)
4753 (setq org-agenda-redo-command
4754 (list 'progn
4755 (list 'switch-to-buffer-other-window (current-buffer))
4756 (list 'org-timeline (list 'quote include-all) t)))
4757 (if (not dopast)
4758 ;; Remove past dates from the list of dates.
4759 (setq day-numbers (delq nil (mapcar (lambda(x)
4760 (if (>= x today) x nil))
4761 day-numbers))))
4762 (switch-to-buffer-other-window
4763 (get-buffer-create org-agenda-buffer-name))
4764 (setq buffer-read-only nil)
4765 (erase-buffer)
4766 (org-agenda-mode) (setq buffer-read-only nil)
4767 (set (make-local-variable 'org-agenda-type) 'timeline)
4768 (if doclosed (push :closed args))
4769 (push :timestamp args)
4770 (if dotodo (push :todo args))
4771 (while (setq d (pop day-numbers))
4772 (if (and (>= d today)
4773 dopast
4774 past)
4775 (progn
4776 (setq past nil)
4777 (insert (make-string 79 ?-) "\n")))
4778 (setq date (calendar-gregorian-from-absolute d))
4779 (setq s (point))
4780 (setq rtn (apply 'org-agenda-get-day-entries
4781 entry date args))
4782 (if (or rtn (equal d today))
4783 (progn
4784 (insert (calendar-day-name date) " "
4785 (number-to-string (extract-calendar-day date)) " "
4786 (calendar-month-name (extract-calendar-month date)) " "
4787 (number-to-string (extract-calendar-year date)) "\n")
4788 (put-text-property s (1- (point)) 'face
4789 'org-link)
4790 (if (equal d today)
4791 (put-text-property s (1- (point)) 'org-today t))
4792 (insert (org-finalize-agenda-entries rtn) "\n")
4793 (put-text-property s (1- (point)) 'day d))))
4794 (goto-char (point-min))
4795 (setq buffer-read-only t)
4796 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4797 (point-min)))
4798 (when (not org-select-timeline-window)
4799 (select-window win)
4800 (goto-char pos1))))
4802 ;;;###autoload
4803 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4804 "Produce a weekly view from all files in variable `org-agenda-files'.
4805 The view will be for the current week, but from the overview buffer you
4806 will be able to go to other weeks.
4807 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4808 also be shown, under the current date.
4809 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4810 on the days are also shown. See the variable `org-log-done' for how
4811 to turn on logging.
4812 START-DAY defaults to TODAY, or to the most recent match for the weekday
4813 given in `org-agenda-start-on-weekday'.
4814 NDAYS defaults to `org-agenda-ndays'."
4815 (interactive "P")
4816 (org-agenda-maybe-reset-markers 'force)
4817 (org-compile-prefix-format org-agenda-prefix-format)
4818 (require 'calendar)
4819 (let* ((org-agenda-start-on-weekday
4820 (if (or (equal ndays 1)
4821 (and (null ndays) (equal 1 org-agenda-ndays)))
4822 nil org-agenda-start-on-weekday))
4823 (org-agenda-keep-modes keep-modes)
4824 (files (copy-sequence (org-agenda-files)))
4825 (win (selected-window))
4826 (today (time-to-days (current-time)))
4827 (sd (or start-day today))
4828 (start (if (or (null org-agenda-start-on-weekday)
4829 (< org-agenda-ndays 7))
4831 (let* ((nt (calendar-day-of-week
4832 (calendar-gregorian-from-absolute sd)))
4833 (n1 org-agenda-start-on-weekday)
4834 (d (- nt n1)))
4835 (- sd (+ (if (< d 0) 7 0) d)))))
4836 (day-numbers (list start))
4837 (inhibit-redisplay t)
4838 s e rtn rtnall file date d start-pos end-pos todayp nd)
4839 (setq org-agenda-redo-command
4840 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4841 ;; Make the list of days
4842 (setq ndays (or ndays org-agenda-ndays)
4843 nd ndays)
4844 (while (> ndays 1)
4845 (push (1+ (car day-numbers)) day-numbers)
4846 (setq ndays (1- ndays)))
4847 (setq day-numbers (nreverse day-numbers))
4848 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4849 (progn
4850 (delete-other-windows)
4851 (switch-to-buffer-other-window
4852 (get-buffer-create org-agenda-buffer-name))))
4853 (setq buffer-read-only nil)
4854 (erase-buffer)
4855 (org-agenda-mode) (setq buffer-read-only nil)
4856 (set (make-local-variable 'org-agenda-type) 'agenda)
4857 (set (make-local-variable 'starting-day) (car day-numbers))
4858 (set (make-local-variable 'include-all-loc) include-all)
4859 (when (and (or include-all org-agenda-include-all-todo)
4860 (member today day-numbers))
4861 (setq files (org-agenda-files)
4862 rtnall nil)
4863 (while (setq file (pop files))
4864 (catch 'nextfile
4865 (org-check-agenda-file file)
4866 (setq date (calendar-gregorian-from-absolute today)
4867 rtn (org-agenda-get-day-entries
4868 file date :todo))
4869 (setq rtnall (append rtnall rtn))))
4870 (when rtnall
4871 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4872 (add-text-properties (point-min) (1- (point))
4873 (list 'face 'org-link))
4874 (insert (org-finalize-agenda-entries rtnall) "\n")))
4875 (while (setq d (pop day-numbers))
4876 (setq date (calendar-gregorian-from-absolute d)
4877 s (point))
4878 (if (or (setq todayp (= d today))
4879 (and (not start-pos) (= d sd)))
4880 (setq start-pos (point))
4881 (if (and start-pos (not end-pos))
4882 (setq end-pos (point))))
4883 (setq files (org-agenda-files)
4884 rtnall nil)
4885 (while (setq file (pop files))
4886 (catch 'nextfile
4887 (org-check-agenda-file file)
4888 (if org-agenda-show-log
4889 (setq rtn (org-agenda-get-day-entries
4890 file date
4891 :deadline :scheduled :timestamp :closed))
4892 (setq rtn (org-agenda-get-day-entries
4893 file date
4894 :deadline :scheduled :timestamp)))
4895 (setq rtnall (append rtnall rtn))))
4896 (if org-agenda-include-diary
4897 (progn
4898 (require 'diary-lib)
4899 (setq rtn (org-get-entries-from-diary date))
4900 (setq rtnall (append rtnall rtn))))
4901 (if (or rtnall org-agenda-show-all-dates)
4902 (progn
4903 (insert (format "%-9s %2d %s %4d\n"
4904 (calendar-day-name date)
4905 (extract-calendar-day date)
4906 (calendar-month-name (extract-calendar-month date))
4907 (extract-calendar-year date)))
4908 (put-text-property s (1- (point)) 'face
4909 'org-link)
4910 (if rtnall (insert
4911 (org-finalize-agenda-entries
4912 (org-agenda-add-time-grid-maybe
4913 rtnall nd todayp))
4914 "\n"))
4915 (put-text-property s (1- (point)) 'day d))))
4916 (goto-char (point-min))
4917 (setq buffer-read-only t)
4918 (org-fit-agenda-window)
4919 (unless (and (pos-visible-in-window-p (point-min))
4920 (pos-visible-in-window-p (point-max)))
4921 (goto-char (1- (point-max)))
4922 (recenter -1)
4923 (if (not (pos-visible-in-window-p (or start-pos 1)))
4924 (progn
4925 (goto-char (or start-pos 1))
4926 (recenter 1))))
4927 (goto-char (or start-pos 1))
4928 (if (not org-select-agenda-window) (select-window win))
4929 (message "")))
4931 (defvar org-select-this-todo-keyword nil)
4933 ;;;###autoload
4934 (defun org-todo-list (arg &optional keep-modes)
4935 "Show all TODO entries from all agenda file in a single list.
4936 The prefix arg can be used to select a specific TODO keyword and limit
4937 the list to these. When using \\[universal-argument], you will be prompted
4938 for a keyword. A numeric prefix directly selects the Nth keyword in
4939 `org-todo-keywords'."
4940 (interactive "P")
4941 (org-agenda-maybe-reset-markers 'force)
4942 (org-compile-prefix-format org-agenda-prefix-format)
4943 (let* ((org-agenda-keep-modes keep-modes)
4944 (today (time-to-days (current-time)))
4945 (date (calendar-gregorian-from-absolute today))
4946 (win (selected-window))
4947 (kwds org-todo-keywords)
4948 (completion-ignore-case t)
4949 (org-select-this-todo-keyword
4950 (if (stringp arg) arg
4951 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
4952 rtn rtnall files file pos)
4953 (when (equal arg '(4))
4954 (setq org-select-this-todo-keyword
4955 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
4956 nil t)))
4957 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
4958 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4959 (progn
4960 (delete-other-windows)
4961 (switch-to-buffer-other-window
4962 (get-buffer-create org-agenda-buffer-name))))
4963 (setq buffer-read-only nil)
4964 (erase-buffer)
4965 (org-agenda-mode) (setq buffer-read-only nil)
4966 (set (make-local-variable 'org-agenda-type) 'todo)
4967 (set (make-local-variable 'last-arg) arg)
4968 (set (make-local-variable 'org-todo-keywords) kwds)
4969 (set (make-local-variable 'org-agenda-redo-command)
4970 '(org-todo-list (or current-prefix-arg last-arg) t))
4971 (setq files (org-agenda-files)
4972 rtnall nil)
4973 (while (setq file (pop files))
4974 (catch 'nextfile
4975 (org-check-agenda-file file)
4976 (setq rtn (org-agenda-get-day-entries file date :todo))
4977 (setq rtnall (append rtnall rtn))))
4978 (insert "Global list of TODO items of type: ")
4979 (add-text-properties (point-min) (1- (point))
4980 (list 'face 'org-link))
4981 (setq pos (point))
4982 (insert (or org-select-this-todo-keyword "ALL") "\n")
4983 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
4984 (setq pos (point))
4985 (insert
4986 "Available with `N r': (0)ALL "
4987 (let ((n 0))
4988 (mapconcat (lambda (x)
4989 (format "(%d)%s" (setq n (1+ n)) x))
4990 org-todo-keywords " "))
4991 "\n")
4992 (add-text-properties pos (1- (point)) (list 'face 'org-link))
4993 (when rtnall
4994 (insert (org-finalize-agenda-entries rtnall) "\n"))
4995 (goto-char (point-min))
4996 (setq buffer-read-only t)
4997 (org-fit-agenda-window)
4998 (if (not org-select-agenda-window) (select-window win))))
5000 (defun org-check-agenda-file (file)
5001 "Make sure FILE exists. If not, ask user what to do."
5002 ;; FIXME: this does not correctly change the menus
5003 ;; Could probably be fixed by explicitly going to the buffer where
5004 ;; the call originated.
5005 (when (not (file-exists-p file))
5006 (message "non-existent file %s. [R]emove from agenda-files or [A]bort?"
5007 file)
5008 (let ((r (downcase (read-char-exclusive))))
5009 (cond
5010 ((equal r ?r)
5011 (org-remove-file file)
5012 (throw 'nextfile t))
5013 (t (error "Abort"))))))
5015 (defun org-agenda-check-type (error &rest types)
5016 "Check if agenda buffer is of allowed type.
5017 If ERROR is non-nil, throw an error, otherwise just return nil."
5018 (if (memq org-agenda-type types)
5020 (if error
5021 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
5022 nil)))
5024 (defun org-agenda-quit ()
5025 "Exit agenda by removing the window or the buffer."
5026 (interactive)
5027 (let ((buf (current-buffer)))
5028 (if (not (one-window-p)) (delete-window))
5029 (kill-buffer buf)
5030 (org-agenda-maybe-reset-markers 'force)))
5032 (defun org-agenda-exit ()
5033 "Exit agenda by removing the window or the buffer.
5034 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
5035 Org-mode buffers visited directly by the user will not be touched."
5036 (interactive)
5037 (org-release-buffers org-agenda-new-buffers)
5038 (setq org-agenda-new-buffers nil)
5039 (org-agenda-quit))
5041 (defun org-agenda-redo ()
5042 "Rebuild Agenda.
5043 When this is the global TODO list, a prefix argument will be interpreted."
5044 (interactive)
5045 (message "Rebuilding agenda buffer...")
5046 (eval org-agenda-redo-command)
5047 (message "Rebuilding agenda buffer...done"))
5049 (defun org-agenda-goto-today ()
5050 "Go to today."
5051 (interactive)
5052 (org-agenda-check-type t 'timeline 'agenda)
5053 (if (boundp 'starting-day)
5054 (let ((cmd (car org-agenda-redo-command))
5055 (iall (nth 1 org-agenda-redo-command))
5056 (nday (nth 3 org-agenda-redo-command))
5057 (keep (nth 4 org-agenda-redo-command)))
5058 (eval (list cmd iall nil nday keep)))
5059 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5060 (point-min)))))
5062 (defun org-agenda-later (arg)
5063 "Go forward in time by `org-agenda-ndays' days.
5064 With prefix ARG, go forward that many times `org-agenda-ndays'."
5065 (interactive "p")
5066 (org-agenda-check-type t 'agenda)
5067 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5068 (+ starting-day (* arg org-agenda-ndays)) nil t))
5070 (defun org-agenda-earlier (arg)
5071 "Go back in time by `org-agenda-ndays' days.
5072 With prefix ARG, go back that many times `org-agenda-ndays'."
5073 (interactive "p")
5074 (org-agenda-check-type t 'agenda)
5075 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5076 (- starting-day (* arg org-agenda-ndays)) nil t))
5078 (defun org-agenda-week-view ()
5079 "Switch to weekly view for agenda."
5080 (interactive)
5081 (org-agenda-check-type t 'agenda)
5082 (setq org-agenda-ndays 7)
5083 (org-agenda-list include-all-loc
5084 (or (get-text-property (point) 'day)
5085 starting-day)
5086 nil t)
5087 (org-agenda-set-mode-name)
5088 (message "Switched to week view"))
5090 (defun org-agenda-day-view ()
5091 "Switch to daily view for agenda."
5092 (interactive)
5093 (org-agenda-check-type t 'agenda)
5094 (setq org-agenda-ndays 1)
5095 (org-agenda-list include-all-loc
5096 (or (get-text-property (point) 'day)
5097 starting-day)
5098 nil t)
5099 (org-agenda-set-mode-name)
5100 (message "Switched to day view"))
5102 (defun org-agenda-next-date-line (&optional arg)
5103 "Jump to the next line indicating a date in agenda buffer."
5104 (interactive "p")
5105 (org-agenda-check-type t 'agenda 'timeline)
5106 (beginning-of-line 1)
5107 (if (looking-at "^\\S-") (forward-char 1))
5108 (if (not (re-search-forward "^\\S-" nil t arg))
5109 (progn
5110 (backward-char 1)
5111 (error "No next date after this line in this buffer")))
5112 (goto-char (match-beginning 0)))
5114 (defun org-agenda-previous-date-line (&optional arg)
5115 "Jump to the previous line indicating a date in agenda buffer."
5116 (interactive "p")
5117 (org-agenda-check-type t 'agenda 'timeline)
5118 (beginning-of-line 1)
5119 (if (not (re-search-backward "^\\S-" nil t arg))
5120 (error "No previous date before this line in this buffer")))
5122 ;; Initialize the highlight
5123 (defvar org-hl (org-make-overlay 1 1))
5124 (org-overlay-put org-hl 'face 'highlight)
5126 (defun org-highlight (begin end &optional buffer)
5127 "Highlight a region with overlay."
5128 (funcall (if org-xemacs-p 'set-extent-endpoints 'move-overlay)
5129 org-hl begin end (or buffer (current-buffer))))
5131 (defun org-unhighlight ()
5132 "Detach overlay INDEX."
5133 (funcall (if org-xemacs-p 'detach-extent 'delete-overlay) org-hl))
5136 (defun org-agenda-follow-mode ()
5137 "Toggle follow mode in an agenda buffer."
5138 (interactive)
5139 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5140 (org-agenda-set-mode-name)
5141 (message "Follow mode is %s"
5142 (if org-agenda-follow-mode "on" "off")))
5144 (defun org-agenda-log-mode ()
5145 "Toggle log mode in an agenda buffer."
5146 (interactive)
5147 (org-agenda-check-type t 'agenda 'timeline)
5148 (setq org-agenda-show-log (not org-agenda-show-log))
5149 (org-agenda-set-mode-name)
5150 (org-agenda-redo)
5151 (message "Log mode is %s"
5152 (if org-agenda-show-log "on" "off")))
5154 (defun org-agenda-toggle-diary ()
5155 "Toggle diary inclusion in an agenda buffer."
5156 (interactive)
5157 (org-agenda-check-type t 'agenda)
5158 (setq org-agenda-include-diary (not org-agenda-include-diary))
5159 (org-agenda-redo)
5160 (org-agenda-set-mode-name)
5161 (message "Diary inclusion turned %s"
5162 (if org-agenda-include-diary "on" "off")))
5164 (defun org-agenda-toggle-time-grid ()
5165 "Toggle time grid in an agenda buffer."
5166 (interactive)
5167 (org-agenda-check-type t 'agenda)
5168 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5169 (org-agenda-redo)
5170 (org-agenda-set-mode-name)
5171 (message "Time-grid turned %s"
5172 (if org-agenda-use-time-grid "on" "off")))
5174 (defun org-agenda-set-mode-name ()
5175 "Set the mode name to indicate all the small mode settings."
5176 (setq mode-name
5177 (concat "Org-Agenda"
5178 (if (equal org-agenda-ndays 1) " Day" "")
5179 (if (equal org-agenda-ndays 7) " Week" "")
5180 (if org-agenda-follow-mode " Follow" "")
5181 (if org-agenda-include-diary " Diary" "")
5182 (if org-agenda-use-time-grid " Grid" "")
5183 (if org-agenda-show-log " Log" "")))
5184 (force-mode-line-update))
5186 (defun org-agenda-post-command-hook ()
5187 (and (eolp) (not (bolp)) (backward-char 1))
5188 (if (and org-agenda-follow-mode
5189 (get-text-property (point) 'org-marker))
5190 (org-agenda-show)))
5192 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5194 (defun org-get-entries-from-diary (date)
5195 "Get the (Emacs Calendar) diary entries for DATE."
5196 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5197 (diary-display-hook '(fancy-diary-display))
5198 (list-diary-entries-hook
5199 (cons 'org-diary-default-entry list-diary-entries-hook))
5200 (diary-file-name-prefix-function nil) ; turn this feature off
5201 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5202 entries
5203 (org-disable-agenda-to-diary t))
5204 (save-excursion
5205 (save-window-excursion
5206 (list-diary-entries date 1)))
5207 (if (not (get-buffer fancy-diary-buffer))
5208 (setq entries nil)
5209 (with-current-buffer fancy-diary-buffer
5210 (setq buffer-read-only nil)
5211 (if (= (point-max) 1)
5212 ;; No entries
5213 (setq entries nil)
5214 ;; Omit the date and other unnecessary stuff
5215 (org-agenda-cleanup-fancy-diary)
5216 ;; Add prefix to each line and extend the text properties
5217 (if (= (point-max) 1)
5218 (setq entries nil)
5219 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5220 (set-buffer-modified-p nil)
5221 (kill-buffer fancy-diary-buffer)))
5222 (when entries
5223 (setq entries (org-split-string entries "\n"))
5224 (setq entries
5225 (mapcar
5226 (lambda (x)
5227 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5228 ;; Extend the text properties to the beginning of the line
5229 (add-text-properties
5230 0 (length x)
5231 (text-properties-at (1- (length x)) x)
5234 entries)))))
5236 (defun org-agenda-cleanup-fancy-diary ()
5237 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5238 This gets rid of the date, the underline under the date, and
5239 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5240 date. It also removes lines that contain only whitespace."
5241 (goto-char (point-min))
5242 (if (looking-at ".*?:[ \t]*")
5243 (progn
5244 (replace-match "")
5245 (re-search-forward "\n=+$" nil t)
5246 (replace-match "")
5247 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5248 (re-search-forward "\n=+$" nil t)
5249 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5250 (goto-char (point-min))
5251 (while (re-search-forward "^ +\n" nil t)
5252 (replace-match ""))
5253 (goto-char (point-min))
5254 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5255 (replace-match "")))
5257 ;; Make sure entries from the diary have the right text properties.
5258 (eval-after-load "diary-lib"
5259 '(if (boundp 'diary-modify-entry-list-string-function)
5260 ;; We can rely on the hook, nothing to do
5262 ;; Hook not avaiable, must use advice to make this work
5263 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5264 "Make the position visible."
5265 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5266 (stringp string)
5267 buffer-file-name)
5268 (setq string (org-modify-diary-entry-string string))))))
5270 (defun org-modify-diary-entry-string (string)
5271 "Add text properties to string, allowing org-mode to act on it."
5272 (add-text-properties
5273 0 (length string)
5274 (list 'mouse-face 'highlight
5275 'keymap org-agenda-keymap
5276 'help-echo
5277 (format
5278 "mouse-2 or RET jump to diary file %s"
5279 (abbreviate-file-name buffer-file-name))
5280 'org-agenda-diary-link t
5281 'org-marker (org-agenda-new-marker (point-at-bol)))
5282 string)
5283 string)
5285 (defun org-diary-default-entry ()
5286 "Add a dummy entry to the diary.
5287 Needed to avoid empty dates which mess up holiday display."
5288 ;; Catch the error if dealing with the new add-to-diary-alist
5289 (when org-disable-agenda-to-diary
5290 (condition-case nil
5291 (add-to-diary-list original-date "Org-mode dummy" "")
5292 (error
5293 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5295 (defun org-cycle-agenda-files ()
5296 "Cycle through the files in `org-agenda-files'.
5297 If the current buffer visits an agenda file, find the next one in the list.
5298 If the current buffer does not, find the first agenda file."
5299 (interactive)
5300 (let ((files (append org-agenda-files (list (car org-agenda-files))))
5301 (tcf (if buffer-file-name (file-truename buffer-file-name)))
5302 file)
5303 (unless files (error "No agenda files"))
5304 (catch 'exit
5305 (while (setq file (pop files))
5306 (if (equal (file-truename file) tcf)
5307 (when (car files)
5308 (find-file (car files))
5309 (throw 'exit t))))
5310 (find-file (car org-agenda-files)))))
5312 (defun org-agenda-file-to-end ()
5313 "Move/add the current file to the end of the agenda file list.
5314 If the file is not present in the list, it is appended to the list. If it is
5315 present, it is moved there."
5316 (interactive)
5317 (org-agenda-file-to-front 'to-end))
5319 (defun org-agenda-file-to-front (&optional to-end)
5320 "Move/add the current file to the top of the agenda file list.
5321 If the file is not present in the list, it is added to the front. If it is
5322 present, it is moved there. With optional argument TO-END, add/move to the
5323 end of the list."
5324 (interactive "P")
5325 (let ((file-alist (mapcar (lambda (x)
5326 (cons (file-truename x) x))
5327 org-agenda-files))
5328 (ctf (file-truename buffer-file-name))
5329 x had)
5330 (setq x (assoc ctf file-alist) had x)
5332 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
5333 (if to-end
5334 (setq file-alist (append (delq x file-alist) (list x)))
5335 (setq file-alist (cons x (delq x file-alist))))
5336 (setq org-agenda-files (mapcar 'cdr file-alist))
5337 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5338 (customize-save-variable 'org-agenda-files org-agenda-files))
5339 (org-install-agenda-files-menu)
5340 (message "File %s to %s of agenda file list"
5341 (if had "moved" "added") (if to-end "end" "front"))))
5343 (defun org-remove-file (&optional file)
5344 "Remove current file from the list of files in variable `org-agenda-files'.
5345 These are the files which are being checked for agenda entries.
5346 Optional argument FILE means, use this file instead of the current."
5347 (interactive)
5348 (let* ((file (or file buffer-file-name))
5349 (true-file (file-truename file))
5350 (afile (abbreviate-file-name file))
5351 (files (delq nil (mapcar
5352 (lambda (x)
5353 (if (equal true-file
5354 (file-truename x))
5355 nil x))
5356 org-agenda-files))))
5357 (if (not (= (length files) (length org-agenda-files)))
5358 (progn
5359 (setq org-agenda-files files)
5360 (customize-save-variable 'org-agenda-files org-agenda-files)
5361 (org-install-agenda-files-menu)
5362 (message "Removed file: %s" afile))
5363 (message "File was not in list: %s" afile))))
5365 (defun org-file-menu-entry (file)
5366 (vector file (list 'find-file file) t))
5367 ;; FIXME: Maybe we removed a buffer visited through the menu from
5368 ;; org-agenda-new-buffers, so that the buffer will not be removed
5369 ;; when exiting the agenda????
5371 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5372 "Return a list of all relevant day numbers from BEG to END buffer positions.
5373 If NO-RANGES is non-nil, include only the start and end dates of a range,
5374 not every single day in the range. If FORCE-TODAY is non-nil, make
5375 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5376 inactive time stamps (those in square brackets) are included."
5377 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5378 dates date day day1 day2 ts1 ts2)
5379 (if force-today
5380 (setq dates (list (time-to-days (current-time)))))
5381 (save-excursion
5382 (goto-char beg)
5383 (while (re-search-forward re end t)
5384 (setq day (time-to-days (org-time-string-to-time
5385 (substring (match-string 1) 0 10))))
5386 (or (memq day dates) (push day dates)))
5387 (unless no-ranges
5388 (goto-char beg)
5389 (while (re-search-forward org-tr-regexp end t)
5390 (setq ts1 (substring (match-string 1) 0 10)
5391 ts2 (substring (match-string 2) 0 10)
5392 day1 (time-to-days (org-time-string-to-time ts1))
5393 day2 (time-to-days (org-time-string-to-time ts2)))
5394 (while (< (setq day1 (1+ day1)) day2)
5395 (or (memq day1 dates) (push day1 dates)))))
5396 (sort dates '<))))
5398 ;;;###autoload
5399 (defun org-diary (&rest args)
5400 "Return diary information from org-files.
5401 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5402 It accesses org files and extracts information from those files to be
5403 listed in the diary. The function accepts arguments specifying what
5404 items should be listed. The following arguments are allowed:
5406 :timestamp List the headlines of items containing a date stamp or
5407 date range matching the selected date. Deadlines will
5408 also be listed, on the expiration day.
5410 :deadline List any deadlines past due, or due within
5411 `org-deadline-warning-days'. The listing occurs only
5412 in the diary for *today*, not at any other date. If
5413 an entry is marked DONE, it is no longer listed.
5415 :scheduled List all items which are scheduled for the given date.
5416 The diary for *today* also contains items which were
5417 scheduled earlier and are not yet marked DONE.
5419 :todo List all TODO items from the org-file. This may be a
5420 long list - so this is not turned on by default.
5421 Like deadlines, these entries only show up in the
5422 diary for *today*, not at any other date.
5424 The call in the diary file should look like this:
5426 &%%(org-diary) ~/path/to/some/orgfile.org
5428 Use a separate line for each org file to check. Or, if you omit the file name,
5429 all files listed in `org-agenda-files' will be checked automatically:
5431 &%%(org-diary)
5433 If you don't give any arguments (as in the example above), the default
5434 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5435 also be written as
5437 &%%(org-diary :deadline :timestamp :scheduled)
5439 The function expects the lisp variables `entry' and `date' to be provided
5440 by the caller, because this is how the calendar works. Don't use this
5441 function from a program - use `org-agenda-get-day-entries' instead."
5442 (org-agenda-maybe-reset-markers)
5443 (org-compile-prefix-format org-agenda-prefix-format)
5444 (setq args (or args '(:deadline :scheduled :timestamp)))
5445 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5446 (list entry)
5447 org-agenda-files))
5448 file rtn results)
5449 ;; If this is called during org-agenda, don't return any entries to
5450 ;; the calendar. Org Agenda will list these entries itself.
5451 (if org-disable-agenda-to-diary (setq files nil))
5452 (while (setq file (pop files))
5453 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5454 (setq results (append results rtn)))
5455 (if results
5456 (concat (org-finalize-agenda-entries results) "\n"))))
5457 (defvar org-category-table nil)
5458 (defun org-get-category-table ()
5459 "Get the table of categories and positions in current buffer."
5460 (let (tbl)
5461 (save-excursion
5462 (goto-char (point-min))
5463 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5464 (push (cons (point) (org-trim (match-string 2))) tbl)))
5465 tbl))
5466 (defun org-get-category (&optional pos)
5467 "Get the category applying to position POS."
5468 (if (not org-category-table)
5469 (cond
5470 ((null org-category)
5471 (setq org-category
5472 (if buffer-file-name
5473 (file-name-sans-extension
5474 (file-name-nondirectory buffer-file-name))
5475 "???")))
5476 ((symbolp org-category) (symbol-name org-category))
5477 (t org-category))
5478 (let ((tbl org-category-table)
5479 (pos (or pos (point))))
5480 (while (and tbl (> (caar tbl) pos))
5481 (pop tbl))
5482 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5483 org-category-table))))))
5485 (defun org-agenda-get-day-entries (file date &rest args)
5486 "Does the work for `org-diary' and `org-agenda'.
5487 FILE is the path to a file to be checked for entries. DATE is date like
5488 the one returned by `calendar-current-date'. ARGS are symbols indicating
5489 which kind of entries should be extracted. For details about these, see
5490 the documentation of `org-diary'."
5491 (setq args (or args '(:deadline :scheduled :timestamp)))
5492 (let* ((org-startup-with-deadline-check nil)
5493 (org-startup-folded nil)
5494 (buffer (if (file-exists-p file)
5495 (org-get-agenda-file-buffer file)
5496 (error "No such file %s" file)))
5497 arg results rtn)
5498 (if (not buffer)
5499 ;; If file does not exist, make sure an error message ends up in diary
5500 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5501 (with-current-buffer buffer
5502 (unless (eq major-mode 'org-mode)
5503 (error "Agenda file %s is not in `org-mode'" file))
5504 (setq org-category-table (org-get-category-table))
5505 (let ((case-fold-search nil))
5506 (save-excursion
5507 (save-restriction
5508 (if org-respect-restriction
5509 (if (org-region-active-p)
5510 ;; Respect a region to restrict search
5511 (narrow-to-region (region-beginning) (region-end)))
5512 ;; If we work for the calendar or many files,
5513 ;; get rid of any restriction
5514 (widen))
5515 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5516 (while (setq arg (pop args))
5517 (cond
5518 ((and (eq arg :todo)
5519 (equal date (calendar-current-date)))
5520 (setq rtn (org-agenda-get-todos))
5521 (setq results (append results rtn)))
5522 ((eq arg :timestamp)
5523 (setq rtn (org-agenda-get-blocks))
5524 (setq results (append results rtn))
5525 (setq rtn (org-agenda-get-timestamps))
5526 (setq results (append results rtn)))
5527 ((eq arg :scheduled)
5528 (setq rtn (org-agenda-get-scheduled))
5529 (setq results (append results rtn)))
5530 ((eq arg :closed)
5531 (setq rtn (org-agenda-get-closed))
5532 (setq results (append results rtn)))
5533 ((and (eq arg :deadline)
5534 (equal date (calendar-current-date)))
5535 (setq rtn (org-agenda-get-deadlines))
5536 (setq results (append results rtn))))))))
5537 results))))
5539 (defun org-entry-is-done-p ()
5540 "Is the current entry marked DONE?"
5541 (save-excursion
5542 (and (re-search-backward "[\r\n]\\*" nil t)
5543 (looking-at org-nl-done-regexp))))
5545 (defun org-at-date-range-p ()
5546 "Is the cursor inside a date range?"
5547 (interactive)
5548 (save-excursion
5549 (catch 'exit
5550 (let ((pos (point)))
5551 (skip-chars-backward "^<\r\n")
5552 (skip-chars-backward "<")
5553 (and (looking-at org-tr-regexp)
5554 (>= (match-end 0) pos)
5555 (throw 'exit t))
5556 (skip-chars-backward "^<\r\n")
5557 (skip-chars-backward "<")
5558 (and (looking-at org-tr-regexp)
5559 (>= (match-end 0) pos)
5560 (throw 'exit t)))
5561 nil)))
5563 (defun org-agenda-get-todos ()
5564 "Return the TODO information for agenda display."
5565 (let* ((props (list 'face nil
5566 'done-face 'org-done
5567 'mouse-face 'highlight
5568 'keymap org-agenda-keymap
5569 'help-echo
5570 (format "mouse-2 or RET jump to org file %s"
5571 (abbreviate-file-name buffer-file-name))))
5572 (regexp (concat "[\n\r]\\*+ *\\("
5573 (if org-select-this-todo-keyword
5574 (concat "\\<\\(" org-select-this-todo-keyword
5575 "\\)\\>")
5576 org-not-done-regexp)
5577 "[^\n\r]*\\)"))
5578 marker priority category tags
5579 ee txt)
5580 (goto-char (point-min))
5581 (while (re-search-forward regexp nil t)
5582 (goto-char (match-beginning 1))
5583 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5584 category (org-get-category)
5585 tags (org-get-tags-at (point))
5586 txt (org-format-agenda-item "" (match-string 1) category tags)
5587 priority
5588 (+ (org-get-priority txt)
5589 (if org-todo-kwd-priority-p
5590 (- org-todo-kwd-max-priority -2
5591 (length
5592 (member (match-string 2) org-todo-keywords)))
5593 1)))
5594 (add-text-properties
5595 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5596 'priority priority 'category category)
5597 props)
5598 txt)
5599 (push txt ee)
5600 (goto-char (match-end 1)))
5601 (nreverse ee)))
5603 (defconst org-agenda-no-heading-message
5604 "No heading for this item in buffer or region.")
5606 (defun org-agenda-get-timestamps ()
5607 "Return the date stamp information for agenda display."
5608 (let* ((props (list 'face nil
5609 'mouse-face 'highlight
5610 'keymap org-agenda-keymap
5611 'help-echo
5612 (format "mouse-2 or RET jump to org file %s"
5613 (abbreviate-file-name buffer-file-name))))
5614 (regexp (regexp-quote
5615 (substring
5616 (format-time-string
5617 (car org-time-stamp-formats)
5618 (apply 'encode-time ; DATE bound by calendar
5619 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5620 0 11)))
5621 marker hdmarker deadlinep scheduledp donep tmp priority category
5622 ee txt timestr tags)
5623 (goto-char (point-min))
5624 (while (re-search-forward regexp nil t)
5625 (if (not (save-match-data (org-at-date-range-p)))
5626 (progn
5627 (setq marker (org-agenda-new-marker (match-beginning 0))
5628 category (org-get-category (match-beginning 0))
5629 tmp (buffer-substring (max (point-min)
5630 (- (match-beginning 0)
5631 org-ds-keyword-length))
5632 (match-beginning 0))
5633 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5634 deadlinep (string-match org-deadline-regexp tmp)
5635 scheduledp (string-match org-scheduled-regexp tmp)
5636 donep (org-entry-is-done-p))
5637 (if (string-match ">" timestr)
5638 ;; substring should only run to end of time stamp
5639 (setq timestr (substring timestr 0 (match-end 0))))
5640 (save-excursion
5641 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5642 (progn
5643 (goto-char (match-end 1))
5644 (setq hdmarker (org-agenda-new-marker)
5645 tags (org-get-tags-at))
5646 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5647 (setq txt (org-format-agenda-item
5648 (format "%s%s"
5649 (if deadlinep "Deadline: " "")
5650 (if scheduledp "Scheduled: " ""))
5651 (match-string 1) category tags timestr)))
5652 (setq txt org-agenda-no-heading-message))
5653 (setq priority (org-get-priority txt))
5654 (add-text-properties
5655 0 (length txt) (append (list 'org-marker marker
5656 'org-hd-marker hdmarker) props)
5657 txt)
5658 (if deadlinep
5659 (add-text-properties
5660 0 (length txt)
5661 (list 'face
5662 (if donep 'org-done 'org-warning)
5663 'undone-face 'org-warning
5664 'done-face 'org-done
5665 'category category
5666 'priority (+ 100 priority))
5667 txt)
5668 (if scheduledp
5669 (add-text-properties
5670 0 (length txt)
5671 (list 'face 'org-scheduled-today
5672 'undone-face 'org-scheduled-today
5673 'done-face 'org-done
5674 'category category
5675 priority (+ 99 priority))
5676 txt)
5677 (add-text-properties
5678 0 (length txt)
5679 (list 'priority priority 'category category) txt)))
5680 (push txt ee))
5681 (outline-next-heading))))
5682 (nreverse ee)))
5684 (defun org-agenda-get-closed ()
5685 "Return the logged TODO entries for agenda display."
5686 (let* ((props (list 'mouse-face 'highlight
5687 'keymap org-agenda-keymap
5688 'help-echo
5689 (format "mouse-2 or RET jump to org file %s"
5690 (abbreviate-file-name buffer-file-name))))
5691 (regexp (concat
5692 "\\<" org-closed-string " *\\["
5693 (regexp-quote
5694 (substring
5695 (format-time-string
5696 (car org-time-stamp-formats)
5697 (apply 'encode-time ; DATE bound by calendar
5698 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5699 1 11))))
5700 marker hdmarker priority category tags
5701 ee txt timestr)
5702 (goto-char (point-min))
5703 (while (re-search-forward regexp nil t)
5704 (if (not (save-match-data (org-at-date-range-p)))
5705 (progn
5706 (setq marker (org-agenda-new-marker (match-beginning 0))
5707 category (org-get-category (match-beginning 0))
5708 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5709 ;; donep (org-entry-is-done-p)
5711 (if (string-match "\\]" timestr)
5712 ;; substring should only run to end of time stamp
5713 (setq timestr (substring timestr 0 (match-end 0))))
5714 (save-excursion
5715 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5716 (progn
5717 (goto-char (match-end 1))
5718 (setq hdmarker (org-agenda-new-marker)
5719 tags (org-get-tags-at))
5720 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5721 (setq txt (org-format-agenda-item
5722 "Closed: "
5723 (match-string 1) category tags timestr)))
5724 (setq txt org-agenda-no-heading-message))
5725 (setq priority 100000)
5726 (add-text-properties
5727 0 (length txt) (append (list 'org-marker marker
5728 'org-hd-marker hdmarker
5729 'face 'org-done
5730 'priority priority
5731 'category category
5732 'undone-face 'org-warning
5733 'done-face 'org-done) props)
5734 txt)
5735 (push txt ee))
5736 (outline-next-heading))))
5737 (nreverse ee)))
5739 (defun org-agenda-get-deadlines ()
5740 "Return the deadline information for agenda display."
5741 (let* ((wdays org-deadline-warning-days)
5742 (props (list 'mouse-face 'highlight
5743 'keymap org-agenda-keymap
5744 'help-echo
5745 (format "mouse-2 or RET jump to org file %s"
5746 (abbreviate-file-name buffer-file-name))))
5747 (regexp org-deadline-time-regexp)
5748 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5749 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5750 d2 diff pos pos1 category tags
5751 ee txt head)
5752 (goto-char (point-min))
5753 (while (re-search-forward regexp nil t)
5754 (setq pos (1- (match-beginning 1))
5755 d2 (time-to-days
5756 (org-time-string-to-time (match-string 1)))
5757 diff (- d2 d1))
5758 ;; When to show a deadline in the calendar:
5759 ;; If the expiration is within wdays warning time.
5760 ;; Past-due deadlines are only shown on the current date
5761 (if (and (< diff wdays) todayp (not (= diff 0)))
5762 (save-excursion
5763 (setq category (org-get-category))
5764 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5765 (progn
5766 (goto-char (match-end 0))
5767 (setq pos1 (match-end 1))
5768 (setq tags (org-get-tags-at pos1))
5769 (setq head (buffer-substring-no-properties
5770 (point)
5771 (progn (skip-chars-forward "^\r\n")
5772 (point))))
5773 (if (string-match org-looking-at-done-regexp head)
5774 (setq txt nil)
5775 (setq txt (org-format-agenda-item
5776 (format "In %3d d.: " diff) head category tags))))
5777 (setq txt org-agenda-no-heading-message))
5778 (when txt
5779 (add-text-properties
5780 0 (length txt)
5781 (append
5782 (list 'org-marker (org-agenda-new-marker pos)
5783 'org-hd-marker (org-agenda-new-marker pos1)
5784 'priority (+ (- 10 diff) (org-get-priority txt))
5785 'category category
5786 'face (cond ((<= diff 0) 'org-warning)
5787 ((<= diff 5) 'org-scheduled-previously)
5788 (t nil))
5789 'undone-face (cond
5790 ((<= diff 0) 'org-warning)
5791 ((<= diff 5) 'org-scheduled-previously)
5792 (t nil))
5793 'done-face 'org-done)
5794 props)
5795 txt)
5796 (push txt ee)))))
5797 ee))
5799 (defun org-agenda-get-scheduled ()
5800 "Return the scheduled information for agenda display."
5801 (let* ((props (list 'face 'org-scheduled-previously
5802 'undone-face 'org-scheduled-previously
5803 'done-face 'org-done
5804 'mouse-face 'highlight
5805 'keymap org-agenda-keymap
5806 'help-echo
5807 (format "mouse-2 or RET jump to org file %s"
5808 (abbreviate-file-name buffer-file-name))))
5809 (regexp org-scheduled-time-regexp)
5810 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5811 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5812 d2 diff pos pos1 category tags
5813 ee txt head)
5814 (goto-char (point-min))
5815 (while (re-search-forward regexp nil t)
5816 (setq pos (1- (match-beginning 1))
5817 d2 (time-to-days
5818 (org-time-string-to-time (match-string 1)))
5819 diff (- d2 d1))
5820 ;; When to show a scheduled item in the calendar:
5821 ;; If it is on or past the date.
5822 (if (and (< diff 0) todayp)
5823 (save-excursion
5824 (setq category (org-get-category))
5825 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5826 (progn
5827 (goto-char (match-end 0))
5828 (setq pos1 (match-end 1))
5829 (setq tags (org-get-tags-at))
5830 (setq head (buffer-substring-no-properties
5831 (point)
5832 (progn (skip-chars-forward "^\r\n") (point))))
5833 (if (string-match org-looking-at-done-regexp head)
5834 (setq txt nil)
5835 (setq txt (org-format-agenda-item
5836 (format "Sched.%2dx: " (- 1 diff)) head
5837 category tags))))
5838 (setq txt org-agenda-no-heading-message))
5839 (when txt
5840 (add-text-properties
5841 0 (length txt)
5842 (append (list 'org-marker (org-agenda-new-marker pos)
5843 'org-hd-marker (org-agenda-new-marker pos1)
5844 'priority (+ (- 5 diff) (org-get-priority txt))
5845 'category category)
5846 props) txt)
5847 (push txt ee)))))
5848 ee))
5850 (defun org-agenda-get-blocks ()
5851 "Return the date-range information for agenda display."
5852 (let* ((props (list 'face nil
5853 'mouse-face 'highlight
5854 'keymap org-agenda-keymap
5855 'help-echo
5856 (format "mouse-2 or RET jump to org file %s"
5857 (abbreviate-file-name buffer-file-name))))
5858 (regexp org-tr-regexp)
5859 (d0 (calendar-absolute-from-gregorian date))
5860 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
5861 (goto-char (point-min))
5862 (while (re-search-forward regexp nil t)
5863 (setq timestr (match-string 0)
5864 s1 (match-string 1)
5865 s2 (match-string 2)
5866 d1 (time-to-days (org-time-string-to-time s1))
5867 d2 (time-to-days (org-time-string-to-time s2)))
5868 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5869 ;; Only allow days between the limits, because the normal
5870 ;; date stamps will catch the limits.
5871 (save-excursion
5872 (setq marker (org-agenda-new-marker (point)))
5873 (setq category (org-get-category))
5874 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5875 (progn
5876 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5877 (goto-char (match-end 1))
5878 (setq tags (org-get-tags-at))
5879 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5880 (setq txt (org-format-agenda-item
5881 (format (if (= d1 d2) "" "(%d/%d): ")
5882 (1+ (- d0 d1)) (1+ (- d2 d1)))
5883 (match-string 1) category tags
5884 (if (= d0 d1) timestr))))
5885 (setq txt org-agenda-no-heading-message))
5886 (add-text-properties
5887 0 (length txt) (append (list 'org-marker marker
5888 'org-hd-marker hdmarker
5889 'priority (org-get-priority txt)
5890 'category category)
5891 props)
5892 txt)
5893 (push txt ee)))
5894 (outline-next-heading))
5895 ;; Sort the entries by expiration date.
5896 (nreverse ee)))
5898 (defconst org-plain-time-of-day-regexp
5899 (concat
5900 "\\(\\<[012]?[0-9]"
5901 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5902 "\\(--?"
5903 "\\(\\<[012]?[0-9]"
5904 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5905 "\\)?")
5906 "Regular expression to match a plain time or time range.
5907 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5908 groups carry important information:
5909 0 the full match
5910 1 the first time, range or not
5911 8 the second time, if it is a range.")
5913 (defconst org-stamp-time-of-day-regexp
5914 (concat
5915 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5916 "\\([012][0-9]:[0-5][0-9]\\)>"
5917 "\\(--?"
5918 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5919 "Regular expression to match a timestamp time or time range.
5920 After a match, the following groups carry important information:
5921 0 the full match
5922 1 date plus weekday, for backreferencing to make sure both times on same day
5923 2 the first time, range or not
5924 4 the second time, if it is a range.")
5926 (defvar org-prefix-has-time nil
5927 "A flag, set by `org-compile-prefix-format'.
5928 The flag is set if the currently compiled format contains a `%t'.")
5929 (defvar org-prefix-has-tag nil
5930 "A flag, set by `org-compile-prefix-format'.
5931 The flag is set if the currently compiled format contains a `%T'.")
5933 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
5934 "Format TXT to be inserted into the agenda buffer.
5935 In particular, it adds the prefix and corresponding text properties. EXTRA
5936 must be a string and replaces the `%s' specifier in the prefix format.
5937 CATEGORY (string, symbol or nil) may be used to overrule the default
5938 category taken from local variable or file name. It will replace the `%c'
5939 specifier in the format. DOTIME, when non-nil, indicates that a
5940 time-of-day should be extracted from TXT for sorting of this entry, and for
5941 the `%t' specifier in the format. When DOTIME is a string, this string is
5942 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5943 only the correctly processes TXT should be returned - this is used by
5944 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
5945 (save-match-data
5946 ;; Diary entries sometimes have extra whitespace at the beginning
5947 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
5948 (let* ((category (or category
5949 org-category
5950 (if buffer-file-name
5951 (file-name-sans-extension
5952 (file-name-nondirectory buffer-file-name))
5953 "")))
5954 (tag (or (nth (1- (or (length tags) 0)) tags) ""))
5955 time ;; needed for the eval of the prefix format
5956 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
5957 (time-of-day (and dotime (org-get-time-of-day ts)))
5958 stamp plain s0 s1 s2 rtn)
5959 (when (and dotime time-of-day org-prefix-has-time)
5960 ;; Extract starting and ending time and move them to prefix
5961 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
5962 (setq plain (string-match org-plain-time-of-day-regexp ts)))
5963 (setq s0 (match-string 0 ts)
5964 s1 (match-string (if plain 1 2) ts)
5965 s2 (match-string (if plain 8 4) ts))
5967 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
5968 ;; them, we might want to remove them there to avoid duplication.
5969 ;; The user can turn this off with a variable.
5970 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
5971 (string-match (concat (regexp-quote s0) " *") txt)
5972 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
5973 (= (match-beginning 0) 0)
5975 (setq txt (replace-match "" nil nil txt))))
5976 ;; Normalize the time(s) to 24 hour
5977 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
5978 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
5980 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
5981 (and org-agenda-remove-tags-when-in-prefix
5982 org-prefix-has-tag))
5983 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
5984 (setq txt (replace-match "" t t txt)))
5986 ;; Create the final string
5987 (if noprefix
5988 (setq rtn txt)
5989 ;; Prepare the variables needed in the eval of the compiled format
5990 (setq time (cond (s2 (concat s1 "-" s2))
5991 (s1 (concat s1 "......"))
5992 (t ""))
5993 extra (or extra "")
5994 category (if (symbolp category) (symbol-name category) category))
5995 ;; Evaluate the compiled format
5996 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
5998 ;; And finally add the text properties
5999 (add-text-properties
6000 0 (length rtn) (list 'category (downcase category)
6001 'tags tags
6002 'prefix-length (- (length rtn) (length txt))
6003 'time-of-day time-of-day
6004 'dotime dotime)
6005 rtn)
6006 rtn)))
6008 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
6009 (catch 'exit
6010 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
6011 ((and todayp (member 'today (car org-agenda-time-grid))))
6012 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
6013 ((member 'weekly (car org-agenda-time-grid)))
6014 (t (throw 'exit list)))
6015 (let* ((have (delq nil (mapcar
6016 (lambda (x) (get-text-property 1 'time-of-day x))
6017 list)))
6018 (string (nth 1 org-agenda-time-grid))
6019 (gridtimes (nth 2 org-agenda-time-grid))
6020 (req (car org-agenda-time-grid))
6021 (remove (member 'remove-match req))
6022 new time)
6023 (if (and (member 'require-timed req) (not have))
6024 ;; don't show empty grid
6025 (throw 'exit list))
6026 (while (setq time (pop gridtimes))
6027 (unless (and remove (member time have))
6028 (setq time (int-to-string time))
6029 (push (org-format-agenda-item
6030 nil string "" nil ;; FIXME: put a category for the grid?
6031 (concat (substring time 0 -2) ":" (substring time -2)))
6032 new)
6033 (put-text-property
6034 1 (length (car new)) 'face 'org-time-grid (car new))))
6035 (if (member 'time-up org-agenda-sorting-strategy)
6036 (append new list)
6037 (append list new)))))
6039 (defun org-compile-prefix-format (format)
6040 "Compile the prefix format into a Lisp form that can be evaluated.
6041 The resulting form is returned and stored in the variable
6042 `org-prefix-format-compiled'."
6043 (setq org-prefix-has-time nil org-prefix-has-tag nil)
6044 (let ((start 0) varform vars var (s format)e c f opt)
6045 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
6046 s start)
6047 (setq var (cdr (assoc (match-string 4 s)
6048 '(("c" . category) ("t" . time) ("s" . extra)
6049 ("T" . tag))))
6050 c (or (match-string 3 s) "")
6051 opt (match-beginning 1)
6052 start (1+ (match-beginning 0)))
6053 (if (equal var 'time) (setq org-prefix-has-time t))
6054 (if (equal var 'tag) (setq org-prefix-has-tag t))
6055 (setq f (concat "%" (match-string 2 s) "s"))
6056 (if opt
6057 (setq varform
6058 `(if (equal "" ,var)
6060 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
6061 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
6062 (setq s (replace-match "%s" t nil s))
6063 (push varform vars))
6064 (setq vars (nreverse vars))
6065 (setq org-prefix-format-compiled `(format ,s ,@vars))))
6067 (defun org-get-time-of-day (s &optional string)
6068 "Check string S for a time of day.
6069 If found, return it as a military time number between 0 and 2400.
6070 If not found, return nil.
6071 The optional STRING argument forces conversion into a 5 character wide string
6072 HH:MM."
6073 (save-match-data
6074 (when
6076 (string-match
6077 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
6078 (string-match
6079 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
6080 (let* ((t0 (+ (* 100
6081 (+ (string-to-number (match-string 1 s))
6082 (if (and (match-beginning 4)
6083 (equal (downcase (match-string 4 s)) "pm"))
6084 12 0)))
6085 (if (match-beginning 3)
6086 (string-to-number (match-string 3 s))
6087 0)))
6088 (t1 (concat " "
6089 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6090 (int-to-string t0))))
6091 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6093 (defun org-finalize-agenda-entries (list)
6094 "Sort and concatenate the agenda items."
6095 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6097 (defsubst org-cmp-priority (a b)
6098 "Compare the priorities of string A and B."
6099 (let ((pa (or (get-text-property 1 'priority a) 0))
6100 (pb (or (get-text-property 1 'priority b) 0)))
6101 (cond ((> pa pb) +1)
6102 ((< pa pb) -1)
6103 (t nil))))
6105 (defsubst org-cmp-category (a b)
6106 "Compare the string values of categories of strings A and B."
6107 (let ((ca (or (get-text-property 1 'category a) ""))
6108 (cb (or (get-text-property 1 'category b) "")))
6109 (cond ((string-lessp ca cb) -1)
6110 ((string-lessp cb ca) +1)
6111 (t nil))))
6113 (defsubst org-cmp-time (a b)
6114 "Compare the time-of-day values of strings A and B."
6115 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6116 (ta (or (get-text-property 1 'time-of-day a) def))
6117 (tb (or (get-text-property 1 'time-of-day b) def)))
6118 (cond ((< ta tb) -1)
6119 ((< tb ta) +1)
6120 (t nil))))
6122 (defun org-entries-lessp (a b)
6123 "Predicate for sorting agenda entries."
6124 ;; The following variables will be used when the form is evaluated.
6125 (let* ((time-up (org-cmp-time a b))
6126 (time-down (if time-up (- time-up) nil))
6127 (priority-up (org-cmp-priority a b))
6128 (priority-down (if priority-up (- priority-up) nil))
6129 (category-up (org-cmp-category a b))
6130 (category-down (if category-up (- category-up) nil))
6131 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
6132 (cdr (assoc
6133 (eval (cons 'or org-agenda-sorting-strategy))
6134 '((-1 . t) (1 . nil) (nil . nil))))))
6136 (defun org-agenda-show-priority ()
6137 "Show the priority of the current item.
6138 This priority is composed of the main priority given with the [#A] cookies,
6139 and by additional input from the age of a schedules or deadline entry."
6140 (interactive)
6141 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6142 (message "Priority is %d" (if pri pri -1000))))
6144 (defun org-agenda-show-tags ()
6145 "Show the tags applicable to the current item."
6146 (interactive)
6147 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6148 (if tags
6149 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6150 (message "No tags associated with this line"))))
6152 (defun org-agenda-goto (&optional highlight)
6153 "Go to the Org-mode file which contains the item at point."
6154 (interactive)
6155 (let* ((marker (or (get-text-property (point) 'org-marker)
6156 (org-agenda-error)))
6157 (buffer (marker-buffer marker))
6158 (pos (marker-position marker)))
6159 (switch-to-buffer-other-window buffer)
6160 (widen)
6161 (goto-char pos)
6162 (when (eq major-mode 'org-mode)
6163 (org-show-hidden-entry)
6164 (save-excursion
6165 (and (outline-next-heading)
6166 (org-flag-heading nil)))) ; show the next heading
6167 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6169 (defun org-agenda-switch-to ()
6170 "Go to the Org-mode file which contains the item at point."
6171 (interactive)
6172 (let* ((marker (or (get-text-property (point) 'org-marker)
6173 (org-agenda-error)))
6174 (buffer (marker-buffer marker))
6175 (pos (marker-position marker)))
6176 (switch-to-buffer buffer)
6177 (delete-other-windows)
6178 (widen)
6179 (goto-char pos)
6180 (when (eq major-mode 'org-mode)
6181 (org-show-hidden-entry)
6182 (save-excursion
6183 (and (outline-next-heading)
6184 (org-flag-heading nil)))))) ; show the next heading
6186 (defun org-agenda-goto-mouse (ev)
6187 "Go to the Org-mode file which contains the item at the mouse click."
6188 (interactive "e")
6189 (mouse-set-point ev)
6190 (org-agenda-goto))
6192 (defun org-agenda-show ()
6193 "Display the Org-mode file which contains the item at point."
6194 (interactive)
6195 (let ((win (selected-window)))
6196 (org-agenda-goto t)
6197 (select-window win)))
6199 (defun org-agenda-recenter (arg)
6200 "Display the Org-mode file which contains the item at point and recenter."
6201 (interactive "P")
6202 (let ((win (selected-window)))
6203 (org-agenda-goto t)
6204 (recenter arg)
6205 (select-window win)))
6207 (defun org-agenda-show-mouse (ev)
6208 "Display the Org-mode file which contains the item at the mouse click."
6209 (interactive "e")
6210 (mouse-set-point ev)
6211 (org-agenda-show))
6213 (defun org-agenda-check-no-diary ()
6214 "Check if the entry is a diary link and abort if yes."
6215 (if (get-text-property (point) 'org-agenda-diary-link)
6216 (org-agenda-error)))
6218 (defun org-agenda-error ()
6219 (error "Command not allowed in this line"))
6221 (defvar org-last-heading-marker (make-marker)
6222 "Marker pointing to the headline that last changed its TODO state
6223 by a remote command from the agenda.")
6225 (defun org-agenda-todo (&optional arg)
6226 "Cycle TODO state of line at point, also in Org-mode file.
6227 This changes the line at point, all other lines in the agenda referring to
6228 the same tree node, and the headline of the tree node in the Org-mode file."
6229 (interactive "P")
6230 (org-agenda-check-no-diary)
6231 (let* ((col (current-column))
6232 (marker (or (get-text-property (point) 'org-marker)
6233 (org-agenda-error)))
6234 (buffer (marker-buffer marker))
6235 (pos (marker-position marker))
6236 (hdmarker (get-text-property (point) 'org-hd-marker))
6237 (buffer-read-only nil)
6238 newhead)
6239 (with-current-buffer buffer
6240 (widen)
6241 (goto-char pos)
6242 (org-show-hidden-entry)
6243 (save-excursion
6244 (and (outline-next-heading)
6245 (org-flag-heading nil))) ; show the next heading
6246 (org-todo arg)
6247 (forward-char 1)
6248 (setq newhead (org-get-heading))
6249 (save-excursion
6250 (org-back-to-heading)
6251 (move-marker org-last-heading-marker (point))))
6252 (beginning-of-line 1)
6253 (save-excursion
6254 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6255 (move-to-column col)))
6257 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6258 "Change all lines in the agenda buffer which match HDMARKER.
6259 The new content of the line will be NEWHEAD (as modified by
6260 `org-format-agenda-item'). HDMARKER is checked with
6261 `equal' against all `org-hd-marker' text properties in the file.
6262 If FIXFACE is non-nil, the face of each item is modified acording to
6263 the new TODO state."
6264 (let* (props m pl undone-face done-face finish new dotime cat tags)
6265 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6266 (save-excursion
6267 (goto-char (point-max))
6268 (beginning-of-line 1)
6269 (while (not finish)
6270 (setq finish (bobp))
6271 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6272 (equal m hdmarker))
6273 (setq props (text-properties-at (point))
6274 dotime (get-text-property (point) 'dotime)
6275 cat (get-text-property (point) 'category)
6276 tags (get-text-property (point) 'tags)
6277 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6278 pl (get-text-property (point) 'prefix-length)
6279 undone-face (get-text-property (point) 'undone-face)
6280 done-face (get-text-property (point) 'done-face))
6281 (move-to-column pl)
6282 (if (looking-at ".*")
6283 (progn
6284 (replace-match new t t)
6285 (beginning-of-line 1)
6286 (add-text-properties (point-at-bol) (point-at-eol) props)
6287 (if fixface
6288 (add-text-properties
6289 (point-at-bol) (point-at-eol)
6290 (list 'face
6291 (if org-last-todo-state-is-todo
6292 undone-face done-face))))
6293 (beginning-of-line 1))
6294 (error "Line update did not work")))
6295 (beginning-of-line 0)))))
6297 (defun org-agenda-priority-up ()
6298 "Increase the priority of line at point, also in Org-mode file."
6299 (interactive)
6300 (org-agenda-priority 'up))
6302 (defun org-agenda-priority-down ()
6303 "Decrease the priority of line at point, also in Org-mode file."
6304 (interactive)
6305 (org-agenda-priority 'down))
6307 (defun org-agenda-priority (&optional force-direction)
6308 "Set the priority of line at point, also in Org-mode file.
6309 This changes the line at point, all other lines in the agenda referring to
6310 the same tree node, and the headline of the tree node in the Org-mode file."
6311 (interactive)
6312 (org-agenda-check-no-diary)
6313 (let* ((marker (or (get-text-property (point) 'org-marker)
6314 (org-agenda-error)))
6315 (buffer (marker-buffer marker))
6316 (pos (marker-position marker))
6317 (hdmarker (get-text-property (point) 'org-hd-marker))
6318 (buffer-read-only nil)
6319 newhead)
6320 (with-current-buffer buffer
6321 (widen)
6322 (goto-char pos)
6323 (org-show-hidden-entry)
6324 (save-excursion
6325 (and (outline-next-heading)
6326 (org-flag-heading nil))) ; show the next heading
6327 (funcall 'org-priority force-direction)
6328 (end-of-line 1)
6329 (setq newhead (org-get-heading)))
6330 (org-agenda-change-all-lines newhead hdmarker)
6331 (beginning-of-line 1)))
6333 (defun org-get-tags-at (&optional pos)
6334 "Get a list of all headline targs applicable at POS.
6335 POS defaults to point. If tags are inherited, the list contains
6336 the targets in the same sequence as the headlines appear, i.e.
6337 the tags of the current headline come last."
6338 (interactive)
6339 (let (tags)
6340 (save-excursion
6341 (goto-char (or pos (point)))
6342 (save-match-data
6343 (org-back-to-heading t)
6344 (condition-case nil
6345 (while t
6346 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6347 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6348 (or org-use-tag-inheritance (error ""))
6349 (org-up-heading-all 1))
6350 (error nil))))
6351 (message "%s" tags)
6352 tags))
6354 (defun org-agenda-set-tags ()
6355 "Set tags for the current headline."
6356 (interactive)
6357 (org-agenda-check-no-diary)
6358 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6359 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6360 (org-agenda-error)))
6361 (buffer (marker-buffer hdmarker))
6362 (pos (marker-position hdmarker))
6363 (buffer-read-only nil)
6364 newhead)
6365 (with-current-buffer buffer
6366 (widen)
6367 (goto-char pos)
6368 (org-show-hidden-entry)
6369 (save-excursion
6370 (and (outline-next-heading)
6371 (org-flag-heading nil))) ; show the next heading
6372 (call-interactively 'org-set-tags)
6373 (end-of-line 1)
6374 (setq newhead (org-get-heading)))
6375 (org-agenda-change-all-lines newhead hdmarker)
6376 (beginning-of-line 1)))
6378 (defun org-agenda-date-later (arg &optional what)
6379 "Change the date of this item to one day later."
6380 (interactive "p")
6381 (org-agenda-check-type t 'agenda 'timeline)
6382 (org-agenda-check-no-diary)
6383 (let* ((marker (or (get-text-property (point) 'org-marker)
6384 (org-agenda-error)))
6385 (buffer (marker-buffer marker))
6386 (pos (marker-position marker)))
6387 (with-current-buffer buffer
6388 (widen)
6389 (goto-char pos)
6390 (if (not (org-at-timestamp-p))
6391 (error "Cannot find time stamp"))
6392 (org-timestamp-change arg (or what 'day))
6393 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6395 (defun org-agenda-date-earlier (arg &optional what)
6396 "Change the date of this item to one day earlier."
6397 (interactive "p")
6398 (org-agenda-date-later (- arg) what))
6400 (defun org-agenda-date-prompt (arg)
6401 "Change the date of this item. Date is prompted for, with default today.
6402 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6403 be used to request time specification in the time stamp."
6404 (interactive "P")
6405 (org-agenda-check-type t 'agenda 'timeline)
6406 (org-agenda-check-no-diary)
6407 (let* ((marker (or (get-text-property (point) 'org-marker)
6408 (org-agenda-error)))
6409 (buffer (marker-buffer marker))
6410 (pos (marker-position marker)))
6411 (with-current-buffer buffer
6412 (widen)
6413 (goto-char pos)
6414 (if (not (org-at-timestamp-p))
6415 (error "Cannot find time stamp"))
6416 (org-time-stamp arg)
6417 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6419 (defun org-get-heading ()
6420 "Return the heading of the current entry, without the stars."
6421 (save-excursion
6422 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6423 ;;FIXME???????? (and (bolp) (end-of-line 1))
6424 (if (and (re-search-backward "[\r\n]\\*" nil t)
6425 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6426 (match-string 1)
6427 "")))
6429 (defun org-agenda-diary-entry ()
6430 "Make a diary entry, like the `i' command from the calendar.
6431 All the standard commands work: block, weekly etc."
6432 (interactive)
6433 (org-agenda-check-type t 'agenda 'timeline)
6434 (require 'diary-lib)
6435 (let* ((char (progn
6436 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6437 (read-char-exclusive)))
6438 (cmd (cdr (assoc char
6439 '((?d . insert-diary-entry)
6440 (?w . insert-weekly-diary-entry)
6441 (?m . insert-monthly-diary-entry)
6442 (?y . insert-yearly-diary-entry)
6443 (?a . insert-anniversary-diary-entry)
6444 (?b . insert-block-diary-entry)
6445 (?c . insert-cyclic-diary-entry)))))
6446 (oldf (symbol-function 'calendar-cursor-to-date))
6447 (point (point))
6448 (mark (or (mark t) (point))))
6449 (unless cmd
6450 (error "No command associated with <%c>" char))
6451 (unless (and (get-text-property point 'day)
6452 (or (not (equal ?b char))
6453 (get-text-property mark 'day)))
6454 (error "Don't know which date to use for diary entry"))
6455 ;; We implement this by hacking the `calendar-cursor-to-date' function
6456 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6457 (let ((calendar-mark-ring
6458 (list (calendar-gregorian-from-absolute
6459 (or (get-text-property mark 'day)
6460 (get-text-property point 'day))))))
6461 (unwind-protect
6462 (progn
6463 (fset 'calendar-cursor-to-date
6464 (lambda (&optional error)
6465 (calendar-gregorian-from-absolute
6466 (get-text-property point 'day))))
6467 (call-interactively cmd))
6468 (fset 'calendar-cursor-to-date oldf)))))
6471 (defun org-agenda-execute-calendar-command (cmd)
6472 "Execute a calendar command from the agenda, with the date associated to
6473 the cursor position."
6474 (org-agenda-check-type t 'agenda 'timeline)
6475 (require 'diary-lib)
6476 (unless (get-text-property (point) 'day)
6477 (error "Don't know which date to use for calendar command"))
6478 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6479 (point (point))
6480 (date (calendar-gregorian-from-absolute
6481 (get-text-property point 'day)))
6482 (displayed-day (extract-calendar-day date))
6483 (displayed-month (extract-calendar-month date))
6484 (displayed-year (extract-calendar-year date)))
6485 (unwind-protect
6486 (progn
6487 (fset 'calendar-cursor-to-date
6488 (lambda (&optional error)
6489 (calendar-gregorian-from-absolute
6490 (get-text-property point 'day))))
6491 (call-interactively cmd))
6492 (fset 'calendar-cursor-to-date oldf))))
6494 (defun org-agenda-phases-of-moon ()
6495 "Display the phases of the moon for the 3 months around the cursor date."
6496 (interactive)
6497 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6499 (defun org-agenda-holidays ()
6500 "Display the holidays for the 3 months around the cursor date."
6501 (interactive)
6502 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6504 (defun org-agenda-sunrise-sunset (arg)
6505 "Display sunrise and sunset for the cursor date.
6506 Latitude and longitude can be specified with the variables
6507 `calendar-latitude' and `calendar-longitude'. When called with prefix
6508 argument, latitude and longitude will be prompted for."
6509 (interactive "P")
6510 (let ((calendar-longitude (if arg nil calendar-longitude))
6511 (calendar-latitude (if arg nil calendar-latitude))
6512 (calendar-location-name
6513 (if arg "the given coordinates" calendar-location-name)))
6514 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6516 (defun org-agenda-goto-calendar ()
6517 "Open the Emacs calendar with the date at the cursor."
6518 (interactive)
6519 (org-agenda-check-type t 'agenda 'timeline)
6520 (let* ((day (or (get-text-property (point) 'day)
6521 (error "Don't know which date to open in calendar")))
6522 (date (calendar-gregorian-from-absolute day))
6523 (calendar-move-hook nil)
6524 (view-diary-entries-initially nil))
6525 (calendar)
6526 (calendar-goto-date date)))
6528 (defun org-calendar-goto-agenda ()
6529 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6530 This is a command that has to be installed in `calendar-mode-map'."
6531 (interactive)
6532 (org-agenda-list nil (calendar-absolute-from-gregorian
6533 (calendar-cursor-to-date))
6534 nil t))
6536 (defun org-agenda-convert-date ()
6537 (interactive)
6538 (org-agenda-check-type t 'agenda 'timeline)
6539 (let ((day (get-text-property (point) 'day))
6540 date s)
6541 (unless day
6542 (error "Don't know which date to convert"))
6543 (setq date (calendar-gregorian-from-absolute day))
6544 (setq s (concat
6545 "Gregorian: " (calendar-date-string date) "\n"
6546 "ISO: " (calendar-iso-date-string date) "\n"
6547 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6548 "Julian: " (calendar-julian-date-string date) "\n"
6549 "Astron. JD: " (calendar-astro-date-string date)
6550 " (Julian date number at noon UTC)\n"
6551 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6552 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6553 "French: " (calendar-french-date-string date) "\n"
6554 "Mayan: " (calendar-mayan-date-string date) "\n"
6555 "Coptic: " (calendar-coptic-date-string date) "\n"
6556 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6557 "Persian: " (calendar-persian-date-string date) "\n"
6558 "Chinese: " (calendar-chinese-date-string date) "\n"))
6559 (with-output-to-temp-buffer "*Dates*"
6560 (princ s))
6561 (if (fboundp 'fit-window-to-buffer)
6562 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6564 ;;; Tags
6566 (defun org-scan-tags (action matcher &optional todo-only)
6567 "Scan headline tags with inheritance and produce output ACTION.
6568 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6569 evaluated, testing if a given set of tags qualifies a headline for
6570 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
6571 are included in the output."
6572 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6573 (mapconcat 'regexp-quote
6574 (nreverse (cdr (reverse org-todo-keywords)))
6575 "\\|")
6576 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
6577 (props (list 'face nil
6578 'done-face 'org-done
6579 'undone-face nil
6580 'mouse-face 'highlight
6581 'keymap org-agenda-keymap
6582 'help-echo
6583 (format "mouse-2 or RET jump to org file %s"
6584 (abbreviate-file-name buffer-file-name))))
6585 lspos
6586 tags tags-list tags-alist (llast 0) rtn level category i txt
6587 todo marker)
6589 (save-excursion
6590 (goto-char (point-min))
6591 (when (eq action 'sparse-tree) (hide-sublevels 1))
6592 (while (re-search-forward re nil t)
6593 (setq todo (if (match-end 1) (match-string 2))
6594 tags (if (match-end 4) (match-string 4)))
6595 (goto-char (setq lspos (1+ (match-beginning 0))))
6596 (setq level (funcall outline-level)
6597 category (org-get-category))
6598 (setq i llast llast level)
6599 ;; remove tag lists from same and sublevels
6600 (while (>= i level)
6601 (when (setq entry (assoc i tags-alist))
6602 (setq tags-alist (delete entry tags-alist)))
6603 (setq i (1- i)))
6604 ;; add the nex tags
6605 (when tags
6606 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6607 tags-alist
6608 (cons (cons level tags) tags-alist)))
6609 ;; compile tags for current headline
6610 (setq tags-list
6611 (if org-use-tag-inheritance
6612 (apply 'append (mapcar 'cdr tags-alist))
6613 tags))
6614 (when (and (or (not todo-only) todo)
6615 (eval matcher))
6616 ;; list this headline
6617 (if (eq action 'sparse-tree)
6618 (progn
6619 (org-show-hierarchy-above))
6620 (setq txt (org-format-agenda-item
6622 (concat
6623 (if org-tags-match-list-sublevels
6624 (make-string (1- level) ?.) "")
6625 (org-get-heading))
6626 category tags-list))
6627 (goto-char lspos)
6628 (setq marker (org-agenda-new-marker))
6629 (add-text-properties
6630 0 (length txt)
6631 (append (list 'org-marker marker 'org-hd-marker marker
6632 'category category)
6633 props)
6634 txt)
6635 (push txt rtn))
6636 ;; if we are to skip sublevels, jump to end of subtree
6637 (point)
6638 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6639 (nreverse rtn)))
6641 (defun org-tags-sparse-tree (&optional arg match)
6642 "Create a sparse tree according to tags search string MATCH.
6643 MATCH can contain positive and negative selection of tags, like
6644 \"+WORK+URGENT-WITHBOSS\"."
6645 (interactive "P")
6646 (let ((org-show-following-heading nil)
6647 (org-show-hierarchy-above nil))
6648 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6650 (defun org-make-tags-matcher (match)
6651 "Create the TAGS matcher form for the tags-selecting string MATCH."
6652 (unless match
6653 ;; Get a new match request, with completion
6654 (setq org-last-tags-completion-table
6655 (or (org-get-buffer-tags)
6656 org-last-tags-completion-table))
6657 (setq match (completing-read
6658 "Tags: " 'org-tags-completion-function nil nil nil
6659 'org-tags-history)))
6660 ;; parse the string and create a lisp form
6661 (let ((match0 match) minus tag mm matcher orterms term orlist)
6662 (setq orterms (org-split-string match "|"))
6663 (while (setq term (pop orterms))
6664 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
6665 (setq minus (and (match-end 1)
6666 (equal (match-string 1 term) "-"))
6667 tag (match-string 2 term)
6668 term (substring term (match-end 0))
6669 mm (list 'member (downcase tag) 'tags-list)
6670 mm (if minus (list 'not mm) mm))
6671 (push mm matcher))
6672 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6673 orlist)
6674 (setq matcher nil))
6675 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6676 ;; Return the string and lisp forms of the matcher
6677 (cons match0 matcher)))
6679 ;;;###autoload
6680 (defun org-tags-view (&optional todo-only match keep-modes)
6681 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
6682 The prefix arg TODO-ONLY limits the search to TODO entries."
6683 (interactive "P")
6684 (org-agenda-maybe-reset-markers 'force)
6685 (org-compile-prefix-format org-agenda-prefix-format)
6686 (let* ((org-agenda-keep-modes keep-modes)
6687 (org-tags-match-list-sublevels
6688 (if todo-only t org-tags-match-list-sublevels))
6689 (win (selected-window))
6690 (completion-ignore-case t)
6691 rtn rtnall files file pos matcher
6692 buffer)
6693 (setq matcher (org-make-tags-matcher match)
6694 match (car matcher) matcher (cdr matcher))
6695 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6696 (progn
6697 (delete-other-windows)
6698 (switch-to-buffer-other-window
6699 (get-buffer-create org-agenda-buffer-name))))
6700 (setq buffer-read-only nil)
6701 (erase-buffer)
6702 (org-agenda-mode) (setq buffer-read-only nil)
6703 (set (make-local-variable 'org-agenda-type) 'tags)
6704 (set (make-local-variable 'org-agenda-redo-command)
6705 (list 'org-tags-view (list 'quote todo-only)
6706 (list 'if 'current-prefix-arg nil match) t))
6707 (setq files (org-agenda-files)
6708 rtnall nil)
6709 (while (setq file (pop files))
6710 (catch 'nextfile
6711 (org-check-agenda-file file)
6712 (setq buffer (if (file-exists-p file)
6713 (org-get-agenda-file-buffer file)
6714 (error "No such file %s" file)))
6715 (if (not buffer)
6716 ;; If file does not exist, merror message to agenda
6717 (setq rtn (list
6718 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6719 rtnall (append rtnall rtn))
6720 (with-current-buffer buffer
6721 (unless (eq major-mode 'org-mode)
6722 (error "Agenda file %s is not in `org-mode'" file))
6723 (save-excursion
6724 (save-restriction
6725 (if org-respect-restriction
6726 (if (org-region-active-p)
6727 ;; Respect a region to restrict search
6728 (narrow-to-region (region-beginning) (region-end)))
6729 ;; If we work for the calendar or many files,
6730 ;; get rid of any restriction
6731 (widen))
6732 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6733 (setq rtnall (append rtnall rtn))))))))
6734 (insert "Headlines with TAGS match: ")
6735 (add-text-properties (point-min) (1- (point))
6736 (list 'face 'org-link))
6737 (setq pos (point))
6738 (insert match "\n")
6739 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6740 (setq pos (point))
6741 (insert "Press `C-u r' to search again with new search string\n")
6742 (add-text-properties pos (1- (point)) (list 'face 'org-link))
6743 (when rtnall
6744 (insert (mapconcat 'identity rtnall "\n")))
6745 (goto-char (point-min))
6746 (setq buffer-read-only t)
6747 (org-fit-agenda-window)
6748 (if (not org-select-agenda-window) (select-window win))))
6750 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
6751 (defun org-set-tags (&optional arg just-align)
6752 "Set the tags for the current headline.
6753 With prefix ARG, realign all tags in headings in the current buffer."
6754 (interactive)
6755 (let* (;(inherit (org-get-inherited-tags))
6756 (re (concat "^" outline-regexp))
6757 (col (current-column))
6758 (current (org-get-tags))
6759 tags hd empty invis)
6760 (if arg
6761 (save-excursion
6762 (goto-char (point-min))
6763 (while (re-search-forward re nil t)
6764 (org-set-tags nil t))
6765 (message "All tags realigned to column %d" org-tags-column))
6766 (if just-align
6767 (setq tags current)
6768 (setq org-last-tags-completion-table
6769 (or (org-get-buffer-tags)
6770 org-last-tags-completion-table))
6771 (setq tags
6772 (let ((org-add-colon-after-tag-completion t))
6773 (completing-read "Tags: " 'org-tags-completion-function
6774 nil nil current 'org-tags-history)))
6775 (while (string-match "[-+&]+" tags)
6776 (setq tags (replace-match ":" t t tags))))
6777 ;; FIXME: still optimize this by not checking when JUST-ALIGN?
6778 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
6779 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
6780 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
6781 (if (equal current "")
6782 (progn
6783 (end-of-line 1)
6784 (or empty (insert-before-markers " ")))
6785 (beginning-of-line 1)
6786 (setq invis (org-invisible-p))
6787 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
6788 (setq hd (match-string 1))
6789 (delete-region (match-beginning 0) (match-end 0))
6790 (insert-before-markers (org-trim hd) (if empty "" " ")))
6791 ;; FIXME: What happens when adding a new tag??? Seems OK!!!
6792 (unless (equal tags "")
6793 (move-to-column (max (current-column)
6794 (if (> org-tags-column 0)
6795 org-tags-column
6796 (- (- org-tags-column) (length tags))))
6798 (insert-before-markers tags)
6799 (if (and (not invis) (org-invisible-p))
6800 (outline-flag-region (point-at-bol) (point) nil)))
6801 (move-to-column col))))
6803 (defun org-tags-completion-function (string predicate &optional flag)
6804 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
6805 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
6806 (setq s1 (match-string 1 string)
6807 s2 (match-string 2 string))
6808 (setq s1 "" s2 string))
6809 (cond
6810 ((eq flag nil)
6811 ;; try completion
6812 (setq rtn (try-completion s2 ctable))
6813 (if (stringp rtn)
6814 (concat s1 s2 (substring rtn (length s2))
6815 (if (and org-add-colon-after-tag-completion
6816 (assoc rtn ctable))
6817 ":" "")))
6819 ((eq flag t)
6820 ;; all-completions
6821 (all-completions s2 ctable)
6823 ((eq flag 'lambda)
6824 ;; exact match?
6825 (assoc s2 ctable)))
6828 (defun org-get-tags ()
6829 "Get the TAGS string in the current headline."
6830 (unless (org-on-heading-p)
6831 (error "Not on a heading"))
6832 (save-excursion
6833 (beginning-of-line 1)
6834 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
6835 (match-string 1)
6836 "")))
6838 (defun org-get-buffer-tags ()
6839 "Get a table of all tags used in the buffer, for completion."
6840 (let (tags)
6841 (save-excursion
6842 (goto-char (point-min))
6843 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
6844 (mapc (lambda (x) (add-to-list 'tags x))
6845 (org-split-string (match-string 1) ":"))))
6846 (mapcar 'list tags)))
6848 ;;; Link Stuff
6850 (defun org-find-file-at-mouse (ev)
6851 "Open file link or URL at mouse."
6852 (interactive "e")
6853 (mouse-set-point ev)
6854 (org-open-at-point 'in-emacs))
6856 (defun org-open-at-mouse (ev)
6857 "Open file link or URL at mouse."
6858 (interactive "e")
6859 (mouse-set-point ev)
6860 (org-open-at-point))
6862 (defun org-open-at-point (&optional in-emacs)
6863 "Open link at or after point.
6864 If there is no link at point, this function will search forward up to
6865 the end of the current subtree.
6866 Normally, files will be opened by an appropriate application. If the
6867 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6868 (interactive "P")
6869 (org-remove-occur-highlights nil nil t)
6870 (if (org-at-timestamp-p)
6871 (org-agenda-list nil (time-to-days (org-time-string-to-time
6872 (substring (match-string 1) 0 10)))
6874 (let (type path link line search (pos (point)))
6875 (catch 'match
6876 (save-excursion
6877 (skip-chars-forward "^]\n\r")
6878 (when (and (re-search-backward "\\[\\[" nil t)
6879 (looking-at org-bracket-link-regexp)
6880 (<= (match-beginning 0) pos)
6881 (>= (match-end 0) pos))
6882 (setq link (match-string 1))
6883 (while (string-match " *\n *" link)
6884 (setq link (replace-match " " t t link)))
6885 (if (string-match org-link-regexp link)
6886 (setq type (match-string 1 link)
6887 path (match-string 2 link))
6888 (setq type "thisfile"
6889 path link))
6890 (throw 'match t)))
6892 (when (get-text-property (point) 'org-linked-text)
6893 (setq type "thisfile"
6894 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6895 (1+ (point)) (point))
6896 path (buffer-substring
6897 (previous-single-property-change pos 'org-linked-text)
6898 (next-single-property-change pos 'org-linked-text)))
6899 (throw 'match t))
6901 (save-excursion
6902 (skip-chars-backward
6903 (concat (if org-allow-space-in-links "^" "^ ")
6904 org-non-link-chars))
6905 (when (or (looking-at org-link-regexp)
6906 (and (re-search-forward org-link-regexp (point-at-eol) t)
6907 (<= (match-beginning 0) pos)
6908 (>= (match-end 0) pos)))
6909 (setq type (match-string 1)
6910 path (match-string 2))
6911 (throw 'match t)))
6912 (save-excursion
6913 (skip-chars-backward "^ \t\n\r")
6914 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
6915 (setq type "tags"
6916 path (match-string 1))
6917 (while (string-match ":" path)
6918 (setq path (replace-match "+" t t path)))
6919 (throw 'match t)))
6920 (save-excursion
6921 (skip-chars-backward "a-zA-Z_")
6922 (when (and org-activate-camels
6923 (looking-at org-camel-regexp))
6924 (setq type "camel" path (match-string 0))
6925 (if (equal (char-before) ?*)
6926 (setq path (concat "*" path))))
6927 (throw 'match t))
6928 (save-excursion
6929 (when (re-search-forward
6930 org-link-regexp
6931 (save-excursion
6932 (condition-case nil
6933 (progn (outline-end-of-subtree) (max pos (point)))
6934 (error (end-of-line 1) (point))))
6936 (setq type (match-string 1)
6937 path (match-string 2)))))
6938 (unless path
6939 (error "No link found"))
6940 ;; Remove any trailing spaces in path
6941 (if (string-match " +\\'" path)
6942 (setq path (replace-match "" t t path)))
6944 (cond
6946 ((member type '("http" "https" "ftp" "mailto" "news"))
6947 (browse-url (concat type ":" path)))
6949 ((string= type "tags")
6950 (org-tags-view in-emacs path))
6951 ((or (string= type "camel")
6952 (string= type "thisfile"))
6953 (org-mark-ring-push)
6954 (org-link-search
6955 path
6956 (cond ((equal in-emacs '(4)) 'occur)
6957 ((equal in-emacs '(16)) 'org-occur)
6958 (t nil))))
6960 ((string= type "file")
6961 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
6962 (setq line (string-to-number (match-string 1 path))
6963 path (substring path 0 (match-beginning 0)))
6964 (if (string-match "::\\(.+\\)\\'" path)
6965 (setq search (match-string 1 path)
6966 path (substring path 0 (match-beginning 0)))))
6967 (org-open-file path in-emacs line search))
6969 ((string= type "news")
6970 (org-follow-gnus-link path))
6972 ((string= type "bbdb")
6973 (org-follow-bbdb-link path))
6975 ((string= type "gnus")
6976 (let (group article)
6977 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6978 (error "Error in Gnus link"))
6979 (setq group (match-string 1 path)
6980 article (match-string 3 path))
6981 (org-follow-gnus-link group article)))
6983 ((string= type "vm")
6984 (let (folder article)
6985 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6986 (error "Error in VM link"))
6987 (setq folder (match-string 1 path)
6988 article (match-string 3 path))
6989 ;; in-emacs is the prefix arg, will be interpreted as read-only
6990 (org-follow-vm-link folder article in-emacs)))
6992 ((string= type "wl")
6993 (let (folder article)
6994 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
6995 (error "Error in Wanderlust link"))
6996 (setq folder (match-string 1 path)
6997 article (match-string 3 path))
6998 (org-follow-wl-link folder article)))
7000 ((string= type "mhe")
7001 (let (folder article)
7002 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7003 (error "Error in MHE link"))
7004 (setq folder (match-string 1 path)
7005 article (match-string 3 path))
7006 (org-follow-mhe-link folder article)))
7008 ((string= type "rmail")
7009 (let (folder article)
7010 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7011 (error "Error in RMAIL link"))
7012 (setq folder (match-string 1 path)
7013 article (match-string 3 path))
7014 (org-follow-rmail-link folder article)))
7016 ((string= type "shell")
7017 (let ((cmd path))
7018 (while (string-match "@{" cmd)
7019 (setq cmd (replace-match "<" t t cmd)))
7020 (while (string-match "@}" cmd)
7021 (setq cmd (replace-match ">" t t cmd)))
7022 (if (or (not org-confirm-shell-links)
7023 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
7024 (shell-command cmd)
7025 (error "Abort"))))
7028 (browse-url-at-point))))))
7030 (defun org-link-search (s &optional type)
7031 "Search for a link search option.
7032 When S is a CamelCaseWord, search for a target, or for a sentence containing
7033 the words. If S is surrounded by forward slashes, it is interpreted as a
7034 regular expression. In org-mode files, this will create an `org-occur'
7035 sparse tree. In ordinary files, `occur' will be used to list matches.
7036 If the current buffer is in `dired-mode', grep will be used to search
7037 in all files."
7038 (let ((case-fold-search t)
7039 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7040 (pos (point))
7041 (pre "") (post "")
7042 words re0 re1 re2 re3 re4 re5 re2a reall camel)
7043 (cond ((save-excursion
7044 (goto-char (point-min))
7045 (and
7046 (re-search-forward
7047 (concat "<<" (regexp-quote s0) ">>") nil t)
7048 (setq pos (match-beginning 0))))
7049 ;; There is an exact target for this
7050 (goto-char pos))
7051 ((string-match "^/\\(.*\\)/$" s)
7052 ;; A regular expression
7053 (cond
7054 ((eq major-mode 'org-mode)
7055 (org-occur (match-string 1 s)))
7056 ;;((eq major-mode 'dired-mode)
7057 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7058 (t (org-do-occur (match-string 1 s)))))
7059 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
7061 ;; A camel or a normal search string
7062 (when (equal (string-to-char s) ?*)
7063 ;; Anchor on headlines, post may include tags.
7064 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
7065 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
7066 s (substring s 1)))
7067 (remove-text-properties
7068 0 (length s)
7069 '(face nil mouse-face nil keymap nil fontified nil) s)
7070 ;; Make a series of regular expressions to find a match
7071 (setq words
7072 (if camel
7073 (org-camel-to-words s)
7074 (org-split-string s "[ \n\r\t]+"))
7075 re0 (concat "<<" (regexp-quote s0) ">>")
7076 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
7077 re2a (concat "\\<" (mapconcat 'downcase words "[ \t\r\n]+") "\\>")
7078 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
7079 re1 (concat pre re2 post)
7080 re3 (concat pre re4 post)
7081 re5 (concat pre ".*" re4)
7082 re2 (concat pre re2)
7083 re2a (concat pre re2a)
7084 re4 (concat pre re4)
7085 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7086 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7087 re5 "\\)"
7089 (cond
7090 ((eq type 'org-occur) (org-occur reall))
7091 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7092 (t (goto-char (point-min))
7093 (if (or (org-search-not-link re0 nil t)
7094 (org-search-not-link re1 nil t)
7095 (org-search-not-link re2 nil t)
7096 (org-search-not-link re2a nil t) ;; FIXME: Right place???
7097 (org-search-not-link re3 nil t)
7098 (org-search-not-link re4 nil t)
7099 (org-search-not-link re5 nil t)
7101 (goto-char (match-beginning 0))
7102 (goto-char pos)
7103 (error "No match")))))
7105 ;; Normal string-search
7106 (goto-char (point-min))
7107 (if (search-forward s nil t)
7108 (goto-char (match-beginning 0))
7109 (error "No match"))))
7110 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
7112 (defun org-search-not-link (&rest args)
7113 "Execute `re-search-forward', but only accept matches that are not a link."
7114 (catch 'exit
7115 (let ((pos (point)) p1)
7116 (while (apply 're-search-forward args)
7117 (setq p1 (point))
7118 (if (not (save-match-data
7119 (and (re-search-backward "\\[\\[" nil t)
7120 (looking-at org-bracket-link-regexp)
7121 (<= (match-beginning 0) p1)
7122 (>= (match-end 0) p1))))
7123 (progn (goto-char (match-end 0))
7124 (throw 'exit (point)))
7125 (goto-char (match-end 0)))))))
7127 (defun org-do-occur (regexp &optional cleanup)
7128 "Call the Emacs command `occur'.
7129 If CLEANUP is non-nil, remove the printout of the regular expression
7130 in the *Occur* buffer. This is useful if the regex is long and not useful
7131 to read."
7132 (occur regexp)
7133 (when cleanup
7134 (let ((cwin (selected-window)) win beg end)
7135 (when (setq win (get-buffer-window "*Occur*"))
7136 (select-window win))
7137 (goto-char (point-min))
7138 (when (re-search-forward "match[a-z]+" nil t)
7139 (setq beg (match-end 0))
7140 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7141 (setq end (1- (match-beginning 0)))))
7142 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
7143 (goto-char (point-min))
7144 (select-window cwin))))
7146 (defvar org-mark-ring nil
7147 "Mark ring for positions before jumps in Org-mode.")
7148 (defvar org-mark-ring-last-goto nil
7149 "Last position in the mark ring used to go back.")
7150 ;; Fill and close the ring
7151 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7152 (loop for i from 1 to org-mark-ring-length do
7153 (push (make-marker) org-mark-ring))
7154 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7155 org-mark-ring)
7157 (defun org-mark-ring-push (&optional pos buffer)
7158 "Put the current position or POS into the mark ring and rotate it."
7159 (interactive)
7160 (setq pos (or pos (point)))
7161 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7162 (move-marker (car org-mark-ring)
7163 (or pos (point))
7164 (or buffer (current-buffer)))
7165 (message
7166 (substitute-command-keys
7167 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7169 (defun org-mark-ring-goto (&optional n)
7170 "Jump to the previous position in the mark ring.
7171 With prefix arg N, jump back that many stored positions. When
7172 called several times in succession, walk through the entire ring.
7173 Org-mode commands jumping to a different position in the current file,
7174 or to another Org-mode file, automatically push the old position
7175 onto the ring."
7176 (interactive "p")
7177 (let (p m)
7178 (if (eq last-command this-command)
7179 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7180 (setq p org-mark-ring))
7181 (setq org-mark-ring-last-goto p)
7182 (setq m (car p))
7183 (switch-to-buffer (marker-buffer m))
7184 (goto-char m)
7185 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7187 (defun org-camel-to-words (s)
7188 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7189 (let ((case-fold-search nil)
7190 words)
7191 (while (string-match "[a-z][A-Z]" s)
7192 (push (substring s 0 (1+ (match-beginning 0))) words)
7193 (setq s (substring s (1+ (match-beginning 0)))))
7194 (nreverse (cons s words))))
7196 (defun org-remove-angle-brackets (s)
7197 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7198 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7200 (defun org-add-angle-brackets (s)
7201 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7202 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7205 (defun org-follow-bbdb-link (name)
7206 "Follow a BBDB link to NAME."
7207 (require 'bbdb)
7208 (let ((inhibit-redisplay t)
7209 (bbdb-electric-p nil))
7210 (catch 'exit
7211 ;; Exact match on name
7212 (bbdb-name (concat "\\`" name "\\'") nil)
7213 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7214 ;; Exact match on name
7215 (bbdb-company (concat "\\`" name "\\'") nil)
7216 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7217 ;; Partial match on name
7218 (bbdb-name name nil)
7219 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7220 ;; Partial match on company
7221 (bbdb-company name nil)
7222 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7223 ;; General match including network address and notes
7224 (bbdb name nil)
7225 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7226 (delete-window (get-buffer-window "*BBDB*"))
7227 (error "No matching BBDB record")))))
7229 (defun org-follow-gnus-link (&optional group article)
7230 "Follow a Gnus link to GROUP and ARTICLE."
7231 (require 'gnus)
7232 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7233 (if group (gnus-fetch-group group))
7234 (if article
7235 (or (gnus-summary-goto-article article nil 'force)
7236 (if (fboundp 'gnus-summary-insert-cached-articles)
7237 (progn
7238 (gnus-summary-insert-cached-articles)
7239 (gnus-summary-goto-article article nil 'force))
7240 (message "Message could not be found.")))))
7242 (defun org-follow-vm-link (&optional folder article readonly)
7243 "Follow a VM link to FOLDER and ARTICLE."
7244 (require 'vm)
7245 (setq article (org-add-angle-brackets article))
7246 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7247 ;; ange-ftp or efs or tramp access
7248 (let ((user (or (match-string 1 folder) (user-login-name)))
7249 (host (match-string 2 folder))
7250 (file (match-string 3 folder)))
7251 (cond
7252 ((featurep 'tramp)
7253 ;; use tramp to access the file
7254 (if org-xemacs-p
7255 (setq folder (format "[%s@%s]%s" user host file))
7256 (setq folder (format "/%s@%s:%s" user host file))))
7258 ;; use ange-ftp or efs
7259 (require (if org-xemacs-p 'efs 'ange-ftp))
7260 (setq folder (format "/%s@%s:%s" user host file))))))
7261 (when folder
7262 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7263 (sit-for 0.1)
7264 (when article
7265 (vm-select-folder-buffer)
7266 (widen)
7267 (let ((case-fold-search t))
7268 (goto-char (point-min))
7269 (if (not (re-search-forward
7270 (concat "^" "message-id: *" (regexp-quote article))))
7271 (error "Could not find the specified message in this folder"))
7272 (vm-isearch-update)
7273 (vm-isearch-narrow)
7274 (vm-beginning-of-message)
7275 (vm-summarize)))))
7277 (defun org-follow-wl-link (folder article)
7278 "Follow a Wanderlust link to FOLDER and ARTICLE."
7279 (setq article (org-add-angle-brackets article))
7280 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7281 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7282 (wl-summary-redisplay))
7284 (defun org-follow-rmail-link (folder article)
7285 "Follow an RMAIL link to FOLDER and ARTICLE."
7286 (setq article (org-add-angle-brackets article))
7287 (let (message-number)
7288 (save-excursion
7289 (save-window-excursion
7290 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7291 (setq message-number
7292 (save-restriction
7293 (widen)
7294 (goto-char (point-max))
7295 (if (re-search-backward
7296 (concat "^Message-ID:\\s-+" (regexp-quote
7297 (or article "")))
7298 nil t)
7299 (rmail-what-message))))))
7300 (if message-number
7301 (progn
7302 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7303 (rmail-show-message message-number)
7304 message-number)
7305 (error "Message not found"))))
7307 ;; mh-e integration based on planner-mode
7308 (defun org-mhe-get-message-real-folder ()
7309 "Return the name of the current message real folder, so if you use
7310 sequences, it will now work."
7311 (save-excursion
7312 (let* ((folder
7313 (if (equal major-mode 'mh-folder-mode)
7314 mh-current-folder
7315 ;; Refer to the show buffer
7316 mh-show-folder-buffer))
7317 (end-index
7318 (if (boundp 'mh-index-folder)
7319 (min (length mh-index-folder) (length folder))))
7321 ;; a simple test on mh-index-data does not work, because
7322 ;; mh-index-data is always nil in a show buffer.
7323 (if (and (boundp 'mh-index-folder)
7324 (string= mh-index-folder (substring folder 0 end-index)))
7325 (if (equal major-mode 'mh-show-mode)
7326 (save-window-excursion
7327 (when (buffer-live-p (get-buffer folder))
7328 (progn
7329 (pop-to-buffer folder)
7330 (org-mhe-get-message-folder-from-index)
7333 (org-mhe-get-message-folder-from-index)
7335 folder
7339 (defun org-mhe-get-message-folder-from-index ()
7340 "Returns the name of the message folder in a index folder buffer."
7341 (save-excursion
7342 (mh-index-previous-folder)
7343 (re-search-forward "^\\(+.*\\)$" nil t)
7344 (message (match-string 1))))
7346 (defun org-mhe-get-message-folder ()
7347 "Return the name of the current message folder. Be careful if you
7348 use sequences."
7349 (save-excursion
7350 (if (equal major-mode 'mh-folder-mode)
7351 mh-current-folder
7352 ;; Refer to the show buffer
7353 mh-show-folder-buffer)))
7355 (defun org-mhe-get-message-num ()
7356 "Return the number of the current message. Be careful if you
7357 use sequences."
7358 (save-excursion
7359 (if (equal major-mode 'mh-folder-mode)
7360 (mh-get-msg-num nil)
7361 ;; Refer to the show buffer
7362 (mh-show-buffer-message-number))))
7364 (defun org-mhe-get-header (header)
7365 "Return a header of the message in folder mode. This will create a
7366 show buffer for the corresponding message. If you have a more clever
7367 idea..."
7368 (let* ((folder (org-mhe-get-message-folder))
7369 (num (org-mhe-get-message-num))
7370 (buffer (get-buffer-create (concat "show-" folder)))
7371 (header-field))
7372 (with-current-buffer buffer
7373 (mh-display-msg num folder)
7374 (if (equal major-mode 'mh-folder-mode)
7375 (mh-header-display)
7376 (mh-show-header-display))
7377 (set-buffer buffer)
7378 (setq header-field (mh-get-header-field header))
7379 (if (equal major-mode 'mh-folder-mode)
7380 (mh-show)
7381 (mh-show-show))
7382 header-field)))
7384 (defun org-follow-mhe-link (folder article)
7385 "Follow an MHE link to FOLDER and ARTICLE.
7386 If ARTICLE is nil FOLDER is shown. If the configuration variable
7387 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
7388 ARTICLE is searched in all folders. Indexed searches (swish++,
7389 namazu, and others supported by MH-E) will always search in all
7390 folders."
7391 (require 'mh-e)
7392 (require 'mh-search)
7393 (require 'mh-utils)
7394 (mh-find-path)
7395 (if (not article)
7396 (mh-visit-folder (mh-normalize-folder-name folder))
7397 (setq article (org-add-angle-brackets article))
7398 (mh-search-choose)
7399 (if (equal mh-searcher 'pick)
7400 (progn
7401 (mh-search folder (list "--message-id" article))
7402 (when (and org-mhe-search-all-folders
7403 (not (org-mhe-get-message-real-folder)))
7404 (kill-this-buffer)
7405 (mh-search "+" (list "--message-id" article))))
7406 (mh-search "+" article))
7407 (if (org-mhe-get-message-real-folder)
7408 (mh-show-msg 1)
7409 (kill-this-buffer)
7410 (error "Message not found"))))
7412 (defun org-open-file (path &optional in-emacs line search)
7413 "Open the file at PATH.
7414 First, this expands any special file name abbreviations. Then the
7415 configuration variable `org-file-apps' is checked if it contains an
7416 entry for this file type, and if yes, the corresponding command is launched.
7417 If no application is found, Emacs simply visits the file.
7418 With optional argument IN-EMACS, Emacs will visit the file.
7419 Optional LINE specifies a line to go to, optional SEARCH a string to
7420 search for. If LINE or SEARCH is given, the file will always be
7421 opened in Emacs.
7422 If the file does not exist, an error is thrown."
7423 (setq in-emacs (or in-emacs line search))
7424 (let* ((file (if (equal path "")
7425 buffer-file-name
7426 (convert-standard-filename (org-expand-file-name path))))
7427 (dirp (file-directory-p file))
7428 (dfile (downcase file))
7429 (old-buffer (current-buffer))
7430 (old-pos (point))
7431 (old-mode major-mode)
7432 ext cmd apps)
7433 (if (and (not (file-exists-p file))
7434 (not org-open-non-existing-files))
7435 (error "No such file: %s" file))
7436 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7437 (setq ext (match-string 1 dfile))
7438 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7439 (setq ext (match-string 1 dfile))))
7440 (setq apps (append org-file-apps (org-default-apps)))
7441 (if in-emacs
7442 (setq cmd 'emacs)
7443 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7444 (cdr (assoc ext apps))
7445 (cdr (assoc t apps)))))
7446 (when (eq cmd 'mailcap)
7447 (require 'mailcap)
7448 (mailcap-parse-mailcaps)
7449 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7450 (command (mailcap-mime-info mime-type)))
7451 (if (stringp command)
7452 (setq cmd command)
7453 (setq cmd 'emacs))))
7454 (cond
7455 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7456 (setq cmd (format cmd (concat "\"" file "\"")))
7457 (save-window-excursion
7458 (shell-command (concat cmd " &"))))
7459 ((or (stringp cmd)
7460 (eq cmd 'emacs))
7461 (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
7462 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7463 (if line (goto-line line)
7464 (if search (org-link-search search))))
7465 ((consp cmd)
7466 (eval cmd))
7467 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7468 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7469 (or (not (equal old-buffer (current-buffer)))
7470 (not (equal old-pos (point))))
7471 (org-mark-ring-push old-pos old-buffer))))
7473 (defun org-default-apps ()
7474 "Return the default applications for this operating system."
7475 (cond
7476 ((eq system-type 'darwin)
7477 org-file-apps-defaults-macosx)
7478 ((eq system-type 'windows-nt)
7479 org-file-apps-defaults-windowsnt)
7480 (t org-file-apps-defaults-gnu)))
7482 (defun org-expand-file-name (path)
7483 "Replace special path abbreviations and expand the file name."
7484 (expand-file-name path))
7487 (defvar org-insert-link-history nil
7488 "Minibuffer history for links inserted with `org-insert-link'.")
7490 (defvar org-stored-links nil
7491 "Contains the links stored with `org-store-link'.")
7493 ;;;###autoload
7494 (defun org-store-link (arg)
7495 "\\<org-mode-map>Store an org-link to the current location.
7496 This link can later be inserted into an org-buffer with
7497 \\[org-insert-link].
7498 For some link types, a prefix arg is interpreted:
7499 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7500 For file links, arg negates `org-context-in-file-links'."
7501 (interactive "P")
7502 (let (link cpltxt txt (pos (point)))
7503 (cond
7505 ((eq major-mode 'bbdb-mode)
7506 (setq cpltxt (concat
7507 "bbdb:"
7508 (or (bbdb-record-name (bbdb-current-record))
7509 (bbdb-record-company (bbdb-current-record))))
7510 link (org-make-link cpltxt)))
7512 ((eq major-mode 'calendar-mode)
7513 (let ((cd (calendar-cursor-to-date)))
7514 (setq link
7515 (format-time-string
7516 (car org-time-stamp-formats)
7517 (apply 'encode-time
7518 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7519 nil nil nil))))))
7521 ((or (eq major-mode 'vm-summary-mode)
7522 (eq major-mode 'vm-presentation-mode))
7523 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7524 (vm-follow-summary-cursor)
7525 (save-excursion
7526 (vm-select-folder-buffer)
7527 (let* ((message (car vm-message-pointer))
7528 (folder buffer-file-name)
7529 (subject (vm-su-subject message))
7530 (author (vm-su-full-name message))
7531 (message-id (vm-su-message-id message)))
7532 (setq message-id (org-remove-angle-brackets message-id))
7533 (setq folder (abbreviate-file-name folder))
7534 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7535 folder)
7536 (setq folder (replace-match "" t t folder)))
7537 (setq cpltxt (concat author " on: " subject))
7538 (setq link (concat cpltxt "\n "
7539 (org-make-link
7540 "vm:" folder "#" message-id))))))
7542 ((eq major-mode 'wl-summary-mode)
7543 (let* ((msgnum (wl-summary-message-number))
7544 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7545 msgnum 'message-id))
7546 (wl-message-entity (elmo-msgdb-overview-get-entity
7547 msgnum (wl-summary-buffer-msgdb)))
7548 (author (wl-summary-line-from)) ; FIXME: how to get author name?
7549 (subject "???")) ; FIXME: How to get subject of email?
7550 (setq message-id (org-remove-angle-brackets message-id))
7551 (setq cpltxt (concat author " on: " subject))
7552 (setq link (concat cpltxt "\n "
7553 (org-make-link
7554 "wl:" wl-summary-buffer-folder-name
7555 "#" message-id)))))
7557 ((or (equal major-mode 'mh-folder-mode)
7558 (equal major-mode 'mh-show-mode))
7559 (let ((from-header (org-mhe-get-header "From:"))
7560 (to-header (org-mhe-get-header "To:"))
7561 (subject (org-mhe-get-header "Subject:")))
7562 (setq cpltxt (concat from-header " on: " subject))
7563 (setq link (concat cpltxt "\n "
7564 (org-make-link
7565 "mhe:" (org-mhe-get-message-real-folder) "#"
7566 (org-remove-angle-brackets
7567 (org-mhe-get-header "Message-Id:")))))))
7569 ((eq major-mode 'rmail-mode)
7570 (save-excursion
7571 (save-restriction
7572 (rmail-narrow-to-non-pruned-header)
7573 (let ((folder buffer-file-name)
7574 (message-id (mail-fetch-field "message-id"))
7575 (author (mail-fetch-field "from"))
7576 (subject (mail-fetch-field "subject")))
7577 (setq message-id (org-remove-angle-brackets message-id))
7578 (setq cpltxt (concat author " on: " subject))
7579 (setq link (concat cpltxt "\n "
7580 (org-make-link
7581 "rmail:" folder "#" message-id)))))))
7583 ((eq major-mode 'gnus-group-mode)
7584 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7585 (gnus-group-group-name)) ; version
7586 ((fboundp 'gnus-group-name)
7587 (gnus-group-name))
7588 (t "???"))))
7589 (setq cpltxt (concat
7590 (if (org-xor arg org-usenet-links-prefer-google)
7591 "http://groups.google.com/groups?group="
7592 "gnus:")
7593 group)
7594 link (org-make-link cpltxt))))
7596 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7597 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7598 (gnus-summary-beginning-of-article)
7599 (let* ((group (car gnus-article-current))
7600 (article (cdr gnus-article-current))
7601 (header (gnus-summary-article-header article))
7602 (author (mail-header-from header))
7603 (message-id (mail-header-id header))
7604 (date (mail-header-date header))
7605 (subject (gnus-summary-subject-string)))
7606 (setq cpltxt (concat author " on: " subject))
7607 (if (org-xor arg org-usenet-links-prefer-google)
7608 (setq link
7609 (concat
7610 cpltxt "\n "
7611 (format "http://groups.google.com/groups?as_umsgid=%s"
7612 (org-fixup-message-id-for-http message-id))))
7613 (setq link (concat cpltxt "\n"
7614 (org-make-link
7615 "gnus:" group
7616 "#" (number-to-string article)))))))
7618 ((eq major-mode 'w3-mode)
7619 (setq cpltxt (url-view-url t)
7620 link (org-make-link cpltxt)))
7621 ((eq major-mode 'w3m-mode)
7622 (setq cpltxt w3m-current-url
7623 link (org-make-link cpltxt)))
7625 ((eq major-mode 'org-mode)
7626 ;; Just link to current headline
7627 (setq cpltxt (concat "file:"
7628 (abbreviate-file-name buffer-file-name)))
7629 ;; Add a context search string
7630 (when (org-xor org-context-in-file-links arg)
7631 ;; Check if we are on a target
7632 (if (save-excursion
7633 (skip-chars-forward "^>\n\r")
7634 (and (re-search-backward "<<" nil t)
7635 (looking-at "<<\\(.*?\\)>>")
7636 (<= (match-beginning 0) pos)
7637 (>= (match-end 0) pos)))
7638 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7639 (setq txt (cond
7640 ((org-on-heading-p) nil)
7641 ((org-region-active-p)
7642 (buffer-substring (region-beginning) (region-end)))
7643 (t (buffer-substring (point-at-bol) (point-at-eol)))))
7644 (setq cpltxt
7645 (concat cpltxt "::"
7646 (if org-file-link-context-use-camel-case
7647 (org-make-org-heading-camel txt)
7648 (org-make-org-heading-search-string txt))))))
7649 (if (string-match "::\\'" cpltxt)
7650 (setq cpltxt (substring cpltxt 0 -2)))
7651 (setq link (org-make-link cpltxt)))
7653 (buffer-file-name
7654 ;; Just link to this file here.
7655 (setq cpltxt (concat "file:"
7656 (abbreviate-file-name buffer-file-name)))
7657 ;; Add a context string
7658 (when (org-xor org-context-in-file-links arg)
7659 (setq txt (if (org-region-active-p)
7660 (buffer-substring (region-beginning) (region-end))
7661 (buffer-substring (point-at-bol) (point-at-eol))))
7662 (setq cpltxt
7663 (concat cpltxt "::"
7664 (if org-file-link-context-use-camel-case
7665 (org-make-org-heading-camel txt)
7666 (org-make-org-heading-search-string txt)))))
7667 (setq link (org-make-link cpltxt)))
7669 ((interactive-p)
7670 (error "Cannot link to a buffer which is not visiting a file"))
7672 (t (setq link nil)))
7674 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7676 (if (and (interactive-p) link)
7677 (progn
7678 (setq org-stored-links
7679 (cons (cons (or cpltxt link) link) org-stored-links))
7680 (message "Stored: %s" (or cpltxt link)))
7681 link)))
7683 (defun org-make-org-heading-search-string (&optional string heading)
7684 "Make search string for STRING or current headline."
7685 (interactive)
7686 (let ((s (or string (org-get-heading))))
7687 (unless (and string (not heading))
7688 ;; We are using a headline, clean up garbage in there.
7689 (if (string-match org-todo-regexp s)
7690 (setq s (replace-match "" t t s)))
7691 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7692 (setq s (replace-match "" t t s)))
7693 (setq s (org-trim s))
7694 (if (string-match (concat "^\\(" org-quote-string "\\|"
7695 org-comment-string "\\)") s)
7696 (setq s (replace-match "" t t s)))
7697 (while (string-match org-ts-regexp s)
7698 (setq s (replace-match "" t t s))))
7699 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7700 (setq s (replace-match " " t t s)))
7701 (or string (setq s (concat "*" s))) ; Add * for headlines
7702 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7704 (defun org-make-org-heading-camel (&optional string heading)
7705 "Make a CamelCase string for STRING or the current headline."
7706 (interactive)
7707 (let ((s (or string (org-get-heading))))
7708 (unless (and string (not heading))
7709 ;; We are using a headline, clean up garbage in there.
7710 (if (string-match org-todo-regexp s)
7711 (setq s (replace-match "" t t s)))
7712 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7713 (setq s (replace-match "" t t s)))
7714 (setq s (org-trim s))
7715 (if (string-match (concat "^\\(" org-quote-string "\\|"
7716 org-comment-string "\\)") s)
7717 (setq s (replace-match "" t t s)))
7718 (while (string-match org-ts-regexp s)
7719 (setq s (replace-match "" t t s))))
7720 (while (string-match "[^a-zA-Z_ \t]+" s)
7721 (setq s (replace-match " " t t s)))
7722 (or string (setq s (concat "*" s))) ; Add * for headlines
7723 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7725 (defun org-make-link (&rest strings)
7726 "Concatenate STRINGS, format resulting string with `org-link-format'."
7727 (format org-link-format (apply 'concat strings)))
7729 (defun org-make-link2 (link &optional description)
7730 "Make a link with brackets."
7731 (concat "[[" link "]"
7732 (if description (concat "[" description "]") "")
7733 "]"))
7735 (defun org-xor (a b)
7736 "Exclusive or."
7737 (if a (not b) b))
7739 (defun org-get-header (header)
7740 "Find a header field in the current buffer."
7741 (save-excursion
7742 (goto-char (point-min))
7743 (let ((case-fold-search t) s)
7744 (cond
7745 ((eq header 'from)
7746 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7747 (setq s (match-string 1)))
7748 (while (string-match "\"" s)
7749 (setq s (replace-match "" t t s)))
7750 (if (string-match "[<(].*" s)
7751 (setq s (replace-match "" t t s))))
7752 ((eq header 'message-id)
7753 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7754 (setq s (match-string 1))))
7755 ((eq header 'subject)
7756 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7757 (setq s (match-string 1)))))
7758 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7759 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7760 s)))
7763 (defun org-fixup-message-id-for-http (s)
7764 "Replace special characters in a message id, so it can be used in an http query."
7765 (while (string-match "<" s)
7766 (setq s (replace-match "%3C" t t s)))
7767 (while (string-match ">" s)
7768 (setq s (replace-match "%3E" t t s)))
7769 (while (string-match "@" s)
7770 (setq s (replace-match "%40" t t s)))
7773 (defun org-insert-link (&optional complete-file)
7774 "Insert a link. At the prompt, enter the link.
7776 Completion can be used to select a link previously stored with
7777 `org-store-link'. When the empty string is entered (i.e. if you just
7778 press RET at the prompt), the link defaults to the most recently
7779 stored link. As SPC triggers completion in the minibuffer, you need to
7780 use M-SPC or C-q SPC to force the insertion of a space character.
7782 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7783 selected using completion. The path to the file will be relative to
7784 the current directory if the file is in the current directory or a
7785 subdirectory. Otherwise, the link will be the absolute path as
7786 completed in the minibuffer (i.e. normally ~/path/to/file).
7788 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7789 is in the current directory or below."
7790 (interactive "P")
7791 (let ((link (if complete-file
7792 (read-file-name "File: ")
7793 (completing-read
7794 "Link: " org-stored-links nil nil nil
7795 org-insert-link-history
7796 (or (car (car org-stored-links))))))
7797 linktxt matched)
7798 (if (or (not link) (equal link ""))
7799 (error "No links available"))
7800 (if complete-file
7801 (let ((pwd (file-name-as-directory (expand-file-name "."))))
7802 (cond
7803 ((equal complete-file '(16))
7804 (insert
7805 (org-make-link
7806 "file:" (abbreviate-file-name (expand-file-name link)))))
7807 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7808 (expand-file-name link))
7809 (insert
7810 (org-make-link
7811 "file:" (match-string 1 (expand-file-name link)))))
7812 (t (insert (org-make-link "file:" link)))))
7813 (setq linktxt (cdr (assoc link org-stored-links)))
7814 (if (not org-keep-stored-link-after-insertion)
7815 (setq org-stored-links (delq (assoc link org-stored-links)
7816 org-stored-links)))
7817 (if (not linktxt) (setq link (org-make-link link)))
7818 (setq link (or linktxt link))
7819 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
7820 (let* ((path (match-string 1 link))
7821 (case-fold-search nil)
7822 (search (match-string 2 link)))
7823 (when (save-match-data
7824 (equal (file-truename buffer-file-name)
7825 (file-truename path)))
7826 ;; We are linking to this same file
7827 (if (and org-file-link-context-use-camel-case
7828 (save-match-data
7829 (string-match (concat "^" org-camel-regexp "$") search)))
7830 (setq link (replace-match search t t link)
7831 matched t)
7832 (setq link (replace-match (concat "[[" search "]]")
7833 t t link)
7834 matched t)))))
7835 (let ((lines (org-split-string link "\n")))
7836 (insert (car lines))
7837 (setq matched (or matched (string-match org-link-regexp (car lines))))
7838 (setq lines (cdr lines))
7839 (while lines
7840 (insert "\n")
7841 (if (save-excursion
7842 (beginning-of-line 0)
7843 (looking-at "[ \t]+\\S-"))
7844 (indent-relative))
7845 (setq matched (or matched
7846 (string-match org-link-regexp (car lines))))
7847 (insert (car lines))
7848 (setq lines (cdr lines))))
7849 (unless matched
7850 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
7852 ;;; Hooks for remember.el
7853 ;;;###autoload
7854 (defun org-remember-annotation ()
7855 "Return a link to the current location as an annotation for remember.el.
7856 If you are using Org-mode files as target for data storage with
7857 remember.el, then the annotations should include a link compatible with the
7858 conventions in Org-mode. This function returns such a link."
7859 (org-store-link nil))
7861 (defconst org-remember-help
7862 "Select a destination location for the note.
7863 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
7864 RET at beg-of-buf -> Append to file as level 2 headline
7865 RET on headline -> Store as sublevel entry to current headline
7866 <left>/<right> -> before/after current headline, same headings level")
7868 ;;;###autoload
7869 (defun org-remember-apply-template ()
7870 "Initialize *remember* buffer with template, invode `org-mode'.
7871 This function should be placed into `remember-mode-hook' and in fact requires
7872 to be run from that hook to fucntion properly."
7873 (when org-remember-templates
7874 (let* ((entry (if (= (length org-remember-templates) 1)
7875 (cdar org-remember-templates)
7876 (message "Select template: %s"
7877 (mapconcat
7878 (lambda (x) (char-to-string (car x)))
7879 org-remember-templates " "))
7880 (cdr (assoc (read-char-exclusive) org-remember-templates))))
7881 (tpl (if (consp (cdr entry)) (cadr entry) (cdr entry)))
7882 (file (if (consp (cdr entry)) (nth 2 entry)))
7883 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
7884 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
7885 (v-u (concat "[" (substring v-t 1 -1) "]"))
7886 (v-U (concat "[" (substring v-T 1 -1) "]"))
7887 (v-a annotation) ; defined in `remember-mode'
7888 (v-i initial) ; defined in `remember-mode'
7889 (v-n user-full-name)
7891 (unless tpl (setq tpl "") (message "No template") (ding))
7892 (insert tpl) (goto-char (point-min))
7893 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
7894 (when (and initial (equal (match-string 0) "%i"))
7895 (save-match-data
7896 (let* ((lead (buffer-substring
7897 (point-at-bol) (match-beginning 0))))
7898 (setq v-i (mapconcat 'identity
7899 (org-split-string initial "\n")
7900 (concat "\n" lead))))))
7901 (replace-match
7902 (or (eval (intern (concat "v-" (match-string 1)))) "")
7903 t t))
7904 (let ((org-startup-folded nil)
7905 (org-startup-with-deadline-check nil))
7906 (org-mode))
7907 ; (use-local-map org-mode-map)
7908 ; (org-set-font-lock-defaults)
7909 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
7910 (set (make-local-variable 'org-default-notes-file) file))
7911 (goto-char (point-min))
7912 (if (re-search-forward "%\\?" nil t) (replace-match "")))))
7914 ;;;###autoload
7915 (defun org-remember-handler ()
7916 "Store stuff from remember.el into an org file.
7917 First prompts for an org file. If the user just presses return, the value
7918 of `org-default-notes-file' is used.
7919 Then the command offers the headings tree of the selected file in order to
7920 file the text at a specific location.
7921 You can either immediately press RET to get the note appended to the
7922 file, or you can use vertical cursor motion and visibility cycling (TAB) to
7923 find a better place. Then press RET or <left> or <right> in insert the note.
7925 Key Cursor position Note gets inserted
7926 -----------------------------------------------------------------------------
7927 RET buffer-start as level 2 heading at end of file
7928 RET on headline as sublevel of the heading at cursor
7929 RET no heading at cursor position, level taken from context.
7930 Or use prefix arg to specify level manually.
7931 <left> on headline as same level, before current heading
7932 <right> on headline as same level, after current heading
7934 So the fastest way to store the note is to press RET RET to append it to
7935 the default file. This way your current train of thought is not
7936 interrupted, in accordance with the principles of remember.el. But with
7937 little extra effort, you can push it directly to the correct location.
7939 Before being stored away, the function ensures that the text has a
7940 headline, i.e. a first line that starts with a \"*\". If not, a headline
7941 is constructed from the current date and some additional data.
7943 If the variable `org-adapt-indentation' is non-nil, the entire text is
7944 also indented so that it starts in the same column as the headline
7945 \(i.e. after the stars).
7947 See also the variable `org-reverse-note-order'."
7948 (catch 'quit
7949 (let* ((txt (buffer-substring (point-min) (point-max)))
7950 (fastp current-prefix-arg)
7951 (file (if fastp org-default-notes-file (org-get-org-file)))
7952 (visiting (find-buffer-visiting file))
7953 (org-startup-with-deadline-check nil)
7954 (org-startup-folded nil)
7955 spos level indent reversed)
7956 ;; Modify text so that it becomes a nice subtree which can be inserted
7957 ;; into an org tree.
7958 (let* ((lines (split-string txt "\n"))
7959 first)
7960 ;; remove empty lines at the beginning
7961 (while (and lines (string-match "^[ \t]*\n" (car lines)))
7962 (setq lines (cdr lines)))
7963 (setq first (car lines) lines (cdr lines))
7964 (if (string-match "^\\*+" first)
7965 ;; Is already a headline
7966 (setq indent nil)
7967 ;; We need to add a headline: Use time and first buffer line
7968 (setq lines (cons first lines)
7969 first (concat "* " (current-time-string)
7970 " (" (remember-buffer-desc) ")")
7971 indent " "))
7972 (if (and org-adapt-indentation indent)
7973 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
7974 (setq txt (concat first "\n"
7975 (mapconcat 'identity lines "\n"))))
7976 ;; Find the file
7977 (if (not visiting)
7978 (find-file-noselect file))
7979 (with-current-buffer (get-file-buffer file)
7980 (setq reversed (org-notes-order-reversed-p))
7981 (save-excursion
7982 (save-restriction
7983 (widen)
7984 ;; Ask the User for a location
7985 (setq spos (if fastp 1 (org-get-location
7986 (current-buffer)
7987 org-remember-help)))
7988 (if (not spos) (throw 'quit nil)) ; return nil to show we did
7989 ; not handle this note
7990 (goto-char spos)
7991 (cond ((bobp)
7992 ;; Put it at the start or end, as level 2
7993 (save-restriction
7994 (widen)
7995 (goto-char (if reversed (point-min) (point-max)))
7996 (if (not (bolp)) (newline))
7997 (org-paste-subtree 2 txt)))
7998 ((and (org-on-heading-p nil) (not current-prefix-arg))
7999 ;; Put it below this entry, at the beg/end of the subtree
8000 (org-back-to-heading)
8001 (setq level (funcall outline-level))
8002 (if reversed
8003 (outline-end-of-heading)
8004 (outline-end-of-subtree))
8005 (if (not (bolp)) (newline))
8006 (beginning-of-line 1)
8007 (org-paste-subtree (1+ level) txt))
8009 ;; Put it right there, with automatic level determined by
8010 ;; org-paste-subtree or from prefix arg
8011 (org-paste-subtree current-prefix-arg txt)))
8012 (when remember-save-after-remembering
8013 (save-buffer)
8014 (if (not visiting) (kill-buffer (current-buffer)))))))))
8015 t) ;; return t to indicate that we took care of this note.
8017 (defun org-get-org-file ()
8018 "Read a filename, with default directory `org-directory'."
8019 (let ((default (or org-default-notes-file remember-data-file)))
8020 (read-file-name (format "File name [%s]: " default)
8021 (file-name-as-directory org-directory)
8022 default)))
8024 (defun org-notes-order-reversed-p ()
8025 "Check if the current file should receive notes in reversed order."
8026 (cond
8027 ((not org-reverse-note-order) nil)
8028 ((eq t org-reverse-note-order) t)
8029 ((not (listp org-reverse-note-order)) nil)
8030 (t (catch 'exit
8031 (let ((all org-reverse-note-order)
8032 entry)
8033 (while (setq entry (pop all))
8034 (if (string-match (car entry) buffer-file-name)
8035 (throw 'exit (cdr entry))))
8036 nil)))))
8038 ;;; Tables
8040 ;; Watch out: Here we are talking about two different kind of tables.
8041 ;; Most of the code is for the tables created with the Org-mode table editor.
8042 ;; Sometimes, we talk about tables created and edited with the table.el
8043 ;; Emacs package. We call the former org-type tables, and the latter
8044 ;; table.el-type tables.
8047 (defun org-before-change-function (beg end)
8048 "Every change indicates that a table might need an update."
8049 (setq org-table-may-need-update t))
8051 (defconst org-table-line-regexp "^[ \t]*|"
8052 "Detects an org-type table line.")
8053 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8054 "Detects an org-type table line.")
8055 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8056 "Detects a table line marked for automatic recalculation.")
8057 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8058 "Detects a table line marked for automatic recalculation.")
8059 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8060 "Detects a table line marked for automatic recalculation.")
8061 (defconst org-table-hline-regexp "^[ \t]*|-"
8062 "Detects an org-type table hline.")
8063 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8064 "Detects a table-type table hline.")
8065 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8066 "Detects an org-type or table-type table.")
8067 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8068 "Searching from within a table (any type) this finds the first line
8069 outside the table.")
8070 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8071 "Searching from within a table (any type) this finds the first line
8072 outside the table.")
8074 (defun org-table-create-with-table.el ()
8075 "Use the table.el package to insert a new table.
8076 If there is already a table at point, convert between Org-mode tables
8077 and table.el tables."
8078 (interactive)
8079 (require 'table)
8080 (cond
8081 ((org-at-table.el-p)
8082 (if (y-or-n-p "Convert table to Org-mode table? ")
8083 (org-table-convert)))
8084 ((org-at-table-p)
8085 (if (y-or-n-p "Convert table to table.el table? ")
8086 (org-table-convert)))
8087 (t (call-interactively 'table-insert))))
8089 (defun org-table-create (&optional size)
8090 "Query for a size and insert a table skeleton.
8091 SIZE is a string Columns x Rows like for example \"3x2\"."
8092 (interactive "P")
8093 (unless size
8094 (setq size (read-string
8095 (concat "Table size Columns x Rows [e.g. "
8096 org-table-default-size "]: ")
8097 "" nil org-table-default-size)))
8099 (let* ((pos (point))
8100 (indent (make-string (current-column) ?\ ))
8101 (split (org-split-string size " *x *"))
8102 (rows (string-to-number (nth 1 split)))
8103 (columns (string-to-number (car split)))
8104 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8105 "\n")))
8106 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8107 (point-at-bol) (point)))
8108 (beginning-of-line 1)
8109 (newline))
8110 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8111 (dotimes (i rows) (insert line))
8112 (goto-char pos)
8113 (if (> rows 1)
8114 ;; Insert a hline after the first row.
8115 (progn
8116 (end-of-line 1)
8117 (insert "\n|-")
8118 (goto-char pos)))
8119 (org-table-align)))
8121 (defun org-table-convert-region (beg0 end0 nspace)
8122 "Convert region to a table.
8123 The region goes from BEG0 to END0, but these borders will be moved
8124 slightly, to make sure a beginning of line in the first line is included.
8125 When NSPACE is non-nil, it indicates the minimum number of spaces that
8126 separate columns (default: just one space)."
8127 (let* ((beg (min beg0 end0))
8128 (end (max beg0 end0))
8129 (tabsep t)
8131 (goto-char beg)
8132 (beginning-of-line 1)
8133 (setq beg (move-marker (make-marker) (point)))
8134 (goto-char end)
8135 (if (bolp) (backward-char 1) (end-of-line 1))
8136 (setq end (move-marker (make-marker) (point)))
8137 ;; Lets see if this is tab-separated material. If every nonempty line
8138 ;; contains a tab, we will assume that it is tab-separated material
8139 (if nspace
8140 (setq tabsep nil)
8141 (goto-char beg)
8142 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
8143 (if nspace (setq tabsep nil))
8144 (if tabsep
8145 (setq re "^\\|\t")
8146 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
8147 (max 1 (prefix-numeric-value nspace)))))
8148 (goto-char beg)
8149 (while (re-search-forward re end t)
8150 (replace-match "|" t t))
8151 (goto-char beg)
8152 (insert " ")
8153 (org-table-align)))
8155 (defun org-table-import (file arg)
8156 "Import FILE as a table.
8157 The file is assumed to be tab-separated. Such files can be produced by most
8158 spreadsheet and database applications. If no tabs (at least one per line)
8159 are found, lines will be split on whitespace into fields."
8160 (interactive "f\nP")
8161 (or (bolp) (newline))
8162 (let ((beg (point))
8163 (pm (point-max)))
8164 (insert-file-contents file)
8165 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8167 (defun org-table-export ()
8168 "Export table as a tab-separated file.
8169 Such a file can be imported into a spreadsheet program like Excel."
8170 (interactive)
8171 (let* ((beg (org-table-begin))
8172 (end (org-table-end))
8173 (table (buffer-substring beg end))
8174 (file (read-file-name "Export table to: "))
8175 buf)
8176 (unless (or (not (file-exists-p file))
8177 (y-or-n-p (format "Overwrite file %s? " file)))
8178 (error "Abort"))
8179 (with-current-buffer (find-file-noselect file)
8180 (setq buf (current-buffer))
8181 (erase-buffer)
8182 (fundamental-mode)
8183 (insert table)
8184 (goto-char (point-min))
8185 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8186 (replace-match "" t t)
8187 (end-of-line 1))
8188 (goto-char (point-min))
8189 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8190 (replace-match "" t t)
8191 (goto-char (min (1+ (point)) (point-max))))
8192 (goto-char (point-min))
8193 (while (re-search-forward "^-[-+]*$" nil t)
8194 (replace-match "")
8195 (if (looking-at "\n")
8196 (delete-char 1)))
8197 (goto-char (point-min))
8198 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8199 (replace-match "\t" t t))
8200 (save-buffer))
8201 (kill-buffer buf)))
8203 (defvar org-table-aligned-begin-marker (make-marker)
8204 "Marker at the beginning of the table last aligned.
8205 Used to check if cursor still is in that table, to minimize realignment.")
8206 (defvar org-table-aligned-end-marker (make-marker)
8207 "Marker at the end of the table last aligned.
8208 Used to check if cursor still is in that table, to minimize realignment.")
8209 (defvar org-table-last-alignment nil
8210 "List of flags for flushright alignment, from the last re-alignment.
8211 This is being used to correctly align a single field after TAB or RET.")
8212 (defvar org-table-last-column-widths nil
8213 "List of max width of fields in each column.
8214 This is being used to correctly align a single field after TAB or RET.")
8216 (defvar org-last-recalc-line nil)
8218 (defun org-table-align ()
8219 "Align the table at point by aligning all vertical bars."
8220 (interactive)
8221 ;; (message "align") (sit-for 2)
8222 (let* (
8223 ;; Limits of table
8224 (beg (org-table-begin))
8225 (end (org-table-end))
8226 ;; Current cursor position
8227 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8228 (colpos (org-table-current-column))
8229 (winstart (window-start))
8230 text lines (new "") lengths l typenums ty fields maxfields i
8231 column
8232 (indent "") cnt frac
8233 rfmt hfmt
8234 (spaces (if (org-in-invisibility-spec-p '(org-table))
8235 org-table-spaces-around-invisible-separators
8236 org-table-spaces-around-separators))
8237 (sp1 (car spaces))
8238 (sp2 (cdr spaces))
8239 (rfmt1 (concat
8240 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8241 (hfmt1 (concat
8242 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8243 emptystrings)
8244 (untabify beg end)
8245 ;; (message "Aligning table...")
8246 ;; Get the rows
8247 (setq lines (org-split-string
8248 (buffer-substring-no-properties beg end) "\n"))
8249 ;; Store the indentation of the first line
8250 (if (string-match "^ *" (car lines))
8251 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8252 ;; Mark the hlines
8253 (setq lines (mapcar (lambda (l)
8254 (if (string-match "^ *|-" l)
8256 (if (string-match "[ \t]+$" l)
8257 (substring l 0 (match-beginning 0))
8258 l)))
8259 lines))
8260 ;; Get the data fields
8261 (setq fields (mapcar
8262 (lambda (l)
8263 (org-split-string l " *| *"))
8264 (delq nil (copy-sequence lines))))
8265 ;; How many fields in the longest line?
8266 (condition-case nil
8267 (setq maxfields (apply 'max (mapcar 'length fields)))
8268 (error
8269 (kill-region beg end)
8270 (org-table-create org-table-default-size)
8271 (error "Empty table - created default table")))
8272 ;; A list of empty string to fill any short rows on output
8273 (setq emptystrings (make-list maxfields ""))
8274 ;; Get the maximum length of a field and the most common datatype
8275 ;; for each column
8276 (setq i -1)
8277 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8278 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8279 ;; maximum length
8280 (push (apply 'max 1 (mapcar 'string-width column)) lengths)
8281 ;; compute the fraction stepwise, ignoring empty fields
8282 (setq cnt 0 frac 0.0)
8283 (mapcar
8284 (lambda (x)
8285 (if (equal x "")
8287 (setq frac ( / (+ (* frac cnt)
8288 (if (string-match org-table-number-regexp x) 1 0))
8289 (setq cnt (1+ cnt))))))
8290 column)
8291 (push (>= frac org-table-number-fraction) typenums))
8292 (setq lengths (nreverse lengths)
8293 typenums (nreverse typenums))
8294 (setq org-table-last-alignment typenums
8295 org-table-last-column-widths lengths)
8296 ;; Compute the formats needed for output of the table
8297 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8298 (while (setq l (pop lengths))
8299 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8300 (setq rfmt (concat rfmt (format rfmt1 ty l))
8301 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8302 (setq rfmt (concat rfmt "\n")
8303 hfmt (concat (substring hfmt 0 -1) "|\n"))
8304 ;; Produce the new table
8305 ;;(while lines
8306 ;; (setq l (pop lines))
8307 ;; (if l
8308 ;; (setq new (concat new (apply 'format rfmt
8309 ;; (append (pop fields) emptystrings))))
8310 ;; (setq new (concat new hfmt))))
8311 (setq new (mapconcat
8312 (lambda (l)
8313 (if l (apply 'format rfmt
8314 (append (pop fields) emptystrings))
8315 hfmt))
8316 lines ""))
8317 ;; Replace the old one
8318 (delete-region beg end)
8319 (move-marker end nil)
8320 (move-marker org-table-aligned-begin-marker (point))
8321 (insert new)
8322 (move-marker org-table-aligned-end-marker (point))
8323 ;; Try to move to the old location (approximately)
8324 (goto-line linepos)
8325 (set-window-start (selected-window) winstart 'noforce)
8326 (org-table-goto-column colpos)
8327 (setq org-table-may-need-update nil)
8328 (if (org-in-invisibility-spec-p '(org-table))
8329 (org-table-add-invisible-to-vertical-lines))
8332 (defun org-table-begin (&optional table-type)
8333 "Find the beginning of the table and return its position.
8334 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8335 (save-excursion
8336 (if (not (re-search-backward
8337 (if table-type org-table-any-border-regexp
8338 org-table-border-regexp)
8339 nil t))
8340 (error "Can't find beginning of table")
8341 (goto-char (match-beginning 0))
8342 (beginning-of-line 2)
8343 (point))))
8345 (defun org-table-end (&optional table-type)
8346 "Find the end of the table and return its position.
8347 With argument TABLE-TYPE, go to the end of a table.el-type table."
8348 (save-excursion
8349 (if (not (re-search-forward
8350 (if table-type org-table-any-border-regexp
8351 org-table-border-regexp)
8352 nil t))
8353 (goto-char (point-max))
8354 (goto-char (match-beginning 0)))
8355 (point-marker)))
8357 (defun org-table-justify-field-maybe (&optional new)
8358 "Justify the current field, text to left, number to right.
8359 Optional argument NEW may specify text to replace the current field content."
8360 (cond
8361 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8362 ((org-at-table-hline-p)
8363 ;; FIXME: I used to enforce realign here, but I think this is not needed.
8364 ;; (setq org-table-may-need-update t)
8366 ((and (not new)
8367 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8368 (current-buffer)))
8369 (< (point) org-table-aligned-begin-marker)
8370 (>= (point) org-table-aligned-end-marker)))
8371 ;; This is not the same table, force a full re-align
8372 (setq org-table-may-need-update t))
8373 (t ;; realign the current field, based on previous full realign
8374 (let* ((pos (point)) s
8375 (col (org-table-current-column))
8376 (num (nth (1- col) org-table-last-alignment))
8377 l f n o e)
8378 (when (> col 0)
8379 (skip-chars-backward "^|\n")
8380 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8381 (progn
8382 (setq s (match-string 1)
8383 o (match-string 0)
8384 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8385 e (not (= (match-beginning 2) (match-end 2))))
8386 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8387 l (if e "|" (setq org-table-may-need-update t) ""))
8388 n (format f s t t))
8389 (if new
8390 (if (<= (length new) l)
8391 (setq n (format f new t t)) ;; FIXME: why t t?????
8392 (setq n (concat new "|") org-table-may-need-update t)))
8393 (or (equal n o)
8394 (let (org-table-may-need-update)
8395 (replace-match n))))
8396 (setq org-table-may-need-update t))
8397 (goto-char pos))))))
8399 (defun org-table-next-field ()
8400 "Go to the next field in the current table, creating new lines as needed.
8401 Before doing so, re-align the table if necessary."
8402 (interactive)
8403 (org-table-maybe-eval-formula)
8404 (org-table-maybe-recalculate-line)
8405 (if (and org-table-automatic-realign
8406 org-table-may-need-update)
8407 (org-table-align))
8408 (let ((end (org-table-end)))
8409 (if (org-at-table-hline-p)
8410 (end-of-line 1))
8411 (condition-case nil
8412 (progn
8413 (re-search-forward "|" end)
8414 (if (looking-at "[ \t]*$")
8415 (re-search-forward "|" end))
8416 (if (and (looking-at "-")
8417 org-table-tab-jumps-over-hlines
8418 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8419 (goto-char (match-beginning 1)))
8420 (if (looking-at "-")
8421 (progn
8422 (beginning-of-line 0)
8423 (org-table-insert-row 'below))
8424 (if (looking-at " ") (forward-char 1))))
8425 (error
8426 (org-table-insert-row 'below)))))
8428 (defun org-table-previous-field ()
8429 "Go to the previous field in the table.
8430 Before doing so, re-align the table if necessary."
8431 (interactive)
8432 (org-table-justify-field-maybe)
8433 (org-table-maybe-recalculate-line)
8434 (if (and org-table-automatic-realign
8435 org-table-may-need-update)
8436 (org-table-align))
8437 (if (org-at-table-hline-p)
8438 (end-of-line 1))
8439 (re-search-backward "|" (org-table-begin))
8440 (re-search-backward "|" (org-table-begin))
8441 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8442 (re-search-backward "|" (org-table-begin)))
8443 (if (looking-at "| ?")
8444 (goto-char (match-end 0))))
8446 (defun org-table-next-row ()
8447 "Go to the next row (same column) in the current table.
8448 Before doing so, re-align the table if necessary."
8449 (interactive)
8450 (org-table-maybe-eval-formula)
8451 (org-table-maybe-recalculate-line)
8452 (if (or (looking-at "[ \t]*$")
8453 (save-excursion (skip-chars-backward " \t") (bolp)))
8454 (newline)
8455 (if (and org-table-automatic-realign
8456 org-table-may-need-update)
8457 (org-table-align))
8458 (let ((col (org-table-current-column)))
8459 (beginning-of-line 2)
8460 (if (or (not (org-at-table-p))
8461 (org-at-table-hline-p))
8462 (progn
8463 (beginning-of-line 0)
8464 (org-table-insert-row 'below)))
8465 (org-table-goto-column col)
8466 (skip-chars-backward "^|\n\r")
8467 (if (looking-at " ") (forward-char 1)))))
8469 (defun org-table-copy-down (n)
8470 "Copy a field down in the current column.
8471 If the field at the cursor is empty, copy into it the content of the nearest
8472 non-empty field above. With argument N, use the Nth non-empty field.
8473 If the current field is not empty, it is copied down to the next row, and
8474 the cursor is moved with it. Therefore, repeating this command causes the
8475 column to be filled row-by-row.
8476 If the variable `org-table-copy-increment' is non-nil and the field is an
8477 integer, it will be incremented while copying."
8478 (interactive "p")
8479 (let* ((colpos (org-table-current-column))
8480 (field (org-table-get-field))
8481 (non-empty (string-match "[^ \t]" field))
8482 (beg (org-table-begin))
8483 txt)
8484 (org-table-check-inside-data-field)
8485 (if non-empty
8486 (progn
8487 (setq txt (org-trim field))
8488 (org-table-next-row)
8489 (org-table-blank-field))
8490 (save-excursion
8491 (setq txt
8492 (catch 'exit
8493 (while (progn (beginning-of-line 1)
8494 (re-search-backward org-table-dataline-regexp
8495 beg t))
8496 (org-table-goto-column colpos t)
8497 (if (and (looking-at
8498 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8499 (= (setq n (1- n)) 0))
8500 (throw 'exit (match-string 1))))))))
8501 (if txt
8502 (progn
8503 (if (and org-table-copy-increment
8504 (string-match "^[0-9]+$" txt))
8505 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8506 (insert txt)
8507 (org-table-maybe-recalculate-line)
8508 (org-table-align))
8509 (error "No non-empty field found"))))
8511 (defun org-table-check-inside-data-field ()
8512 "Is point inside a table data field?
8513 I.e. not on a hline or before the first or after the last column?
8514 This actually throws an error, so it aborts the current command."
8515 (if (or (not (org-at-table-p))
8516 (= (org-table-current-column) 0)
8517 (org-at-table-hline-p)
8518 (looking-at "[ \t]*$"))
8519 (error "Not in table data field")))
8521 (defvar org-table-clip nil
8522 "Clipboard for table regions.")
8524 (defun org-table-blank-field ()
8525 "Blank the current table field or active region."
8526 (interactive)
8527 (org-table-check-inside-data-field)
8528 (if (and (interactive-p) (org-region-active-p))
8529 (let (org-table-clip)
8530 (org-table-cut-region (region-beginning) (region-end)))
8531 (skip-chars-backward "^|")
8532 (backward-char 1)
8533 (if (looking-at "|[^|\n]+")
8534 (let* ((pos (match-beginning 0))
8535 (match (match-string 0))
8536 (len (string-width match)))
8537 (replace-match (concat "|" (make-string (1- len) ?\ )))
8538 (goto-char (+ 2 pos))
8539 (substring match 1)))))
8541 (defun org-table-get-field (&optional n replace)
8542 "Return the value of the field in column N of current row.
8543 N defaults to current field.
8544 If REPLACE is a string, replace field with this value. The return value
8545 is always the old value."
8546 (and n (org-table-goto-column n))
8547 (skip-chars-backward "^|\n")
8548 (backward-char 1)
8549 (if (looking-at "|[^|\r\n]*")
8550 (let* ((pos (match-beginning 0))
8551 (val (buffer-substring (1+ pos) (match-end 0))))
8552 (if replace
8553 (replace-match (concat "|" replace)))
8554 (goto-char (min (point-at-eol) (+ 2 pos)))
8555 val)
8556 (forward-char 1) ""))
8558 (defun org-table-current-column ()
8559 "Find out which column we are in.
8560 When called interactively, column is also displayed in echo area."
8561 (interactive)
8562 (if (interactive-p) (org-table-check-inside-data-field))
8563 (save-excursion
8564 (let ((cnt 0) (pos (point)))
8565 (beginning-of-line 1)
8566 (while (search-forward "|" pos t)
8567 (setq cnt (1+ cnt)))
8568 (if (interactive-p) (message "This is table column %d" cnt))
8569 cnt)))
8571 (defun org-table-goto-column (n &optional on-delim force)
8572 "Move the cursor to the Nth column in the current table line.
8573 With optional argument ON-DELIM, stop with point before the left delimiter
8574 of the field.
8575 If there are less than N fields, just go to after the last delimiter.
8576 However, when FORCE is non-nil, create new columns if necessary."
8577 (interactive "p")
8578 (let ((pos (point-at-eol)))
8579 (beginning-of-line 1)
8580 (when (> n 0)
8581 (while (and (> (setq n (1- n)) -1)
8582 (or (search-forward "|" pos t)
8583 (and force
8584 (progn (end-of-line 1)
8585 (skip-chars-backward "^|")
8586 (insert " | "))))))
8587 ; (backward-char 2) t)))))
8588 (when (and force (not (looking-at ".*|")))
8589 (save-excursion (end-of-line 1) (insert " | ")))
8590 (if on-delim
8591 (backward-char 1)
8592 (if (looking-at " ") (forward-char 1))))))
8594 (defun org-at-table-p (&optional table-type)
8595 "Return t if the cursor is inside an org-type table.
8596 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8597 (if org-enable-table-editor
8598 (save-excursion
8599 (beginning-of-line 1)
8600 (looking-at (if table-type org-table-any-line-regexp
8601 org-table-line-regexp)))
8602 nil))
8604 (defun org-at-table.el-p ()
8605 "Return t if and only if we are at a table.el table."
8606 (and (org-at-table-p 'any)
8607 (save-excursion
8608 (goto-char (org-table-begin 'any))
8609 (looking-at org-table1-hline-regexp))))
8611 (defun org-table-recognize-table.el ()
8612 "If there is a table.el table nearby, recognize it and move into it."
8613 (if org-table-tab-recognizes-table.el
8614 (if (org-at-table.el-p)
8615 (progn
8616 (beginning-of-line 1)
8617 (if (looking-at org-table-dataline-regexp)
8619 (if (looking-at org-table1-hline-regexp)
8620 (progn
8621 (beginning-of-line 2)
8622 (if (looking-at org-table-any-border-regexp)
8623 (beginning-of-line -1)))))
8624 (if (re-search-forward "|" (org-table-end t) t)
8625 (progn
8626 (require 'table)
8627 (if (table--at-cell-p (point))
8629 (message "recognizing table.el table...")
8630 (table-recognize-table)
8631 (message "recognizing table.el table...done")))
8632 (error "This should not happen..."))
8634 nil)
8635 nil))
8637 (defun org-at-table-hline-p ()
8638 "Return t if the cursor is inside a hline in a table."
8639 (if org-enable-table-editor
8640 (save-excursion
8641 (beginning-of-line 1)
8642 (looking-at org-table-hline-regexp))
8643 nil))
8645 (defun org-table-insert-column ()
8646 "Insert a new column into the table."
8647 (interactive)
8648 (if (not (org-at-table-p))
8649 (error "Not at a table"))
8650 (org-table-find-dataline)
8651 (let* ((col (max 1 (org-table-current-column)))
8652 (beg (org-table-begin))
8653 (end (org-table-end))
8654 ;; Current cursor position
8655 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8656 (colpos col))
8657 (goto-char beg)
8658 (while (< (point) end)
8659 (if (org-at-table-hline-p)
8661 (org-table-goto-column col t)
8662 (insert "| "))
8663 (beginning-of-line 2))
8664 (move-marker end nil)
8665 (goto-line linepos)
8666 (org-table-goto-column colpos)
8667 (org-table-align)
8668 (org-table-modify-formulas 'insert col)))
8670 (defun org-table-find-dataline ()
8671 "Find a dataline in the current table, which is needed for column commands."
8672 (if (and (org-at-table-p)
8673 (not (org-at-table-hline-p)))
8675 (let ((col (current-column))
8676 (end (org-table-end)))
8677 (move-to-column col)
8678 (while (and (< (point) end)
8679 (or (not (= (current-column) col))
8680 (org-at-table-hline-p)))
8681 (beginning-of-line 2)
8682 (move-to-column col))
8683 (if (and (org-at-table-p)
8684 (not (org-at-table-hline-p)))
8686 (error
8687 "Please position cursor in a data line for column operations")))))
8689 (defun org-table-delete-column ()
8690 "Delete a column into the table."
8691 (interactive)
8692 (if (not (org-at-table-p))
8693 (error "Not at a table"))
8694 (org-table-find-dataline)
8695 (org-table-check-inside-data-field)
8696 (let* ((col (org-table-current-column))
8697 (beg (org-table-begin))
8698 (end (org-table-end))
8699 ;; Current cursor position
8700 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8701 (colpos col))
8702 (goto-char beg)
8703 (while (< (point) end)
8704 (if (org-at-table-hline-p)
8706 (org-table-goto-column col t)
8707 (and (looking-at "|[^|\n]+|")
8708 (replace-match "|")))
8709 (beginning-of-line 2))
8710 (move-marker end nil)
8711 (goto-line linepos)
8712 (org-table-goto-column colpos)
8713 (org-table-align)
8714 (org-table-modify-formulas 'remove col)))
8716 (defun org-table-move-column-right ()
8717 "Move column to the right."
8718 (interactive)
8719 (org-table-move-column nil))
8720 (defun org-table-move-column-left ()
8721 "Move column to the left."
8722 (interactive)
8723 (org-table-move-column 'left))
8725 (defun org-table-move-column (&optional left)
8726 "Move the current column to the right. With arg LEFT, move to the left."
8727 (interactive "P")
8728 (if (not (org-at-table-p))
8729 (error "Not at a table"))
8730 (org-table-find-dataline)
8731 (org-table-check-inside-data-field)
8732 (let* ((col (org-table-current-column))
8733 (col1 (if left (1- col) col))
8734 (beg (org-table-begin))
8735 (end (org-table-end))
8736 ;; Current cursor position
8737 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8738 (colpos (if left (1- col) (1+ col))))
8739 (if (and left (= col 1))
8740 (error "Cannot move column further left"))
8741 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8742 (error "Cannot move column further right"))
8743 (goto-char beg)
8744 (while (< (point) end)
8745 (if (org-at-table-hline-p)
8747 (org-table-goto-column col1 t)
8748 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8749 (replace-match "|\\2|\\1|")))
8750 (beginning-of-line 2))
8751 (move-marker end nil)
8752 (goto-line linepos)
8753 (org-table-goto-column colpos)
8754 (org-table-align)
8755 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
8757 (defun org-table-move-row-down ()
8758 "Move table row down."
8759 (interactive)
8760 (org-table-move-row nil))
8761 (defun org-table-move-row-up ()
8762 "Move table row up."
8763 (interactive)
8764 (org-table-move-row 'up))
8766 (defun org-table-move-row (&optional up)
8767 "Move the current table line down. With arg UP, move it up."
8768 (interactive "P")
8769 (let ((col (current-column))
8770 (pos (point))
8771 (tonew (if up 0 2))
8772 txt)
8773 (beginning-of-line tonew)
8774 (if (not (org-at-table-p))
8775 (progn
8776 (goto-char pos)
8777 (error "Cannot move row further")))
8778 (goto-char pos)
8779 (beginning-of-line 1)
8780 (setq pos (point))
8781 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8782 (delete-region (point) (1+ (point-at-eol)))
8783 (beginning-of-line tonew)
8784 (insert txt)
8785 (beginning-of-line 0)
8786 (move-to-column col)))
8788 (defun org-table-insert-row (&optional arg)
8789 "Insert a new row above the current line into the table.
8790 With prefix ARG, insert below the current line."
8791 (interactive "P")
8792 (if (not (org-at-table-p))
8793 (error "Not at a table"))
8794 (let* ((line
8795 (org-expand-wide-chars
8796 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8797 new)
8798 (if (string-match "^[ \t]*|-" line)
8799 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
8800 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
8801 ;; Fix the first field if necessary
8802 (setq new (concat new))
8803 (if (string-match "^[ \t]*| *[#$] *|" line)
8804 (setq new (replace-match (match-string 0 line) t t new)))
8805 (beginning-of-line (if arg 2 1))
8806 (let (org-table-may-need-update)
8807 (insert-before-markers new)
8808 (insert-before-markers "\n"))
8809 (beginning-of-line 0)
8810 (re-search-forward "| ?" (point-at-eol) t)
8811 (and org-table-may-need-update (org-table-align))))
8813 (defun org-table-insert-hline (&optional arg)
8814 "Insert a horizontal-line below the current line into the table.
8815 With prefix ARG, insert above the current line."
8816 (interactive "P")
8817 (if (not (org-at-table-p))
8818 (error "Not at a table"))
8819 (let ((line
8820 (org-expand-wide-chars
8821 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8822 (col (current-column))
8823 start)
8824 (if (string-match "^[ \t]*|-" line)
8825 (setq line
8826 (mapcar (lambda (x) (if (member x '(?| ?+))
8827 (prog1 (if start ?+ ?|) (setq start t))
8828 (if start ?- ?\ )))
8829 line))
8830 (setq line
8831 (mapcar (lambda (x) (if (equal x ?|)
8832 (prog1 (if start ?+ ?|) (setq start t))
8833 (if start ?- ?\ )))
8834 line)))
8835 (beginning-of-line (if arg 1 2))
8836 (apply 'insert line)
8837 (if (equal (char-before (point)) ?+)
8838 (progn (backward-delete-char 1) (insert "|")))
8839 (insert "\n")
8840 (beginning-of-line (if arg 1 -1))
8841 (move-to-column col)))
8843 (defun org-expand-wide-chars (s)
8844 "Expand wide characters to spaces."
8845 (let (w a)
8846 (mapconcat
8847 (lambda (x)
8848 (if (> (setq w (string-width (setq a (char-to-string x)))) 1)
8849 (make-string w ?\ )
8851 s "")))
8853 (defun org-table-kill-row ()
8854 "Delete the current row or horizontal line from the table."
8855 (interactive)
8856 (if (not (org-at-table-p))
8857 (error "Not at a table"))
8858 (let ((col (current-column)))
8859 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8860 (if (not (org-at-table-p)) (beginning-of-line 0))
8861 (move-to-column col)))
8863 (defun org-table-sort-lines (beg end numericp)
8864 "Sort table lines in region.
8865 Point and mark define the first and last line to include. Both point and
8866 mark should be in the column that is used for sorting. For example, to
8867 sort according to column 3, put the mark in the first line to sort, in
8868 table column 3. Put point into the last line to be included in the sorting,
8869 also in table column 3. The command will prompt for the sorting method
8870 \(n for numerical, a for alphanumeric)."
8871 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
8872 (setq numericp (string-match "[nN]" numericp))
8873 (org-table-align) ;; Just to be safe
8874 (let* (bcol ecol cmp column lns)
8875 (goto-char beg)
8876 (org-table-check-inside-data-field)
8877 (setq column (org-table-current-column)
8878 beg (move-marker (make-marker) (point-at-bol)))
8879 (goto-char end)
8880 (org-table-check-inside-data-field)
8881 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
8882 (untabify beg end)
8883 (goto-char beg)
8884 (org-table-goto-column column)
8885 (skip-chars-backward "^|")
8886 (setq bcol (current-column))
8887 (org-table-goto-column (1+ column))
8888 (skip-chars-backward "^|")
8889 (setq ecol (1- (current-column)))
8890 (setq cmp (if numericp
8891 (lambda (a b) (< (car a) (car b)))
8892 (lambda (a b) (string< (car a) (car b)))))
8893 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8894 (split-string (buffer-substring beg end) "\n")))
8895 (if numericp
8896 (setq lns (mapcar (lambda(x)
8897 (cons (string-to-number (car x)) (cdr x)))
8898 lns)))
8899 (delete-region beg end)
8900 (move-marker beg nil)
8901 (move-marker end nil)
8902 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
8903 (message "%d lines sorted %s based on column %d"
8904 (length lns)
8905 (if numericp "numerically" "alphabetically") column)))
8907 (defun org-table-cut-region (beg end)
8908 "Copy region in table to the clipboard and blank all relevant fields."
8909 (interactive "r")
8910 (org-table-copy-region beg end 'cut))
8912 (defun org-table-copy-region (beg end &optional cut)
8913 "Copy rectangular region in table to clipboard.
8914 A special clipboard is used which can only be accessed
8915 with `org-table-paste-rectangle'."
8916 (interactive "rP")
8917 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8918 region cols
8919 (rpl (if cut " " nil)))
8920 (goto-char beg)
8921 (org-table-check-inside-data-field)
8922 (setq l01 (count-lines (point-min) (point))
8923 c01 (org-table-current-column))
8924 (goto-char end)
8925 (org-table-check-inside-data-field)
8926 (setq l02 (count-lines (point-min) (point))
8927 c02 (org-table-current-column))
8928 (setq l1 (min l01 l02) l2 (max l01 l02)
8929 c1 (min c01 c02) c2 (max c01 c02))
8930 (catch 'exit
8931 (while t
8932 (catch 'nextline
8933 (if (> l1 l2) (throw 'exit t))
8934 (goto-line l1)
8935 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8936 (setq cols nil ic1 c1 ic2 c2)
8937 (while (< ic1 (1+ ic2))
8938 (push (org-table-get-field ic1 rpl) cols)
8939 (setq ic1 (1+ ic1)))
8940 (push (nreverse cols) region)
8941 (setq l1 (1+ l1)))))
8942 (setq org-table-clip (nreverse region))
8943 (if cut (org-table-align))
8944 org-table-clip))
8946 (defun org-table-paste-rectangle ()
8947 "Paste a rectangular region into a table.
8948 The upper right corner ends up in the current field. All involved fields
8949 will be overwritten. If the rectangle does not fit into the present table,
8950 the table is enlarged as needed. The process ignores horizontal separator
8951 lines."
8952 (interactive)
8953 (unless (and org-table-clip (listp org-table-clip))
8954 (error "First cut/copy a region to paste!"))
8955 (org-table-check-inside-data-field)
8956 (let* ((clip org-table-clip)
8957 (line (count-lines (point-min) (point)))
8958 (col (org-table-current-column))
8959 (org-enable-table-editor t)
8960 (org-table-automatic-realign nil)
8961 c cols field)
8962 (while (setq cols (pop clip))
8963 (while (org-at-table-hline-p) (beginning-of-line 2))
8964 (if (not (org-at-table-p))
8965 (progn (end-of-line 0) (org-table-next-field)))
8966 (setq c col)
8967 (while (setq field (pop cols))
8968 (org-table-goto-column c nil 'force)
8969 (org-table-get-field nil field)
8970 (setq c (1+ c)))
8971 (beginning-of-line 2))
8972 (goto-line line)
8973 (org-table-goto-column col)
8974 (org-table-align)))
8976 (defun org-table-convert ()
8977 "Convert from `org-mode' table to table.el and back.
8978 Obviously, this only works within limits. When an Org-mode table is
8979 converted to table.el, all horizontal separator lines get lost, because
8980 table.el uses these as cell boundaries and has no notion of horizontal lines.
8981 A table.el table can be converted to an Org-mode table only if it does not
8982 do row or column spanning. Multiline cells will become multiple cells.
8983 Beware, Org-mode does not test if the table can be successfully converted - it
8984 blindly applies a recipe that works for simple tables."
8985 (interactive)
8986 (require 'table)
8987 (if (org-at-table.el-p)
8988 ;; convert to Org-mode table
8989 (let ((beg (move-marker (make-marker) (org-table-begin t)))
8990 (end (move-marker (make-marker) (org-table-end t))))
8991 (table-unrecognize-region beg end)
8992 (goto-char beg)
8993 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
8994 (replace-match ""))
8995 (goto-char beg))
8996 (if (org-at-table-p)
8997 ;; convert to table.el table
8998 (let ((beg (move-marker (make-marker) (org-table-begin)))
8999 (end (move-marker (make-marker) (org-table-end))))
9000 ;; first, get rid of all horizontal lines
9001 (goto-char beg)
9002 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9003 (replace-match ""))
9004 ;; insert a hline before first
9005 (goto-char beg)
9006 (org-table-insert-hline 'above)
9007 (beginning-of-line -1)
9008 ;; insert a hline after each line
9009 (while (progn (beginning-of-line 3) (< (point) end))
9010 (org-table-insert-hline))
9011 (goto-char beg)
9012 (setq end (move-marker end (org-table-end)))
9013 ;; replace "+" at beginning and ending of hlines
9014 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9015 (replace-match "\\1+-"))
9016 (goto-char beg)
9017 (while (re-search-forward "-|[ \t]*$" end t)
9018 (replace-match "-+"))
9019 (goto-char beg)))))
9021 (defun org-table-wrap-region (arg)
9022 "Wrap several fields in a column like a paragraph.
9023 This is useful if you'd like to spread the contents of a field over several
9024 lines, in order to keep the table compact.
9026 If there is an active region, and both point and mark are in the same column,
9027 the text in the column is wrapped to minimum width for the given number of
9028 lines. Generally, this makes the table more compact. A prefix ARG may be
9029 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9030 formats the selected text to two lines. If the region was longer than two
9031 lines, the remaining lines remain empty. A negative prefix argument reduces
9032 the current number of lines by that amount. The wrapped text is pasted back
9033 into the table. If you formatted it to more lines than it was before, fields
9034 further down in the table get overwritten - so you might need to make space in
9035 the table first.
9037 If there is no region, the current field is split at the cursor position and
9038 the text fragment to the right of the cursor is prepended to the field one
9039 line down.
9041 If there is no region, but you specify a prefix ARG, the current field gets
9042 blank, and the content is appended to the field above."
9043 (interactive "P")
9044 (org-table-check-inside-data-field)
9045 (if (org-region-active-p)
9046 ;; There is a region: fill as a paragraph
9047 (let ((beg (region-beginning))
9048 nlines)
9049 (org-table-cut-region (region-beginning) (region-end))
9050 (if (> (length (car org-table-clip)) 1)
9051 (error "Region must be limited to single column"))
9052 (setq nlines (if arg
9053 (if (< arg 1)
9054 (+ (length org-table-clip) arg)
9055 arg)
9056 (length org-table-clip)))
9057 (setq org-table-clip
9058 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9059 nil nlines)))
9060 (goto-char beg)
9061 (org-table-paste-rectangle))
9062 ;; No region, split the current field at point
9063 (if arg
9064 ;; combine with field above
9065 (let ((s (org-table-blank-field))
9066 (col (org-table-current-column)))
9067 (beginning-of-line 0)
9068 (while (org-at-table-hline-p) (beginning-of-line 0))
9069 (org-table-goto-column col)
9070 (skip-chars-forward "^|")
9071 (skip-chars-backward " ")
9072 (insert " " (org-trim s))
9073 (org-table-align))
9074 ;; split field
9075 (when (looking-at "\\([^|]+\\)+|")
9076 (let ((s (match-string 1)))
9077 (replace-match " |")
9078 (goto-char (match-beginning 0))
9079 (org-table-next-row)
9080 (insert (org-trim s) " ")
9081 (org-table-align))))))
9083 (defun org-trim (s)
9084 "Remove whitespace at beginning and end of string."
9085 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
9086 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
9089 (defun org-wrap (string &optional width lines)
9090 "Wrap string to either a number of lines, or a width in characters.
9091 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9092 that costs. If there is a word longer than WIDTH, the text is actually
9093 wrapped to the length of that word.
9094 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9095 many lines, whatever width that takes.
9096 The return value is a list of lines, without newlines at the end."
9097 (let* ((words (org-split-string string "[ \t\n]+"))
9098 (maxword (apply 'max (mapcar 'string-width words)))
9099 w ll)
9100 (cond (width
9101 (org-do-wrap words (max maxword width)))
9102 (lines
9103 (setq w maxword)
9104 (setq ll (org-do-wrap words maxword))
9105 (if (<= (length ll) lines)
9107 (setq ll words)
9108 (while (> (length ll) lines)
9109 (setq w (1+ w))
9110 (setq ll (org-do-wrap words w)))
9111 ll))
9112 (t (error "Cannot wrap this")))))
9115 (defun org-do-wrap (words width)
9116 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9117 (let (lines line)
9118 (while words
9119 (setq line (pop words))
9120 (while (and words (< (+ (length line) (length (car words))) width))
9121 (setq line (concat line " " (pop words))))
9122 (setq lines (push line lines)))
9123 (nreverse lines)))
9125 ;; FIXME: I think I can make this more efficient
9126 (defun org-split-string (string &optional separators)
9127 "Splits STRING into substrings at SEPARATORS.
9128 No empty strings are returned if there are matches at the beginning
9129 and end of string."
9130 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9131 (start 0)
9132 notfirst
9133 (list nil))
9134 (while (and (string-match rexp string
9135 (if (and notfirst
9136 (= start (match-beginning 0))
9137 (< start (length string)))
9138 (1+ start) start))
9139 (< (match-beginning 0) (length string)))
9140 (setq notfirst t)
9141 (or (eq (match-beginning 0) 0)
9142 (and (eq (match-beginning 0) (match-end 0))
9143 (eq (match-beginning 0) start))
9144 (setq list
9145 (cons (substring string start (match-beginning 0))
9146 list)))
9147 (setq start (match-end 0)))
9148 (or (eq start (length string))
9149 (setq list
9150 (cons (substring string start)
9151 list)))
9152 (nreverse list)))
9154 (defun org-table-add-invisible-to-vertical-lines ()
9155 "Add an `invisible' property to vertical lines of current table."
9156 (interactive)
9157 (let* ((beg (org-table-begin))
9158 (end (org-table-end))
9159 (end1))
9160 (save-excursion
9161 (goto-char beg)
9162 (while (< (point) end)
9163 (setq end1 (point-at-eol))
9164 (if (looking-at org-table-dataline-regexp)
9165 (while (re-search-forward "|" end1 t)
9166 (add-text-properties (1- (point)) (point)
9167 '(invisible org-table)))
9168 (while (re-search-forward "[+|]" end1 t)
9169 (add-text-properties (1- (point)) (point)
9170 '(invisible org-table))))
9171 (beginning-of-line 2)))))
9173 (defun org-table-toggle-vline-visibility (&optional arg)
9174 "Toggle the visibility of table vertical lines.
9175 The effect is immediate and on all tables in the file.
9176 With prefix ARG, make lines invisible when ARG is positive, make lines
9177 visible when ARG is not positive."
9178 (interactive "P")
9179 (let ((action (cond
9180 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
9181 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
9182 (t (if (org-in-invisibility-spec-p '(org-table))
9183 'off
9184 'on)))))
9185 (if (eq action 'off)
9186 (progn
9187 (org-remove-from-invisibility-spec '(org-table))
9188 (org-table-map-tables 'org-table-align)
9189 (message "Vertical table lines visible")
9190 (if (org-at-table-p)
9191 (org-table-align)))
9192 (org-add-to-invisibility-spec '(org-table))
9193 (org-table-map-tables 'org-table-align)
9194 (message "Vertical table lines invisible"))
9195 (redraw-frame (selected-frame))))
9197 (defun org-table-map-tables (function)
9198 "Apply FUNCTION to the start of all tables in the buffer."
9199 (save-excursion
9200 (save-restriction
9201 (widen)
9202 (goto-char (point-min))
9203 (while (re-search-forward org-table-any-line-regexp nil t)
9204 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9205 (beginning-of-line 1)
9206 (if (looking-at org-table-line-regexp)
9207 (save-excursion (funcall function)))
9208 (re-search-forward org-table-any-border-regexp nil 1)))))
9210 (defun org-table-sum (&optional beg end nlast)
9211 "Sum numbers in region of current table column.
9212 The result will be displayed in the echo area, and will be available
9213 as kill to be inserted with \\[yank].
9215 If there is an active region, it is interpreted as a rectangle and all
9216 numbers in that rectangle will be summed. If there is no active
9217 region and point is located in a table column, sum all numbers in that
9218 column.
9220 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9221 numbers are assumed to be times as well (in decimal hours) and the
9222 numbers are added as such.
9224 If NLAST is a number, only the NLAST fields will actually be summed."
9225 (interactive)
9226 (save-excursion
9227 (let (col (timecnt 0) diff h m s org-table-clip)
9228 (cond
9229 ((and beg end)) ; beg and end given explicitly
9230 ((org-region-active-p)
9231 (setq beg (region-beginning) end (region-end)))
9233 (setq col (org-table-current-column))
9234 (goto-char (org-table-begin))
9235 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9236 (error "No table data"))
9237 (org-table-goto-column col)
9238 ;not needed? (skip-chars-backward "^|")
9239 (setq beg (point))
9240 (goto-char (org-table-end))
9241 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9242 (error "No table data"))
9243 (org-table-goto-column col)
9244 ;not needed? (skip-chars-forward "^|")
9245 (setq end (point))))
9246 (let* ((items (apply 'append (org-table-copy-region beg end)))
9247 (items1 (cond ((not nlast) items)
9248 ((>= nlast (length items)) items)
9249 (t (setq items (reverse items))
9250 (setcdr (nthcdr (1- nlast) items) nil)
9251 (nreverse items))))
9252 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9253 items1)))
9254 (res (apply '+ numbers))
9255 (sres (if (= timecnt 0)
9256 (format "%g" res)
9257 (setq diff (* 3600 res)
9258 h (floor (/ diff 3600)) diff (mod diff 3600)
9259 m (floor (/ diff 60)) diff (mod diff 60)
9260 s diff)
9261 (format "%d:%02d:%02d" h m s))))
9262 (kill-new sres)
9263 (if (interactive-p)
9264 (message "%s"
9265 (substitute-command-keys
9266 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9267 (length numbers) sres))))
9268 sres))))
9270 (defun org-table-get-number-for-summing (s)
9271 (let (n)
9272 (if (string-match "^ *|? *" s)
9273 (setq s (replace-match "" nil nil s)))
9274 (if (string-match " *|? *$" s)
9275 (setq s (replace-match "" nil nil s)))
9276 (setq n (string-to-number s))
9277 (cond
9278 ((and (string-match "0" s)
9279 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9280 ((string-match "\\`[ \t]+\\'" s) nil)
9281 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9282 (let ((h (string-to-number (or (match-string 1 s) "0")))
9283 (m (string-to-number (or (match-string 2 s) "0")))
9284 (s (string-to-number (or (match-string 4 s) "0"))))
9285 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9286 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9287 ((equal n 0) nil)
9288 (t n))))
9290 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9291 "Get a calc vector from a column, accorting to descriptor DESC.
9292 Optional arguments TBEG and COL can give the beginning of the table and
9293 the current column, to avoid unnecessary parsing."
9294 (save-excursion
9295 (or tbeg (setq tbeg (org-table-begin)))
9296 (or col (setq col (org-table-current-column)))
9297 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9298 (cond
9299 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9300 (setq n1 (- (match-end 1) (match-beginning 1)))
9301 (if (match-beginning 3)
9302 (setq n2 (- (match-end 2) (match-beginning 3))))
9303 (setq n (if n2 (max n1 n2) n1))
9304 (setq n1 (if n2 (min n1 n2)))
9305 (setq nn n)
9306 (while (and (> nn 0)
9307 (re-search-backward org-table-hline-regexp tbeg t))
9308 (push (org-current-line) hline-list)
9309 (setq nn (1- nn)))
9310 (setq hline-list (nreverse hline-list))
9311 (goto-line (nth (1- n) hline-list))
9312 (when (re-search-forward org-table-dataline-regexp)
9313 (org-table-goto-column col)
9314 (setq beg (point)))
9315 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9316 (when (re-search-backward org-table-dataline-regexp)
9317 (org-table-goto-column col)
9318 (setq end (point)))
9319 (setq l (apply 'append (org-table-copy-region beg end)))
9320 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9321 (if (equal x "") "0" x))
9322 l ",") "]"))
9323 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9324 (setq n1 (string-to-number (match-string 1 desc))
9325 n2 (string-to-number (match-string 2 desc)))
9326 (beginning-of-line 1)
9327 (save-excursion
9328 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9329 (org-table-goto-column col)
9330 (setq beg (point))))
9331 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9332 (org-table-goto-column col)
9333 (setq end (point)))
9334 (setq l (apply 'append (org-table-copy-region beg end)))
9335 (concat "[" (mapconcat
9336 (lambda (x) (setq x (org-trim x))
9337 (if (equal x "") "0" x))
9338 l ",") "]"))
9339 ((string-match "\\([0-9]+\\)" desc)
9340 (beginning-of-line 1)
9341 (when (re-search-backward org-table-dataline-regexp tbeg t
9342 (string-to-number (match-string 0 desc)))
9343 (org-table-goto-column col)
9344 (org-trim (org-table-get-field))))))))
9346 (defvar org-table-formula-history nil)
9348 (defvar org-table-column-names nil
9349 "Alist with column names, derived from the `!' line.")
9350 (defvar org-table-column-name-regexp nil
9351 "Regular expression matching the current column names.")
9352 (defvar org-table-local-parameters nil
9353 "Alist with parameter names, derived from the `$' line.")
9354 (defvar org-table-named-field-locations nil
9355 "Alist with locations of named fields.")
9357 (defun org-table-get-formula (&optional equation named)
9358 "Read a formula from the minibuffer, offer stored formula as default."
9359 (let* ((name (car (rassoc (list (org-current-line)
9360 (org-table-current-column))
9361 org-table-named-field-locations)))
9362 (scol (if named
9363 (if name name
9364 (error "Not in a named field"))
9365 (int-to-string (org-table-current-column))))
9366 (dummy (and name (not named)
9367 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9368 (error "Abort")))
9369 (org-table-may-need-update nil)
9370 (stored-list (org-table-get-stored-formulas))
9371 (stored (cdr (assoc scol stored-list)))
9372 (eq (cond
9373 ((and stored equation (string-match "^ *=? *$" equation))
9374 stored)
9375 ((stringp equation)
9376 equation)
9377 (t (read-string
9378 (format "%s formula $%s=" (if named "Field" "Column") scol)
9379 (or stored "") 'org-table-formula-history
9380 ;stored
9381 ))))
9382 mustsave)
9383 (when (not (string-match "\\S-" eq))
9384 ;; remove formula
9385 (setq stored-list (delq (assoc scol stored-list) stored-list))
9386 (org-table-store-formulas stored-list)
9387 (error "Formula removed"))
9388 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9389 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9390 (if (and name (not named))
9391 ;; We set the column equation, delete the named one.
9392 (setq stored-list (delq (assoc name stored-list) stored-list)
9393 mustsave t))
9394 (if stored
9395 (setcdr (assoc scol stored-list) eq)
9396 (setq stored-list (cons (cons scol eq) stored-list)))
9397 (if (or mustsave (not (equal stored eq)))
9398 (org-table-store-formulas stored-list))
9399 eq))
9401 (defun org-table-store-formulas (alist)
9402 "Store the list of formulas below the current table."
9403 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9404 (save-excursion
9405 (goto-char (org-table-end))
9406 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9407 (delete-region (point) (match-end 0)))
9408 (insert "#+TBLFM: "
9409 (mapconcat (lambda (x)
9410 (concat "$" (car x) "=" (cdr x)))
9411 alist "::")
9412 "\n")))
9414 (defun org-table-get-stored-formulas ()
9415 "Return an alist with the t=stored formulas directly after current table."
9416 (interactive)
9417 (let (scol eq eq-alist strings string seen)
9418 (save-excursion
9419 (goto-char (org-table-end))
9420 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9421 (setq strings (org-split-string (match-string 2) " *:: *"))
9422 (while (setq string (pop strings))
9423 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9424 (setq scol (match-string 1 string)
9425 eq (match-string 2 string)
9426 eq-alist (cons (cons scol eq) eq-alist))
9427 (if (member scol seen)
9428 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9429 (push scol seen))))))
9430 (nreverse eq-alist)))
9432 (defun org-table-modify-formulas (action &rest columns)
9433 "Modify the formulas stored below the current table.
9434 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
9435 expected, for the other actions only a single column number is needed."
9436 (let ((list (org-table-get-stored-formulas))
9437 (nmax (length (org-split-string
9438 (buffer-substring (point-at-bol) (point-at-eol))
9439 "|")))
9440 col col1 col2 scol si sc1 sc2)
9441 (cond
9442 ((null list)) ; No action needed if there are no stored formulas
9443 ((eq action 'remove)
9444 (setq col (car columns)
9445 scol (int-to-string col))
9446 (org-table-replace-in-formulas list scol "INVALID")
9447 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
9448 (loop for i from (1+ col) upto nmax by 1 do
9449 (setq si (int-to-string i))
9450 (org-table-replace-in-formulas list si (int-to-string (1- i)))
9451 (if (assoc si list) (setcar (assoc si list)
9452 (int-to-string (1- i))))))
9453 ((eq action 'insert)
9454 (setq col (car columns))
9455 (loop for i from nmax downto col by 1 do
9456 (setq si (int-to-string i))
9457 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
9458 (if (assoc si list) (setcar (assoc si list)
9459 (int-to-string (1+ i))))))
9460 ((eq action 'swap)
9461 (setq col1 (car columns) col2 (nth 1 columns)
9462 sc1 (int-to-string col1) sc2 (int-to-string col2))
9463 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
9464 (org-table-replace-in-formulas list sc1 "ZqZ")
9465 (org-table-replace-in-formulas list sc2 sc1)
9466 (org-table-replace-in-formulas list "ZqZ" sc2)
9467 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
9468 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
9469 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
9470 (t (error "Invalid action in `org-table-modify-formulas'")))
9471 (if list (org-table-store-formulas list))))
9473 (defun org-table-replace-in-formulas (list s1 s2)
9474 (let (elt re s)
9475 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
9476 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
9477 re (concat (regexp-quote s1) "\\>"))
9478 (while (setq elt (pop list))
9479 (setq s (cdr elt))
9480 (while (string-match re s)
9481 (setq s (replace-match s2 t t s)))
9482 (setcdr elt s))))
9484 (defun org-table-get-specials ()
9485 "Get the column names and local parameters for this table."
9486 (save-excursion
9487 (let ((beg (org-table-begin)) (end (org-table-end))
9488 names name fields fields1 field cnt c v line col)
9489 (setq org-table-column-names nil
9490 org-table-local-parameters nil
9491 org-table-named-field-locations nil)
9492 (goto-char beg)
9493 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9494 (setq names (org-split-string (match-string 1) " *| *")
9495 cnt 1)
9496 (while (setq name (pop names))
9497 (setq cnt (1+ cnt))
9498 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9499 (push (cons name (int-to-string cnt)) org-table-column-names))))
9500 (setq org-table-column-names (nreverse org-table-column-names))
9501 (setq org-table-column-name-regexp
9502 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9503 (goto-char beg)
9504 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9505 (setq fields (org-split-string (match-string 1) " *| *"))
9506 (while (setq field (pop fields))
9507 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9508 (push (cons (match-string 1 field) (match-string 2 field))
9509 org-table-local-parameters))))
9510 (goto-char beg)
9511 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9512 (setq c (match-string 1)
9513 fields (org-split-string (match-string 2) " *| *"))
9514 (save-excursion
9515 (beginning-of-line (if (equal c "_") 2 0))
9516 (setq line (org-current-line) col 1)
9517 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9518 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9519 (while (and fields1 (setq field (pop fields)))
9520 (setq v (pop fields1) col (1+ col))
9521 (when (and (stringp field) (stringp v)
9522 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9523 (push (cons field v) org-table-local-parameters)
9524 (push (list field line col) org-table-named-field-locations)))))))
9526 (defun org-this-word ()
9527 ;; Get the current word
9528 (save-excursion
9529 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
9530 (end (progn (skip-chars-forward "^ \t\n") (point))))
9531 (buffer-substring-no-properties beg end))))
9533 (defun org-table-maybe-eval-formula ()
9534 "Check if the current field starts with \"=\" or \":=\".
9535 If yes, store the formula and apply it."
9536 ;; We already know we are in a table. Get field will only return a formula
9537 ;; when appropriate. It might return a separator line, but no problem.
9538 (when org-table-formula-evaluate-inline
9539 (let* ((field (org-trim (or (org-table-get-field) "")))
9540 named eq)
9541 (when (string-match "^:?=\\(.*\\)" field)
9542 (setq named (equal (string-to-char field) ?:)
9543 eq (match-string 1 field))
9544 (if (fboundp 'calc-eval)
9545 (org-table-eval-formula (if named '(4) nil) eq))))))
9547 (defvar org-recalc-commands nil
9548 "List of commands triggering the recalculation of a line.
9549 Will be filled automatically during use.")
9551 (defvar org-recalc-marks
9552 '((" " . "Unmarked: no special line, no automatic recalculation")
9553 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9554 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9555 ("!" . "Column name definition line. Reference in formula as $name.")
9556 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9557 ("_" . "Names for values in row below this one.")
9558 ("^" . "Names for values in row above this one.")))
9560 (defun org-table-rotate-recalc-marks (&optional newchar)
9561 "Rotate the recalculation mark in the first column.
9562 If in any row, the first field is not consistent with a mark,
9563 insert a new column for the markers.
9564 When there is an active region, change all the lines in the region,
9565 after prompting for the marking character.
9566 After each change, a message will be displayed indicating the meaning
9567 of the new mark."
9568 (interactive)
9569 (unless (org-at-table-p) (error "Not at a table"))
9570 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9571 (beg (org-table-begin))
9572 (end (org-table-end))
9573 (l (org-current-line))
9574 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9575 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9576 (have-col
9577 (save-excursion
9578 (goto-char beg)
9579 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9580 (col (org-table-current-column))
9581 (forcenew (car (assoc newchar org-recalc-marks)))
9582 epos new)
9583 (when l1
9584 (message "Change region to what mark? Type # * ! $ or SPC: ")
9585 (setq newchar (char-to-string (read-char-exclusive))
9586 forcenew (car (assoc newchar org-recalc-marks))))
9587 (if (and newchar (not forcenew))
9588 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9589 newchar))
9590 (if l1 (goto-line l1))
9591 (save-excursion
9592 (beginning-of-line 1)
9593 (unless (looking-at org-table-dataline-regexp)
9594 (error "Not at a table data line")))
9595 (unless have-col
9596 (org-table-goto-column 1)
9597 (org-table-insert-column)
9598 (org-table-goto-column (1+ col)))
9599 (setq epos (point-at-eol))
9600 (save-excursion
9601 (beginning-of-line 1)
9602 (org-table-get-field
9603 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9604 (concat " "
9605 (setq new (or forcenew
9606 (cadr (member (match-string 1) marks))))
9607 " ")
9608 " # ")))
9609 (if (and l1 l2)
9610 (progn
9611 (goto-line l1)
9612 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9613 (and (looking-at org-table-dataline-regexp)
9614 (org-table-get-field 1 (concat " " new " "))))
9615 (goto-line l1)))
9616 (if (not (= epos (point-at-eol))) (org-table-align))
9617 (goto-line l)
9618 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9620 (defun org-table-maybe-recalculate-line ()
9621 "Recompute the current line if marked for it, and if we haven't just done it."
9622 (interactive)
9623 (and org-table-allow-automatic-line-recalculation
9624 (not (and (memq last-command org-recalc-commands)
9625 (equal org-last-recalc-line (org-current-line))))
9626 (save-excursion (beginning-of-line 1)
9627 (looking-at org-table-auto-recalculate-regexp))
9628 (fboundp 'calc-eval)
9629 (org-table-recalculate) t))
9631 (defvar org-table-formula-debug nil
9632 "Non-nil means, debug table formulas.
9633 When nil, simply write \"#ERROR\" in corrupted fields.")
9635 (defvar modes)
9636 (defsubst org-set-calc-mode (var &optional value)
9637 (if (stringp var)
9638 (setq var (assoc var '(("D" calc-angle-mode deg)
9639 ("R" calc-angle-mode rad)
9640 ("F" calc-prefer-frac t)
9641 ("S" calc-symbolic-mode t)))
9642 value (nth 2 var) var (nth 1 var)))
9643 (if (memq var modes)
9644 (setcar (cdr (memq var modes)) value)
9645 (cons var (cons value modes)))
9646 modes)
9648 (defun org-table-eval-formula (&optional arg equation
9649 suppress-align suppress-const
9650 suppress-store)
9651 "Replace the table field value at the cursor by the result of a calculation.
9653 This function makes use of Dave Gillespie's Calc package, in my view the
9654 most exciting program ever written for GNU Emacs. So you need to have Calc
9655 installed in order to use this function.
9657 In a table, this command replaces the value in the current field with the
9658 result of a formula. It also installs the formula as the \"current\" column
9659 formula, by storing it in a special line below the table. When called
9660 with a `C-u' prefix, the current field must ba a named field, and the
9661 formula is installed as valid in only this specific field.
9663 When called, the command first prompts for a formula, which is read in
9664 the minibuffer. Previously entered formulas are available through the
9665 history list, and the last used formula is offered as a default.
9666 These stored formulas are adapted correctly when moving, inserting, or
9667 deleting columns with the corresponding commands.
9669 The formula can be any algebraic expression understood by the Calc package.
9670 For details, see the Org-mode manual.
9672 This function can also be called from Lisp programs and offers
9673 additional arguments: EQUATION can be the formula to apply. If this
9674 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9675 used to speed-up recursive calls by by-passing unnecessary aligns.
9676 SUPPRESS-CONST suppresses the interpretation of constants in the
9677 formula, assuming that this has been done already outside the function.
9678 SUPPRESS-STORE means the formula should not be stored, either because
9679 it is already stored, or because it is a modified equation that should
9680 not overwrite the stored one."
9681 (interactive "P")
9682 (require 'calc)
9683 (org-table-check-inside-data-field)
9684 (org-table-get-specials)
9685 (let* (fields
9686 (ndown (if (integerp arg) arg 1))
9687 (org-table-automatic-realign nil)
9688 (case-fold-search nil)
9689 (down (> ndown 1))
9690 (formula (if (and equation suppress-store)
9691 equation
9692 (org-table-get-formula equation (equal arg '(4)))))
9693 (n0 (org-table-current-column))
9694 (modes (copy-sequence org-calc-default-modes))
9695 n form fmt x ev orig c)
9696 ;; Parse the format string. Since we have a lot of modes, this is
9697 ;; a lot of work. However, I think calc still uses most of the time.
9698 (if (string-match ";" formula)
9699 (let ((tmp (org-split-string formula ";")))
9700 (setq formula (car tmp)
9701 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9702 (nth 1 tmp)))
9703 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
9704 (setq c (string-to-char (match-string 1 fmt))
9705 n (string-to-number (or (match-string 1 fmt) "")))
9706 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
9707 (setq modes (org-set-calc-mode
9708 'calc-float-format
9709 (list (cdr (assoc c '((?n . float) (?f . fix)
9710 (?s . sci) (?e . eng))))
9711 n))))
9712 (setq fmt (replace-match "" t t fmt)))
9713 (while (string-match "[DRFS]" fmt)
9714 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9715 (setq fmt (replace-match "" t t fmt)))
9716 (unless (string-match "\\S-" fmt)
9717 (setq fmt nil))))
9718 (if (and (not suppress-const) org-table-formula-use-constants)
9719 (setq formula (org-table-formula-substitute-names formula)))
9720 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9721 (while (> ndown 0)
9722 (setq fields (org-split-string
9723 (buffer-substring
9724 (point-at-bol) (point-at-eol)) " *| *"))
9725 (if org-table-formula-numbers-only
9726 (setq fields (mapcar
9727 (lambda (x) (number-to-string (string-to-number x)))
9728 fields)))
9729 (setq ndown (1- ndown))
9730 (setq form (copy-sequence formula))
9731 ;; Insert the references to fields in same row
9732 (while (string-match "\\$\\([0-9]+\\)?" form)
9733 (setq n (if (match-beginning 1)
9734 (string-to-number (match-string 1 form))
9736 x (nth (1- n) fields))
9737 (unless x (error "Invalid field specifier \"%s\""
9738 (match-string 0 form)))
9739 (if (equal x "") (setq x "0"))
9740 (setq form (replace-match (concat "(" x ")") t t form)))
9741 ;; Insert ranges in current column
9742 (while (string-match "\\&[-I0-9]+" form)
9743 (setq form (replace-match
9744 (save-match-data
9745 (org-table-get-vertical-vector (match-string 0 form)
9746 nil n0))
9747 t t form)))
9748 (setq ev (calc-eval (cons form modes)
9749 (if org-table-formula-numbers-only 'num)))
9751 (when org-table-formula-debug
9752 (with-output-to-temp-buffer "*Help*"
9753 (princ (format "Substitution history of formula
9754 Orig: %s
9755 $xyz-> %s
9756 $1-> %s\n" orig formula form))
9757 (if (listp ev)
9758 (princ (format " %s^\nError: %s"
9759 (make-string (car ev) ?\-) (nth 1 ev)))
9760 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9761 ev (or fmt "NONE")
9762 (if fmt (format fmt (string-to-number ev)) ev)))))
9763 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
9764 (unless (and (interactive-p) (not ndown))
9765 (unless (let (inhibit-redisplay)
9766 (y-or-n-p "Debugging Formula. Continue to next? "))
9767 (org-table-align)
9768 (error "Abort"))
9769 (delete-window (get-buffer-window "*Help*"))
9770 (message "")))
9771 (if (listp ev) (setq fmt nil ev "#ERROR"))
9772 (org-table-justify-field-maybe
9773 (if fmt (format fmt (string-to-number ev)) ev))
9774 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9775 (call-interactively 'org-return)
9776 (setq ndown 0)))
9777 (and down (org-table-maybe-recalculate-line))
9778 (or suppress-align (and org-table-may-need-update
9779 (org-table-align)))))
9781 (defun org-table-recalculate (&optional all noalign)
9782 "Recalculate the current table line by applying all stored formulas."
9783 (interactive "P")
9784 (or (memq this-command org-recalc-commands)
9785 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9786 (unless (org-at-table-p) (error "Not at a table"))
9787 (org-table-get-specials)
9788 (let* ((eqlist (sort (org-table-get-stored-formulas)
9789 (lambda (a b) (string< (car a) (car b)))))
9790 (inhibit-redisplay t)
9791 (line-re org-table-dataline-regexp)
9792 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9793 (thiscol (org-table-current-column))
9794 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
9795 ;; Insert constants in all formulas
9796 (setq eqlist
9797 (mapcar (lambda (x)
9798 (setcdr x (org-table-formula-substitute-names (cdr x)))
9800 eqlist))
9801 ;; Split the equation list
9802 (while (setq eq (pop eqlist))
9803 (if (<= (string-to-char (car eq)) ?9)
9804 (push eq eqlnum)
9805 (push eq eqlname)))
9806 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9807 (if all
9808 (progn
9809 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9810 (goto-char (setq beg (org-table-begin)))
9811 (if (re-search-forward org-table-calculate-mark-regexp end t)
9812 ;; This is a table with marked lines, only compute selected lines
9813 (setq line-re org-table-recalculate-regexp)
9814 ;; Move forward to the first non-header line
9815 (if (and (re-search-forward org-table-dataline-regexp end t)
9816 (re-search-forward org-table-hline-regexp end t)
9817 (re-search-forward org-table-dataline-regexp end t))
9818 (setq beg (match-beginning 0))
9819 nil))) ;; just leave beg where it is
9820 (setq beg (point-at-bol)
9821 end (move-marker (make-marker) (1+ (point-at-eol)))))
9822 (goto-char beg)
9823 (and all (message "Re-applying formulas to full table..."))
9824 (while (re-search-forward line-re end t)
9825 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
9826 ;; Unprotected line, recalculate
9827 (and all (message "Re-applying formulas to full table...(line %d)"
9828 (setq cnt (1+ cnt))))
9829 (setq org-last-recalc-line (org-current-line))
9830 (setq eql eqlnum)
9831 (while (setq entry (pop eql))
9832 (goto-line org-last-recalc-line)
9833 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9834 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
9835 (goto-line thisline)
9836 (org-table-goto-column thiscol)
9837 (or noalign (and org-table-may-need-update (org-table-align))
9838 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9839 ;; Now do the names fields
9840 (while (setq eq (pop eqlname))
9841 (setq name (car eq)
9842 a (assoc name org-table-named-field-locations))
9843 (when a
9844 (message "Re-applying formula to named field: %s" name)
9845 (goto-line (nth 1 a))
9846 (org-table-goto-column (nth 2 a))
9847 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
9848 ;; back to initial position
9849 (goto-line thisline)
9850 (org-table-goto-column thiscol)
9851 (or noalign (and org-table-may-need-update (org-table-align))
9852 (and all (message "Re-applying formulas...done")))))
9854 (defun org-table-formula-substitute-names (f)
9855 "Replace $const with values in string F."
9856 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
9857 ;; First, check for column names
9858 (while (setq start (string-match org-table-column-name-regexp f start))
9859 (setq start (1+ start))
9860 (setq a (assoc (match-string 1 f) org-table-column-names))
9861 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9862 ;; Expand ranges to vectors
9863 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
9864 (setq n1 (string-to-number (match-string 1 f))
9865 n2 (string-to-number (match-string 2 f))
9866 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
9867 s (concat "[($" (number-to-string (1- nn1)) ")"))
9868 (loop for i from nn1 upto nn2 do
9869 (setq s (concat s ",($" (int-to-string i) ")")))
9870 (setq s (concat s "]"))
9871 (if (< n2 n1) (setq s (concat "rev(" s ")")))
9872 (setq f (replace-match s t t f)))
9873 ;; Parameters and constants
9874 (setq start 0)
9875 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
9876 (setq start (1+ start))
9877 (if (setq a (save-match-data
9878 (org-table-get-constant (match-string 1 f))))
9879 (setq f (replace-match (concat "(" a ")") t t f))))
9880 (if org-table-formula-debug
9881 (put-text-property 0 (length f) :orig-formula f1 f))
9884 (defun org-table-get-constant (const)
9885 "Find the value for a parameter or constant in a formula.
9886 Parameters get priority."
9887 (or (cdr (assoc const org-table-local-parameters))
9888 (cdr (assoc const org-table-formula-constants))
9889 (and (fboundp 'constants-get) (constants-get const))
9890 "#UNDEFINED_NAME"))
9892 (defvar org-edit-formulas-map (make-sparse-keymap))
9893 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
9894 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
9895 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
9897 (defvar org-pos)
9898 (defvar org-window-configuration)
9900 (defun org-table-edit-formulas ()
9901 "Edit the formulas of the current table in a separate buffer."
9902 (interactive)
9903 (unless (org-at-table-p)
9904 (error "Not at a table"))
9905 (org-table-get-specials)
9906 (let ((eql (org-table-get-stored-formulas))
9907 (pos (move-marker (make-marker) (point)))
9908 (wc (current-window-configuration))
9909 entry loc s)
9910 (switch-to-buffer-other-window "*Edit Formulas*")
9911 (erase-buffer)
9912 (fundamental-mode)
9913 (set (make-local-variable 'org-pos) pos)
9914 (set (make-local-variable 'org-window-configuration) wc)
9915 (use-local-map org-edit-formulas-map)
9916 (setq s "# Edit formulas and finish with `C-c C-c'.
9917 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
9918 # Use `C-c ?' to get information about $name at point.
9919 # To cancel editing, press `C-c C-q'.\n")
9920 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9921 (insert s)
9922 (while (setq entry (pop eql))
9923 (when (setq loc (assoc (car entry) org-table-named-field-locations))
9924 (setq s (format "# Named formula, referring to column %d in line %d\n"
9925 (nth 2 loc) (nth 1 loc)))
9926 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9927 (insert s))
9928 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
9929 (remove-text-properties 0 (length s) '(face nil) s)
9930 (insert s))
9931 (goto-char (point-min))
9932 (message "Edit formulas and finish with `C-c C-c'.")))
9934 (defun org-show-variable ()
9935 "Show the location/value of the $ expression at point."
9936 (interactive)
9937 (let (var (pos org-pos) (win (selected-window)) e)
9938 (save-excursion
9939 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
9940 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
9941 (setq var (match-string 1))
9942 (error "No variable at point")))
9943 (cond
9944 ((setq e (assoc var org-table-named-field-locations))
9945 (switch-to-buffer-other-window (marker-buffer pos))
9946 (goto-line (nth 1 e))
9947 (org-table-goto-column (nth 2 e))
9948 (select-window win)
9949 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
9950 ((setq e (assoc var org-table-column-names))
9951 (switch-to-buffer-other-window (marker-buffer pos))
9952 (goto-char pos)
9953 (goto-char (org-table-begin))
9954 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
9955 (org-table-end) t)
9956 (progn
9957 (goto-char (match-beginning 1))
9958 (message "Named column (column %s)" (cdr e)))
9959 (error "Column name not found"))
9960 (select-window win))
9961 ((string-match "^[0-9]$" var)
9962 ;; column number
9963 (switch-to-buffer-other-window (marker-buffer pos))
9964 (goto-char pos)
9965 (goto-char (org-table-begin))
9966 (recenter 1)
9967 (if (re-search-forward org-table-dataline-regexp
9968 (org-table-end) t)
9969 (progn
9970 (goto-char (match-beginning 0))
9971 (org-table-goto-column (string-to-number var))
9972 (message "Column %s" var))
9973 (error "Column name not found"))
9974 (select-window win))
9975 ((setq e (assoc var org-table-local-parameters))
9976 (switch-to-buffer-other-window (marker-buffer pos))
9977 (goto-char pos)
9978 (goto-char (org-table-begin))
9979 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
9980 (progn
9981 (goto-char (match-beginning 1))
9982 (message "Local parameter."))
9983 (error "Parameter not found"))
9984 (select-window win))
9986 (cond
9987 ((setq e (assoc var org-table-formula-constants))
9988 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
9989 ((setq e (and (fboundp 'constants-get) (constants-get var)))
9990 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
9991 (t (error "Undefined name $%s" var)))))))
9993 (defun org-finish-edit-formulas (&optional arg)
9994 "Parse the buffer for formula definitions and install them.
9995 With prefix ARG, apply the new formulas to the table."
9996 (interactive "P")
9997 (let ((pos org-pos) eql)
9998 (goto-char (point-min))
9999 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
10000 (push (cons (match-string 1) (match-string 2)) eql))
10001 (set-window-configuration org-window-configuration)
10002 (select-window (get-buffer-window (marker-buffer pos)))
10003 (goto-char pos)
10004 (unless (org-at-table-p)
10005 (error "Lost table position - cannot install formulae"))
10006 (org-table-store-formulas eql)
10007 (move-marker pos nil)
10008 (kill-buffer "*Edit Formulas*")
10009 (if arg
10010 (org-table-recalculate 'all)
10011 (message "New formulas installed - press C-u C-c C-c to apply."))))
10013 (defun org-abort-edit-formulas ()
10014 "Abort editing formulas, without installing the changes."
10015 (interactive)
10016 (let ((pos org-pos))
10017 (set-window-configuration org-window-configuration)
10018 (select-window (get-buffer-window (marker-buffer pos)))
10019 (goto-char pos)
10020 (message "Formula editing aborted without installing changes")))
10022 ;;; The orgtbl minor mode
10024 ;; Define a minor mode which can be used in other modes in order to
10025 ;; integrate the org-mode table editor.
10027 ;; This is really a hack, because the org-mode table editor uses several
10028 ;; keys which normally belong to the major mode, for example the TAB and
10029 ;; RET keys. Here is how it works: The minor mode defines all the keys
10030 ;; necessary to operate the table editor, but wraps the commands into a
10031 ;; function which tests if the cursor is currently inside a table. If that
10032 ;; is the case, the table editor command is executed. However, when any of
10033 ;; those keys is used outside a table, the function uses `key-binding' to
10034 ;; look up if the key has an associated command in another currently active
10035 ;; keymap (minor modes, major mode, global), and executes that command.
10036 ;; There might be problems if any of the keys used by the table editor is
10037 ;; otherwise used as a prefix key.
10039 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10040 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10041 ;; addresses this by checking explicitly for both bindings.
10043 ;; The optimized version (see variable `orgtbl-optimized') takes over
10044 ;; all keys which are bound to `self-insert-command' in the *global map*.
10045 ;; Some modes bind other commands to simple characters, for example
10046 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10047 ;; active, this binding is ignored inside tables and replaced with a
10048 ;; modified self-insert.
10050 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
10051 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
10052 In the optimized version, the table editor takes over all simple keys that
10053 normally just insert a character. In tables, the characters are inserted
10054 in a way to minimize disturbing the table structure (i.e. in overwrite mode
10055 for empty fields). Outside tables, the correct binding of the keys is
10056 restored.
10058 The default for this option is t if the optimized version is also used in
10059 Org-mode. See the variable `org-enable-table-editor' for details. Changing
10060 this variable requires a restart of Emacs to become effective."
10061 :group 'org-table
10062 :type 'boolean)
10064 (defvar orgtbl-mode nil
10065 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10066 table editor in arbitrary modes.")
10067 (make-variable-buffer-local 'orgtbl-mode)
10069 (defvar orgtbl-mode-map (make-keymap)
10070 "Keymap for `orgtbl-mode'.")
10072 ;;;###autoload
10073 (defun turn-on-orgtbl ()
10074 "Unconditionally turn on `orgtbl-mode'."
10075 (orgtbl-mode 1))
10077 ;;;###autoload
10078 (defun orgtbl-mode (&optional arg)
10079 "The `org-mode' table editor as a minor mode for use in other modes."
10080 (interactive)
10081 (if (eq major-mode 'org-mode)
10082 ;; Exit without error, in case some hook functions calls this
10083 ;; by accident in org-mode.
10084 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10085 (setq orgtbl-mode
10086 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10087 (if orgtbl-mode
10088 (progn
10089 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10090 ;; Make sure we are first in minor-mode-map-alist
10091 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10092 (and c (setq minor-mode-map-alist
10093 (cons c (delq c minor-mode-map-alist)))))
10094 (set (make-local-variable (quote org-table-may-need-update)) t)
10095 (org-add-hook 'before-change-functions 'org-before-change-function
10096 nil 'local)
10097 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
10098 auto-fill-inhibit-regexp)
10099 (set (make-local-variable 'auto-fill-inhibit-regexp)
10100 (if auto-fill-inhibit-regexp
10101 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
10102 "[ \t]*|"))
10103 (easy-menu-add orgtbl-mode-menu)
10104 (run-hooks 'orgtbl-mode-hook))
10105 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10106 (remove-hook 'before-change-functions 'org-before-change-function t)
10107 (easy-menu-remove orgtbl-mode-menu)
10108 (force-mode-line-update 'all))))
10110 ;; Install it as a minor mode.
10111 (put 'orgtbl-mode :included t)
10112 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10113 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10115 (defun orgtbl-make-binding (fun n &rest keys)
10116 "Create a function for binding in the table minor mode.
10117 FUN is the command to call inside a table. N is used to create a unique
10118 command name. KEYS are keys that should be checked in for a command
10119 to execute outside of tables."
10120 (eval
10121 (list 'defun
10122 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10123 '(arg)
10124 (concat "In tables, run `" (symbol-name fun) "'.\n"
10125 "Outside of tables, run the binding of `"
10126 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10127 "'.")
10128 '(interactive "p")
10129 (list 'if
10130 '(org-at-table-p)
10131 (list 'call-interactively (list 'quote fun))
10132 (list 'let '(orgtbl-mode)
10133 (list 'call-interactively
10134 (append '(or)
10135 (mapcar (lambda (k)
10136 (list 'key-binding k))
10137 keys)
10138 '('orgtbl-error))))))))
10140 (defun orgtbl-error ()
10141 "Error when there is no default binding for a table key."
10142 (interactive)
10143 (error "This key is has no function outside tables"))
10145 (defun orgtbl-setup ()
10146 "Setup orgtbl keymaps."
10147 (let ((nfunc 0)
10148 (bindings
10149 (list
10150 '([(meta shift left)] org-table-delete-column)
10151 '([(meta left)] org-table-move-column-left)
10152 '([(meta right)] org-table-move-column-right)
10153 '([(meta shift right)] org-table-insert-column)
10154 '([(meta shift up)] org-table-kill-row)
10155 '([(meta shift down)] org-table-insert-row)
10156 '([(meta up)] org-table-move-row-up)
10157 '([(meta down)] org-table-move-row-down)
10158 '("\C-c\C-w" org-table-cut-region)
10159 '("\C-c\M-w" org-table-copy-region)
10160 '("\C-c\C-y" org-table-paste-rectangle)
10161 '("\C-c-" org-table-insert-hline)
10162 ; '([(shift tab)] org-table-previous-field)
10163 '("\C-m" org-table-next-row)
10164 (list (org-key 'S-return) 'org-table-copy-down)
10165 '([(meta return)] org-table-wrap-region)
10166 '("\C-c\C-q" org-table-wrap-region)
10167 '("\C-c?" org-table-current-column)
10168 '("\C-c " org-table-blank-field)
10169 '("\C-c+" org-table-sum)
10170 '("\C-c|" org-table-toggle-vline-visibility)
10171 '("\C-c=" org-table-eval-formula)
10172 '("\C-c'" org-table-edit-formulas)
10173 '("\C-c*" org-table-recalculate)
10174 '("\C-c^" org-table-sort-lines)
10175 '([(control ?#)] org-table-rotate-recalc-marks)))
10176 elt key fun cmd)
10177 (while (setq elt (pop bindings))
10178 (setq nfunc (1+ nfunc))
10179 (setq key (car elt)
10180 fun (nth 1 elt)
10181 cmd (orgtbl-make-binding fun nfunc key))
10182 (define-key orgtbl-mode-map key cmd))
10183 ;; Special treatment needed for TAB and RET
10184 (define-key orgtbl-mode-map [(return)]
10185 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10186 (define-key orgtbl-mode-map "\C-m"
10187 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10188 (define-key orgtbl-mode-map [(tab)]
10189 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10190 (define-key orgtbl-mode-map "\C-i"
10191 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
10192 (define-key orgtbl-mode-map "\C-i"
10193 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
10194 (define-key orgtbl-mode-map "\C-c\C-c"
10195 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
10196 (when orgtbl-optimized
10197 ;; If the user wants maximum table support, we need to hijack
10198 ;; some standard editing functions
10199 (org-remap orgtbl-mode-map
10200 'self-insert-command 'orgtbl-self-insert-command
10201 'delete-char 'orgtbl-delete-char
10202 'delete-backward-char 'orgtbl-delete-backward-char)
10203 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
10204 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10205 '("OrgTbl"
10206 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10207 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10208 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10209 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10210 "--"
10211 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10212 ["Copy Field from Above"
10213 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10214 "--"
10215 ("Column"
10216 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10217 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10218 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10219 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10220 ("Row"
10221 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10222 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10223 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10224 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10225 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10226 "--"
10227 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10228 ("Rectangle"
10229 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10230 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10231 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10232 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10233 "--"
10234 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10235 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10236 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10237 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10238 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10239 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10240 ["Sum Column/Rectangle" org-table-sum
10241 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10242 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10243 ["Debug Formulas"
10244 (setq org-table-formula-debug (not org-table-formula-debug))
10245 :style toggle :selected org-table-formula-debug]
10249 (defun orgtbl-tab ()
10250 "Justification and field motion for `orgtbl-mode'."
10251 (interactive)
10252 (org-table-justify-field-maybe)
10253 (org-table-next-field))
10255 (defun orgtbl-ret ()
10256 "Justification and field motion for `orgtbl-mode'."
10257 (interactive)
10258 (org-table-justify-field-maybe)
10259 (org-table-next-row))
10261 (defun orgtbl-self-insert-command (N)
10262 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10263 If the cursor is in a table looking at whitespace, the whitespace is
10264 overwritten, and the table is not marked as requiring realignment."
10265 (interactive "p")
10266 (if (and (org-at-table-p)
10268 (and org-table-auto-blank-field
10269 (member last-command
10270 '(orgtbl-hijacker-command-100
10271 orgtbl-hijacker-command-101
10272 orgtbl-hijacker-command-102
10273 orgtbl-hijacker-command-103
10274 orgtbl-hijacker-command-104
10275 orgtbl-hijacker-command-105))
10276 (org-table-blank-field))
10278 (eq N 1)
10279 (looking-at "[^|\n]* +|"))
10280 (let (org-table-may-need-update)
10281 (goto-char (1- (match-end 0)))
10282 (delete-backward-char 1)
10283 (goto-char (match-beginning 0))
10284 (self-insert-command N))
10285 (setq org-table-may-need-update t)
10286 (let (orgtbl-mode)
10287 (call-interactively (key-binding (vector last-input-event))))))
10289 (defun org-force-self-insert (N)
10290 "Needed to enforce self-insert under remapping."
10291 (interactive "p")
10292 (self-insert-command N))
10294 (defun orgtbl-delete-backward-char (N)
10295 "Like `delete-backward-char', insert whitespace at field end in tables.
10296 When deleting backwards, in tables this function will insert whitespace in
10297 front of the next \"|\" separator, to keep the table aligned. The table will
10298 still be marked for re-alignment, because a narrow field may lead to a
10299 reduced column width."
10300 (interactive "p")
10301 (if (and (org-at-table-p)
10302 (eq N 1)
10303 (string-match "|" (buffer-substring (point-at-bol) (point)))
10304 (looking-at ".*?|"))
10305 (let ((pos (point)))
10306 (backward-delete-char N)
10307 (skip-chars-forward "^|")
10308 (insert " ")
10309 (goto-char (1- pos)))
10310 (delete-backward-char N)))
10312 (defun orgtbl-delete-char (N)
10313 "Like `delete-char', but insert whitespace at field end in tables.
10314 When deleting characters, in tables this function will insert whitespace in
10315 front of the next \"|\" separator, to keep the table aligned. The table
10316 will still be marked for re-alignment, because a narrow field may lead to
10317 a reduced column width."
10318 (interactive "p")
10319 (if (and (org-at-table-p)
10320 (not (bolp))
10321 (not (= (char-after) ?|))
10322 (eq N 1))
10323 (if (looking-at ".*?|")
10324 (let ((pos (point)))
10325 (replace-match (concat
10326 (substring (match-string 0) 1 -1)
10327 " |"))
10328 (goto-char pos)))
10329 (delete-char N)))
10331 ;;; Exporting
10333 (defconst org-level-max 20)
10335 (defun org-export-find-first-heading-line (list)
10336 "Remove all lines from LIST which are before the first headline."
10337 (let ((orig-list list)
10338 (re (concat "^" outline-regexp)))
10339 (while (and list
10340 (not (string-match re (car list))))
10341 (pop list))
10342 (or list orig-list)))
10344 (defun org-skip-comments (lines)
10345 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10346 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10347 (re2 "^\\(\\*+\\)[ \t\n\r]")
10348 rtn line level)
10349 (while (setq line (pop lines))
10350 (cond
10351 ((and (string-match re1 line)
10352 (setq level (- (match-end 1) (match-beginning 1))))
10353 ;; Beginning of a COMMENT subtree. Skip it.
10354 (while (and (setq line (pop lines))
10355 (or (not (string-match re2 line))
10356 (> (- (match-end 1) (match-beginning 1)) level))))
10357 (setq lines (cons line lines)))
10358 ((string-match "^#" line)
10359 ;; an ordinary comment line
10361 ((and org-export-table-remove-special-lines
10362 (string-match "^[ \t]*| *[!_^] *|" line))
10363 ;; a special table line that should be removed
10365 (t (setq rtn (cons line rtn)))))
10366 (nreverse rtn)))
10368 ;; ASCII
10370 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10371 "Characters for underlining headings in ASCII export.")
10373 (defconst org-html-entities
10374 '(("nbsp")
10375 ("iexcl")
10376 ("cent")
10377 ("pound")
10378 ("curren")
10379 ("yen")
10380 ("brvbar")
10381 ("sect")
10382 ("uml")
10383 ("copy")
10384 ("ordf")
10385 ("laquo")
10386 ("not")
10387 ("shy")
10388 ("reg")
10389 ("macr")
10390 ("deg")
10391 ("plusmn")
10392 ("sup2")
10393 ("sup3")
10394 ("acute")
10395 ("micro")
10396 ("para")
10397 ("middot")
10398 ("odot"."o")
10399 ("star"."*")
10400 ("cedil")
10401 ("sup1")
10402 ("ordm")
10403 ("raquo")
10404 ("frac14")
10405 ("frac12")
10406 ("frac34")
10407 ("iquest")
10408 ("Agrave")
10409 ("Aacute")
10410 ("Acirc")
10411 ("Atilde")
10412 ("Auml")
10413 ("Aring") ("AA"."&Aring;")
10414 ("AElig")
10415 ("Ccedil")
10416 ("Egrave")
10417 ("Eacute")
10418 ("Ecirc")
10419 ("Euml")
10420 ("Igrave")
10421 ("Iacute")
10422 ("Icirc")
10423 ("Iuml")
10424 ("ETH")
10425 ("Ntilde")
10426 ("Ograve")
10427 ("Oacute")
10428 ("Ocirc")
10429 ("Otilde")
10430 ("Ouml")
10431 ("times")
10432 ("Oslash")
10433 ("Ugrave")
10434 ("Uacute")
10435 ("Ucirc")
10436 ("Uuml")
10437 ("Yacute")
10438 ("THORN")
10439 ("szlig")
10440 ("agrave")
10441 ("aacute")
10442 ("acirc")
10443 ("atilde")
10444 ("auml")
10445 ("aring")
10446 ("aelig")
10447 ("ccedil")
10448 ("egrave")
10449 ("eacute")
10450 ("ecirc")
10451 ("euml")
10452 ("igrave")
10453 ("iacute")
10454 ("icirc")
10455 ("iuml")
10456 ("eth")
10457 ("ntilde")
10458 ("ograve")
10459 ("oacute")
10460 ("ocirc")
10461 ("otilde")
10462 ("ouml")
10463 ("divide")
10464 ("oslash")
10465 ("ugrave")
10466 ("uacute")
10467 ("ucirc")
10468 ("uuml")
10469 ("yacute")
10470 ("thorn")
10471 ("yuml")
10472 ("fnof")
10473 ("Alpha")
10474 ("Beta")
10475 ("Gamma")
10476 ("Delta")
10477 ("Epsilon")
10478 ("Zeta")
10479 ("Eta")
10480 ("Theta")
10481 ("Iota")
10482 ("Kappa")
10483 ("Lambda")
10484 ("Mu")
10485 ("Nu")
10486 ("Xi")
10487 ("Omicron")
10488 ("Pi")
10489 ("Rho")
10490 ("Sigma")
10491 ("Tau")
10492 ("Upsilon")
10493 ("Phi")
10494 ("Chi")
10495 ("Psi")
10496 ("Omega")
10497 ("alpha")
10498 ("beta")
10499 ("gamma")
10500 ("delta")
10501 ("epsilon")
10502 ("varepsilon"."&epsilon;")
10503 ("zeta")
10504 ("eta")
10505 ("theta")
10506 ("iota")
10507 ("kappa")
10508 ("lambda")
10509 ("mu")
10510 ("nu")
10511 ("xi")
10512 ("omicron")
10513 ("pi")
10514 ("rho")
10515 ("sigmaf") ("varsigma"."&sigmaf;")
10516 ("sigma")
10517 ("tau")
10518 ("upsilon")
10519 ("phi")
10520 ("chi")
10521 ("psi")
10522 ("omega")
10523 ("thetasym") ("vartheta"."&thetasym;")
10524 ("upsih")
10525 ("piv")
10526 ("bull") ("bullet"."&bull;")
10527 ("hellip") ("dots"."&hellip;")
10528 ("prime")
10529 ("Prime")
10530 ("oline")
10531 ("frasl")
10532 ("weierp")
10533 ("image")
10534 ("real")
10535 ("trade")
10536 ("alefsym")
10537 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
10538 ("uarr") ("uparrow"."&uarr;")
10539 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
10540 ("darr")("downarrow"."&darr;")
10541 ("harr") ("leftrightarrow"."&harr;")
10542 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
10543 ("lArr") ("Leftarrow"."&lArr;")
10544 ("uArr") ("Uparrow"."&uArr;")
10545 ("rArr") ("Rightarrow"."&rArr;")
10546 ("dArr") ("Downarrow"."&dArr;")
10547 ("hArr") ("Leftrightarrow"."&hArr;")
10548 ("forall")
10549 ("part") ("partial"."&part;")
10550 ("exist") ("exists"."&exist;")
10551 ("empty") ("emptyset"."&empty;")
10552 ("nabla")
10553 ("isin") ("in"."&isin;")
10554 ("notin")
10555 ("ni")
10556 ("prod")
10557 ("sum")
10558 ("minus")
10559 ("lowast") ("ast"."&lowast;")
10560 ("radic")
10561 ("prop") ("proptp"."&prop;")
10562 ("infin") ("infty"."&infin;")
10563 ("ang") ("angle"."&ang;")
10564 ("and") ("vee"."&and;")
10565 ("or") ("wedge"."&or;")
10566 ("cap")
10567 ("cup")
10568 ("int")
10569 ("there4")
10570 ("sim")
10571 ("cong") ("simeq"."&cong;")
10572 ("asymp")("approx"."&asymp;")
10573 ("ne") ("neq"."&ne;")
10574 ("equiv")
10575 ("le")
10576 ("ge")
10577 ("sub") ("subset"."&sub;")
10578 ("sup") ("supset"."&sup;")
10579 ("nsub")
10580 ("sube")
10581 ("supe")
10582 ("oplus")
10583 ("otimes")
10584 ("perp")
10585 ("sdot") ("cdot"."&sdot;")
10586 ("lceil")
10587 ("rceil")
10588 ("lfloor")
10589 ("rfloor")
10590 ("lang")
10591 ("rang")
10592 ("loz") ("Diamond"."&loz;")
10593 ("spades") ("spadesuit"."&spades;")
10594 ("clubs") ("clubsuit"."&clubs;")
10595 ("hearts") ("diamondsuit"."&hearts;")
10596 ("diams") ("diamondsuit"."&diams;")
10597 ("quot")
10598 ("amp")
10599 ("lt")
10600 ("gt")
10601 ("OElig")
10602 ("oelig")
10603 ("Scaron")
10604 ("scaron")
10605 ("Yuml")
10606 ("circ")
10607 ("tilde")
10608 ("ensp")
10609 ("emsp")
10610 ("thinsp")
10611 ("zwnj")
10612 ("zwj")
10613 ("lrm")
10614 ("rlm")
10615 ("ndash")
10616 ("mdash")
10617 ("lsquo")
10618 ("rsquo")
10619 ("sbquo")
10620 ("ldquo")
10621 ("rdquo")
10622 ("bdquo")
10623 ("dagger")
10624 ("Dagger")
10625 ("permil")
10626 ("lsaquo")
10627 ("rsaquo")
10628 ("euro")
10630 ("arccos"."arccos")
10631 ("arcsin"."arcsin")
10632 ("arctan"."arctan")
10633 ("arg"."arg")
10634 ("cos"."cos")
10635 ("cosh"."cosh")
10636 ("cot"."cot")
10637 ("coth"."coth")
10638 ("csc"."csc")
10639 ("deg"."deg")
10640 ("det"."det")
10641 ("dim"."dim")
10642 ("exp"."exp")
10643 ("gcd"."gcd")
10644 ("hom"."hom")
10645 ("inf"."inf")
10646 ("ker"."ker")
10647 ("lg"."lg")
10648 ("lim"."lim")
10649 ("liminf"."liminf")
10650 ("limsup"."limsup")
10651 ("ln"."ln")
10652 ("log"."log")
10653 ("max"."max")
10654 ("min"."min")
10655 ("Pr"."Pr")
10656 ("sec"."sec")
10657 ("sin"."sin")
10658 ("sinh"."sinh")
10659 ("sup"."sup")
10660 ("tan"."tan")
10661 ("tanh"."tanh")
10663 "Entities for TeX->HTML translation.
10664 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
10665 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
10666 In that case, \"\\ent\" will be translated to \"&other;\".
10667 The list contains HTML entities for Latin-1, Greek and other symbols.
10668 It is supplemented by a number of commonly used TeX macros with appropriate
10669 translations. There is currently no way for users to extend this.")
10671 (defun org-cleaned-string-for-export (string)
10672 "Cleanup a buffer substring so that links can be created safely."
10673 (interactive)
10674 (let* ((cb (current-buffer))
10675 (re-radio (and org-target-link-regexp
10676 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
10677 rtn)
10678 (save-excursion
10679 (set-buffer (get-buffer-create " org-mode-tmp"))
10680 (erase-buffer)
10681 (insert string)
10682 (org-mode)
10683 ;; Find targets in comments and move them out of comments,
10684 ;; but mark them as targets that should be invisible
10685 (goto-char (point-min))
10686 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
10687 (replace-match "\\1(INVISIBLE)"))
10688 ;; Find matches for radio targets and turn them into links
10689 (goto-char (point-min))
10690 (when re-radio
10691 (while (re-search-forward re-radio nil t)
10692 (replace-match "\\1[[\\2]]")))
10693 ;; Find all links that contain a newline and put them into a single line
10694 (goto-char (point-min))
10695 (while (re-search-forward "\\(\\[\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\]\\)" nil t)
10696 (replace-match "\\1 \\2")
10697 (goto-char (match-beginning 0)))
10698 ;; Remove comments
10699 (goto-char (point-min))
10700 (while (re-search-forward "^#.*\n?" nil t)
10701 (replace-match ""))
10702 (setq rtn (buffer-string)))
10703 (kill-buffer " org-mode-tmp")
10704 rtn))
10706 (defun org-solidify-link-text (s &optional alist)
10707 "Take link text and make a safe target out of it."
10708 (save-match-data
10709 (let* ((rtn
10710 (mapconcat
10711 'identity
10712 (org-split-string s "[ \t\r\n]+") "--"))
10713 (a (assoc rtn alist)))
10714 (or (cdr a) rtn))))
10716 (defun org-convert-to-odd-levels ()
10717 "Convert an org-mode file with all levels allowed to one with odd levels.
10718 This will leave level 1 alone, convert level 2 to level 3, level 3 to
10719 level 5 etc."
10720 (interactive)
10721 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
10722 (let ((org-odd-levels-only nil) n)
10723 (save-excursion
10724 (goto-char (point-min))
10725 (while (re-search-forward "^\\*\\*+" nil t)
10726 (setq n (1- (length (match-string 0))))
10727 (while (>= (setq n (1- n)) 0)
10728 (org-demote))
10729 (end-of-line 1))))))
10732 (defun org-convert-to-oddeven-levels ()
10733 "Convert an org-mode file with only odd levels to one with odd and even levels.
10734 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
10735 section with an even level, conversion would destroy the structure of the file. An error
10736 is signaled in this case."
10737 (interactive)
10738 (goto-char (point-min))
10739 ;; First check if there are no even levels
10740 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
10741 (org-show-hierarchy-above)
10742 (error "Not all levels are odd in this file. Conversion not possible."))
10743 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
10744 (let ((org-odd-levels-only nil) n)
10745 (save-excursion
10746 (goto-char (point-min))
10747 (while (re-search-forward "^\\*\\*+" nil t)
10748 (setq n (/ (length (match-string 0)) 2))
10749 (while (>= (setq n (1- n)) 0)
10750 (org-promote))
10751 (end-of-line 1))))))
10753 (defun org-tr-level (n)
10754 "Make N odd if required."
10755 (if org-odd-levels-only (1+ (/ n 2)) n))
10757 (defvar org-last-level nil) ; dynamically scoped variable
10759 (defun org-export-as-ascii (arg)
10760 "Export the outline as a pretty ASCII file.
10761 If there is an active region, export only the region.
10762 The prefix ARG specifies how many levels of the outline should become
10763 underlined headlines. The default is 3."
10764 (interactive "P")
10765 (setq-default org-todo-line-regexp org-todo-line-regexp)
10766 (let* ((region
10767 (buffer-substring
10768 (if (org-region-active-p) (region-beginning) (point-min))
10769 (if (org-region-active-p) (region-end) (point-max))))
10770 (lines (org-export-find-first-heading-line
10771 (org-skip-comments
10772 (org-split-string
10773 (org-cleaned-string-for-export region)
10774 "[\r\n]"))))
10775 (org-startup-with-deadline-check nil)
10776 (level 0) line txt
10777 (umax nil)
10778 (case-fold-search nil)
10779 (filename (concat (file-name-sans-extension buffer-file-name)
10780 ".txt"))
10781 (buffer (find-file-noselect filename))
10782 (levels-open (make-vector org-level-max nil))
10783 (date (format-time-string "%Y/%m/%d" (current-time)))
10784 (time (format-time-string "%X" (org-current-time)))
10785 (author user-full-name)
10786 (title (buffer-name))
10787 (options nil)
10788 (email user-mail-address)
10789 (language org-export-default-language)
10790 (text nil)
10791 (todo nil)
10792 (lang-words nil))
10794 (setq org-last-level 1)
10795 (org-init-section-numbers)
10797 (find-file-noselect filename)
10799 ;; Search for the export key lines
10800 (org-parse-key-lines)
10802 (setq lang-words (or (assoc language org-export-language-setup)
10803 (assoc "en" org-export-language-setup)))
10804 (if org-export-ascii-show-new-buffer
10805 (switch-to-buffer-other-window buffer)
10806 (set-buffer buffer))
10807 (erase-buffer)
10808 (fundamental-mode)
10809 (if options (org-parse-export-options options))
10810 (setq umax (if arg (prefix-numeric-value arg)
10811 org-export-headline-levels))
10813 ;; File header
10814 (if title (org-insert-centered title ?=))
10815 (insert "\n")
10816 (if (or author email)
10817 (insert (concat (nth 1 lang-words) ": " (or author "")
10818 (if email (concat " <" email ">") "")
10819 "\n")))
10820 (if (and date time)
10821 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
10822 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
10824 (insert "\n\n")
10826 (if org-export-with-toc
10827 (progn
10828 (insert (nth 3 lang-words) "\n"
10829 (make-string (length (nth 3 lang-words)) ?=) "\n")
10830 (mapcar '(lambda (line)
10831 (if (string-match org-todo-line-regexp
10832 line)
10833 ;; This is a headline
10834 (progn
10835 (setq level (- (match-end 1) (match-beginning 1))
10836 level (org-tr-level level)
10837 txt (match-string 3 line)
10838 todo
10839 (or (and (match-beginning 2)
10840 (not (equal (match-string 2 line)
10841 org-done-string)))
10842 ; TODO, not DONE
10843 (and (= level umax)
10844 (org-search-todo-below
10845 line lines level))))
10846 (setq txt (org-html-expand-for-ascii txt))
10848 (if org-export-with-section-numbers
10849 (setq txt (concat (org-section-number level)
10850 " " txt)))
10851 (if (<= level umax)
10852 (progn
10853 (insert
10854 (make-string (* (1- level) 4) ?\ )
10855 (format (if todo "%s (*)\n" "%s\n") txt))
10856 (setq org-last-level level))
10857 ))))
10858 lines)))
10860 (org-init-section-numbers)
10861 (while (setq line (pop lines))
10862 ;; Remove the quoted HTML tags.
10863 (setq line (org-html-expand-for-ascii line))
10864 ;; Remove targets
10865 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
10866 (setq line (replace-match "" t t line)))
10867 ;; Replace internal links
10868 (while (string-match org-bracket-link-regexp line)
10869 (setq line (replace-match
10870 (if (match-end 3) "[\\3]" "[\\1]")
10871 t nil line)))
10872 (cond
10873 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10874 ;; a Headline
10875 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
10876 txt (match-string 2 line))
10877 (org-ascii-level-start level txt umax))
10878 (t (insert line "\n"))))
10879 (normal-mode)
10880 (save-buffer)
10881 (goto-char (point-min))))
10883 (defun org-search-todo-below (line lines level)
10884 "Search the subtree below LINE for any TODO entries."
10885 (let ((rest (cdr (memq line lines)))
10886 (re org-todo-line-regexp)
10887 line lv todo)
10888 (catch 'exit
10889 (while (setq line (pop rest))
10890 (if (string-match re line)
10891 (progn
10892 (setq lv (- (match-end 1) (match-beginning 1))
10893 todo (and (match-beginning 2)
10894 (not (equal (match-string 2 line)
10895 org-done-string))))
10896 ; TODO, not DONE
10897 (if (<= lv level) (throw 'exit nil))
10898 (if todo (throw 'exit t))))))))
10900 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
10901 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
10902 (defun org-html-expand-for-ascii (line)
10903 "Handle quoted HTML for ASCII export."
10904 (if org-export-html-expand
10905 (while (string-match "@<[^<>\n]*>" line)
10906 ;; We just remove the tags for now.
10907 (setq line (replace-match "" nil nil line))))
10908 line)
10910 (defun org-insert-centered (s &optional underline)
10911 "Insert the string S centered and underline it with character UNDERLINE."
10912 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
10913 (insert (make-string ind ?\ ) s "\n")
10914 (if underline
10915 (insert (make-string ind ?\ )
10916 (make-string (string-width s) underline)
10917 "\n"))))
10919 (defun org-ascii-level-start (level title umax)
10920 "Insert a new level in ASCII export."
10921 (let (char)
10922 (if (> level umax)
10923 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
10924 (if (or (not (equal (char-before) ?\n))
10925 (not (equal (char-before (1- (point))) ?\n)))
10926 (insert "\n"))
10927 (setq char (nth (- umax level) (reverse org-ascii-underline)))
10928 (if org-export-with-section-numbers
10929 (setq title (concat (org-section-number level) " " title)))
10930 (insert title "\n" (make-string (string-width title) char) "\n"))))
10932 (defun org-export-copy-visible ()
10933 "Copy the visible part of the buffer to another buffer, for printing.
10934 Also removes the first line of the buffer if it specifies a mode,
10935 and all options lines."
10936 (interactive)
10937 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
10938 ".txt"))
10939 (buffer (find-file-noselect filename))
10940 (ore (concat
10941 (org-make-options-regexp
10942 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
10943 "STARTUP" "ARCHIVE"
10944 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
10945 (if org-noutline-p "\\(\n\\|$\\)" "")))
10946 s e)
10947 (with-current-buffer buffer
10948 (erase-buffer)
10949 (text-mode))
10950 (save-excursion
10951 (setq s (goto-char (point-min)))
10952 (while (not (= (point) (point-max)))
10953 (goto-char (org-find-invisible))
10954 (append-to-buffer buffer s (point))
10955 (setq s (goto-char (org-find-visible)))))
10956 (switch-to-buffer-other-window buffer)
10957 (newline)
10958 (goto-char (point-min))
10959 (if (looking-at ".*-\\*- mode:.*\n")
10960 (replace-match ""))
10961 (while (re-search-forward ore nil t)
10962 (replace-match ""))
10963 (goto-char (point-min))))
10965 (defun org-find-visible ()
10966 (if (featurep 'noutline)
10967 (let ((s (point)))
10968 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10969 (get-char-property s 'invisible)))
10971 (skip-chars-forward "^\n")
10972 (point)))
10973 (defun org-find-invisible ()
10974 (if (featurep 'noutline)
10975 (let ((s (point)))
10976 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
10977 (not (get-char-property s 'invisible))))
10979 (skip-chars-forward "^\r")
10980 (point)))
10982 ;; HTML
10984 (defun org-get-current-options ()
10985 "Return a string with current options as keyword options.
10986 Does include HTML export options as well as TODO and CATEGORY stuff."
10987 (format
10988 "#+TITLE: %s
10989 #+AUTHOR: %s
10990 #+EMAIL: %s
10991 #+LANGUAGE: %s
10992 #+TEXT: Some descriptive text to be emitted. Several lines OK.
10993 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
10994 #+CATEGORY: %s
10995 #+SEQ_TODO: %s
10996 #+TYP_TODO: %s
10997 #+STARTUP: %s %s %s %s
10998 #+ARCHIVE: %s
11000 (buffer-name) (user-full-name) user-mail-address org-export-default-language
11001 org-export-headline-levels
11002 org-export-with-section-numbers
11003 org-export-with-toc
11004 org-export-preserve-breaks
11005 org-export-html-expand
11006 org-export-with-fixed-width
11007 org-export-with-tables
11008 org-export-with-sub-superscripts
11009 org-export-with-emphasize
11010 org-export-with-TeX-macros
11011 (file-name-nondirectory buffer-file-name)
11012 (if (equal org-todo-interpretation 'sequence)
11013 (mapconcat 'identity org-todo-keywords " ")
11014 "TODO FEEDBACK VERIFY DONE")
11015 (if (equal org-todo-interpretation 'type)
11016 (mapconcat 'identity org-todo-keywords " ")
11017 "Me Jason Marie DONE")
11018 (cdr (assoc org-startup-folded
11019 '((nil . "nofold")(t . "fold")(content . "content"))))
11020 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
11021 (if org-odd-levels-only "odd" "oddeven")
11022 (if org-hide-leading-stars "hidestars" "showstars")
11023 org-archive-location
11026 (defun org-insert-export-options-template ()
11027 "Insert into the buffer a template with information for exporting."
11028 (interactive)
11029 (if (not (bolp)) (newline))
11030 (let ((s (org-get-current-options)))
11031 (and (string-match "#\\+CATEGORY" s)
11032 (setq s (substring s 0 (match-beginning 0))))
11033 (insert s)))
11035 (defun org-toggle-fixed-width-section (arg)
11036 "Toggle the fixed-width export.
11037 If there is no active region, the QUOTE keyword at the current headline is
11038 inserted or removed. When present, it causes the text between this headline
11039 and the next to be exported as fixed-width text, and unmodified.
11040 If there is an active region, this command adds or removes a colon as the
11041 first character of this line. If the first character of a line is a colon,
11042 this line is also exported in fixed-width font."
11043 (interactive "P")
11044 (let* ((cc 0)
11045 (regionp (org-region-active-p))
11046 (beg (if regionp (region-beginning) (point)))
11047 (end (if regionp (region-end)))
11048 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
11049 (re "[ \t]*\\(:\\)")
11050 off)
11051 (if regionp
11052 (save-excursion
11053 (goto-char beg)
11054 (setq cc (current-column))
11055 (beginning-of-line 1)
11056 (setq off (looking-at re))
11057 (while (> nlines 0)
11058 (setq nlines (1- nlines))
11059 (beginning-of-line 1)
11060 (cond
11061 (arg
11062 (move-to-column cc t)
11063 (insert ":\n")
11064 (forward-line -1))
11065 ((and off (looking-at re))
11066 (replace-match "" t t nil 1))
11067 ((not off) (move-to-column cc t) (insert ":")))
11068 (forward-line 1)))
11069 (save-excursion
11070 (org-back-to-heading)
11071 (if (looking-at (concat outline-regexp
11072 "\\( +\\<" org-quote-string "\\>\\)"))
11073 (replace-match "" t t nil 1)
11074 (if (looking-at outline-regexp)
11075 (progn
11076 (goto-char (match-end 0))
11077 (insert " " org-quote-string))))))))
11079 (defun org-export-as-html-and-open (arg)
11080 "Export the outline as HTML and immediately open it with a browser.
11081 If there is an active region, export only the region.
11082 The prefix ARG specifies how many levels of the outline should become
11083 headlines. The default is 3. Lower levels will become bulleted lists."
11084 (interactive "P")
11085 (org-export-as-html arg 'hidden)
11086 (org-open-file buffer-file-name))
11088 (defun org-export-as-html-batch ()
11089 "Call `org-export-as-html', may be used in batch processing as
11090 emacs --batch
11091 --load=$HOME/lib/emacs/org.el
11092 --eval \"(setq org-export-headline-levels 2)\"
11093 --visit=MyFile --funcall org-export-as-html-batch"
11094 (org-export-as-html org-export-headline-levels 'hidden))
11096 (defun org-export-as-html (arg &optional hidden)
11097 "Export the outline as a pretty HTML file.
11098 If there is an active region, export only the region.
11099 The prefix ARG specifies how many levels of the outline should become
11100 headlines. The default is 3. Lower levels will become bulleted lists."
11101 (interactive "P")
11102 (setq-default org-todo-line-regexp org-todo-line-regexp)
11103 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
11104 (setq-default org-done-string org-done-string)
11105 (let* ((style org-export-html-style)
11106 (odd org-odd-levels-only)
11107 (region-p (org-region-active-p))
11108 (region
11109 (buffer-substring
11110 (if region-p (region-beginning) (point-min))
11111 (if region-p (region-end) (point-max))))
11112 (all_lines
11113 (org-skip-comments (org-split-string
11114 (org-cleaned-string-for-export region)
11115 "[\r\n]")))
11116 (lines (org-export-find-first-heading-line all_lines))
11117 (level 0) (line "") (origline "") txt todo
11118 (umax nil)
11119 (filename (concat (file-name-sans-extension buffer-file-name)
11120 ".html"))
11121 (buffer (find-file-noselect filename))
11122 (levels-open (make-vector org-level-max nil))
11123 (date (format-time-string "%Y/%m/%d" (current-time)))
11124 (time (format-time-string "%X" (org-current-time)))
11125 (author user-full-name)
11126 (title (buffer-name))
11127 (options nil)
11128 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
11129 (inquote nil)
11130 (infixed nil)
11131 (in-local-list nil)
11132 (local-list-num nil)
11133 (local-list-indent nil)
11134 (llt org-plain-list-ordered-item-terminator)
11135 (email user-mail-address)
11136 (language org-export-default-language)
11137 (text nil)
11138 (lang-words nil)
11139 (target-alist nil) tg
11140 (head-count 0) cnt
11141 (start 0)
11142 ;; FIXME: The following returns always nil under XEmacs
11143 (coding-system (and (fboundp 'coding-system-get)
11144 (boundp 'buffer-file-coding-system)
11145 buffer-file-coding-system))
11146 (coding-system-for-write (or coding-system coding-system-for-write))
11147 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
11148 (charset (and coding-system
11149 (coding-system-get coding-system 'mime-charset)))
11150 table-open type
11151 table-buffer table-orig-buffer
11152 ind start-is-num starter
11154 (message "Exporting...")
11156 (setq org-last-level 1)
11157 (org-init-section-numbers)
11159 ;; Search for the export key lines
11160 (org-parse-key-lines)
11161 (setq lang-words (or (assoc language org-export-language-setup)
11162 (assoc "en" org-export-language-setup)))
11164 ;; Switch to the output buffer
11165 (if (or hidden (not org-export-html-show-new-buffer))
11166 (set-buffer buffer)
11167 (switch-to-buffer-other-window buffer))
11168 (erase-buffer)
11169 (fundamental-mode)
11170 (let ((case-fold-search nil)
11171 (org-odd-levels-only odd))
11172 (if options (org-parse-export-options options))
11173 (setq umax (if arg (prefix-numeric-value arg)
11174 org-export-headline-levels))
11176 ;; File header
11177 (insert (format
11178 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
11179 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
11180 <html lang=\"%s\"><head>
11181 <title>%s</title>
11182 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
11183 <meta name=generator content=\"Org-mode\">
11184 <meta name=generated content=\"%s %s\">
11185 <meta name=author content=\"%s\">
11187 </head><body>
11189 language (org-html-expand title) (or charset "iso-8859-1")
11190 date time author style))
11191 (if title (insert (concat "<H1 class=\"title\">"
11192 (org-html-expand title) "</H1>\n")))
11193 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
11194 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
11195 email "&gt;</a>\n")))
11196 (if (or author email) (insert "<br>\n"))
11197 (if (and date time) (insert (concat (nth 2 lang-words) ": "
11198 date " " time "<br>\n")))
11199 (if text (insert (concat "<p>\n" (org-html-expand text))))
11200 (if org-export-with-toc
11201 (progn
11202 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
11203 (insert "<ul>\n")
11204 (setq lines
11205 (mapcar '(lambda (line)
11206 (if (string-match org-todo-line-regexp line)
11207 ;; This is a headline
11208 (progn
11209 (setq level (- (match-end 1) (match-beginning 1))
11210 level (org-tr-level level)
11211 txt (save-match-data
11212 (org-html-expand
11213 (match-string 3 line)))
11214 todo
11215 (or (and (match-beginning 2)
11216 (not (equal (match-string 2 line)
11217 org-done-string)))
11218 ; TODO, not DONE
11219 (and (= level umax)
11220 (org-search-todo-below
11221 line lines level))))
11222 (if org-export-with-section-numbers
11223 (setq txt (concat (org-section-number level)
11224 " " txt)))
11225 (if (<= level umax)
11226 (progn
11227 (setq head-count (+ head-count 1))
11228 (if (> level org-last-level)
11229 (progn
11230 (setq cnt (- level org-last-level))
11231 (while (>= (setq cnt (1- cnt)) 0)
11232 (insert "<ul>"))
11233 (insert "\n")))
11234 (if (< level org-last-level)
11235 (progn
11236 (setq cnt (- org-last-level level))
11237 (while (>= (setq cnt (1- cnt)) 0)
11238 (insert "</ul>"))
11239 (insert "\n")))
11240 ;; Check for targets
11241 (while (string-match org-target-regexp line)
11242 (setq tg (match-string 1 line)
11243 line (replace-match
11244 (concat "@<span class=\"target\">" tg "@</span> ")
11245 t t line))
11246 (push (cons (org-solidify-link-text tg)
11247 (format "sec-%d" head-count))
11248 target-alist))
11249 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
11250 (setq txt (replace-match "" t t txt)))
11251 (insert
11252 (format
11253 (if todo
11254 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
11255 "<li><a href=\"#sec-%d\">%s</a>\n")
11256 head-count txt))
11258 (setq org-last-level level))
11260 line)
11261 lines))
11262 (while (> org-last-level 0)
11263 (setq org-last-level (1- org-last-level))
11264 (insert "</ul>\n"))
11266 (setq head-count 0)
11267 (org-init-section-numbers)
11269 (while (setq line (pop lines) origline line)
11270 (catch 'nextline
11272 ;; end of quote section?
11273 (when (and inquote (string-match "^\\*+" line))
11274 (insert "</pre>\n")
11275 (setq inquote nil))
11276 ;; inside a quote section?
11277 (when inquote
11278 (insert (org-html-protect line) "\n")
11279 (throw 'nextline nil))
11281 ;; verbatim lines
11282 (when (and org-export-with-fixed-width
11283 (string-match "^[ \t]*:\\(.*\\)" line))
11284 (when (not infixed)
11285 (setq infixed t)
11286 (insert "<pre>\n"))
11287 (insert (org-html-protect (match-string 1 line)) "\n")
11288 (when (and lines
11289 (not (string-match "^[ \t]*\\(:.*\\)"
11290 (car lines))))
11291 (setq infixed nil)
11292 (insert "</pre>\n"))
11293 (throw 'nextline nil))
11296 ;; make targets to anchors
11297 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
11298 (cond
11299 ((match-end 2)
11300 (setq line (replace-match
11301 (concat "@<a name=\""
11302 (org-solidify-link-text (match-string 1 line))
11303 "\">\\nbsp@</a>")
11304 t t line)))
11305 ((and org-export-with-toc (equal (string-to-char line) ?*))
11306 (setq line (replace-match
11307 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
11308 ; (concat "@<i>" (match-string 1 line) "@</i> ")
11309 t t line)))
11311 (setq line (replace-match
11312 (concat "@<a name=\""
11313 (org-solidify-link-text (match-string 1 line))
11314 "\" class=\"target\">" (match-string 1 line) "@</a> ")
11315 t t line)))))
11316 ;; Replace internal links
11317 (while (string-match org-bracket-link-regexp line)
11318 (setq line (replace-match
11319 (concat
11320 "@<a href=\"#"
11321 (org-solidify-link-text (match-string 1 line) target-alist)
11322 "\">"
11323 (match-string (if (match-end 3) 3 1) line)
11324 "@</a>")
11325 t t line)))
11327 ;; Protect the external links
11328 (setq start 0)
11329 (while (string-match org-link-maybe-angles-regexp line start)
11330 (setq start (match-end 0))
11331 (setq line (replace-match
11332 (concat "\000" (match-string 1 line) "\000")
11333 t t line)))
11335 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
11336 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
11337 (setq line (org-html-expand line))
11339 ;; Format the links
11340 (setq start 0)
11341 (while (string-match org-protected-link-regexp line start)
11342 (setq start (- (match-end 0) 2))
11343 (setq type (match-string 1 line))
11344 (cond
11345 ((member type '("http" "https" "ftp" "mailto" "news"))
11346 ;; standard URL
11347 (setq line (replace-match
11348 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
11349 "<a href=\"\\1:\\2\">\\1:\\2</a>"
11350 nil nil line)))
11351 ((string= type "file")
11352 ;; FILE link
11353 (let* ((filename (match-string 2 line))
11354 (abs-p (file-name-absolute-p filename))
11355 (thefile (if abs-p (expand-file-name filename) filename))
11356 (thefile (save-match-data
11357 (if (string-match ":[0-9]+$" thefile)
11358 (replace-match "" t t thefile)
11359 thefile)))
11360 (file-is-image-p
11361 (save-match-data
11362 (string-match (org-image-file-name-regexp) thefile))))
11363 (setq line (replace-match
11364 (if (and org-export-html-inline-images
11365 file-is-image-p)
11366 (concat "<img src=\"" thefile "\"/>")
11367 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
11368 nil nil line))))
11370 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11371 (setq line (replace-match
11372 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
11374 ;; TODO items
11375 (if (and (string-match org-todo-line-regexp line)
11376 (match-beginning 2))
11377 (if (equal (match-string 2 line) org-done-string)
11378 (setq line (replace-match
11379 "<span class=\"done\">\\2</span>"
11380 nil nil line 2))
11381 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11382 nil nil line 2))))
11384 ;; DEADLINES
11385 (if (string-match org-deadline-line-regexp line)
11386 (progn
11387 (if (save-match-data
11388 (string-match "<a href"
11389 (substring line 0 (match-beginning 0))))
11390 nil ; Don't do the replacement - it is inside a link
11391 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11392 nil nil line 1)))))
11393 (cond
11394 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11395 ;; This is a headline
11396 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11397 txt (match-string 2 line))
11398 (if (<= level umax) (setq head-count (+ head-count 1)))
11399 (when in-local-list
11400 ;; Close any local lists before inserting a new header line
11401 (while local-list-num
11402 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11403 (pop local-list-num))
11404 (setq local-list-indent nil
11405 in-local-list nil))
11406 (org-html-level-start level txt umax
11407 (and org-export-with-toc (<= level umax))
11408 head-count)
11409 ;; QUOTES
11410 (when (string-match quote-re line)
11411 (insert "<pre>")
11412 (setq inquote t)))
11414 ((and org-export-with-tables
11415 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11416 (if (not table-open)
11417 ;; New table starts
11418 (setq table-open t table-buffer nil table-orig-buffer nil))
11419 ;; Accumulate lines
11420 (setq table-buffer (cons line table-buffer)
11421 table-orig-buffer (cons origline table-orig-buffer))
11422 (when (or (not lines)
11423 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11424 (car lines))))
11425 (setq table-open nil
11426 table-buffer (nreverse table-buffer)
11427 table-orig-buffer (nreverse table-orig-buffer))
11428 (insert (org-format-table-html table-buffer table-orig-buffer))))
11430 ;; Normal lines
11431 (when (and (> org-export-plain-list-max-depth 0)
11432 (string-match
11433 (cond
11434 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11435 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11436 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11437 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
11438 line))
11439 (setq ind (org-get-string-indentation line)
11440 start-is-num (match-beginning 4)
11441 starter (if (match-beginning 2) (match-string 2 line))
11442 line (substring line (match-beginning 5)))
11443 (unless (string-match "[^ \t]" line)
11444 ;; empty line. Pretend indentation is large.
11445 (setq ind (1+ (or (car local-list-indent) 1))))
11446 (while (and in-local-list
11447 (or (and (= ind (car local-list-indent))
11448 (not starter))
11449 (< ind (car local-list-indent))))
11450 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11451 (pop local-list-num) (pop local-list-indent)
11452 (setq in-local-list local-list-indent))
11453 (cond
11454 ((and starter
11455 (or (not in-local-list)
11456 (> ind (car local-list-indent)))
11457 (< (length local-list-indent)
11458 org-export-plain-list-max-depth))
11459 ;; Start new (level of ) list
11460 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
11461 (push start-is-num local-list-num)
11462 (push ind local-list-indent)
11463 (setq in-local-list t))
11464 (starter
11465 ;; continue current list
11466 (insert "<li>\n"))))
11467 ;; Empty lines start a new paragraph. If hand-formatted lists
11468 ;; are not fully interpreted, lines starting with "-", "+", "*"
11469 ;; also start a new paragraph.
11470 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
11471 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
11473 (if org-export-html-with-timestamp
11474 (insert org-export-html-html-helper-timestamp))
11475 (insert "</body>\n</html>\n")
11476 (normal-mode)
11477 (save-buffer)
11478 (goto-char (point-min)))))
11480 (defun org-format-table-html (lines olines)
11481 "Find out which HTML converter to use and return the HTML code."
11482 (if (string-match "^[ \t]*|" (car lines))
11483 ;; A normal org table
11484 (org-format-org-table-html lines)
11485 ;; Table made by table.el - test for spanning
11486 (let* ((hlines (delq nil (mapcar
11487 (lambda (x)
11488 (if (string-match "^[ \t]*\\+-" x) x
11489 nil))
11490 lines)))
11491 (first (car hlines))
11492 (ll (and (string-match "\\S-+" first)
11493 (match-string 0 first)))
11494 (re (concat "^[ \t]*" (regexp-quote ll)))
11495 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
11496 hlines))))
11497 (if (and (not spanning)
11498 (not org-export-prefer-native-exporter-for-tables))
11499 ;; We can use my own converter with HTML conversions
11500 (org-format-table-table-html lines)
11501 ;; Need to use the code generator in table.el, with the original text.
11502 (org-format-table-table-html-using-table-generate-source olines)))))
11504 (defun org-format-org-table-html (lines)
11505 "Format a table into HTML."
11506 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11507 (setq lines (nreverse lines))
11508 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11509 (setq lines (nreverse lines))
11510 (when org-export-table-remove-special-lines
11511 ;; Check if the table has a marking column. If yes remove the
11512 ;; column and the special lines
11513 (let* ((special
11514 (not
11515 (memq nil
11516 (mapcar
11517 (lambda (x)
11518 (or (string-match "^[ \t]*|-" x)
11519 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
11520 lines)))))
11521 (if special
11522 (setq lines
11523 (delq nil
11524 (mapcar
11525 (lambda (x)
11526 (if (string-match "^[ \t]*| *[!_^] *|" x)
11527 nil ; ignore this line
11528 (and (or (string-match "^[ \t]*|-+\\+" x)
11529 (string-match "^[ \t]*|[^|]*|" x))
11530 (replace-match "|" t t x))))
11531 lines))))))
11533 (let ((head (and org-export-highlight-first-table-line
11534 (delq nil (mapcar
11535 (lambda (x) (string-match "^[ \t]*|-" x))
11536 (cdr lines)))))
11537 line fields html)
11538 (setq html (concat org-export-html-table-tag "\n"))
11539 (while (setq line (pop lines))
11540 (catch 'next-line
11541 (if (string-match "^[ \t]*|-" line)
11542 (progn
11543 (setq head nil) ;; head ends here, first time around
11544 ;; ignore this line
11545 (throw 'next-line t)))
11546 ;; Break the line into fields
11547 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11548 (setq html (concat
11549 html
11550 "<tr>"
11551 (mapconcat (lambda (x)
11552 (if head
11553 (concat "<th>" x "</th>")
11554 (concat "<td>" x "</td>")))
11555 fields "")
11556 "</tr>\n"))))
11557 (setq html (concat html "</table>\n"))
11558 html))
11560 (defun org-fake-empty-table-line (line)
11561 "Replace everything except \"|\" with spaces."
11562 (let ((i (length line))
11563 (newstr (copy-sequence line)))
11564 (while (> i 0)
11565 (setq i (1- i))
11566 (if (not (eq (aref newstr i) ?|))
11567 (aset newstr i ?\ )))
11568 newstr))
11570 (defun org-format-table-table-html (lines)
11571 "Format a table generated by table.el into HTML.
11572 This conversion does *not* use `table-generate-source' from table.el.
11573 This has the advantage that Org-mode's HTML conversions can be used.
11574 But it has the disadvantage, that no cell- or row-spanning is allowed."
11575 (let (line field-buffer
11576 (head org-export-highlight-first-table-line)
11577 fields html empty)
11578 (setq html (concat org-export-html-table-tag "\n"))
11579 (while (setq line (pop lines))
11580 (setq empty "&nbsp")
11581 (catch 'next-line
11582 (if (string-match "^[ \t]*\\+-" line)
11583 (progn
11584 (if field-buffer
11585 (progn
11586 (setq html (concat
11587 html
11588 "<tr>"
11589 (mapconcat
11590 (lambda (x)
11591 (if (equal x "") (setq x empty))
11592 (if head
11593 (concat "<th>" x "</th>\n")
11594 (concat "<td>" x "</td>\n")))
11595 field-buffer "\n")
11596 "</tr>\n"))
11597 (setq head nil)
11598 (setq field-buffer nil)))
11599 ;; Ignore this line
11600 (throw 'next-line t)))
11601 ;; Break the line into fields and store the fields
11602 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11603 (if field-buffer
11604 (setq field-buffer (mapcar
11605 (lambda (x)
11606 (concat x "<br>" (pop fields)))
11607 field-buffer))
11608 (setq field-buffer fields))))
11609 (setq html (concat html "</table>\n"))
11610 html))
11612 (defun org-format-table-table-html-using-table-generate-source (lines)
11613 "Format a table into html, using `table-generate-source' from table.el.
11614 This has the advantage that cell- or row-spanning is allowed.
11615 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
11616 (require 'table)
11617 (with-current-buffer (get-buffer-create " org-tmp1 ")
11618 (erase-buffer)
11619 (insert (mapconcat 'identity lines "\n"))
11620 (goto-char (point-min))
11621 (if (not (re-search-forward "|[^+]" nil t))
11622 (error "Error processing table"))
11623 (table-recognize-table)
11624 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
11625 (table-generate-source 'html " org-tmp2 ")
11626 (set-buffer " org-tmp2 ")
11627 (buffer-substring (point-min) (point-max))))
11629 (defun org-html-protect (s)
11630 ;; convert & to &amp;, < to &lt; and > to &gt;
11631 (let ((start 0))
11632 (while (string-match "&" s start)
11633 (setq s (replace-match "&amp;" t t s)
11634 start (1+ (match-beginning 0))))
11635 (while (string-match "<" s)
11636 (setq s (replace-match "&lt;" t t s)))
11637 (while (string-match ">" s)
11638 (setq s (replace-match "&gt;" t t s))))
11641 (defun org-html-expand (string)
11642 "Prepare STRING for HTML export. Applies all active conversions."
11643 ;; First check if there is a link in the line - if yes, apply conversions
11644 ;; only before the start of the link.
11645 ;; FIXME: This is no longer correct, because links now have an end.
11646 (let* ((m (string-match org-link-regexp string))
11647 (s (if m (substring string 0 m) string))
11648 (r (if m (substring string m) "")))
11649 ;; convert & to &amp;, < to &lt; and > to &gt;
11650 (setq s (org-html-protect s))
11651 (if org-export-html-expand
11652 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
11653 (setq s (replace-match "<\\1>" nil nil s))))
11654 (if org-export-with-emphasize
11655 (setq s (org-export-html-convert-emphasize s)))
11656 (if org-export-with-sub-superscripts
11657 (setq s (org-export-html-convert-sub-super s)))
11658 (if org-export-with-TeX-macros
11659 (let ((start 0) wd ass)
11660 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
11661 (setq wd (match-string 1 s))
11662 (if (setq ass (assoc wd org-html-entities))
11663 (setq s (replace-match (or (cdr ass)
11664 (concat "&" (car ass) ";"))
11665 t t s))
11666 (setq start (+ start (length wd)))))))
11667 (concat s r)))
11669 (defun org-create-multibrace-regexp (left right n)
11670 "Create a regular expression which will match a balanced sexp.
11671 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
11672 as single character strings.
11673 The regexp returned will match the entire expression including the
11674 delimiters. It will also define a single group which contains the
11675 match except for the outermost delimiters. The maximum depth of
11676 stacked delimiters is N. Escaping delimiters is not possible."
11677 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
11678 (or "\\|")
11679 (re nothing)
11680 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
11681 (while (> n 1)
11682 (setq n (1- n)
11683 re (concat re or next)
11684 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
11685 (concat left "\\(" re "\\)" right)))
11687 (defvar org-match-substring-regexp
11688 (concat
11689 "\\([^\\]\\)\\([_^]\\)\\("
11690 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
11691 "\\|"
11692 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
11693 "\\|"
11694 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
11695 "The regular expression matching a sub- or superscript.")
11697 (defun org-export-html-convert-sub-super (string)
11698 "Convert sub- and superscripts in STRING to HTML."
11699 (let (key c)
11700 (while (string-match org-match-substring-regexp string)
11701 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
11702 (setq c (or (match-string 8 string)
11703 (match-string 6 string)
11704 (match-string 5 string)))
11705 (setq string (replace-match
11706 (concat (match-string 1 string)
11707 "<" key ">" c "</" key ">")
11708 t t string)))
11709 (while (string-match "\\\\\\([_^]\\)" string)
11710 (setq string (replace-match (match-string 1 string) t t string))))
11711 string)
11713 (defun org-export-html-convert-emphasize (string)
11714 (let (c (s 0))
11715 (while (string-match "\\(\\W\\|^\\)\\([*/_]\\)\\(\\w+\\)\\2\\(\\W\\|$\\)" string s)
11716 (setq c (cdr (assoc (match-string 2 string)
11717 '(("*" . "b") ("/" . "i") ("_" . "u"))))
11718 s (+ (match-end 0) 3)
11719 string (replace-match
11720 (concat "\\1<" c ">\\3</" c ">\\4") t nil string)))
11721 string))
11723 (defun org-parse-key-lines ()
11724 "Find the special key lines with the information for exporters."
11725 (save-excursion
11726 (goto-char 0)
11727 (let ((re (org-make-options-regexp
11728 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
11729 key)
11730 (while (re-search-forward re nil t)
11731 (setq key (match-string 1))
11732 (cond ((string-equal key "TITLE")
11733 (setq title (match-string 2)))
11734 ((string-equal key "AUTHOR")
11735 (setq author (match-string 2)))
11736 ((string-equal key "EMAIL")
11737 (setq email (match-string 2)))
11738 ((string-equal key "LANGUAGE")
11739 (setq language (match-string 2)))
11740 ((string-equal key "TEXT")
11741 (setq text (concat text "\n" (match-string 2))))
11742 ((string-equal key "OPTIONS")
11743 (setq options (match-string 2))))))))
11745 (defun org-parse-export-options (s)
11746 "Parse the export options line."
11747 (let ((op '(("H" . org-export-headline-levels)
11748 ("num" . org-export-with-section-numbers)
11749 ("toc" . org-export-with-toc)
11750 ("\\n" . org-export-preserve-breaks)
11751 ("@" . org-export-html-expand)
11752 (":" . org-export-with-fixed-width)
11753 ("|" . org-export-with-tables)
11754 ("^" . org-export-with-sub-superscripts)
11755 ("*" . org-export-with-emphasize)
11756 ("TeX" . org-export-with-TeX-macros)))
11758 (while (setq o (pop op))
11759 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
11761 (set (make-local-variable (cdr o))
11762 (car (read-from-string (match-string 1 s))))))))
11764 (defun org-html-level-start (level title umax with-toc head-count)
11765 "Insert a new level in HTML export."
11766 (let ((l (1+ (max level umax))))
11767 (while (<= l org-level-max)
11768 (if (aref levels-open (1- l))
11769 (progn
11770 (org-html-level-close l)
11771 (aset levels-open (1- l) nil)))
11772 (setq l (1+ l)))
11773 (if (> level umax)
11774 (progn
11775 (if (aref levels-open (1- level))
11776 (insert "<li>" title "<p>\n")
11777 (aset levels-open (1- level) t)
11778 (insert "<ul><li>" title "<p>\n")))
11779 (if org-export-with-section-numbers
11780 (setq title (concat (org-section-number level) " " title)))
11781 (setq level (+ level 1))
11782 (if with-toc
11783 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
11784 level head-count title level))
11785 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
11787 (defun org-html-level-close (&rest args)
11788 "Terminate one level in HTML export."
11789 (insert "</ul>"))
11791 ;; Variable holding the vector with section numbers
11792 (defvar org-section-numbers (make-vector org-level-max 0))
11794 (defun org-init-section-numbers ()
11795 "Initialize the vector for the section numbers."
11796 (let* ((level -1)
11797 (numbers (nreverse (org-split-string "" "\\.")))
11798 (depth (1- (length org-section-numbers)))
11799 (i depth) number-string)
11800 (while (>= i 0)
11801 (if (> i level)
11802 (aset org-section-numbers i 0)
11803 (setq number-string (or (car numbers) "0"))
11804 (if (string-match "\\`[A-Z]\\'" number-string)
11805 (aset org-section-numbers i
11806 (- (string-to-char number-string) ?A -1))
11807 (aset org-section-numbers i (string-to-number number-string)))
11808 (pop numbers))
11809 (setq i (1- i)))))
11811 (defun org-section-number (&optional level)
11812 "Return a string with the current section number.
11813 When LEVEL is non-nil, increase section numbers on that level."
11814 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
11815 (when level
11816 (when (> level -1)
11817 (aset org-section-numbers
11818 level (1+ (aref org-section-numbers level))))
11819 (setq idx (1+ level))
11820 (while (<= idx depth)
11821 (if (not (= idx 1))
11822 (aset org-section-numbers idx 0))
11823 (setq idx (1+ idx))))
11824 (setq idx 0)
11825 (while (<= idx depth)
11826 (setq n (aref org-section-numbers idx))
11827 (setq string (concat string (if (not (string= string "")) "." "")
11828 (int-to-string n)))
11829 (setq idx (1+ idx)))
11830 (save-match-data
11831 (if (string-match "\\`\\([@0]\\.\\)+" string)
11832 (setq string (replace-match "" nil nil string)))
11833 (if (string-match "\\(\\.0\\)+\\'" string)
11834 (setq string (replace-match "" nil nil string))))
11835 string))
11838 (defun org-export-icalendar-this-file ()
11839 "Export current file as an iCalendar file.
11840 The iCalendar file will be located in the same directory as the Org-mode
11841 file, but with extension `.ics'."
11842 (interactive)
11843 (org-export-icalendar nil buffer-file-name))
11845 ;;;###autoload
11846 (defun org-export-icalendar-all-agenda-files ()
11847 "Export all files in `org-agenda-files' to iCalendar .ics files.
11848 Each iCalendar file will be located in the same directory as the Org-mode
11849 file, but with extension `.ics'."
11850 (interactive)
11851 (apply 'org-export-icalendar nil org-agenda-files))
11853 ;;;###autoload
11854 (defun org-export-icalendar-combine-agenda-files ()
11855 "Export all files in `org-agenda-files' to a single combined iCalendar file.
11856 The file is stored under the name `org-combined-agenda-icalendar-file'."
11857 (interactive)
11858 (apply 'org-export-icalendar t org-agenda-files))
11860 (defun org-export-icalendar (combine &rest files)
11861 "Create iCalendar files for all elements of FILES.
11862 If COMBINE is non-nil, combine all calendar entries into a single large
11863 file and store it under the name `org-combined-agenda-icalendar-file'."
11864 (save-excursion
11865 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
11866 (when combine
11867 (setq ical-file org-combined-agenda-icalendar-file
11868 ical-buffer (org-get-agenda-file-buffer ical-file))
11869 (set-buffer ical-buffer) (erase-buffer))
11870 (while (setq file (pop files))
11871 (catch 'nextfile
11872 (org-check-agenda-file file)
11873 (unless combine
11874 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
11875 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
11876 (set-buffer ical-buffer) (erase-buffer))
11877 (set-buffer (org-get-agenda-file-buffer file))
11878 (setq category (or org-category
11879 (file-name-sans-extension
11880 (file-name-nondirectory buffer-file-name))))
11881 (if (symbolp category) (setq category (symbol-name category)))
11882 (let ((standard-output ical-buffer))
11883 (if combine
11884 (and (not started) (setq started t)
11885 (org-start-icalendar-file org-icalendar-combined-name))
11886 (org-start-icalendar-file category))
11887 (org-print-icalendar-entries combine category)
11888 (when (or (and combine (not files)) (not combine))
11889 (org-finish-icalendar-file)
11890 (set-buffer ical-buffer)
11891 (save-buffer)
11892 (run-hooks 'org-after-save-iCalendar-file-hook)))))
11893 (org-release-buffers org-agenda-new-buffers))))
11895 (defvar org-after-save-iCalendar-file-hook nil
11896 "Hook run after an iCalendar file has been saved.
11897 The iCalendar buffer is still current when this hook is run.
11898 A good way to use this is to tell a desktop calenndar application to re-read
11899 the iCalendar file.")
11901 (defun org-print-icalendar-entries (&optional combine category)
11902 "Print iCalendar entries for the current Org-mode file to `standard-output'.
11903 When COMBINE is non nil, add the category to each line."
11904 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
11905 (dts (org-ical-ts-to-string
11906 (format-time-string (cdr org-time-stamp-formats) (current-time))
11907 "DTSTART"))
11908 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
11909 (save-excursion
11910 (goto-char (point-min))
11911 (while (re-search-forward org-ts-regexp nil t)
11912 (setq pos (match-beginning 0)
11913 ts (match-string 0)
11914 inc t
11915 hd (org-get-heading))
11916 (if (looking-at re2)
11917 (progn
11918 (goto-char (match-end 0))
11919 (setq ts2 (match-string 1) inc nil))
11920 (setq ts2 ts
11921 tmp (buffer-substring (max (point-min)
11922 (- pos org-ds-keyword-length))
11923 pos)
11924 deadlinep (string-match org-deadline-regexp tmp)
11925 scheduledp (string-match org-scheduled-regexp tmp)
11926 ;; donep (org-entry-is-done-p)
11928 (if (or (string-match org-tr-regexp hd)
11929 (string-match org-ts-regexp hd))
11930 (setq hd (replace-match "" t t hd)))
11931 (if combine
11932 (setq hd (concat hd " (category " category ")")))
11933 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
11934 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
11935 (princ (format "BEGIN:VEVENT
11938 SUMMARY:%s
11939 END:VEVENT\n"
11940 (org-ical-ts-to-string ts "DTSTART")
11941 (org-ical-ts-to-string ts2 "DTEND" inc)
11942 hd)))
11943 (when org-icalendar-include-todo
11944 (goto-char (point-min))
11945 (while (re-search-forward org-todo-line-regexp nil t)
11946 (setq state (match-string 1))
11947 (unless (equal state org-done-string)
11948 (setq hd (match-string 3))
11949 (if (string-match org-priority-regexp hd)
11950 (setq pri (string-to-char (match-string 2 hd))
11951 hd (concat (substring hd 0 (match-beginning 1))
11952 (substring hd (- (match-end 1)))))
11953 (setq pri org-default-priority))
11954 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
11955 (- org-lowest-priority ?A))))))
11957 (princ (format "BEGIN:VTODO
11959 SUMMARY:%s
11960 SEQUENCE:1
11961 PRIORITY:%d
11962 END:VTODO\n"
11963 dts hd pri))))))))
11965 (defun org-start-icalendar-file (name)
11966 "Start an iCalendar file by inserting the header."
11967 (let ((user user-full-name)
11968 (name (or name "unknown"))
11969 (timezone (cadr (current-time-zone))))
11970 (princ
11971 (format "BEGIN:VCALENDAR
11972 VERSION:2.0
11973 X-WR-CALNAME:%s
11974 PRODID:-//%s//Emacs with Org-mode//EN
11975 X-WR-TIMEZONE:%s
11976 CALSCALE:GREGORIAN\n" name user timezone))))
11978 (defun org-finish-icalendar-file ()
11979 "Finish an iCalendar file by inserting the END statement."
11980 (princ "END:VCALENDAR\n"))
11982 (defun org-ical-ts-to-string (s keyword &optional inc)
11983 "Take a time string S and convert it to iCalendar format.
11984 KEYWORD is added in front, to make a complete line like DTSTART....
11985 When INC is non-nil, increase the hour by two (if time string contains
11986 a time), or the day by one (if it does not contain a time)."
11987 (let ((t1 (org-parse-time-string s 'nodefault))
11988 t2 fmt have-time time)
11989 (if (and (car t1) (nth 1 t1) (nth 2 t1))
11990 (setq t2 t1 have-time t)
11991 (setq t2 (org-parse-time-string s)))
11992 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
11993 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
11994 (when inc
11995 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
11996 (setq time (encode-time s mi h d m y)))
11997 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
11998 (concat keyword (format-time-string fmt time))))
12001 ;;; Key bindings
12003 ;; - Bindings in Org-mode map are currently
12004 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
12005 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
12006 ;; e (?) useful from outline-mode
12007 ;; i k @ expendable from outline-mode
12008 ;; 0123456789 % & ()_{} " ` free
12010 ;; Make `C-c C-x' a prefix key
12011 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
12013 ;; TAB key with modifiers
12014 (define-key org-mode-map "\C-i" 'org-cycle)
12015 (define-key org-mode-map [(tab)] 'org-cycle)
12016 (define-key org-mode-map [(meta tab)] 'org-complete)
12017 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
12018 ;; The following line is necessary under Suse GNU/Linux
12019 (unless org-xemacs-p
12020 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
12021 (define-key org-mode-map [(shift tab)] 'org-shifttab)
12023 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
12024 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
12025 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12026 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
12027 (define-key org-mode-map [(meta return)] 'org-meta-return)
12028 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
12029 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
12031 ;; Cursor keys with modifiers
12032 (define-key org-mode-map [(meta left)] 'org-metaleft)
12033 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
12034 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
12035 (define-key org-mode-map [(meta right)] 'org-metaright)
12036 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
12037 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
12038 (define-key org-mode-map [(meta up)] 'org-metaup)
12039 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
12040 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
12041 (define-key org-mode-map [(meta down)] 'org-metadown)
12042 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
12043 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
12045 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12046 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
12047 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
12048 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
12049 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
12050 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
12051 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
12052 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
12053 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
12054 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
12055 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
12056 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
12057 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
12058 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
12059 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
12060 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
12062 ;; All the other keys
12063 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
12064 (define-key org-mode-map "\C-c\C-j" 'org-goto)
12065 (define-key org-mode-map "\C-c\C-t" 'org-todo)
12066 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
12067 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
12068 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
12069 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12070 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
12071 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
12072 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12073 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
12074 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
12075 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
12076 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
12077 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
12078 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
12079 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
12080 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12081 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12082 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12083 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12084 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
12085 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
12086 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12087 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
12088 (define-key org-mode-map "\C-c]" 'org-remove-file)
12089 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
12090 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
12091 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
12092 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12093 (define-key org-mode-map "\C-m" 'org-return)
12094 (define-key org-mode-map "\C-c?" 'org-table-current-column)
12095 (define-key org-mode-map "\C-c " 'org-table-blank-field)
12096 (define-key org-mode-map "\C-c+" 'org-table-sum)
12097 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
12098 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
12099 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
12100 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
12101 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12102 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
12103 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12104 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
12105 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
12106 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
12107 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
12108 ;; OPML support is only an option for the future
12109 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
12110 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
12111 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
12112 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
12113 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
12114 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
12115 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
12116 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12117 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
12118 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
12119 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
12121 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12122 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12123 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12124 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12126 (defsubst org-table-p () (org-at-table-p))
12128 (defun org-self-insert-command (N)
12129 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12130 If the cursor is in a table looking at whitespace, the whitespace is
12131 overwritten, and the table is not marked as requiring realignment."
12132 (interactive "p")
12133 (if (and (org-table-p)
12135 (and org-table-auto-blank-field
12136 (member last-command
12137 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12138 (org-table-blank-field))
12140 (eq N 1)
12141 (looking-at "[^|\n]* +|"))
12142 (let (org-table-may-need-update)
12143 (goto-char (1- (match-end 0)))
12144 (delete-backward-char 1)
12145 (goto-char (match-beginning 0))
12146 (self-insert-command N))
12147 (setq org-table-may-need-update t)
12148 (self-insert-command N)))
12150 ;; FIXME:
12151 ;; The following two functions might still be optimized to trigger
12152 ;; re-alignment less frequently.
12154 (defun org-delete-backward-char (N)
12155 "Like `delete-backward-char', insert whitespace at field end in tables.
12156 When deleting backwards, in tables this function will insert whitespace in
12157 front of the next \"|\" separator, to keep the table aligned. The table will
12158 still be marked for re-alignment, because a narrow field may lead to a
12159 reduced column width."
12160 (interactive "p")
12161 (if (and (org-table-p)
12162 (eq N 1)
12163 (string-match "|" (buffer-substring (point-at-bol) (point)))
12164 (looking-at ".*?|"))
12165 (let ((pos (point)))
12166 (backward-delete-char N)
12167 (skip-chars-forward "^|")
12168 (insert " ")
12169 (goto-char (1- pos)))
12170 (backward-delete-char N)))
12172 (defun org-delete-char (N)
12173 "Like `delete-char', but insert whitespace at field end in tables.
12174 When deleting characters, in tables this function will insert whitespace in
12175 front of the next \"|\" separator, to keep the table aligned. The table
12176 will still be marked for re-alignment, because a narrow field may lead to
12177 a reduced column width."
12178 (interactive "p")
12179 (if (and (org-table-p)
12180 (not (bolp))
12181 (not (= (char-after) ?|))
12182 (eq N 1))
12183 (if (looking-at ".*?|")
12184 (let ((pos (point)))
12185 (replace-match (concat
12186 (substring (match-string 0) 1 -1)
12187 " |"))
12188 (goto-char pos)))
12189 (delete-char N)))
12191 ;; How to do this: Measure non-white length of current string
12192 ;; If equal to column width, we should realign.
12194 (defun org-remap (map &rest commands)
12195 "In MAP, remap the functions given in COMMANDS.
12196 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12197 (let (new old)
12198 (while commands
12199 (setq old (pop commands) new (pop commands))
12200 (if (fboundp 'command-remapping)
12201 (define-key map (vector 'remap old) new)
12202 (substitute-key-definition old new map global-map)))))
12204 (when (eq org-enable-table-editor 'optimized)
12205 ;; If the user wants maximum table support, we need to hijack
12206 ;; some standard editing functions
12207 (org-remap org-mode-map
12208 'self-insert-command 'org-self-insert-command
12209 'delete-char 'org-delete-char
12210 'delete-backward-char 'org-delete-backward-char)
12211 (define-key org-mode-map "|" 'org-force-self-insert))
12213 (defun org-shiftcursor-error ()
12214 "Throw an error because Shift-Cursor command was applied in wrong context."
12215 (error "This command is active in special context like tables, headlines or timestamps"))
12217 (defun org-shifttab ()
12218 "Global visibility cycling or move to previous table field.
12219 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
12220 See the individual commands for more information."
12221 (interactive)
12222 (cond
12223 ((org-at-table-p) (org-table-previous-field))
12224 (t (org-cycle '(4)))))
12226 (defun org-shiftmetaleft ()
12227 "Promote subtree or delete table column.
12228 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
12229 See the individual commands for more information."
12230 (interactive)
12231 (cond
12232 ((org-at-table-p) (org-table-delete-column))
12233 ((org-on-heading-p) (org-promote-subtree))
12234 ((org-at-item-p) (call-interactively 'org-outdent-item))
12235 (t (org-shiftcursor-error))))
12237 (defun org-shiftmetaright ()
12238 "Demote subtree or insert table column.
12239 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
12240 See the individual commands for more information."
12241 (interactive)
12242 (cond
12243 ((org-at-table-p) (org-table-insert-column))
12244 ((org-on-heading-p) (org-demote-subtree))
12245 ((org-at-item-p) (call-interactively 'org-indent-item))
12246 (t (org-shiftcursor-error))))
12248 (defun org-shiftmetaup (&optional arg)
12249 "Move subtree up or kill table row.
12250 Calls `org-move-subtree-up' or `org-table-kill-row' or
12251 `org-move-item-up' depending on context. See the individual commands
12252 for more information."
12253 (interactive "P")
12254 (cond
12255 ((org-at-table-p) (org-table-kill-row))
12256 ((org-on-heading-p) (org-move-subtree-up arg))
12257 ((org-at-item-p) (org-move-item-up arg))
12258 (t (org-shiftcursor-error))))
12259 (defun org-shiftmetadown (&optional arg)
12260 "Move subtree down or insert table row.
12261 Calls `org-move-subtree-down' or `org-table-insert-row' or
12262 `org-move-item-down', depending on context. See the individual
12263 commands for more information."
12264 (interactive "P")
12265 (cond
12266 ((org-at-table-p) (org-table-insert-row arg))
12267 ((org-on-heading-p) (org-move-subtree-down arg))
12268 ((org-at-item-p) (org-move-item-down arg))
12269 (t (org-shiftcursor-error))))
12271 (defun org-metaleft (&optional arg)
12272 "Promote heading or move table column to left.
12273 Calls `org-do-promote' or `org-table-move-column', depending on context.
12274 With no specific context, calls the Emacs default `backward-word'.
12275 See the individual commands for more information."
12276 (interactive "P")
12277 (cond
12278 ((org-at-table-p) (org-table-move-column 'left))
12279 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
12280 (t (backward-word (prefix-numeric-value arg)))))
12282 (defun org-metaright (&optional arg)
12283 "Demote subtree or move table column to right.
12284 Calls `org-do-demote' or `org-table-move-column', depending on context.
12285 With no specific context, calls the Emacs default `forward-word'.
12286 See the individual commands for more information."
12287 (interactive "P")
12288 (cond
12289 ((org-at-table-p) (org-table-move-column nil))
12290 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
12291 (t (forward-word (prefix-numeric-value arg)))))
12293 (defun org-metaup (&optional arg)
12294 "Move subtree up or move table row up.
12295 Calls `org-move-subtree-up' or `org-table-move-row' or
12296 `org-move-item-up', depending on context. See the individual commands
12297 for more information."
12298 (interactive "P")
12299 (cond
12300 ((org-at-table-p) (org-table-move-row 'up))
12301 ((org-on-heading-p) (org-move-subtree-up arg))
12302 ((org-at-item-p) (org-move-item-up arg))
12303 (t (org-shiftcursor-error))))
12305 (defun org-metadown (&optional arg)
12306 "Move subtree down or move table row down.
12307 Calls `org-move-subtree-down' or `org-table-move-row' or
12308 `org-move-item-down', depending on context. See the individual
12309 commands for more information."
12310 (interactive "P")
12311 (cond
12312 ((org-at-table-p) (org-table-move-row nil))
12313 ((org-on-heading-p) (org-move-subtree-down arg))
12314 ((org-at-item-p) (org-move-item-down arg))
12315 (t (org-shiftcursor-error))))
12317 (defun org-shiftup (&optional arg)
12318 "Increase item in timestamp or increase priority of current item.
12319 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12320 See the individual commands for more information."
12321 (interactive "P")
12322 (cond
12323 ((org-at-timestamp-p) (org-timestamp-up arg))
12324 (t (org-priority-up))))
12326 (defun org-shiftdown (&optional arg)
12327 "Decrease item in timestamp or decrease priority of current item.
12328 Calls `org-timestamp-down' or `org-priority-down', depending on context.
12329 See the individual commands for more information."
12330 (interactive "P")
12331 (cond
12332 ((org-at-timestamp-p) (org-timestamp-down arg))
12333 (t (org-priority-down))))
12335 (defun org-shiftright ()
12336 "Next TODO keyword or timestamp one day later, depending on context."
12337 (interactive)
12338 (cond
12339 ((org-at-timestamp-p) (org-timestamp-up-day))
12340 ((org-on-heading-p) (org-todo 'right))
12341 (t (org-shiftcursor-error))))
12343 (defun org-shiftleft ()
12344 "Previous TODO keyword or timestamp one day earlier, depending on context."
12345 (interactive)
12346 (cond
12347 ((org-at-timestamp-p) (org-timestamp-down-day))
12348 ((org-on-heading-p) (org-todo 'left))
12349 (t (org-shiftcursor-error))))
12351 (defun org-copy-special ()
12352 "Copy region in table or copy current subtree.
12353 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12354 See the individual commands for more information."
12355 (interactive)
12356 (call-interactively
12357 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12359 (defun org-cut-special ()
12360 "Cut region in table or cut current subtree.
12361 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12362 See the individual commands for more information."
12363 (interactive)
12364 (call-interactively
12365 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12367 (defun org-paste-special (arg)
12368 "Paste rectangular region into table, or past subtree relative to level.
12369 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12370 See the individual commands for more information."
12371 (interactive "P")
12372 (if (org-at-table-p)
12373 (org-table-paste-rectangle)
12374 (org-paste-subtree arg)))
12376 (defun org-ctrl-c-ctrl-c (&optional arg)
12377 "Call realign table, or recognize a table.el table, or update keywords.
12378 When the cursor is inside a table created by the table.el package,
12379 activate that table. Otherwise, if the cursor is at a normal table
12380 created with org.el, re-align that table. This command works even if
12381 the automatic table editor has been turned off.
12383 If the cursor is in a headline, prompt for tags and insert them into
12384 the current line, aligned to `org-tags-column'. When in a headline and
12385 called with prefix arg, realign all tags in the current buffer.
12387 If the cursor is in one of the special #+KEYWORD lines, this triggers
12388 scanning the buffer for these lines and updating the information.
12389 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
12390 (interactive "P")
12391 (let ((org-enable-table-editor t))
12392 (cond
12393 ((and (boundp 'remember-buffer) (equal (buffer-name) remember-buffer))
12394 (remember-buffer))
12395 ((org-on-target-p) (org-update-radio-target-regexp))
12396 ((org-on-heading-p) (org-set-tags arg))
12397 ((org-at-table.el-p)
12398 (require 'table)
12399 (beginning-of-line 1)
12400 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12401 (table-recognize-table))
12402 ((org-at-table-p)
12403 (org-table-maybe-eval-formula)
12404 (if arg
12405 (org-table-recalculate t)
12406 (org-table-maybe-recalculate-line))
12407 (org-table-align))
12408 ((org-at-item-p)
12409 (org-renumber-ordered-list (prefix-numeric-value arg)))
12410 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12411 (cond
12412 ((equal (match-string 1) "TBLFM")
12413 ;; Recalculate the table before this line
12414 (save-excursion
12415 (beginning-of-line 1)
12416 (skip-chars-backward " \r\n\t")
12417 (if (org-at-table-p) (org-table-recalculate t))))
12419 (org-mode-restart))))
12420 ((org-region-active-p)
12421 (org-table-convert-region (region-beginning) (region-end) arg))
12422 ((condition-case nil
12423 (and (region-beginning) (region-end))
12424 (error nil))
12425 (if (y-or-n-p "Convert inactive region to table? ")
12426 (org-table-convert-region (region-beginning) (region-end) arg)
12427 (error "Abort")))
12428 (t (error "C-c C-c can do nothing useful at this location.")))))
12430 (defun org-mode-restart ()
12431 "Restart Org-mode, to scan again for special lines.
12432 Also updates the keyword regular expressions."
12433 (interactive)
12434 (let ((org-inhibit-startup t)) (org-mode))
12435 (message "Org-mode restarted to refresh keyword and special line setup"))
12437 (defun org-return ()
12438 "Goto next table row or insert a newline.
12439 Calls `org-table-next-row' or `newline', depending on context.
12440 See the individual commands for more information."
12441 (interactive)
12442 (cond
12443 ((org-at-table-p)
12444 (org-table-justify-field-maybe)
12445 (org-table-next-row))
12446 (t (newline))))
12448 (defun org-meta-return (&optional arg)
12449 "Insert a new heading or wrap a region in a table.
12450 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12451 See the individual commands for more information."
12452 (interactive "P")
12453 (cond
12454 ((org-at-table-p)
12455 (org-table-wrap-region arg))
12456 (t (org-insert-heading arg))))
12458 ;;; Menu entries
12460 ;; Define the Org-mode menus
12461 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12462 '("Tbl"
12463 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
12464 ["Next Field" org-cycle (org-at-table-p)]
12465 ["Previous Field" org-shifttab (org-at-table-p)]
12466 ["Next Row" org-return (org-at-table-p)]
12467 "--"
12468 ["Blank Field" org-table-blank-field (org-at-table-p)]
12469 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12470 "--"
12471 ("Column"
12472 ["Move Column Left" org-metaleft (org-at-table-p)]
12473 ["Move Column Right" org-metaright (org-at-table-p)]
12474 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12475 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12476 ("Row"
12477 ["Move Row Up" org-metaup (org-at-table-p)]
12478 ["Move Row Down" org-metadown (org-at-table-p)]
12479 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12480 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12481 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12482 "--"
12483 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
12484 ("Rectangle"
12485 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12486 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12487 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12488 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12489 "--"
12490 ("Calculate"
12491 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12492 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12493 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12494 "--"
12495 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12496 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12497 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12498 "--"
12499 ["Sum Column/Rectangle" org-table-sum
12500 (or (org-at-table-p) (org-region-active-p))]
12501 ["Which Column?" org-table-current-column (org-at-table-p)])
12502 ["Debug Formulas"
12503 (setq org-table-formula-debug (not org-table-formula-debug))
12504 :style toggle :selected org-table-formula-debug]
12505 "--"
12506 ["Invisible Vlines" org-table-toggle-vline-visibility
12507 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
12508 "--"
12509 ["Create" org-table-create (and (not (org-at-table-p))
12510 org-enable-table-editor)]
12511 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
12512 ["Import from File" org-table-import (not (org-at-table-p))]
12513 ["Export to File" org-table-export (org-at-table-p)]
12514 "--"
12515 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12517 (easy-menu-define org-org-menu org-mode-map "Org menu"
12518 '("Org"
12519 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
12520 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
12521 ["Sparse Tree" org-occur t]
12522 ["Show All" show-all t]
12523 "--"
12524 ["New Heading" org-insert-heading t]
12525 ("Navigate Headings"
12526 ["Up" outline-up-heading t]
12527 ["Next" outline-next-visible-heading t]
12528 ["Previous" outline-previous-visible-heading t]
12529 ["Next Same Level" outline-forward-same-level t]
12530 ["Previous Same Level" outline-backward-same-level t]
12531 "--"
12532 ["Jump" org-goto t])
12533 ("Edit Structure"
12534 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12535 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12536 "--"
12537 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12538 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12539 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12540 "--"
12541 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12542 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12543 ["Demote Heading" org-metaright (not (org-at-table-p))]
12544 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12545 "--"
12546 ["Archive Subtree" org-archive-subtree t]
12547 "--"
12548 ["Convert to odd levels" org-convert-to-odd-levels t]
12549 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12550 "--"
12551 ("TODO Lists"
12552 ["TODO/DONE/-" org-todo t]
12553 ["Show TODO Tree" org-show-todo-tree t]
12554 ["Global TODO list" org-todo-list t]
12555 "--"
12556 ["Set Priority" org-priority t]
12557 ["Priority Up" org-shiftup t]
12558 ["Priority Down" org-shiftdown t])
12559 ("Dates and Scheduling"
12560 ["Timestamp" org-time-stamp t]
12561 ["Timestamp (inactive)" org-time-stamp-inactive t]
12562 ("Change Date"
12563 ["1 Day Later" org-timestamp-up-day t]
12564 ["1 Day Earlier" org-timestamp-down-day t]
12565 ["1 ... Later" org-shiftup t]
12566 ["1 ... Earlier" org-shiftdown t])
12567 ["Compute Time Range" org-evaluate-time-range t]
12568 ["Schedule Item" org-schedule t]
12569 ["Deadline" org-deadline t]
12570 "--"
12571 ["Goto Calendar" org-goto-calendar t]
12572 ["Date from Calendar" org-date-from-calendar t])
12573 "--"
12574 ["Agenda Command" org-agenda t]
12575 ("File List for Agenda")
12576 ("Special views current file"
12577 ["TODO Tree" org-show-todo-tree t]
12578 ["Check Deadlines" org-check-deadlines t]
12579 ["Timeline" org-timeline t]
12580 ["Tags Tree" org-tags-sparse-tree t])
12581 "--"
12582 ("Hyperlinks"
12583 ["Store Link (Global)" org-store-link t]
12584 ["Insert Link" org-insert-link t]
12585 ["Follow Link" org-open-at-point t])
12586 "--"
12587 ("Export"
12588 ["ASCII" org-export-as-ascii t]
12589 ["Extract Visible Text" org-export-copy-visible t]
12590 ["HTML" org-export-as-html t]
12591 ["HTML and Open" org-export-as-html-and-open t]
12592 ; ["OPML" org-export-as-opml nil]
12593 "--"
12594 ["iCalendar this file" org-export-icalendar-this-file t]
12595 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
12596 :active t :keys "C-c C-x C-i"]
12597 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
12598 "--"
12599 ["Option Template" org-insert-export-options-template t]
12600 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
12601 "--"
12602 ("Documentation"
12603 ["Show Version" org-version t]
12604 ["Info Documentation" org-info t])
12605 ("Customize"
12606 ["Browse Org Group" org-customize t]
12607 "--"
12608 ["Build Full Customize Menu" org-create-customize-menu
12609 (fboundp 'customize-menu-create)])
12610 "--"
12611 ["Refresh setup" org-mode-restart t]
12614 (defun org-info (&optional node)
12615 "Read documentation for Org-mode in the info system.
12616 With optional NODE, go directly to that node."
12617 (interactive)
12618 (require 'info)
12619 (Info-goto-node (format "(org)%s" (or node ""))))
12621 (defun org-install-agenda-files-menu ()
12622 (easy-menu-change
12623 '("Org") "File List for Agenda"
12624 (append
12625 (list
12626 ["Edit File List" (customize-variable 'org-agenda-files) t]
12627 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12628 ["Remove Current File from List" org-remove-file t]
12629 ["Cycle through agenda files" org-cycle-agenda-files t]
12630 "--")
12631 (mapcar 'org-file-menu-entry org-agenda-files))))
12633 ;;; Documentation
12635 (defun org-customize ()
12636 "Call the customize function with org as argument."
12637 (interactive)
12638 (customize-browse 'org))
12640 (defun org-create-customize-menu ()
12641 "Create a full customization menu for Org-mode, insert it into the menu."
12642 (interactive)
12643 (if (fboundp 'customize-menu-create)
12644 (progn
12645 (easy-menu-change
12646 '("Org") "Customize"
12647 `(["Browse Org group" org-customize t]
12648 "--"
12649 ,(customize-menu-create 'org)
12650 ["Set" Custom-set t]
12651 ["Save" Custom-save t]
12652 ["Reset to Current" Custom-reset-current t]
12653 ["Reset to Saved" Custom-reset-saved t]
12654 ["Reset to Standard Settings" Custom-reset-standard t]))
12655 (message "\"Org\"-menu now contains full customization menu"))
12656 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12658 ;;; Miscellaneous stuff
12660 (defun org-move-line-down (arg)
12661 "Move the current line down. With prefix argument, move it past ARG lines."
12662 (interactive "p")
12663 (let ((col (current-column))
12664 beg end pos)
12665 (beginning-of-line 1) (setq beg (point))
12666 (beginning-of-line 2) (setq end (point))
12667 (beginning-of-line (+ 1 arg))
12668 (setq pos (move-marker (make-marker) (point)))
12669 (insert (delete-and-extract-region beg end))
12670 (goto-char pos)
12671 (move-to-column col)))
12673 (defun org-move-line-up (arg)
12674 "Move the current line up. With prefix argument, move it past ARG lines."
12675 (interactive "p")
12676 (let ((col (current-column))
12677 beg end pos)
12678 (beginning-of-line 1) (setq beg (point))
12679 (beginning-of-line 2) (setq end (point))
12680 (beginning-of-line (- arg))
12681 (setq pos (move-marker (make-marker) (point)))
12682 (insert (delete-and-extract-region beg end))
12683 (goto-char pos)
12684 (move-to-column col)))
12686 ;; Paragraph filling stuff.
12687 ;; We want this to be just right, so use the full arsenal.
12688 ;; FIXME: This very likely does not work correctly for XEmacs, because the
12689 ;; filladapt package works slightly differently.
12691 (defun org-set-autofill-regexps ()
12692 (interactive)
12693 ;; In the paragraph separator we include headlines, because filling
12694 ;; text in a line directly attached to a headline would otherwise
12695 ;; fill the headline as well.
12696 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
12697 ;; The paragraph starter includes hand-formatted lists.
12698 (set (make-local-variable 'paragraph-start)
12699 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
12700 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
12701 ;; But only if the user has not turned off tables or fixed-width regions
12702 (set (make-local-variable 'auto-fill-inhibit-regexp)
12703 (concat "\\*\\|#"
12704 (if (or org-enable-table-editor org-enable-fixed-width-editor)
12705 (concat
12706 "\\|[ \t]*["
12707 (if org-enable-table-editor "|" "")
12708 (if org-enable-fixed-width-editor ":" "")
12709 "]"))))
12710 ;; We use our own fill-paragraph function, to make sure that tables
12711 ;; and fixed-width regions are not wrapped. That function will pass
12712 ;; through to `fill-paragraph' when appropriate.
12713 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
12714 ;; Adaptive filling: To get full control, first make sure that
12715 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
12716 (setq adaptive-fill-regexp "\000")
12717 (setq adaptive-fill-function 'org-adaptive-fill-function))
12719 (defun org-fill-paragraph (&optional justify)
12720 "Re-align a table, pass through to fill-paragraph if no table."
12721 (let ((table-p (org-at-table-p))
12722 (table.el-p (org-at-table.el-p)))
12723 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
12724 (table.el-p t) ; skip table.el tables
12725 (table-p (org-table-align) t) ; align org-mode tables
12726 (t nil)))) ; call paragraph-fill
12728 ;; For reference, this is the default value of adaptive-fill-regexp
12729 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
12731 (defun org-adaptive-fill-function ()
12732 "Return a fill prefix for org-mode files.
12733 In particular, this makes sure hanging paragraphs for hand-formatted lists
12734 work correctly."
12735 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
12736 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
12738 ;; Functions needed for Emacs/XEmacs region compatibility
12740 (defun org-add-hook (hook function &optional append local)
12741 "Add-hook, compatible with both Emacsen."
12742 (if (and local org-xemacs-p)
12743 (add-local-hook hook function append)
12744 (add-hook hook function append local)))
12746 (defun org-region-active-p ()
12747 "Is `transient-mark-mode' on and the region active?
12748 Works on both Emacs and XEmacs."
12749 (if org-ignore-region
12751 (if org-xemacs-p
12752 (and zmacs-regions (region-active-p))
12753 (and transient-mark-mode mark-active))))
12755 (defun org-add-to-invisibility-spec (arg)
12756 "Add elements to `buffer-invisibility-spec'.
12757 See documentation for `buffer-invisibility-spec' for the kind of elements
12758 that can be added."
12759 (cond
12760 ((fboundp 'add-to-invisibility-spec)
12761 (add-to-invisibility-spec arg))
12762 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
12763 (setq buffer-invisibility-spec (list arg)))
12765 (setq buffer-invisibility-spec
12766 (cons arg buffer-invisibility-spec)))))
12768 (defun org-remove-from-invisibility-spec (arg)
12769 "Remove elements from `buffer-invisibility-spec'."
12770 (if (fboundp 'remove-from-invisibility-spec)
12771 (remove-from-invisibility-spec arg)
12772 (if (consp buffer-invisibility-spec)
12773 (setq buffer-invisibility-spec
12774 (delete arg buffer-invisibility-spec)))))
12776 (defun org-in-invisibility-spec-p (arg)
12777 "Is ARG a member of `buffer-invisibility-spec'?"
12778 (if (consp buffer-invisibility-spec)
12779 (member arg buffer-invisibility-spec)
12780 nil))
12782 (defun org-image-file-name-regexp ()
12783 "Return regexp matching the file names of images."
12784 (if (fboundp 'image-file-name-regexp)
12785 (image-file-name-regexp)
12786 (let ((image-file-name-extensions
12787 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
12788 "xbm" "xpm" "pbm" "pgm" "ppm")))
12789 (concat "\\."
12790 (regexp-opt (nconc (mapcar 'upcase
12791 image-file-name-extensions)
12792 image-file-name-extensions)
12794 "\\'"))))
12796 ;; Functions needed for compatibility with old outline.el.
12798 ;; Programming for the old outline.el (that uses selective display
12799 ;; instead of `invisible' text properties) is a nightmare, mostly
12800 ;; because regular expressions can no longer be anchored at
12801 ;; beginning/end of line. Therefore a number of function need special
12802 ;; treatment when the old outline.el is being used.
12804 ;; The following functions capture almost the entire compatibility code
12805 ;; between the different versions of outline-mode. The only other
12806 ;; places where this is important are the font-lock-keywords, and in
12807 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
12809 ;; C-a should go to the beginning of a *visible* line, also in the
12810 ;; new outline.el. I guess this should be patched into Emacs?
12811 (defun org-beginning-of-line ()
12812 "Go to the beginning of the current line. If that is invisible, continue
12813 to a visible line beginning. This makes the function of C-a more intuitive."
12814 (interactive)
12815 (beginning-of-line 1)
12816 (if (bobp)
12818 (backward-char 1)
12819 (if (org-invisible-p)
12820 (while (and (not (bobp)) (org-invisible-p))
12821 (backward-char 1)
12822 (beginning-of-line 1))
12823 (forward-char 1))))
12825 (when org-noutline-p
12826 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
12827 ;; FIXME: should I use substitute-key-definition to reach other bindings
12828 ;; of beginning-of-line?
12830 (defun org-invisible-p ()
12831 "Check if point is at a character currently not visible."
12832 (if org-noutline-p
12833 ;; Early versions of noutline don't have `outline-invisible-p'.
12834 (if (fboundp 'outline-invisible-p)
12835 (outline-invisible-p)
12836 (get-char-property (point) 'invisible))
12837 (save-excursion
12838 (skip-chars-backward "^\r\n")
12839 (equal (char-before) ?\r))))
12841 (defun org-invisible-p2 ()
12842 "Check if point is at a character currently not visible."
12843 (save-excursion
12844 (if org-noutline-p
12845 (progn
12846 (if (and (eolp) (not (bobp))) (backward-char 1))
12847 ;; Early versions of noutline don't have `outline-invisible-p'.
12848 (if (fboundp 'outline-invisible-p)
12849 (outline-invisible-p)
12850 (get-char-property (point) 'invisible)))
12851 (skip-chars-backward "^\r\n")
12852 (equal (char-before) ?\r))))
12854 (defun org-back-to-heading (&optional invisible-ok)
12855 "Move to previous heading line, or beg of this line if it's a heading.
12856 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
12857 (if org-noutline-p
12858 (outline-back-to-heading invisible-ok)
12859 (if (and (memq (char-before) '(?\n ?\r))
12860 (looking-at outline-regexp))
12862 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
12863 outline-regexp)
12864 nil t)
12865 (if invisible-ok
12866 (progn (goto-char (match-end 1))
12867 (looking-at outline-regexp)))
12868 (error "Before first heading")))))
12870 (defun org-on-heading-p (&optional invisible-ok)
12871 "Return t if point is on a (visible) heading line.
12872 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
12873 (if org-noutline-p
12874 (outline-on-heading-p 'invisible-ok)
12875 (save-excursion
12876 (skip-chars-backward "^\n\r")
12877 (and (looking-at outline-regexp)
12878 (or invisible-ok
12879 (bobp)
12880 (equal (char-before) ?\n))))))
12882 (defun org-on-target-p ()
12883 (let ((pos (point)))
12884 (save-excursion
12885 (skip-chars-forward "<")
12886 (and (re-search-backward "<<" nil t)
12887 (or (looking-at org-target-regexp)
12888 (looking-at org-radio-target-regexp))
12889 (<= (match-beginning 0) pos)
12890 (>= (match-end 0) pos)))))
12892 (defun org-up-heading-all (arg)
12893 "Move to the heading line of which the present line is a subheading.
12894 This function considers both visible and invisible heading lines.
12895 With argument, move up ARG levels."
12896 (if org-noutline-p
12897 (if (fboundp 'outline-up-heading-all)
12898 (outline-up-heading-all arg) ; emacs 21 version of outline.el
12899 (outline-up-heading arg t)) ; emacs 22 version of outline.el
12900 (org-back-to-heading t)
12901 (looking-at outline-regexp)
12902 (if (<= (- (match-end 0) (match-beginning 0)) arg)
12903 (error "Cannot move up %d levels" arg)
12904 (re-search-backward
12905 (concat "[\n\r]" (regexp-quote
12906 (make-string (- (match-end 0) (match-beginning 0) arg)
12907 ?*))
12908 "[^*]"))
12909 (forward-char 1))))
12911 (defun org-show-hidden-entry ()
12912 "Show an entry where even the heading is hidden."
12913 (save-excursion
12914 (if (not org-noutline-p)
12915 (progn
12916 (org-back-to-heading t)
12917 (org-flag-heading nil)))
12918 (org-show-entry)))
12920 (defun org-check-occur-regexp (regexp)
12921 "If REGEXP starts with \"^\", modify it to check for \\r as well.
12922 Of course, only for the old outline mode."
12923 (if org-noutline-p
12924 regexp
12925 (if (string-match "^\\^" regexp)
12926 (concat "[\n\r]" (substring regexp 1))
12927 regexp)))
12929 (defun org-flag-heading (flag &optional entry)
12930 "Flag the current heading. FLAG non-nil means make invisible.
12931 When ENTRY is non-nil, show the entire entry."
12932 (save-excursion
12933 (org-back-to-heading t)
12934 (if (not org-noutline-p)
12935 ;; Make the current headline visible
12936 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
12937 ;; Check if we should show the entire entry
12938 (if entry
12939 (progn
12940 (org-show-entry)
12941 (save-excursion ;; FIXME: Is this the fix for points in the -|
12942 ;; middle of text? |
12943 (and (outline-next-heading) ;; |
12944 (org-flag-heading nil)))) ; show the next heading _|
12945 (outline-flag-region (max 1 (1- (point)))
12946 (save-excursion (outline-end-of-heading) (point))
12947 (if org-noutline-p
12948 flag
12949 (if flag ?\r ?\n))))))
12951 (defun org-end-of-subtree (&optional invisible-OK)
12952 ;; This is an exact copy of the original function, but it uses
12953 ;; `org-back-to-heading', to make it work also in invisible
12954 ;; trees. And is uses an invisible-OK argument.
12955 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
12956 (org-back-to-heading invisible-OK)
12957 (let ((first t)
12958 (level (funcall outline-level)))
12959 (while (and (not (eobp))
12960 (or first (> (funcall outline-level) level)))
12961 (setq first nil)
12962 (outline-next-heading))
12963 (if (memq (preceding-char) '(?\n ?\^M))
12964 (progn
12965 ;; Go to end of line before heading
12966 (forward-char -1)
12967 (if (memq (preceding-char) '(?\n ?\^M))
12968 ;; leave blank line before heading
12969 (forward-char -1))))))
12971 (defun org-show-subtree ()
12972 "Show everything after this heading at deeper levels."
12973 (outline-flag-region
12974 (point)
12975 (save-excursion
12976 (outline-end-of-subtree) (outline-next-heading) (point))
12977 (if org-noutline-p nil ?\n)))
12979 (defun org-show-entry ()
12980 "Show the body directly following this heading.
12981 Show the heading too, if it is currently invisible."
12982 (interactive)
12983 (save-excursion
12984 (org-back-to-heading t)
12985 (outline-flag-region
12986 (1- (point))
12987 (save-excursion
12988 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
12989 (or (match-beginning 1) (point-max)))
12990 (if org-noutline-p nil ?\n))))
12993 (defun org-make-options-regexp (kwds)
12994 "Make a regular expression for keyword lines."
12995 (concat
12996 (if org-noutline-p "^" "[\n\r]")
12997 "#?[ \t]*\\+\\("
12998 (mapconcat 'regexp-quote kwds "\\|")
12999 "\\):[ \t]*"
13000 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
13002 ;; Make `bookmark-jump' show the jump location if it was hidden.
13003 (eval-after-load "bookmark"
13004 '(if (boundp 'bookmark-after-jump-hook)
13005 ;; We can use the hook
13006 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13007 ;; Hook not available, use advice
13008 (defadvice bookmark-jump (after org-make-visible activate)
13009 "Make the position visible."
13010 (org-bookmark-jump-unhide))))
13012 (defun org-bookmark-jump-unhide ()
13013 "Unhide the current position, to show the bookmark location."
13014 (and (eq major-mode 'org-mode)
13015 (or (org-invisible-p)
13016 (save-excursion (goto-char (max (point-min) (1- (point))))
13017 (org-invisible-p)))
13018 (org-show-hierarchy-above)))
13020 ;;; Finish up
13022 (provide 'org)
13024 (run-hooks 'org-load-hook)
13026 ;; Experimental code
13030 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13031 ;;; org.el ends here