4.13
[org-mode.git] / org.el
blob512404bb52e3c7d17477f544079f236d702d6f30
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.13
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.13
85 ;; - The list of agenda files can be maintainted in an external file.
86 ;; - Bug fixes.
88 ;; Version 4.12
89 ;; - Templates for remember buffer. Note that the remember setup changes.
90 ;; To set up templates, see `org-remember-templates'.
91 ;; - The time in new time stamps can be rounded, see new option
92 ;; `org-time-stamp-rounding-minutes'.
93 ;; - Bug fixes (there are *always* more bugs).
95 ;; Version 4.10
96 ;; - Bug fixes.
98 ;; Version 4.09
99 ;; - Bug fixes.
100 ;; - Small improvements to font-lock support.
101 ;; - MHE support finalized.
103 ;; Version 4.08
104 ;; - Bug fixes.
105 ;; - Improved MHE support
107 ;; Version 4.07
108 ;; - Bug fixes.
109 ;; - Leading stars in headlines can be hidden, so make the outline look
110 ;; cleaner.
111 ;; - Mouse-1 can be used to follow links.
113 ;; Version 4.06
114 ;; - HTML exporter treats targeted internal links.
115 ;; - Bug fixes.
117 ;; Version 4.05
118 ;; - Changes to internal link system (thanks to David Wainberg for ideas).
119 ;; - in-file links: [[Search String]] instead of <file:::Search String>
120 ;; - automatic links to "radio targets".
121 ;; - CamelCase not longer active by default, configure org-activate-camels
122 ;; if you want to turn it back on.
123 ;; - After following a link, `C-c &' jumps back to it.
124 ;; - MH-E link support (thanks to Thomas Baumann).
125 ;; - Special table lines are no longer exported.
126 ;; - Bug fixes and minor improvements.
128 ;; Version 4.04
129 ;; - Cleanup tags display in agenda.
130 ;; - Bug fixes.
132 ;; Version 4.03
133 ;; - Table alignment fixed for use with wide characters.
134 ;; - `C-c -' leaves cursor in current table line.
135 ;; - The current TAG can be incorporated into the agenda prefix.
136 ;; See option `org-agenda-prefix-format' for details.
138 ;; Version 4.02
139 ;; - Minor bug fixes and improvements around tag searches.
140 ;; - XEmacs compatibility fixes.
142 ;; Version 4.01
143 ;; - Tags can also be set remotely from agenda buffer.
144 ;; - Boolean logic for tag searches.
145 ;; - Additional agenda commands can be configured through the variable
146 ;; `org-agenda-custom-commands'.
147 ;; - Minor bug fixes.
149 ;;; Code:
151 (eval-when-compile (require 'cl) (require 'calendar))
152 (require 'outline)
153 (require 'time-date)
154 (require 'easymenu)
156 (defvar calc-embedded-close-formula) ; defined by the calc package
157 (defvar calc-embedded-open-formula) ; defined by the calc package
158 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
160 ;;; Customization variables
162 (defvar org-version "4.13"
163 "The version number of the file org.el.")
164 (defun org-version ()
165 (interactive)
166 (message "Org-mode version %s" org-version))
168 ;; The following constant is for compatibility with different versions
169 ;; of outline.el.
170 (defconst org-noutline-p (featurep 'noutline)
171 "Are we using the new outline mode?")
173 (defgroup org nil
174 "Outline-based notes management and organizer."
175 :tag "Org"
176 :group 'outlines
177 :group 'hypermedia
178 :group 'calendar)
180 (defgroup org-startup nil
181 "Options concerning startup of Org-mode."
182 :tag "Org Startup"
183 :group 'org)
185 (defcustom org-CUA-compatible nil
186 "Non-nil means use alternative key bindings for S-<cursor movement>.
187 Org-mode used S-<cursor movement> for changing timestamps and priorities.
188 S-<cursor movement> is also used for example by `CUA-mode' to select text.
189 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
190 alternative bindings. Setting this variable to t will replace the following
191 keys both in Org-mode and in the Org-agenda buffer.
193 S-RET -> C-S-RET
194 S-up -> M-p
195 S-down -> M-n
196 S-left -> M--
197 S-right -> M-+
199 If you do not like the alternative keys, take a look at the variable
200 `org-disputed-keys'.
202 This option is only relevant at load-time of Org-mode. Changing it requires
203 a restart of Emacs to become effective."
204 :group 'org-startup
205 :type 'boolean)
207 (defvar org-disputed-keys
208 '((S-up [(shift up)] [(meta ?p)])
209 (S-down [(shift down)] [(meta ?n)])
210 (S-left [(shift left)] [(meta ?-)])
211 (S-right [(shift right)] [(meta ?+)])
212 (S-return [(shift return)] [(control shift return)]))
213 "Keys for which Org-mode and other modes compete.
214 This is an alist, cars are symbols for lookup, 1st element is the default key,
215 second element will be used when `org-CUA-compatible' is t.")
217 (defun org-key (key)
218 "Select a key according to `org-CUA-compatible'."
219 (nth (if org-CUA-compatible 2 1)
220 (or (assq key org-disputed-keys)
221 (error "Invalid Key %s in `org-key'" key))))
223 (defcustom org-startup-folded t
224 "Non-nil means, entering Org-mode will switch to OVERVIEW.
225 This can also be configured on a per-file basis by adding one of
226 the following lines anywhere in the buffer:
228 #+STARTUP: fold
229 #+STARTUP: nofold
230 #+STARTUP: content"
231 :group 'org-startup
232 :type '(choice
233 (const :tag "nofold: show all" nil)
234 (const :tag "fold: overview" t)
235 (const :tag "content: all headlines" content)))
237 (defcustom org-startup-truncated t
238 "Non-nil means, entering Org-mode will set `truncate-lines'.
239 This is useful since some lines containing links can be very long and
240 uninteresting. Also tables look terrible when wrapped."
241 :group 'org-startup
242 :type 'boolean)
244 (defcustom org-startup-with-deadline-check nil
245 "Non-nil means, entering Org-mode will run the deadline check.
246 This means, if you start editing an org file, you will get an
247 immediate reminder of any due deadlines.
248 This can also be configured on a per-file basis by adding one of
249 the following lines anywhere in the buffer:
251 #+STARTUP: dlcheck
252 #+STARTUP: nodlcheck"
253 :group 'org-startup
254 :type 'boolean)
256 (defcustom org-insert-mode-line-in-empty-file nil
257 "Non-nil means insert the first line setting Org-mode in empty files.
258 When the function `org-mode' is called interactively in an empty file, this
259 normally means that the file name does not automatically trigger Org-mode.
260 To ensure that the file will always be in Org-mode in the future, a
261 line enforcing Org-mode will be inserted into the buffer, if this option
262 has been set."
263 :group 'org-startup
264 :type 'boolean)
266 (defgroup org-keywords nil
267 "Options concerning TODO items in Org-mode."
268 :tag "Org Keywords"
269 :group 'org)
271 (defcustom org-todo-keywords '("TODO" "DONE")
272 "List of TODO entry keywords.
273 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
274 considered to mean that the entry is \"done\". All the other mean that
275 action is required, and will make the entry show up in todo lists, diaries
276 etc.
277 The command \\[org-todo] cycles an entry through these states, and an
278 additional state where no keyword is present. For details about this
279 cycling, see also the variable `org-todo-interpretation'
280 Changes become only effective after restarting Emacs."
281 :group 'org-keywords
282 :type '(repeat (string :tag "Keyword")))
284 (defcustom org-todo-interpretation 'sequence
285 "Controls how TODO keywords are interpreted.
286 \\<org-mode-map>Possible values are `sequence' and `type'.
287 This variable is only relevant if `org-todo-keywords' contains more than two
288 states. There are two ways how these keywords can be used:
290 - As a sequence in the process of working on a TODO item, for example
291 (setq org-todo-keywords '(\"TODO\" \"STARTED\" \"VERIFY\" \"DONE\")
292 org-todo-interpretation 'sequence)
294 - As different types of TODO items, for example
295 (setq org-todo-keywords '(\"URGENT\" \"RELAXED\" \"REMIND\" \"FOR_TOM\" \"DONE\")
296 org-todo-interpretation 'type)
298 When the states are interpreted as a sequence, \\[org-todo] always cycles
299 to the next state, in order to walk through all different states. So with
300 \\[org-todo], you turn an empty entry into the state TODO. When you started
301 working on the item, you use \\[org-todo] again to switch it to \"STARTED\",
302 later to VERIFY and finally to DONE.
304 When the states are interpreted as types, \\[org-todo] still cycles through
305 when it is called several times in direct succession, in order to initially
306 select the type. However, if not called immediately after a previous
307 \\[org-todo], it switches from each type directly to DONE. So with the
308 above example, you could use `\\[org-todo] \\[org-todo]' to label an entry
309 RELAXED. If you later return to this entry and press \\[org-todo] again,
310 RELAXED will not be changed REMIND, but directly to DONE.
312 You can create a large number of types. To initially select a
313 type, it is then best to use \\[universal-argument] \\[org-todo] in order to specify the
314 type with completion. Of course, you can also type the keyword
315 directly into the buffer. M-TAB completes TODO keywords at the
316 beginning of a headline."
317 :group 'org-keywords
318 :type '(choice (const sequence)
319 (const type)))
321 (defcustom org-default-priority ?B
322 "The default priority of TODO items.
323 This is the priority an item get if no explicit priority is given."
324 :group 'org-keywords
325 :type 'character)
327 (defcustom org-lowest-priority ?C
328 "The lowest priority of TODO items. A character like ?A, ?B etc."
329 :group 'org-keywords
330 :type 'character)
332 (defcustom org-deadline-string "DEADLINE:"
333 "String to mark deadline entries.
334 A deadline is this string, followed by a time stamp. Should be a word,
335 terminated by a colon. You can insert a schedule keyword and
336 a timestamp with \\[org-deadline].
337 Changes become only effective after restarting Emacs."
338 :group 'org-keywords
339 :type 'string)
341 (defcustom org-scheduled-string "SCHEDULED:"
342 "String to mark scheduled TODO entries.
343 A schedule is this string, followed by a time stamp. Should be a word,
344 terminated by a colon. You can insert a schedule keyword and
345 a timestamp with \\[org-schedule].
346 Changes become only effective after restarting Emacs."
347 :group 'org-keywords
348 :type 'string)
350 (defcustom org-closed-string "CLOSED:"
351 "String used as the prefix for timestamps logging closing a TODO entry."
352 :group 'org-keywords
353 :type 'string)
355 (defcustom org-comment-string "COMMENT"
356 "Entries starting with this keyword will never be exported.
357 An entry can be toggled between COMMENT and normal with
358 \\[org-toggle-comment].
359 Changes become only effective after restarting Emacs."
360 :group 'org-keywords
361 :type 'string)
363 (defcustom org-quote-string "QUOTE"
364 "Entries starting with this keyword will be exported in fixed-width font.
365 Quoting applies only to the text in the entry following the headline, and does
366 not extend beyond the next headline, even if that is lower level.
367 An entry can be toggled between QUOTE and normal with
368 \\[org-toggle-fixed-width-section]."
369 :group 'org-keywords
370 :type 'string)
372 (defcustom org-after-todo-state-change-hook nil
373 "Hook which is run after the state of a TODO item was changed.
374 The new state (a string with a TODO keyword, or nil) is available in the
375 Lisp variable `state'."
376 :group 'org-keywords
377 :type 'hook)
379 ;; Variables for pre-computed regular expressions, all buffer local
380 (defvar org-todo-kwd-priority-p nil
381 "Do TODO items have priorities?")
382 (make-variable-buffer-local 'org-todo-kwd-priority-p)
383 (defvar org-todo-kwd-max-priority nil
384 "Maximum priority of TODO items.")
385 (make-variable-buffer-local 'org-todo-kwd-max-priority)
386 (defvar org-ds-keyword-length 12
387 "Maximum length of the Deadline and SCHEDULED keywords.")
388 (make-variable-buffer-local 'org-ds-keyword-length)
389 (defvar org-done-string nil
390 "The last string in `org-todo-keywords', indicating an item is DONE.")
391 (make-variable-buffer-local 'org-done-string)
392 (defvar org-todo-regexp nil
393 "Matches any of the TODO state keywords.")
394 (make-variable-buffer-local 'org-todo-regexp)
395 (defvar org-not-done-regexp nil
396 "Matches any of the TODO state keywords except the last one.")
397 (make-variable-buffer-local 'org-not-done-regexp)
398 (defvar org-todo-line-regexp nil
399 "Matches a headline and puts TODO state into group 2 if present.")
400 (make-variable-buffer-local 'org-todo-line-regexp)
401 (defvar org-nl-done-regexp nil
402 "Matches newline followed by a headline with the DONE keyword.")
403 (make-variable-buffer-local 'org-nl-done-regexp)
404 (defvar org-looking-at-done-regexp nil
405 "Matches the DONE keyword a point.")
406 (make-variable-buffer-local 'org-looking-at-done-regexp)
407 (defvar org-deadline-regexp nil
408 "Matches the DEADLINE keyword.")
409 (make-variable-buffer-local 'org-deadline-regexp)
410 (defvar org-deadline-time-regexp nil
411 "Matches the DEADLINE keyword together with a time stamp.")
412 (make-variable-buffer-local 'org-deadline-time-regexp)
413 (defvar org-deadline-line-regexp nil
414 "Matches the DEADLINE keyword and the rest of the line.")
415 (make-variable-buffer-local 'org-deadline-line-regexp)
416 (defvar org-scheduled-regexp nil
417 "Matches the SCHEDULED keyword.")
418 (make-variable-buffer-local 'org-scheduled-regexp)
419 (defvar org-scheduled-time-regexp nil
420 "Matches the SCHEDULED keyword together with a time stamp.")
421 (make-variable-buffer-local 'org-scheduled-time-regexp)
423 (defvar org-category nil
424 "Variable used by org files to set a category for agenda display.
425 Such files should use a file variable to set it, for example
427 -*- mode: org; org-category: \"ELisp\"
429 or contain a special line
431 #+CATEGORY: ELisp
433 If the file does not specify a category, then file's base name
434 is used instead.")
435 (make-variable-buffer-local 'org-category)
437 (defgroup org-time nil
438 "Options concerning time stamps and deadlines in Org-mode."
439 :tag "Org Time"
440 :group 'org)
442 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
443 "Formats for `format-time-string' which are used for time stamps.
444 It is not recommended to change this constant.")
446 (defcustom org-time-stamp-rounding-minutes 0
447 "Number of minutes to round time stamps to upon insertion.
448 When zero, insert the time unmodified. Useful rounding numbers
449 should be factors of 60, so for example 5, 10, 15.
450 When this is not zero, you can still force an exact time-stamp by using
451 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
452 :group 'org-time
453 :type 'integer)
455 (defcustom org-deadline-warning-days 30
456 "No. of days before expiration during which a deadline becomes active.
457 This variable governs the display in the org file."
458 :group 'org-time
459 :type 'number)
461 (defcustom org-popup-calendar-for-date-prompt t
462 "Non-nil means, pop up a calendar when prompting for a date.
463 In the calendar, the date can be selected with mouse-1. However, the
464 minibuffer will also be active, and you can simply enter the date as well.
465 When nil, only the minibuffer will be available."
466 :group 'org-time
467 :type 'boolean)
469 (defcustom org-calendar-follow-timestamp-change t
470 "Non-nil means, make the calendar window follow timestamp changes.
471 When a timestamp is modified and the calendar window is visible, it will be
472 moved to the new date."
473 :group 'org-time
474 :type 'boolean)
476 (defcustom org-log-done nil
477 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
478 When the state of an entry is changed from nothing to TODO, remove a previous
479 closing date."
480 :group 'org-time
481 :type 'boolean)
483 (defgroup org-agenda nil
484 "Options concerning agenda display Org-mode."
485 :tag "Org Agenda"
486 :group 'org)
488 (defcustom org-agenda-files nil
489 "The files to be used for agenda display.
490 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
491 \\[org-remove-file]. You can also use customize to edit the list.
493 If the value of the variable is not a list but a single file name, then
494 the list of agenda files is actually stored in that file, one agenda file
495 per line"
496 :group 'org-agenda
497 :type '(choice
498 (repeat :tag "List of files" file)
499 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
501 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
502 "Custom commands for the agenda.
503 These commands will be offered on the splash screen displayed by the
504 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
506 key The key (a single char as a string) to be associated with the command.
507 type The command type, any of the following symbols:
508 todo Entries with a specific TODO keyword, in all agenda files.
509 tags Tags match in all agenda files.
510 todo-tree Sparse tree of specific TODO keyword in *current* file.
511 tags-tree Sparse tree with all tags matches in *current* file.
512 occur-tree Occur sparse tree for current file.
513 match What to search for:
514 - a single keyword for TODO keyword searches
515 - a tags match expression for tags searches
516 - a regular expression for occur searches"
517 :group 'org-agenda
518 :type '(repeat
519 (list (string :tag "Key")
520 (choice :tag "Type"
521 (const :tag "Tags search in all agenda files" tags)
522 (const :tag "TODO keyword search in all agenda files" todo)
523 (const :tag "Tags sparse tree in current buffer" tags-tree)
524 (const :tag "TODO keyword tree in current buffer" todo-tree)
525 (const :tag "Occur tree in current buffer" occur-tree))
526 (string :tag "Match"))))
528 (defcustom org-select-timeline-window t
529 "Non-nil means, after creating a timeline, move cursor into Timeline window.
530 When nil, cursor will remain in the current window."
531 :group 'org-agenda
532 :type 'boolean)
534 (defcustom org-select-agenda-window t
535 "Non-nil means, after creating an agenda, move cursor into Agenda window.
536 When nil, cursor will remain in the current window."
537 :group 'org-agenda
538 :type 'boolean)
540 (defcustom org-fit-agenda-window t
541 "Non-nil means, change window size of agenda to fit content."
542 :group 'org-agenda
543 :type 'boolean)
545 (defcustom org-agenda-show-all-dates t
546 "Non-nil means, `org-agenda' shows every day in the selected range.
547 When nil, only the days which actually have entries are shown."
548 :group 'org-agenda
549 :type 'boolean)
551 ;; FIXME: First day of month works only for current month because it would
552 ;; require a variable ndays treatment.
553 (defcustom org-agenda-start-on-weekday 1
554 "Non-nil means, start the overview always on the specified weekday.
555 0 Denotes Sunday, 1 denotes Monday etc.
556 When nil, always start on the current day."
557 :group 'org-agenda
558 :type '(choice (const :tag "Today" nil)
559 (const :tag "First day of month" t)
560 (number :tag "Weekday No.")))
562 (defcustom org-agenda-ndays 7
563 "Number of days to include in overview display."
564 :group 'org-agenda
565 :type 'number)
567 (defcustom org-agenda-include-all-todo t
568 "Non-nil means, the agenda will always contain all TODO entries.
569 When nil, date-less entries will only be shown if `org-agenda' is called
570 with a prefix argument.
571 When non-nil, the TODO entries will be listed at the top of the agenda, before
572 the entries for specific days."
573 :group 'org-agenda
574 :type 'boolean)
576 (defcustom org-agenda-include-diary nil
577 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
578 :group 'org-agenda
579 :type 'boolean)
581 (defcustom org-calendar-to-agenda-key [?c]
582 "The key to be installed in `calendar-mode-map' for switching to the agenda.
583 The command `org-calendar-goto-agenda' will be bound to this key. The
584 default is the character `c' because then `c' can be used to switch back and
585 forth between agenda and calendar."
586 :group 'org-agenda
587 :type 'sexp)
589 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
590 "Sorting structure for the agenda items of a single day.
591 This is a list of symbols which will be used in sequence to determine
592 if an entry should be listed before another entry. The following
593 symbols are recognized:
595 time-up Put entries with time-of-day indications first, early first
596 time-down Put entries with time-of-day indications first, late first
597 category-keep Keep the default order of categories, corresponding to the
598 sequence in `org-agenda-files'.
599 category-up Sort alphabetically by category, A-Z.
600 category-down Sort alphabetically by category, Z-A.
601 priority-up Sort numerically by priority, high priority last.
602 priority-down Sort numerically by priority, high priority first.
604 The different possibilities will be tried in sequence, and testing stops
605 if one comparison returns a \"not-equal\". For example, the default
606 '(time-up category-keep priority-down)
607 means: Pull out all entries having a specified time of day and sort them,
608 in order to make a time schedule for the current day the first thing in the
609 agenda listing for the day. Of the entries without a time indication, keep
610 the grouped in categories, don't sort the categories, but keep them in
611 the sequence given in `org-agenda-files'. Within each category sort by
612 priority.
614 Leaving out `category-keep' would mean that items will be sorted across
615 categories by priority."
616 :group 'org-agenda
617 :type '(repeat
618 (choice
619 (const time-up)
620 (const time-down)
621 (const category-keep)
622 (const category-up)
623 (const category-down)
624 (const priority-up)
625 (const priority-down))))
627 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
628 "Format specification for the prefix of items in the agenda buffer.
629 This format works similar to a printf format, with the following meaning:
631 %c the category of the item, \"Diary\" for entries from the diary, or
632 as given by the CATEGORY keyword or derived from the file name.
633 %T the first tag of the item.
634 %t the time-of-day specification if one applies to the entry, in the
635 format HH:MM
636 %s Scheduling/Deadline information, a short string
638 All specifiers work basically like the standard `%s' of printf, but may
639 contain two additional characters: A question mark just after the `%' and
640 a whitespace/punctuation character just before the final letter.
642 If the first character after `%' is a question mark, the entire field
643 will only be included if the corresponding value applies to the
644 current entry. This is useful for fields which should have fixed
645 width when present, but zero width when absent. For example,
646 \"%?-12t\" will result in a 12 character time field if a time of the
647 day is specified, but will completely disappear in entries which do
648 not contain a time.
650 If there is punctuation or whitespace character just before the final
651 format letter, this character will be appended to the field value if
652 the value is not empty. For example, the format \"%-12:c\" leads to
653 \"Diary: \" if the category is \"Diary\". If the category were be
654 empty, no additional colon would be interted.
656 The default value of this option is \" %-12:c%?-12t% s\", meaning:
657 - Indent the line with two space characters
658 - Give the category in a 12 chars wide field, padded with whitespace on
659 the right (because of `-'). Append a colon if there is a category
660 (because of `:').
661 - If there is a time-of-day, put it into a 12 chars wide field. If no
662 time, don't put in an empty field, just skip it (because of '?').
663 - Finally, put the scheduling information and append a whitespace.
665 As another example, if you don't want the time-of-day of entries in
666 the prefix, you could use:
668 (setq org-agenda-prefix-format \" %-11:c% s\")
670 See also the variables `org-agenda-remove-times-when-in-prefix' and
671 `org-agenda-remove-tags-when-in-prefix'."
672 :type 'string
673 :group 'org-agenda)
675 (defcustom org-timeline-prefix-format " % s"
676 "Like `org-agenda-prefix-format', but for the timeline of a single file."
677 :type 'string
678 :group 'org-agenda)
680 (defvar org-prefix-format-compiled nil
681 "The compiled version of the most recently used prefix format.
682 Depending on which command was used last, this may be the compiled version
683 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
685 (defcustom org-agenda-use-time-grid t
686 "Non-nil means, show a time grid in the agenda schedule.
687 A time grid is a set of lines for specific times (like every two hours between
688 8:00 and 20:00). The items scheduled for a day at specific times are
689 sorted in between these lines.
690 For details about when the grid will be shown, and what it will look like, see
691 the variable `org-agenda-time-grid'."
692 :group 'org-agenda
693 :type 'boolean)
695 (defcustom org-agenda-time-grid
696 '((daily today require-timed)
697 "----------------"
698 (800 1000 1200 1400 1600 1800 2000))
700 "The settings for time grid for agenda display.
701 This is a list of three items. The first item is again a list. It contains
702 symbols specifying conditions when the grid should be displayed:
704 daily if the agenda shows a single day
705 weekly if the agenda shows an entire week
706 today show grid on current date, independent of daily/weekly display
707 require-timed show grid only if at least on item has a time specification
709 The second item is a string which will be places behing the grid time.
711 The third item is a list of integers, indicating the times that should have
712 a grid line."
713 :group 'org-agenda
714 :type
715 '(list
716 (set :greedy t :tag "Grid Display Options"
717 (const :tag "Show grid in single day agenda display" daily)
718 (const :tag "Show grid in weekly agenda display" weekly)
719 (const :tag "Always show grid for today" today)
720 (const :tag "Show grid only if any timed entries are present"
721 require-timed)
722 (const :tag "Skip grid times already present in an entry"
723 remove-match))
724 (string :tag "Grid String")
725 (repeat :tag "Grid Times" (integer :tag "Time"))))
727 (defcustom org-agenda-remove-times-when-in-prefix t
728 "Non-nil means, remove duplicate time specifications in agenda items.
729 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
730 time-of-day specification in a headline or diary entry is extracted and
731 placed into the prefix. If this option is non-nil, the original specification
732 \(a timestamp or -range, or just a plain time(range) specification like
733 11:30-4pm) will be removed for agenda display. This makes the agenda less
734 cluttered.
735 The option can be t or nil. It may also be the symbol `beg', indicating
736 that the time should only be removed what it is located at the beginning of
737 the headline/diary entry."
738 :group 'org-agenda
739 :type '(choice
740 (const :tag "Always" t)
741 (const :tag "Never" nil)
742 (const :tag "When at beginning of entry" beg)))
744 (defcustom org-sort-agenda-notime-is-late t
745 "Non-nil means, items without time are considered late.
746 This is only relevant for sorting. When t, items which have no explicit
747 time like 15:30 will be considered as 24:01, i.e. later than any items which
748 do have a time. When nil, the default time is before 0:00. You can use this
749 option to decide if the schedule for today should come before or after timeless
750 agenda entries."
751 :group 'org-agenda
752 :type 'boolean)
754 (defcustom org-agenda-remove-tags-when-in-prefix nil
755 "Non-nil means, the tags from copy of headline in agenda.
756 When this is the symbol `prefix', only remove tags when
757 `org-agenda-prefix-format' contains a `%T' specifier."
758 :group 'org-agenda
759 :type '(choice
760 (const :tag "Always" t)
761 (const :tag "Never" nil)
762 (const :tag "When prefix format contains %T" prefix)))
764 (defgroup org-structure nil
765 "Options concerning structure editing in Org-mode."
766 :tag "Org Structure"
767 :group 'org)
769 (defcustom org-cycle-include-plain-lists nil
770 "Non-nil means, include plain lists into visibility cycling.
771 This means that during cycling, plain list items will *temporarily* be
772 interpreted as outline headlines with a level given by 1000+i where i is the
773 indentation of the bullet. In all other operations, plain list items are
774 not seen as headlines. For example, you cannot assign a TODO keyword to
775 such an item."
776 :group 'org-structure
777 :type 'boolean)
779 (defcustom org-cycle-emulate-tab t
780 "Where should `org-cycle' emulate TAB.
781 nil Never
782 white Only in completely white lines
783 t Everywhere except in headlines"
784 :group 'org-structure
785 :type '(choice (const :tag "Never" nil)
786 (const :tag "Only in completely white lines" white)
787 (const :tag "Everywhere except in headlines" t)
790 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
791 "Hook that is run after `org-cycle' has changed the buffer visibility.
792 The function(s) in this hook must accept a single argument which indicates
793 the new state that was set by the most recent `org-cycle' command. The
794 argument is a symbol. After a global state change, it can have the values
795 `overview', `content', or `all'. After a local state change, it can have
796 the values `folded', `children', or `subtree'."
797 :group 'org-structure
798 :type 'hook)
800 (defcustom org-highlight-sparse-tree-matches t
801 "Non-nil means, highlight all matches that define a sparse tree.
802 The highlights will automatically disappear the next time the buffer is
803 changed by an edit command."
804 :group 'org-structure
805 :type 'boolean)
807 (defcustom org-show-hierarchy-above t
808 "Non-nil means, show full hierarchy when showing a spot in the tree.
809 Turning this off makes sparse trees more compact, but also less clear."
810 :group 'org-structure
811 :type 'boolean)
813 (defcustom org-show-following-heading t
814 "Non-nil means, show heading following match in `org-occur'.
815 When doing an `org-occur' it is useful to show the headline which
816 follows the match, even if they do not match the regexp. This makes it
817 easier to edit directly inside the sparse tree. However, if you use
818 `org-occur' mainly as an overview, the following headlines are
819 unnecessary clutter."
820 :group 'org-structure
821 :type 'boolean)
823 (defcustom org-occur-hook '(org-first-headline-recenter)
824 "Hook that is run after `org-occur' has constructed a sparse tree.
825 This can be used to recenter the window to show as much of the structure
826 as possible."
827 :group 'org-structure
828 :type 'hook)
830 (defcustom org-odd-levels-only nil
831 "Non-nil means, skip even levels and only use odd levels for the outline.
832 This has the effect that two stars are being added/taken away in
833 promotion/demotion commands. It also influences how levels are
834 handled by the exporters.
835 Changing it requires restart of `font-lock-mode' to become effective
836 for fontification also in regions already fontified."
837 :group 'org-structure
838 :group 'org-font-lock
839 :type 'boolean)
841 (defcustom org-adapt-indentation t
842 "Non-nil means, adapt indentation when promoting and demoting.
843 When this is set and the *entire* text in an entry is indented, the
844 indentation is increased by one space in a demotion command, and
845 decreased by one in a promotion command. If any line in the entry
846 body starts at column 0, indentation is not changed at all."
847 :group 'org-structure
848 :type 'boolean)
850 (defcustom org-plain-list-ordered-item-terminator t
851 "The character that makes a line with leading number an ordered list item.
852 Valid values are ?. and ?\). To get both terminators, use t. While
853 ?. may look nicer, it creates the danger that a line with leading
854 number may be incorrectly interpreted as an item. ?\) therefore is
855 the safe choice."
856 :group 'org-structure
857 :type '(choice (const :tag "dot like in \"2.\"" ?.)
858 (const :tag "paren like in \"2)\"" ?\))
859 (const :tab "both" t)))
861 (defcustom org-auto-renumber-ordered-lists t
862 "Non-nil means, automatically renumber ordered plain lists.
863 Renumbering happens when the sequence have been changed with
864 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
865 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
866 :group 'org-structure
867 :type 'boolean)
869 (defcustom org-enable-fixed-width-editor t
870 "Non-nil means, lines starting with \":\" are treated as fixed-width.
871 This currently only means, they are never auto-wrapped.
872 When nil, such lines will be treated like ordinary lines.
873 See also the QUOTE keyword."
874 :group 'org-structure
875 :type 'boolean)
877 (defcustom org-archive-location "%s_archive::"
878 "The location where subtrees should be archived.
879 This string consists of two parts, separated by a double-colon.
881 The first part is a file name - when omitted, archiving happens in the same
882 file. %s will be replaced by the current file name (without directory part).
883 Archiving to a different file is useful to keep archived entries from
884 contributing to the Org-mode Agenda.
886 The part after the double colon is a headline. The archived entries will be
887 filed under that headline. When omitted, the subtrees are simply filed away
888 at the end of the file, as top-level entries.
890 Here are a few examples:
891 \"%s_archive::\"
892 If the current file is Projects.org, archive in file
893 Projects.org_archive, as top-level trees. This is the default.
895 \"::* Archived Tasks\"
896 Archive in the current file, under the top-level headline
897 \"* Archived Tasks\".
899 \"~/org/archive.org::\"
900 Archive in file ~/org/archive.org (absolute path), as top-level trees.
902 \"basement::** Finished Tasks\"
903 Archive in file ./basement (relative path), as level 3 trees
904 below the level 2 heading \"** Finished Tasks\".
906 You may set this option on a per-file basis by adding to the buffer a
907 line like
909 #+ARCHIVE: basement::** Finished Tasks"
910 :group 'org-structure
911 :type 'string)
913 (defcustom org-archive-mark-done t
914 "Non-nil means, mark archived entries as DONE."
915 :group 'org-structure
916 :type 'boolean)
918 (defcustom org-archive-stamp-time t
919 "Non-nil means, add a time stamp to archived entries.
920 The time stamp will be added directly after the TODO state keyword in the
921 first line, so it is probably best to use this in combinations with
922 `org-archive-mark-done'."
923 :group 'org-structure
924 :type 'boolean)
926 (defgroup org-tags nil
927 "Options concerning startup of Org-mode."
928 :tag "Org Tags"
929 :group 'org)
931 (defcustom org-tags-column 48
932 "The column to which tags should be indented in a headline.
933 If this number is positive, it specifies the column. If it is negative,
934 it means that the tags should be flushright to that column. For example,
935 -79 works well for a normal 80 character screen."
936 :group 'org-tags
937 :type 'integer)
939 (defcustom org-auto-align-tags t
940 "Non-nil means, realign tags after pro/demotion of TODO state change.
941 These operations change the length of a headline and therefore shift
942 the tags around. With this options turned on, after each such operation
943 the tags are again aligned to `org-tags-column'."
944 :group 'org-tags
945 :type 'boolean)
947 (defcustom org-use-tag-inheritance t
948 "Non-nil means, tags in levels apply also for sublevels.
949 When nil, only the tags directly given in a specific line apply there.
950 If you turn off this option, you very likely want to turn on the
951 companion option `org-tags-match-list-sublevels'."
952 :group 'org-tags
953 :type 'boolean)
955 (defcustom org-tags-match-list-sublevels nil
956 "Non-nil means list also sublevels of headlines matching tag search.
957 Because of tag inheritance (see variable `org-use-tag-inheritance'),
958 the sublevels of a headline matching a tag search often also match
959 the same search. Listing all of them can create very long lists.
960 Setting this variable to nil causes subtrees to be skipped.
961 This option is off by default, because inheritance in on. If you turn
962 inheritance off, you very likely want to turn this option on.
964 As a special case, if the tag search is restricted to TODO items, the
965 value of this variable is ignored and sublevels are always checked, to
966 make sure all corresponding TODO items find their way into the list."
967 :group 'org-tags
968 :type 'boolean)
970 (defvar org-tags-history nil
971 "History of minibuffer reads for tags.")
972 (defvar org-last-tags-completion-table nil
973 "The last used completion table for tags.")
975 (defgroup org-link nil
976 "Options concerning links in Org-mode."
977 :tag "Org Link"
978 :group 'org)
980 (defcustom org-tab-follows-link nil
981 "Non-nil means, on links TAB will follow the link.
982 Needs to be set before org.el is loaded."
983 :group 'org-link
984 :type 'boolean)
986 (defcustom org-return-follows-link nil
987 "Non-nil means, on links RET will follow the link.
988 Needs to be set before org.el is loaded."
989 :group 'org-link
990 :type 'boolean)
992 (defcustom org-mark-ring-length 4
993 "Number of different positions to be recorded in the ring
994 Changing this requires a restart of Emacs to work correctly."
995 :group 'org-link
996 :type 'interger)
998 (defcustom org-link-format "<%s>"
999 "Default format for linkes in the buffer.
1000 This is a format string for printf, %s will be replaced by the link text.
1001 If you want to make sure that your link is always properly terminated,
1002 include angle brackets into this format, like \"<%s>\". Some people also
1003 recommend an additional URL: prefix, so the format would be \"<URL:%s>\"."
1004 :group 'org-link
1005 :type '(choice
1006 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
1007 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
1008 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
1009 (string :tag "Other" :value "<%s>")))
1011 (defcustom org-allow-space-in-links t
1012 "Non-nil means, file names in links may contain space characters.
1013 When nil, it becomes possible to put several links into a line.
1014 Note that in tables, a link never extends accross fields, so in a table
1015 it is always possible to put several links into a line.
1016 Changing this variable requires a restart of Emacs of become effective."
1017 :group 'org-link
1018 :type 'boolean)
1020 (defcustom org-radio-targets t
1021 "Non-nil means activate text matching a link target.
1022 Radio targets are strings in triple angular brackets, like <<<My Target>>>.
1023 When this option is set, any occurrence of \"my target\" in normal text
1024 becomes a link."
1025 :group 'org-link
1026 :type 'boolean)
1028 (defcustom org-activate-camels nil
1029 "Non-nil means, treat words in CamelCase as in-file links.
1030 Changing this requires restart of Emacs to become effective."
1031 :group 'org-link
1032 :type 'boolean)
1034 (defcustom org-context-in-file-links t
1035 "Non-nil means, file links from `org-store-link' contain context.
1036 A search string will be added to the file name with :: as separator and
1037 used to find the context when the link is activated by the command
1038 `org-open-at-point'.
1039 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1040 negates this setting for the duration of the command."
1041 :group 'org-link
1042 :type 'boolean)
1044 (defcustom org-file-link-context-use-camel-case nil
1045 "Non-nil means, use CamelCase to store a search context in a file link.
1046 When nil, the search string simply consists of the words of the string."
1047 :group 'org-link
1048 :type 'boolean)
1050 (defcustom org-keep-stored-link-after-insertion nil
1051 "Non-nil means, keep link in list for entire session.
1053 The command `org-store-link' adds a link pointing to the current
1054 location to an internal list. These links accumulate during a session.
1055 The command `org-insert-link' can be used to insert links into any
1056 Org-mode file (offering completion for all stored links). When this
1057 option is nil, every link which has been inserted once using \\[org-insert-link]
1058 will be removed from the list, to make completing the unused links
1059 more efficient."
1060 :group 'org-link
1061 :type 'boolean)
1063 (defcustom org-link-frame-setup
1064 '((vm . vm-visit-folder-other-frame)
1065 (gnus . gnus-other-frame)
1066 (file . find-file-other-window))
1067 "Setup the frame configuration for following links.
1068 When following a link with Emacs, it may often be useful to display
1069 this link in another window or frame. This variable can be used to
1070 set this up for the different types of links.
1071 For VM, use any of
1072 `vm-visit-folder'
1073 `vm-visit-folder-other-frame'
1074 For Gnus, use any of
1075 `gnus'
1076 `gnus-other-frame'
1077 For FILE, use any of
1078 `find-file'
1079 `find-file-other-window'
1080 `find-file-other-frame'
1081 For the calendar, use the variable `calendar-setup'.
1082 For BBDB, it is currently only possible to display the matches in
1083 another window."
1084 :group 'org-link
1085 :type '(list
1086 (cons (const vm)
1087 (choice
1088 (const vm-visit-folder)
1089 (const vm-visit-folder-other-window)
1090 (const vm-visit-folder-other-frame)))
1091 (cons (const gnus)
1092 (choice
1093 (const gnus)
1094 (const gnus-other-frame)))
1095 (cons (const file)
1096 (choice
1097 (const find-file)
1098 (const find-file-other-window)
1099 (const find-file-other-frame)))))
1101 (defcustom org-usenet-links-prefer-google nil
1102 "Non-nil means, `org-store-link' will create web links to Google groups.
1103 When nil, Gnus will be used for such links.
1104 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1105 negates this setting for the duration of the command."
1106 :group 'org-link
1107 :type 'boolean)
1109 (defcustom org-open-non-existing-files nil
1110 "Non-nil means, `org-open-file' will open non-existing file.
1111 When nil, an error will be generated."
1112 :group 'org-link
1113 :type 'boolean)
1115 (defcustom org-confirm-shell-links t
1116 "Non-nil means, ask for confirmation before executing shell links.
1117 The default is true, to keep new users from shooting into their own foot."
1118 :group 'org-link
1119 :type 'boolean)
1121 (defconst org-file-apps-defaults-gnu
1122 '((t . mailcap))
1123 "Default file applications on a UNIX or GNU/Linux system.
1124 See `org-file-apps'.")
1126 (defconst org-file-apps-defaults-macosx
1127 '((t . "open %s")
1128 ("ps" . "gv %s")
1129 ("ps.gz" . "gv %s")
1130 ("eps" . "gv %s")
1131 ("eps.gz" . "gv %s")
1132 ("dvi" . "xdvi %s")
1133 ("fig" . "xfig %s"))
1134 "Default file applications on a MacOS X system.
1135 The system \"open\" is known as a default, but we use X11 applications
1136 for some files for which the OS does not have a good default.
1137 See `org-file-apps'.")
1139 (defconst org-file-apps-defaults-windowsnt
1140 '((t . (w32-shell-execute "open" file)))
1141 "Default file applications on a Windows NT system.
1142 The system \"open\" is used for most files.
1143 See `org-file-apps'.")
1145 (defcustom org-file-apps
1147 ("txt" . emacs)
1148 ("tex" . emacs)
1149 ("ltx" . emacs)
1150 ("org" . emacs)
1151 ("el" . emacs)
1153 "External applications for opening `file:path' items in a document.
1154 Org-mode uses system defaults for different file types, but
1155 you can use this variable to set the application for a given file
1156 extension. The entries in this list are cons cells with a file extension
1157 and the corresponding command. Possible values for the command are:
1158 `emacs' The file will be visited by the current Emacs process.
1159 `default' Use the default application for this file type.
1160 string A command to be executed by a shell; %s will be replaced
1161 by the path to the file.
1162 sexp A Lisp form which will be evaluated. The file path will
1163 be available in the Lisp variable `file'.
1164 For more examples, see the system specific constants
1165 `org-file-apps-defaults-macosx'
1166 `org-file-apps-defaults-windowsnt'
1167 `org-file-apps-defaults-gnu'."
1168 :group 'org-link
1169 :type '(repeat
1170 (cons (choice :value ""
1171 (string :tag "Extension")
1172 (const :tag "Default for unrecognized files" t)
1173 (const :tag "Links to a directory" directory))
1174 (choice :value ""
1175 (const :tag "Visit with Emacs" emacs)
1176 (const :tag "Use system default" default)
1177 (string :tag "Command")
1178 (sexp :tag "Lisp form")))))
1180 (defcustom org-mhe-search-all-folders nil
1181 "Non-nil means, that the search for the mh-message will be extended to
1182 all folders if the message cannot be found in the folder given in the link.
1183 Searching all folders is very effective with one of the search engines
1184 supported by MH-E, but will be slow with pick."
1185 :group 'org-link
1186 :type 'boolean)
1188 (defgroup org-remember nil
1189 "Options concerning interaction with remember.el."
1190 :tag "Org Remember"
1191 :group 'org)
1193 (defcustom org-directory "~/org"
1194 "Directory with org files.
1195 This directory will be used as default to prompt for org files.
1196 Used by the hooks for remember.el."
1197 :group 'org-remember
1198 :type 'directory)
1200 (defcustom org-default-notes-file "~/.notes"
1201 "Default target for storing notes.
1202 Used by the hooks for remember.el. This can be a string, or nil to mean
1203 the value of `remember-data-file'."
1204 :group 'org-remember
1205 :type '(choice
1206 (const :tag "Default from remember-data-file" nil)
1207 file))
1209 (defcustom org-remember-templates nil
1210 "Templates for the creation of remember buffers.
1211 When nil, just let remember make the buffer.
1212 When not nil, this is a list of 3-element lists. In each entry, the first
1213 element is a character, a unique key to select this template.
1214 The second element is the template. The third element is optional and can
1215 specify a destination file for remember items created with this template.
1216 The default file is given by `org-default-notes-file'.
1218 The template specifies the structure of the remember buffer. It should have
1219 a first line starting with a star, to act as the org-mode headline.
1220 Furthermore, the following %-escapes will be replaced with content:
1221 %t time stamp, date only
1222 %T time stamp with date and time
1223 %u inactive time stamp, date only
1224 %U inactive time stamp with date and time
1225 %n user name
1226 %a annotation, normally the link created with org-store-link
1227 %i initial content, the region when remember is called with C-u.
1228 If %i is indented, the entire inserted text will be indented as well.
1229 %? This will be removed, and the cursor placed at this position."
1230 :group 'org-remember
1231 :type '(repeat :tag "enabled"
1232 (list :value (?a "\n" nil)
1233 (character :tag "Selection Key")
1234 (string :tag "Template")
1235 (file :tag "Destination file (optional)"))))
1237 (defcustom org-reverse-note-order nil
1238 "Non-nil means, store new notes at the beginning of a file or entry.
1239 When nil, new notes will be filed to the end of a file or entry."
1240 :group 'org-remember
1241 :type '(choice
1242 (const :tag "Reverse always" t)
1243 (const :tag "Reverse never" nil)
1244 (repeat :tag "By file name regexp"
1245 (cons regexp boolean))))
1247 (defgroup org-table nil
1248 "Options concerning tables in Org-mode."
1249 :tag "Org Table"
1250 :group 'org)
1252 (defcustom org-enable-table-editor 'optimized
1253 "Non-nil means, lines starting with \"|\" are handled by the table editor.
1254 When nil, such lines will be treated like ordinary lines.
1256 When equal to the symbol `optimized', the table editor will be optimized to
1257 do the following:
1258 - Use automatic overwrite mode in front of whitespace in table fields.
1259 This make the structure of the table stay in tact as long as the edited
1260 field does not exceed the column width.
1261 - Minimize the number of realigns. Normally, the table is aligned each time
1262 TAB or RET are pressed to move to another field. With optimization this
1263 happens only if changes to a field might have changed the column width.
1264 Optimization requires replacing the functions `self-insert-command',
1265 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1266 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1267 very good at guessing when a re-align will be necessary, but you can always
1268 force one with \\[org-ctrl-c-ctrl-c].
1270 If you would like to use the optimized version in Org-mode, but the
1271 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1273 This variable can be used to turn on and off the table editor during a session,
1274 but in order to toggle optimization, a restart is required.
1276 See also the variable `org-table-auto-blank-field'."
1277 :group 'org-table
1278 :type '(choice
1279 (const :tag "off" nil)
1280 (const :tag "on" t)
1281 (const :tag "on, optimized" optimized)))
1283 ;; FIXME: We could have a third option which makes it jump only over the first
1284 ;; hline in a table.
1285 (defcustom org-table-tab-jumps-over-hlines t
1286 "Non-nil means, tab in the last column of a table with jump over a hline.
1287 If a horizontal separator line is following the current line,
1288 `org-table-next-field' can either create a new row before that line, or jump
1289 over the line. When this option is nil, a new line will be created before
1290 this line."
1291 :group 'org-table
1292 :type 'boolean)
1294 (defcustom org-table-auto-blank-field t
1295 "Non-nil means, automatically blank table field when starting to type into it.
1296 This only happens when typing immediately after a field motion
1297 command (TAB, S-TAB or RET).
1298 Only relevant when `org-enable-table-editor' is equal to `optimized'."
1299 :group 'org-table
1300 :type 'boolean)
1302 (defcustom org-table-default-size "5x2"
1303 "The default size for newly created tables, Columns x Rows."
1304 :group 'org-table
1305 :type 'string)
1307 (defcustom org-table-automatic-realign t
1308 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
1309 When nil, aligning is only done with \\[org-table-align], or after column
1310 removal/insertion."
1311 :group 'org-table
1312 :type 'boolean)
1314 (defcustom org-table-spaces-around-separators '(1 . 1)
1315 "The number of spaces to be placed before and after separators."
1316 :group 'org-table
1317 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1319 (defcustom org-table-spaces-around-invisible-separators '(1 . 2)
1320 "The number of spaces to be placed before and after separators.
1321 This option applies when the column separators have been made invisible."
1322 :group 'org-table
1323 :type '(cons (number :tag "Before \"|\"") (number :tag " After \"|\"")))
1325 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
1326 "Regular expression for recognizing numbers in table columns.
1327 If a table column contains mostly numbers, it will be aligned to the
1328 right. If not, it will be aligned to the left.
1330 The default value of this option is a regular expression which allows
1331 anything which looks remotely like a number as used in scientific
1332 context. For example, all of the following will be considered a
1333 number:
1334 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
1336 Other options offered by the customize interface are more restrictive."
1337 :group 'org-table
1338 :type '(choice
1339 (const :tag "Positive Integers"
1340 "^[0-9]+$")
1341 (const :tag "Integers"
1342 "^[-+]?[0-9]+$")
1343 (const :tag "Floating Point Numbers"
1344 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
1345 (const :tag "Floating Point Number or Integer"
1346 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
1347 (const :tag "Exponential, Floating point, Integer"
1348 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
1349 (const :tag "Very General Number-Like"
1350 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
1351 (string :tag "Regexp:")))
1353 (defcustom org-table-number-fraction 0.5
1354 "Fraction of numbers in a column required to make the column align right.
1355 In a column all non-white fields are considered. If at least this
1356 fraction of fields is matched by `org-table-number-fraction',
1357 alignment to the right border applies."
1358 :group 'org-table
1359 :type 'number)
1361 (defcustom org-export-highlight-first-table-line t
1362 "Non-nil means, highlight the first table line.
1363 In HTML export, this means use <th> instead of <td>.
1364 In tables created with table.el, this applies to the first table line.
1365 In Org-mode tables, all lines before the first horizontal separator
1366 line will be formatted with <th> tags."
1367 :group 'org-table
1368 :type 'boolean)
1370 (defcustom org-table-tab-recognizes-table.el t
1371 "Non-nil means, TAB will automatically notice a table.el table.
1372 When it sees such a table, it moves point into it and - if necessary -
1373 calls `table-recognize-table'."
1374 :group 'org-table
1375 :type 'boolean)
1377 (defgroup org-table-calculation nil
1378 "Options concerning tables in Org-mode."
1379 :tag "Org Table Calculation"
1380 :group 'org)
1382 (defcustom org-table-copy-increment t
1383 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
1384 :group 'org-table-calculation
1385 :type 'boolean)
1387 (defcustom org-calc-default-modes
1388 '(calc-internal-prec 12
1389 calc-float-format (float 5)
1390 calc-angle-mode deg
1391 calc-prefer-frac nil
1392 calc-symbolic-mode nil
1393 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
1394 calc-display-working-message t
1396 "List with Calc mode settings for use in calc-eval for table formulas.
1397 The list must contain alternating symbols (Calc modes variables and values).
1398 Don't remove any of the default settings, just change the values. Org-mode
1399 relies on the variables to be present in the list."
1400 :group 'org-table-calculation
1401 :type 'plist)
1403 (defcustom org-table-formula-evaluate-inline t
1404 "Non-nil means, TAB and RET evaluate a formula in current table field.
1405 If the current field starts with an equal sign, it is assumed to be a formula
1406 which should be evaluated as described in the manual and in the documentation
1407 string of the command `org-table-eval-formula'. This feature requires the
1408 Emacs calc package.
1409 When this variable is nil, formula calculation is only available through
1410 the command \\[org-table-eval-formula]."
1411 :group 'org-table-calculation
1412 :type 'boolean)
1415 (defcustom org-table-formula-use-constants t
1416 "Non-nil means, interpret constants in formulas in tables.
1417 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
1418 by the value given in `org-table-formula-constants', or by a value obtained
1419 from the `constants.el' package."
1420 :group 'org-table-calculation
1421 :type 'boolean)
1423 (defcustom org-table-formula-constants nil
1424 "Alist with constant names and values, for use in table formulas.
1425 The car of each element is a name of a constant, without the `$' before it.
1426 The cdr is the value as a string. For example, if you'd like to use the
1427 speed of light in a formula, you would configure
1429 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
1431 and then use it in an equation like `$1*$c'."
1432 :group 'org-table-calculation
1433 :type '(repeat
1434 (cons (string :tag "name")
1435 (string :tag "value"))))
1437 (defcustom org-table-formula-numbers-only nil
1438 "Non-nil means, calculate only with numbers in table formulas.
1439 Then all input fields will be converted to a number, and the result
1440 must also be a number. When nil, calc's full potential is available
1441 in table calculations, including symbolics etc."
1442 :group 'org-table-calculation
1443 :type 'boolean)
1445 (defcustom org-table-allow-automatic-line-recalculation t
1446 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
1447 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
1448 :group 'org-table-calculation
1449 :type 'boolean)
1451 (defgroup org-export nil
1452 "Options for exporting org-listings."
1453 :tag "Org Export"
1454 :group 'org)
1456 (defcustom org-export-language-setup
1457 '(("en" "Author" "Date" "Table of Contents")
1458 ("da" "Ophavsmand" "Dato" "Indhold")
1459 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1460 ("es" "Autor" "Fecha" "\xccndice")
1461 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1462 ("it" "Autore" "Data" "Indice")
1463 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1464 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1465 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1466 "Terms used in export text, translated to different languages.
1467 Use the variable `org-export-default-language' to set the language,
1468 or use the +OPTION lines for a per-file setting."
1469 :group 'org-export
1470 :type '(repeat
1471 (list
1472 (string :tag "HTML language tag")
1473 (string :tag "Author")
1474 (string :tag "Date")
1475 (string :tag "Table of Contents"))))
1477 (defcustom org-export-default-language "en"
1478 "The default language of HTML export, as a string.
1479 This should have an association in `org-export-language-setup'."
1480 :group 'org-export
1481 :type 'string)
1483 (defcustom org-export-html-style
1484 "<style type=\"text/css\">
1485 html {
1486 font-family: Times, serif;
1487 font-size: 12pt;
1489 .title { text-align: center; }
1490 .todo, .deadline { color: red; }
1491 .done { color: green; }
1492 .target { background-color: lavender; }
1493 pre {
1494 border: 1pt solid #AEBDCC;
1495 background-color: #F3F5F7;
1496 padding: 5pt;
1497 font-family: courier, monospace;
1499 table { border-collapse: collapse; }
1500 td, th {
1501 vertical-align: top;
1502 border: 1pt solid #ADB9CC;
1504 </style>"
1505 "The default style specification for exported HTML files.
1506 Since there are different ways of setting style information, this variable
1507 needs to contain the full HTML structure to provide a style, including the
1508 surrounding HTML tags. The style specifications should include definitions
1509 for new classes todo, done, title, and deadline. For example, legal values
1510 would be:
1512 <style type=\"text/css\">
1513 p { font-weight: normal; color: gray; }
1514 h1 { color: black; }
1515 .title { text-align: center; }
1516 .todo, .deadline { color: red; }
1517 .done { color: green; }
1518 </style>
1520 or, if you want to keep the style in a file,
1522 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1524 As the value of this option simply gets inserted into the HTML <head> header,
1525 you can \"misuse\" it to add arbitrary text to the header."
1526 :group 'org-export
1527 :type 'string)
1529 (defcustom org-export-headline-levels 3
1530 "The last level which is still exported as a headline.
1531 Inferior levels will produce itemize lists when exported.
1532 Note that a numeric prefix argument to an exporter function overrides
1533 this setting.
1535 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1536 :group 'org-export
1537 :type 'number)
1539 (defcustom org-export-with-section-numbers t
1540 "Non-nil means, add section numbers to headlines when exporting.
1542 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1543 :group 'org-export
1544 :type 'boolean)
1546 (defcustom org-export-with-toc t
1547 "Non-nil means, create a table of contents in exported files.
1548 The TOC contains headlines with levels up to`org-export-headline-levels'.
1550 Headlines which contain any TODO items will be marked with \"(*)\" in
1551 ASCII export, and with red color in HTML output.
1553 In HTML output, the TOC will be clickable.
1555 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1556 :group 'org-export
1557 :type 'boolean)
1559 (defcustom org-export-plain-list-max-depth 20
1560 "Maximum depth of hand-formatted lists in HTML export.
1562 Org-mode parses hand-formatted enumeration and bullet lists and
1563 transforms them to HTML open export. Different indentation of the
1564 bullet or number indicates different list nesting levels. To avoid
1565 confusion, only a single level is allowed by default. When this is
1566 larger than 1, deeper indentation leads to deeper list nesting. For
1567 example, the default value of 3 allows the following list to be
1568 formatted correctly in HTML:
1570 * Fruit
1571 - Apple
1572 - Banana
1573 1. from Africa
1574 2. from South America
1575 - Pineapple
1576 * Bread
1577 * Dairy products"
1578 :group 'org-export
1579 :type 'integer)
1581 (defcustom org-export-preserve-breaks nil
1582 "Non-nil means, preserve all line breaks when exporting.
1583 Normally, in HTML output paragraphs will be reformatted. In ASCII
1584 export, line breaks will always be preserved, regardless of this variable.
1586 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1587 :group 'org-export
1588 :type 'boolean)
1590 (defcustom org-export-html-inline-images t
1591 "Non-nil means, inline images into exported HTML pages.
1592 The link will still be to the original location of the image file.
1593 So if you are moving the page, lets say to your public HTML site,
1594 you will have to move the image and maybe change the link."
1595 :group 'org-export
1596 :type 'boolean)
1598 (defcustom org-export-html-expand t
1599 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1600 When nil, these tags will be exported as plain text and therefore
1601 not be interpreted by a browser.
1603 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1604 :group 'org-export
1605 :type 'boolean)
1607 (defcustom org-export-with-fixed-width t
1608 "Non-nil means, lines starting with \":\" will be in fixed width font.
1609 This can be used to have pre-formatted text, fragments of code etc. For
1610 example:
1611 : ;; Some Lisp examples
1612 : (while (defc cnt)
1613 : (ding))
1614 will be looking just like this in also HTML. In ASCII export, this option
1615 has no effect.
1617 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1618 :group 'org-export
1619 :type 'boolean)
1621 (defcustom org-export-with-tables t
1622 "If non-nil, lines starting with \"|\" define a table.
1623 For example:
1625 | Name | Address | Birthday |
1626 |-------------+----------+-----------|
1627 | Arthur Dent | England | 29.2.2100 |
1629 In ASCII export, this option has no effect.
1631 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1632 :group 'org-export
1633 :type 'boolean)
1635 (defcustom org-export-table-remove-special-lines t
1636 "Remove special lines and marking characters in calculating tables.
1637 This removes the special marking character column from tables that are set
1638 up for spreadsheet calculations. It also removes the entire lines
1639 marked with `!', `_', or `^'. The lines with `$' are kept, because
1640 the values of constants may be useful to have."
1641 :group 'org-export
1642 :type 'boolean)
1644 (defcustom org-export-prefer-native-exporter-for-tables nil
1645 "Non-nil means, always export tables created with table.el natively.
1646 Natively means, use the HTML code generator in table.el.
1647 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1648 the table does not use row- or column-spanning). This has the
1649 advantage, that the automatic HTML conversions for math symbols and
1650 sub/superscripts can be applied. Org-mode's HTML generator is also
1651 much faster."
1652 :group 'org-export
1653 :type 'boolean)
1655 (defcustom org-export-html-table-tag
1656 "<table border=1 cellspacing=0 cellpadding=6>"
1657 "The HTML tag used to start a table.
1658 This must be a <table> tag, but you may change the options like
1659 borders and spacing."
1660 :group 'org-export
1661 :type 'string)
1663 (defcustom org-export-with-emphasize t
1664 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1665 If the export target supports emphasizing text, the word will be
1666 typeset in bold, italic, or underlined, respectively. Works only for
1667 single words, but you can say: I *really* *mean* *this*.
1668 In ASCII export, this option has no effect.
1670 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1671 :group 'org-export
1672 :type 'boolean)
1674 (defcustom org-match-sexp-depth 3
1675 "Number of stacked braces for sub/superscript matching.
1676 This has to be set before loading org.el to be effective."
1677 :group 'org-export
1678 :type 'integer)
1680 ;; FIXME: Should () parens be removed as well in sub/superscripts?
1681 (defcustom org-export-with-sub-superscripts t
1682 "Non-nil means, interpret \"_\" and \"^\" for export.
1683 When this option is turned on, you can use TeX-like syntax for sub- and
1684 superscripts. Several characters after \"_\" or \"^\" will be
1685 considered as a single item - so grouping with {} is normally not
1686 needed. For example, the following things will be parsed as single
1687 sub- or superscripts.
1689 10^24 or 10^tau several digits will be considered 1 item.
1690 10^-12 or 10^-tau a leading sign with digits or a word
1691 x^2-y^3 will be read as x^2 - y^3, because items are
1692 terminated by almost any nonword/nondigit char.
1693 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1695 Still, ambiguity is possible - so when in doubt use {} to enclose the
1696 sub/superscript.
1697 In ASCII export, this option has no effect.
1699 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1700 :group 'org-export
1701 :type 'boolean)
1703 (defcustom org-export-with-TeX-macros t
1704 "Non-nil means, interpret simple TeX-like macros when exporting.
1705 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1706 No only real TeX macros will work here, but the standard HTML entities
1707 for math can be used as macro names as well. For a list of supported
1708 names in HTML export, see the constant `org-html-entities'.
1709 In ASCII export, this option has no effect.
1711 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1712 :group 'org-export
1713 :type 'boolean)
1715 (defcustom org-export-html-with-timestamp nil
1716 "If non-nil, write `org-export-html-html-helper-timestamp'
1717 into the exported HTML text. Otherwise, the buffer will just be saved
1718 to a file."
1719 :group 'org-export
1720 :type 'boolean)
1722 (defcustom org-export-html-html-helper-timestamp
1723 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1724 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1725 :group 'org-export
1726 :type 'string)
1728 (defcustom org-export-ascii-show-new-buffer t
1729 "Non-nil means, popup buffer containing the exported ASCII text.
1730 Otherwise the buffer will just be saved to a file and stay hidden."
1731 :group 'org-export
1732 :type 'boolean)
1734 (defcustom org-export-html-show-new-buffer nil
1735 "Non-nil means, popup buffer containing the exported html text.
1736 Otherwise, the buffer will just be saved to a file and stay hidden."
1737 :group 'org-export
1738 :type 'boolean)
1740 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1741 "The file name for the iCalendar file covering all agenda files.
1742 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1743 :group 'org-export
1744 :type 'file)
1746 (defcustom org-icalendar-include-todo nil
1747 "Non-nil means, export to iCalendar files should also cover TODO items."
1748 :group 'org-export
1749 :type 'boolean)
1751 (defcustom org-icalendar-combined-name "OrgMode"
1752 "Calendar name for the combined iCalendar representing all agenda files."
1753 :group 'org-export
1754 :type 'string)
1756 (defgroup org-font-lock nil
1757 "Faces and settings for highlighting in Org-mode."
1758 :tag "Org Font Lock"
1759 :group 'org)
1761 (defcustom org-level-color-stars-only nil
1762 "Non-nil means fontify only the stars in each headline.
1763 When nil, the entire headline is fontified.
1764 Changing it requires restart of `font-lock-mode' to become effective
1765 also in regions already fontified."
1766 :group 'org-font-lock
1767 :type 'boolean)
1769 (defcustom org-hide-leading-stars nil
1770 "Non-nil means, hide the first N-1 stars in a headline.
1771 This works by using the face `org-hide' for these stars. This
1772 face is white for a light background, and black for a dark
1773 background. You may have to customize the face `org-hide' to
1774 make this work.
1775 Changing it requires restart of `font-lock-mode' to become effective
1776 also in regions already fontified."
1777 :group 'org-font-lock
1778 :type 'boolean)
1780 (defcustom org-fontify-done-headline nil
1781 "Non-nil means, change the face of a headline if it is marked DONE.
1782 Normally, only the TODO/DONE keyword indicates the state of a headline.
1783 When this is non-nil, the headline after the keyword is set to the
1784 `org-headline-done' as an additional indication."
1785 :group 'org-font-lock
1786 :type 'boolean)
1788 (defcustom org-fontify-emphasized-text t
1789 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
1790 Changing this variable requires a restart of Emacs to take effect."
1791 :group 'org-font-lock
1792 :type 'boolean)
1794 (defface org-hide
1796 (((type tty) (class color)) (:foreground "white"))
1797 (((class color) (background light)) (:foreground "white"))
1798 (((class color) (background dark)) (:foreground "black"))
1799 ; (((class color) (backgro6und light)) (:foreground "grey90"))
1800 ; (((class color) (background dark)) (:foreground "grey10"))
1801 (t (:inverse-video nil)))
1802 "Face used for level 1 headlines."
1803 :group 'org-font-lock)
1805 (defface org-level-1 ;; font-lock-function-name-face
1806 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1807 (((class color) (background light)) (:foreground "Blue"))
1808 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1809 (t (:inverse-video t :bold t)))
1810 "Face used for level 1 headlines."
1811 :group 'org-font-lock)
1813 (defface org-level-2 ;; font-lock-variable-name-face
1814 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1815 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1816 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1817 (t (:bold t :italic t)))
1818 "Face used for level 2 headlines."
1819 :group 'org-font-lock)
1821 (defface org-level-3 ;; font-lock-keyword-face
1822 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1823 (((class color) (background light)) (:foreground "Purple"))
1824 (((class color) (background dark)) (:foreground "Cyan"))
1825 (t (:bold t)))
1826 "Face used for level 3 headlines."
1827 :group 'org-font-lock)
1829 (defface org-level-4 ;; font-lock-comment-face
1830 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1831 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1832 (((class color) (background light)) (:foreground "Firebrick"))
1833 (((class color) (background dark)) (:foreground "chocolate1"))
1834 (t (:bold t :italic t)))
1835 "Face used for level 4 headlines."
1836 :group 'org-font-lock)
1838 (defface org-level-5 ;; font-lock-type-face
1839 '((((type tty) (class color)) (:foreground "green"))
1840 (((class color) (background light)) (:foreground "ForestGreen"))
1841 (((class color) (background dark)) (:foreground "PaleGreen"))
1842 (t (:bold t :underline t)))
1843 "Face used for level 5 headlines."
1844 :group 'org-font-lock)
1846 (defface org-level-6 ;; font-lock-constant-face
1847 '((((type tty) (class color)) (:foreground "magenta"))
1848 (((class color) (background light)) (:foreground "CadetBlue"))
1849 (((class color) (background dark)) (:foreground "Aquamarine"))
1850 (t (:bold t :underline t)))
1851 "Face used for level 6 headlines."
1852 :group 'org-font-lock)
1854 (defface org-level-7 ;; font-lock-builtin-face
1855 '((((type tty) (class color)) (:foreground "blue" :weight light))
1856 (((class color) (background light)) (:foreground "Orchid"))
1857 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1858 (t (:bold t)))
1859 "Face used for level 7 headlines."
1860 :group 'org-font-lock)
1862 (defface org-level-8 ;; font-lock-string-face
1863 '((((type tty) (class color)) (:foreground "green"))
1864 (((class color) (background light)) (:foreground "RosyBrown"))
1865 (((class color) (background dark)) (:foreground "LightSalmon"))
1866 (t (:italic t)))
1867 "Face used for level 8 headlines."
1868 :group 'org-font-lock)
1870 (defface org-special-keyword ;; font-lock-string-face
1871 '((((type tty) (class color)) (:foreground "green"))
1872 (((class color) (background light)) (:foreground "RosyBrown"))
1873 (((class color) (background dark)) (:foreground "LightSalmon"))
1874 (t (:italic t)))
1875 "Face used for special keywords."
1876 :group 'org-font-lock)
1878 (defface org-warning ;; font-lock-warning-face
1879 '((((type tty) (class color)) (:foreground "red"))
1880 (((class color) (background light)) (:foreground "Red" :bold t))
1881 (((class color) (background dark)) (:foreground "Red1" :bold t))
1882 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1883 (t (:inverse-video t :bold t)))
1884 "Face for deadlines and TODO keywords."
1885 :group 'org-font-lock)
1887 (defface org-headline-done ;; font-lock-string-face
1888 '((((type tty) (class color)) (:foreground "green"))
1889 (((class color) (background light)) (:foreground "RosyBrown"))
1890 (((class color) (background dark)) (:foreground "LightSalmon"))
1891 (t (:italic t)))
1892 "Face used to indicate that a headline is DONE. See also the variable
1893 `org-fontify-done-headline'."
1894 :group 'org-font-lock)
1896 ;; Inheritance does not yet work for xemacs. So we just copy...
1898 (defface org-deadline-announce
1899 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1900 (((class color) (background light)) (:foreground "Blue"))
1901 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1902 (t (:inverse-video t :bold t)))
1903 "Face for upcoming deadlines."
1904 :group 'org-font-lock)
1906 (defface org-scheduled-today
1907 '((((type tty) (class color)) (:foreground "green"))
1908 (((class color) (background light)) (:foreground "DarkGreen"))
1909 (((class color) (background dark)) (:foreground "PaleGreen"))
1910 (t (:bold t :underline t)))
1911 "Face for items scheduled for a certain day."
1912 :group 'org-font-lock)
1914 (defface org-scheduled-previously
1915 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1916 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1917 (((class color) (background light)) (:foreground "Firebrick"))
1918 (((class color) (background dark)) (:foreground "chocolate1"))
1919 (t (:bold t :italic t)))
1920 "Face for items scheduled previously, and not yet done."
1921 :group 'org-font-lock)
1923 (defface org-formula
1924 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1925 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1926 (((class color) (background light)) (:foreground "Firebrick"))
1927 (((class color) (background dark)) (:foreground "chocolate1"))
1928 (t (:bold t :italic t)))
1929 "Face for formulas."
1930 :group 'org-font-lock)
1932 (defface org-link
1933 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1934 (((class color) (background light)) (:foreground "Purple"))
1935 (((class color) (background dark)) (:foreground "Cyan"))
1936 (t (:bold t)))
1937 "Face for links."
1938 :group 'org-font-lock)
1940 (defface org-tag
1941 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1942 (((class color) (background light)) (:foreground "Purple" :weight bold))
1943 (((class color) (background dark)) (:foreground "Cyan" :weight bold))
1944 (t (:bold t)))
1945 "Face for tags."
1946 :group 'org-font-lock)
1948 (defface org-done ;; font-lock-type-face
1949 '((((type tty) (class color)) (:foreground "green"))
1950 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
1951 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
1952 (t (:bold t :underline t)))
1953 "Face used for DONE."
1954 :group 'org-font-lock)
1956 (defface org-table ;; font-lock-function-name-face
1957 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1958 (((class color) (background light)) (:foreground "Blue"))
1959 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1960 (t (:inverse-video t :bold t)))
1961 "Face used for tables."
1962 :group 'org-font-lock)
1964 (defface org-time-grid ;; font-lock-variable-name-face
1965 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1966 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1967 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1968 (t (:bold t :italic t)))
1969 "Face used for time grids."
1970 :group 'org-font-lock)
1972 (defvar org-level-faces
1973 '(org-level-1 org-level-2 org-level-3 org-level-4
1974 org-level-5 org-level-6 org-level-7 org-level-8
1976 (defvar org-n-levels (length org-level-faces))
1978 (defun org-set-regexps-and-options ()
1979 "Precompute regular expressions for current buffer."
1980 (when (eq major-mode 'org-mode)
1981 (let ((re (org-make-options-regexp
1982 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
1983 "STARTUP" "ARCHIVE")))
1984 (splitre "[ \t]+")
1985 kwds int key value cat arch)
1986 (save-excursion
1987 (save-restriction
1988 (widen)
1989 (goto-char (point-min))
1990 (while (re-search-forward re nil t)
1991 (setq key (match-string 1) value (match-string 2))
1992 (cond
1993 ((equal key "CATEGORY")
1994 (if (string-match "[ \t]+$" value)
1995 (setq value (replace-match "" t t value)))
1996 (setq cat (intern value)))
1997 ((equal key "SEQ_TODO")
1998 (setq int 'sequence
1999 kwds (append kwds (org-split-string value splitre))))
2000 ((equal key "PRI_TODO")
2001 (setq int 'priority
2002 kwds (append kwds (org-split-string value splitre))))
2003 ((equal key "TYP_TODO")
2004 (setq int 'type
2005 kwds (append kwds (org-split-string value splitre))))
2006 ((equal key "STARTUP")
2007 (let ((opts (org-split-string value splitre))
2008 (set '(("fold" org-startup-folded t)
2009 ("nofold" org-startup-folded nil)
2010 ("content" org-startup-folded content)
2011 ("hidestars" org-hide-leading-stars t)
2012 ("showstars" org-hide-leading-stars nil)
2013 ("odd" org-odd-levels-only t)
2014 ("oddeven" org-odd-levels-only nil)
2015 ("dlcheck" org-startup-with-deadline-check t)
2016 ("nodlcheck" org-startup-with-deadline-check nil)))
2017 l var val)
2018 (while (setq l (assoc (pop opts) set))
2019 (setq var (nth 1 l) val (nth 2 l))
2020 (set (make-local-variable var) val))))
2021 ((equal key "ARCHIVE")
2022 (string-match " *$" value)
2023 (setq arch (replace-match "" t t value))
2024 (remove-text-properties 0 (length arch)
2025 '(face t fontified t) arch)))
2027 (and cat (set (make-local-variable 'org-category) cat))
2028 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2029 (and arch (set (make-local-variable 'org-archive-location) arch))
2030 (and int (set (make-local-variable 'org-todo-interpretation) int)))
2031 ;; Compute the regular expressions and other local variables
2032 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2033 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2034 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2035 (length org-scheduled-string)))
2036 org-done-string
2037 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2038 org-todo-regexp
2039 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2040 "\\|") "\\)\\>")
2041 org-not-done-regexp
2042 (concat "\\<\\("
2043 (mapconcat 'regexp-quote
2044 (nreverse (cdr (reverse org-todo-keywords)))
2045 "\\|")
2046 "\\)\\>")
2047 org-todo-line-regexp
2048 (concat "^\\(\\*+\\)[ \t]*\\("
2049 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2050 "\\)? *\\(.*\\)")
2051 org-nl-done-regexp
2052 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2053 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2054 org-deadline-regexp (concat "\\<" org-deadline-string)
2055 org-deadline-time-regexp
2056 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2057 org-deadline-line-regexp
2058 (concat "\\<\\(" org-deadline-string "\\).*")
2059 org-scheduled-regexp
2060 (concat "\\<" org-scheduled-string)
2061 org-scheduled-time-regexp
2062 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
2063 (org-set-font-lock-defaults)))
2065 ;; Tell the compiler about dynamically scoped variables,
2066 ;; and variables from other packages
2067 (defvar zmacs-regions) ; XEmacs regions
2068 (defvar original-date) ; dynamically scoped in calendar
2069 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2070 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2071 (defvar org-html-entities) ; defined later in this file
2072 (defvar org-goto-start-pos) ; dynamically scoped parameter
2073 (defvar org-time-was-given) ; dynamically scoped parameter
2074 (defvar org-ts-what) ; dynamically scoped parameter
2075 (defvar mark-active) ; Emacs only, not available in XEmacs.
2076 (defvar timecnt) ; dynamically scoped parameter
2077 (defvar levels-open) ; dynamically scoped parameter
2078 (defvar title) ; dynamically scoped parameter
2079 (defvar author) ; dynamically scoped parameter
2080 (defvar email) ; dynamically scoped parameter
2081 (defvar text) ; dynamically scoped parameter
2082 (defvar entry) ; dynamically scoped parameter
2083 (defvar date) ; dynamically scoped parameter
2084 (defvar language) ; dynamically scoped parameter
2085 (defvar options) ; dynamically scoped parameter
2086 (defvar ans1) ; dynamically scoped parameter
2087 (defvar ans2) ; dynamically scoped parameter
2088 (defvar starting-day) ; local variable
2089 (defvar include-all-loc) ; local variable
2090 (defvar vm-message-pointer) ; from vm
2091 (defvar vm-folder-directory) ; from vm
2092 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2093 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2094 (defvar gnus-group-name) ; from gnus
2095 (defvar gnus-article-current) ; from gnus
2096 (defvar w3m-current-url) ; from w3m
2097 (defvar mh-progs) ; from MH-E
2098 (defvar mh-current-folder) ; from MH-E
2099 (defvar mh-show-folder-buffer) ; from MH-E
2100 (defvar mh-index-folder) ; from MH-E
2101 (defvar mh-searcher) ; from MH-E
2102 (defvar org-selected-point) ; dynamically scoped parameter
2103 (defvar calendar-mode-map) ; from calendar.el
2104 (defvar last-arg) ; local variable
2105 (defvar remember-save-after-remembering) ; from remember.el
2106 (defvar remember-data-file) ; from remember.el
2107 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2108 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2110 ;;; Define the mode
2112 (defvar org-mode-map (copy-keymap outline-mode-map)
2113 "Keymap for Org-mode.")
2115 (defvar org-struct-menu) ; defined later in this file
2116 (defvar org-org-menu) ; defined later in this file
2117 (defvar org-tbl-menu) ; defined later in this file
2119 ;; We use a before-change function to check if a table might need
2120 ;; an update.
2121 (defvar org-table-may-need-update t
2122 "Indicates that a table might need an update.
2123 This variable is set by `org-before-change-function'.
2124 `org-table-align' sets it back to nil.")
2125 (defvar org-mode-hook nil)
2126 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2127 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2130 ;;;###autoload
2131 (define-derived-mode org-mode outline-mode "Org"
2132 "Outline-based notes management and organizer, alias
2133 \"Carsten's outline-mode for keeping track of everything.\"
2135 Org-mode develops organizational tasks around a NOTES file which
2136 contains information about projects as plain text. Org-mode is
2137 implemented on top of outline-mode, which is ideal to keep the content
2138 of large files well structured. It supports ToDo items, deadlines and
2139 time stamps, which magically appear in the diary listing of the Emacs
2140 calendar. Tables are easily created with a built-in table editor.
2141 Plain text URL-like links connect to websites, emails (VM), Usenet
2142 messages (Gnus), BBDB entries, and any files related to the project.
2143 For printing and sharing of notes, an Org-mode file (or a part of it)
2144 can be exported as a structured ASCII or HTML file.
2146 The following commands are available:
2148 \\{org-mode-map}"
2149 (easy-menu-add org-org-menu)
2150 (easy-menu-add org-tbl-menu)
2151 (org-install-agenda-files-menu)
2152 (setq outline-regexp "\\*+")
2153 ; (setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2154 (setq outline-level 'org-outline-level)
2155 (if org-startup-truncated (setq truncate-lines t))
2156 (org-set-regexps-and-options)
2157 (set (make-local-variable 'font-lock-unfontify-region-function)
2158 'org-unfontify-region)
2159 ;; Activate before-change-function
2160 (set (make-local-variable 'org-table-may-need-update) t)
2161 (org-add-hook 'before-change-functions 'org-before-change-function nil
2162 'local)
2163 ;; Paragraphs and auto-filling
2164 (org-set-autofill-regexps)
2165 (org-update-radio-target-regexp)
2166 ;; Settings for Calc embedded mode
2167 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2168 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2169 (if (and org-insert-mode-line-in-empty-file
2170 (interactive-p)
2171 (= (point-min) (point-max)))
2172 (insert " -*- mode: org -*-\n\n"))
2174 ;; Get rid of Outline menus, they are not needed
2175 ;; Need to do this here because define-derived-mode sets up
2176 ;; the keymap so late.
2177 (if (featurep 'xemacs)
2178 (progn
2179 (delete-menu-item '("Headings"))
2180 (delete-menu-item '("Show"))
2181 (delete-menu-item '("Hide"))
2182 (set-menubar-dirty-flag))
2183 (define-key org-mode-map [menu-bar headings] 'undefined)
2184 (define-key org-mode-map [menu-bar hide] 'undefined)
2185 (define-key org-mode-map [menu-bar show] 'undefined))
2187 (unless org-inhibit-startup
2188 (if org-startup-with-deadline-check
2189 (call-interactively 'org-check-deadlines)
2190 (cond
2191 ((eq org-startup-folded t)
2192 (org-cycle '(4)))
2193 ((eq org-startup-folded 'content)
2194 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2195 (org-cycle '(4)) (org-cycle '(4))))))))
2197 (defsubst org-current-line (&optional pos)
2198 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2200 (defun org-current-time ()
2201 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2202 (if (> org-time-stamp-rounding-minutes 0)
2203 (let ((r org-time-stamp-rounding-minutes)
2204 (time (decode-time)))
2205 (apply 'encode-time
2206 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2207 (nthcdr 2 time))))
2208 (current-time)))
2210 ;; FIXME: Do we need to copy?
2211 (defun org-string-props (string &rest properties)
2212 "Add PROPERTIES to string."
2213 (add-text-properties 0 (length string) properties string)
2214 string)
2216 ;;; Font-Lock stuff
2218 (defvar org-mouse-map (make-sparse-keymap))
2219 (define-key org-mouse-map
2220 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
2221 (define-key org-mouse-map
2222 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
2223 (define-key org-mouse-map [follow-link] 'mouse-face)
2224 (when org-tab-follows-link
2225 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2226 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2227 (when org-return-follows-link
2228 (define-key org-mouse-map [(return)] 'org-open-at-point)
2229 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2231 (require 'font-lock)
2233 (defconst org-non-link-chars "\t\n\r|<>\000")
2234 (defconst org-link-regexp
2235 (if org-allow-space-in-links
2236 (concat
2237 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|mhe\\|rmail\\|gnus\\|shell\\):\\([^" org-non-link-chars "]+[^ " org-non-link-chars "]\\)")
2238 (concat
2239 "\\(https?\\|ftp\\|mailto\\|file\\|news\\|bbdb\\|vm\\|wl\\|mhe\\|rmail\\|gnus\\|shell\\):\\([^ " org-non-link-chars "]+\\)")
2241 "Regular expression for matching links.")
2242 (defconst org-link-maybe-angles-regexp
2243 (concat "<?\\(" org-link-regexp "\\)>?")
2244 "Matches a link and optionally surrounding angle brackets.")
2245 (defconst org-protected-link-regexp
2246 (concat "\000" org-link-regexp "\000")
2247 "Matches a link and optionally surrounding angle brackets.")
2249 (defconst org-bracket-link-regexp
2250 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2251 "Matches a link in double brackets.")
2253 (defconst org-ts-lengths
2254 (cons (length (format-time-string (car org-time-stamp-formats)))
2255 (length (format-time-string (cdr org-time-stamp-formats))))
2256 "This holds the lengths of the two different time formats.")
2257 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2258 "Regular expression for fast time stamp matching.")
2259 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2260 "Regular expression for fast time stamp matching.")
2261 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2262 "Regular expression matching time strings for analysis.")
2263 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2264 "Regular expression matching time stamps, with groups.")
2265 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2266 "Regular expression matching a time stamp range.")
2267 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2268 org-ts-regexp "\\)?")
2269 "Regular expression matching a time stamp or time stamp range.")
2271 (defun org-activate-links (limit)
2272 "Run through the buffer and add overlays to links."
2273 (if (re-search-forward org-link-regexp limit t)
2274 (progn
2275 (add-text-properties (match-beginning 0) (match-end 0)
2276 (list 'mouse-face 'highlight
2277 'keymap org-mouse-map))
2278 t)))
2280 (defun org-activate-links2 (limit)
2281 "Run through the buffer and add overlays to links."
2282 (if (re-search-forward org-bracket-link-regexp limit t)
2283 (progn
2284 (add-text-properties (match-beginning 0) (match-end 0)
2285 (list 'mouse-face 'highlight
2286 'keymap org-mouse-map))
2287 t)))
2289 (defun org-activate-dates (limit)
2290 "Run through the buffer and add overlays to dates."
2291 (if (re-search-forward org-tsr-regexp limit t)
2292 (progn
2293 (add-text-properties (match-beginning 0) (match-end 0)
2294 (list 'mouse-face 'highlight
2295 'keymap org-mouse-map))
2296 t)))
2298 (defvar org-target-link-regexp nil
2299 "Regular expression matching radio targets in plain text.")
2300 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2301 "Regular expression matching a link target.")
2302 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2303 "Regular expression matching a link target.")
2305 (defun org-activate-target-links (limit)
2306 "Run through the buffer and add overlays to target matches."
2307 (when (and org-radio-targets org-target-link-regexp)
2308 (let ((case-fold-search t))
2309 (if (re-search-forward org-target-link-regexp limit t)
2310 (progn
2311 (add-text-properties (match-beginning 0) (match-end 0)
2312 (list 'mouse-face 'highlight
2313 'keymap org-mouse-map
2314 'org-linked-text t))
2315 t)))))
2317 (defun org-update-radio-target-regexp ()
2318 "Find all radio targets in this file and update the regular expression."
2319 (interactive)
2320 (when org-radio-targets
2321 (setq org-target-link-regexp
2322 (org-make-target-link-regexp (org-all-targets 'radio)))
2323 (font-lock-mode -1)
2324 (font-lock-mode 1)))
2326 (defun org-all-targets (&optional radio)
2327 "Return a list of all targets in this file.
2328 With optional argument RADIO, only find radio targets."
2329 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2330 rtn)
2331 (save-excursion
2332 (goto-char (point-min))
2333 (while (re-search-forward re nil t)
2334 (add-to-list 'rtn (downcase
2335 (if (fboundp 'match-string-no-properties)
2336 (match-string-no-properties 1)
2337 (match-string 1)))))
2338 rtn)))
2340 (defun org-make-target-link-regexp (targets)
2341 "Make regular expression matching all strings in TARGETS.
2342 The regular expression finds the targets also if there is a line break
2343 between words."
2344 (and targets
2345 (concat
2346 "\\<\\("
2347 (mapconcat
2348 (lambda (x)
2349 (while (string-match " +" x)
2350 (setq x (replace-match "\\s-+" t t x)))
2352 targets
2353 "\\|")
2354 "\\)\\>")))
2356 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2357 "Matches CamelCase words, possibly with a star before it.")
2359 (defun org-activate-camels (limit)
2360 "Run through the buffer and add overlays to dates."
2361 (if org-activate-camels
2362 (if (re-search-forward org-camel-regexp limit t)
2363 (progn
2364 (add-text-properties (match-beginning 0) (match-end 0)
2365 (list 'mouse-face 'highlight
2366 'keymap org-mouse-map))
2367 t))))
2369 (defun org-activate-tags (limit)
2370 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2371 (progn
2372 (add-text-properties (match-beginning 1) (match-end 1)
2373 (list 'mouse-face 'highlight
2374 'keymap org-mouse-map))
2375 t)))
2377 (defun org-font-lock-level ()
2378 (save-excursion
2379 (org-back-to-heading t)
2380 (- (match-end 0) (match-beginning 0))))
2382 (defun org-outline-level ()
2383 (save-excursion
2384 (looking-at outline-regexp)
2385 (if (match-beginning 1)
2386 (+ (org-get-string-indentation (match-string 1)) 1000)
2387 (- (match-end 0) (match-beginning 0)))))
2389 (defvar org-font-lock-keywords nil)
2391 (defun org-set-font-lock-defaults ()
2392 (let* ((em org-fontify-emphasized-text)
2393 (org-font-lock-extra-keywords
2394 (list
2395 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
2396 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
2397 '(org-activate-links (0 'org-link t))
2398 '(org-activate-links2 (0 'org-link t))
2399 '(org-activate-target-links (0 'org-link t))
2400 '(org-activate-dates (0 'org-link t))
2401 '(org-activate-camels (0 'org-link t))
2402 '(org-activate-tags (1 'org-tag t))
2403 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2404 '(1 'org-warning t))
2405 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2406 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2407 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2408 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2409 (if em '("\\(\\W\\|^\\)\\(\\*\\w+\\*\\)\\(\\W\\|$\\)" 2 'bold))
2410 (if em '("\\(\\W\\|^\\)\\(/\\w+/\\)\\(\\W\\|$\\)" 2 'italic))
2411 (if em '("\\(\\W\\|^\\)\\(_\\w+_\\)\\(\\W\\|$\\)" 2 'underline))
2412 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2413 "\\|" org-quote-string "\\)\\>")
2414 '(1 'org-special-keyword t))
2415 '("^#.*" (0 'font-lock-comment-face t))
2416 (if org-fontify-done-headline
2417 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2418 '(1 'org-done t) '(2 'org-headline-done t))
2419 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2420 '(1 'org-done t)))
2421 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2422 (1 'org-table t))
2423 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2424 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2425 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2427 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
2428 ;; Now set the full font-lock-keywords
2429 (set (make-local-variable 'org-font-lock-keywords)
2430 org-font-lock-extra-keywords)
2431 (set (make-local-variable 'font-lock-defaults)
2432 '(org-font-lock-keywords t nil nil backward-paragraph))
2433 (kill-local-variable 'font-lock-keywords) nil))
2435 (defvar org-m nil)
2436 (defvar org-l nil)
2437 (defvar org-f nil)
2438 (defun org-get-level-face (n)
2439 "Get the right face for match N in font-lock matching of healdines."
2440 (setq org-l (- (match-end 2) (match-beginning 1)))
2441 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
2442 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
2443 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
2444 (cond
2445 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
2446 ((eq n 2) org-f)
2447 (t (if org-level-color-stars-only nil org-f))))
2449 (defun org-unfontify-region (beg end &optional maybe_loudly)
2450 "Remove fontification and activation overlays from links."
2451 (font-lock-default-unfontify-region beg end)
2452 (let* ((buffer-undo-list t)
2453 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2454 (inhibit-modification-hooks t)
2455 deactivate-mark buffer-file-name buffer-file-truename)
2456 (remove-text-properties beg end
2457 '(mouse-face nil keymap nil org-linked-text nil))))
2459 ;;; Visibility cycling
2461 (defvar org-cycle-global-status nil)
2462 (defvar org-cycle-subtree-status nil)
2463 (defun org-cycle (&optional arg)
2464 "Visibility cycling for Org-mode.
2466 - When this function is called with a prefix argument, rotate the entire
2467 buffer through 3 states (global cycling)
2468 1. OVERVIEW: Show only top-level headlines.
2469 2. CONTENTS: Show all headlines of all levels, but no body text.
2470 3. SHOW ALL: Show everything.
2472 - When point is at the beginning of a headline, rotate the subtree started
2473 by this line through 3 different states (local cycling)
2474 1. FOLDED: Only the main headline is shown.
2475 2. CHILDREN: The main headline and the direct children are shown.
2476 From this state, you can move to one of the children
2477 and zoom in further.
2478 3. SUBTREE: Show the entire subtree, including body text.
2480 - When there is a numeric prefix, go up to a heading with level ARG, do
2481 a `show-subtree' and return to the previous cursor position. If ARG
2482 is negative, go up that many levels.
2484 - When point is not at the beginning of a headline, execute
2485 `indent-relative', like TAB normally does. See the option
2486 `org-cycle-emulate-tab' for details.
2488 - Special case: if point is the the beginning of the buffer and there is
2489 no headline in line 1, this function will act as if called with prefix arg."
2490 (interactive "P")
2492 (if (or (and (bobp) (not (looking-at outline-regexp)))
2493 (equal arg '(4)))
2494 ;; special case: use global cycling
2495 (setq arg t))
2497 (let ((outline-regexp
2498 (if org-cycle-include-plain-lists
2499 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2500 outline-regexp)))
2502 (cond
2504 ((org-at-table-p 'any)
2505 ;; Enter the table or move to the next field in the table
2506 (or (org-table-recognize-table.el)
2507 (progn
2508 (org-table-justify-field-maybe)
2509 (org-table-next-field))))
2511 ((eq arg t) ;; Global cycling
2513 (cond
2514 ((and (eq last-command this-command)
2515 (eq org-cycle-global-status 'overview))
2516 ;; We just created the overview - now do table of contents
2517 ;; This can be slow in very large buffers, so indicate action
2518 (message "CONTENTS...")
2519 (save-excursion
2520 ;; Visit all headings and show their offspring
2521 (goto-char (point-max))
2522 (catch 'exit
2523 (while (and (progn (condition-case nil
2524 (outline-previous-visible-heading 1)
2525 (error (goto-char (point-min))))
2527 (looking-at outline-regexp))
2528 (show-branches)
2529 (if (bobp) (throw 'exit nil))))
2530 (message "CONTENTS...done"))
2531 (setq org-cycle-global-status 'contents)
2532 (run-hook-with-args 'org-cycle-hook 'contents))
2534 ((and (eq last-command this-command)
2535 (eq org-cycle-global-status 'contents))
2536 ;; We just showed the table of contents - now show everything
2537 (show-all)
2538 (message "SHOW ALL")
2539 (setq org-cycle-global-status 'all)
2540 (run-hook-with-args 'org-cycle-hook 'all))
2543 ;; Default action: go to overview
2544 (hide-sublevels 1)
2545 (message "OVERVIEW")
2546 (setq org-cycle-global-status 'overview)
2547 (run-hook-with-args 'org-cycle-hook 'overview))))
2549 ((integerp arg)
2550 ;; Show-subtree, ARG levels up from here.
2551 (save-excursion
2552 (org-back-to-heading)
2553 (outline-up-heading (if (< arg 0) (- arg)
2554 (- (funcall outline-level) arg)))
2555 (org-show-subtree)))
2557 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2558 ;; At a heading: rotate between three different views
2559 (org-back-to-heading)
2560 (let ((goal-column 0) eoh eol eos)
2561 ;; First, some boundaries
2562 (save-excursion
2563 (org-back-to-heading)
2564 (save-excursion
2565 (beginning-of-line 2)
2566 (while (and (not (eobp)) ;; this is like `next-line'
2567 (get-char-property (1- (point)) 'invisible))
2568 (beginning-of-line 2)) (setq eol (point)))
2569 (outline-end-of-heading) (setq eoh (point))
2570 (org-end-of-subtree t) (setq eos (point))
2571 (outline-next-heading))
2572 ;; Find out what to do next and set `this-command'
2573 (cond
2574 ((= eos eoh)
2575 ;; Nothing is hidden behind this heading
2576 (message "EMPTY ENTRY")
2577 (setq org-cycle-subtree-status nil))
2578 ((>= eol eos)
2579 ;; Entire subtree is hidden in one line: open it
2580 (org-show-entry)
2581 (show-children)
2582 (message "CHILDREN")
2583 (setq org-cycle-subtree-status 'children)
2584 (run-hook-with-args 'org-cycle-hook 'children))
2585 ((and (eq last-command this-command)
2586 (eq org-cycle-subtree-status 'children))
2587 ;; We just showed the children, now show everything.
2588 (org-show-subtree)
2589 (message "SUBTREE")
2590 (setq org-cycle-subtree-status 'subtree)
2591 (run-hook-with-args 'org-cycle-hook 'subtree))
2593 ;; Default action: hide the subtree.
2594 (hide-subtree)
2595 (message "FOLDED")
2596 (setq org-cycle-subtree-status 'folded)
2597 (run-hook-with-args 'org-cycle-hook 'folded)))))
2599 ;; TAB emulation
2600 (buffer-read-only (org-back-to-heading))
2601 ((if (and (eq org-cycle-emulate-tab 'white)
2602 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2604 (eq org-cycle-emulate-tab t))
2605 (if (and (looking-at "[ \n\r\t]")
2606 (string-match "^[ \t]*$" (buffer-substring
2607 (point-at-bol) (point))))
2608 (progn
2609 (beginning-of-line 1)
2610 (and (looking-at "[ \t]+") (replace-match ""))))
2611 (indent-relative))
2613 (t (save-excursion
2614 (org-back-to-heading)
2615 (org-cycle))))))
2617 (defun org-optimize-window-after-visibility-change (state)
2618 "Adjust the window after a change in outline visibility.
2619 This function is the default value of the hook `org-cycle-hook'."
2620 (cond
2621 ((eq state 'overview) (org-first-headline-recenter 1))
2622 ((eq state 'content) nil)
2623 ((eq state 'all) nil)
2624 ((eq state 'folded) nil)
2625 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2626 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1)))))
2628 (defun org-subtree-end-visible-p ()
2629 "Is the end of the current subtree visible?"
2630 (pos-visible-in-window-p
2631 (save-excursion (org-end-of-subtree t) (point))))
2633 (defun org-first-headline-recenter (&optional N)
2634 "Move cursor to the first headline and recenter the headline.
2635 Optional argument N means, put the headline into the Nth line of the window."
2636 (goto-char (point-min))
2637 (when (re-search-forward (concat "^" outline-regexp) nil t)
2638 (beginning-of-line)
2639 (recenter (prefix-numeric-value N))))
2641 (defvar org-goto-window-configuration nil)
2642 (defvar org-goto-marker nil)
2643 (defvar org-goto-map (make-sparse-keymap))
2644 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2645 (while (setq cmd (pop cmds))
2646 (substitute-key-definition cmd cmd org-goto-map global-map)))
2647 (define-key org-goto-map "\C-m" 'org-goto-ret)
2648 (define-key org-goto-map [(left)] 'org-goto-left)
2649 (define-key org-goto-map [(right)] 'org-goto-right)
2650 (define-key org-goto-map [(?q)] 'org-goto-quit)
2651 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2652 (define-key org-goto-map "\C-i" 'org-cycle)
2653 (define-key org-goto-map [(tab)] 'org-cycle)
2654 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2655 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2656 (define-key org-goto-map "n" 'outline-next-visible-heading)
2657 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2658 (define-key org-goto-map "f" 'outline-forward-same-level)
2659 (define-key org-goto-map "b" 'outline-backward-same-level)
2660 (define-key org-goto-map "u" 'outline-up-heading)
2661 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2662 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2663 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2664 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2665 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2666 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2667 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2669 (defconst org-goto-help
2670 "Select a location to jump to, press RET
2671 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2673 (defun org-goto ()
2674 "Go to a different location of the document, keeping current visibility.
2676 When you want to go to a different location in a document, the fastest way
2677 is often to fold the entire buffer and then dive into the tree. This
2678 method has the disadvantage, that the previous location will be folded,
2679 which may not be what you want.
2681 This command works around this by showing a copy of the current buffer in
2682 overview mode. You can dive into the tree in that copy, to find the
2683 location you want to reach. When pressing RET, the command returns to the
2684 original buffer in which the visibility is still unchanged. It then jumps
2685 to the new location, making it and the headline hierarchy above it visible."
2686 (interactive)
2687 (let* ((org-goto-start-pos (point))
2688 (selected-point
2689 (org-get-location (current-buffer) org-goto-help)))
2690 (if selected-point
2691 (progn
2692 (org-mark-ring-push org-goto-start-pos)
2693 (goto-char selected-point)
2694 (if (or (org-invisible-p) (org-invisible-p2))
2695 (org-show-hierarchy-above)))
2696 (error "Quit"))))
2698 (defun org-get-location (buf help)
2699 "Let the user select a location in the Org-mode buffer BUF.
2700 This function uses a recursive edit. It returns the selected position
2701 or nil."
2702 (let (org-selected-point)
2703 (save-excursion
2704 (save-window-excursion
2705 (delete-other-windows)
2706 (switch-to-buffer (get-buffer-create "*org-goto*"))
2707 (with-output-to-temp-buffer "*Help*"
2708 (princ help))
2709 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2710 (setq buffer-read-only nil)
2711 (erase-buffer)
2712 (insert-buffer-substring buf)
2713 (let ((org-startup-truncated t)
2714 (org-startup-folded t)
2715 (org-startup-with-deadline-check nil))
2716 (org-mode))
2717 (setq buffer-read-only t)
2718 (if (boundp 'org-goto-start-pos)
2719 (goto-char org-goto-start-pos)
2720 (goto-char (point-min)))
2721 (org-beginning-of-line)
2722 (message "Select location and press RET")
2723 ;; now we make sure that during selection, ony very few keys work
2724 ;; and that it is impossible to switch to another window.
2725 (let ((gm (current-global-map))
2726 (overriding-local-map org-goto-map))
2727 (unwind-protect
2728 (progn
2729 (use-global-map org-goto-map)
2730 (recursive-edit))
2731 (use-global-map gm)))))
2732 (kill-buffer "*org-goto*")
2733 org-selected-point))
2735 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2736 (defun org-goto-ret (&optional arg)
2737 "Finish `org-goto' by going to the new location."
2738 (interactive "P")
2739 (setq org-selected-point (point)
2740 current-prefix-arg arg)
2741 (throw 'exit nil))
2743 (defun org-goto-left ()
2744 "Finish `org-goto' by going to the new location."
2745 (interactive)
2746 (if (org-on-heading-p)
2747 (progn
2748 (beginning-of-line 1)
2749 (setq org-selected-point (point)
2750 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2751 (throw 'exit nil))
2752 (error "Not on a heading")))
2754 (defun org-goto-right ()
2755 "Finish `org-goto' by going to the new location."
2756 (interactive)
2757 (if (org-on-heading-p)
2758 (progn
2759 (outline-end-of-subtree)
2760 (or (eobp) (forward-char 1))
2761 (setq org-selected-point (point)
2762 current-prefix-arg (- (match-end 0) (match-beginning 0)))
2763 (throw 'exit nil))
2764 (error "Not on a heading")))
2766 (defun org-goto-quit ()
2767 "Finish `org-goto' without cursor motion."
2768 (interactive)
2769 (setq org-selected-point nil)
2770 (throw 'exit nil))
2772 ;;; Promotion, Demotion, Inserting new headlines
2774 (defvar org-ignore-region nil
2775 "To temporarily disable the active region.")
2777 (defun org-insert-heading (&optional force-heading)
2778 "Insert a new heading or item with same depth at point."
2779 (interactive "P")
2780 (when (or force-heading (not (org-insert-item)))
2781 (let* ((head (save-excursion
2782 (condition-case nil
2783 (org-back-to-heading)
2784 (error (outline-next-heading)))
2785 (prog1 (match-string 0)
2786 (funcall outline-level)))))
2787 (unless (bolp) (newline))
2788 (insert head)
2789 (unless (eolp)
2790 (save-excursion (newline-and-indent)))
2791 (unless (equal (char-before) ?\ )
2792 (insert " "))
2793 (run-hooks 'org-insert-heading-hook))))
2795 (defun org-insert-item ()
2796 "Insert a new item at the current level.
2797 Return t when things worked, nil when we are not in an item."
2798 (when (save-excursion
2799 (condition-case nil
2800 (progn
2801 (org-beginning-of-item)
2802 (org-at-item-p)
2804 (error nil)))
2805 (unless (bolp) (newline))
2806 (insert (match-string 0))
2807 (org-maybe-renumber-ordered-list)
2810 (defun org-insert-todo-heading (arg)
2811 "Insert a new heading with the same level and TODO state as current heading.
2812 If the heading has no TODO state, or if the state is DONE, use the first
2813 state (TODO by default). Also with prefix arg, force first state."
2814 (interactive "P")
2815 (org-insert-heading)
2816 (save-excursion
2817 (org-back-to-heading)
2818 (outline-previous-heading)
2819 (looking-at org-todo-line-regexp))
2820 (if (or arg
2821 (not (match-beginning 2))
2822 (equal (match-string 2) org-done-string))
2823 (insert (car org-todo-keywords) " ")
2824 (insert (match-string 2) " ")))
2826 (defun org-promote-subtree ()
2827 "Promote the entire subtree.
2828 See also `org-promote'."
2829 (interactive)
2830 (save-excursion
2831 (org-map-tree 'org-promote)))
2833 (defun org-demote-subtree ()
2834 "Demote the entire subtree. See `org-demote'.
2835 See also `org-promote'."
2836 (interactive)
2837 (save-excursion
2838 (org-map-tree 'org-demote)))
2840 (defun org-do-promote ()
2841 "Promote the current heading higher up the tree.
2842 If the region is active in `transient-mark-mode', promote all headings
2843 in the region."
2844 (interactive)
2845 (save-excursion
2846 (if (org-region-active-p)
2847 (org-map-region 'org-promote (region-beginning) (region-end))
2848 (org-promote)))
2849 (org-fix-position-after-promote))
2851 (defun org-do-demote ()
2852 "Demote the current heading lower down the tree.
2853 If the region is active in `transient-mark-mode', demote all headings
2854 in the region."
2855 (interactive)
2856 (save-excursion
2857 (if (org-region-active-p)
2858 (org-map-region 'org-demote (region-beginning) (region-end))
2859 (org-demote)))
2860 (org-fix-position-after-promote))
2862 (defun org-fix-position-after-promote ()
2863 "Make sure that after pro/demotion cursor position is right."
2864 (and (equal (char-after) ?\ )
2865 (equal (char-before) ?*)
2866 (forward-char 1)))
2868 (defun org-get-legal-level (level change)
2869 "Rectify a level change under the influence of `org-odd-levels-only'
2870 LEVEL is a current level, CHANGE is by how much the level should be
2871 modified. Even if CHANGE is nil, LEVEL may be returned modified because
2872 even level numbers will become the next higher odd number."
2873 (if org-odd-levels-only
2874 (cond ((not change) (1+ (* 2 (/ level 2))))
2875 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
2876 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
2877 (max 1 (+ level change))))
2879 (defun org-promote ()
2880 "Promote the current heading higher up the tree.
2881 If the region is active in `transient-mark-mode', promote all headings
2882 in the region."
2883 (org-back-to-heading t)
2884 (let* ((level (save-match-data (funcall outline-level)))
2885 (up-head (make-string (org-get-legal-level level -1) ?*))
2886 (diff (abs (- level (length up-head)))))
2887 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
2888 (replace-match up-head nil t)
2889 ;; Fixup tag positioning
2890 (and org-auto-align-tags (org-set-tags nil t))
2891 (if org-adapt-indentation
2892 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
2893 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
2895 (defun org-demote ()
2896 "Demote the current heading lower down the tree.
2897 If the region is active in `transient-mark-mode', demote all headings
2898 in the region."
2899 (org-back-to-heading t)
2900 (let* ((level (save-match-data (funcall outline-level)))
2901 (down-head (make-string (org-get-legal-level level 1) ?*))
2902 (diff (abs (- level (length down-head)))))
2903 (replace-match down-head nil t)
2904 ;; Fixup tag positioning
2905 (and org-auto-align-tags (org-set-tags nil t))
2906 (if org-adapt-indentation
2907 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
2909 (defun org-map-tree (fun)
2910 "Call FUN for every heading underneath the current one."
2911 (org-back-to-heading)
2912 (let ((level (funcall outline-level)))
2913 (save-excursion
2914 (funcall fun)
2915 (while (and (progn
2916 (outline-next-heading)
2917 (> (funcall outline-level) level))
2918 (not (eobp)))
2919 (funcall fun)))))
2921 (defun org-map-region (fun beg end)
2922 "Call FUN for every heading between BEG and END."
2923 (let ((org-ignore-region t))
2924 (save-excursion
2925 (setq end (copy-marker end))
2926 (goto-char beg)
2927 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
2928 (< (point) end))
2929 (funcall fun))
2930 (while (and (progn
2931 (outline-next-heading)
2932 (< (point) end))
2933 (not (eobp)))
2934 (funcall fun)))))
2936 (defun org-fixup-indentation (from to prohibit)
2937 "Change the indentation in the current entry by re-replacing FROM with TO.
2938 However, if the regexp PROHIBIT matches at all, don't do anything.
2939 This is being used to change indentation along with the length of the
2940 heading marker. But if there are any lines which are not indented, nothing
2941 is changed at all."
2942 (save-excursion
2943 (let ((end (save-excursion (outline-next-heading)
2944 (point-marker))))
2945 (unless (save-excursion (re-search-forward prohibit end t))
2946 (while (re-search-forward from end t)
2947 (replace-match to)
2948 (beginning-of-line 2)))
2949 (move-marker end nil))))
2951 ;;; Vertical tree motion, cutting and pasting of subtrees
2953 (defun org-move-subtree-up (&optional arg)
2954 "Move the current subtree up past ARG headlines of the same level."
2955 (interactive "p")
2956 (org-move-subtree-down (- (prefix-numeric-value arg))))
2958 (defun org-move-subtree-down (&optional arg)
2959 "Move the current subtree down past ARG headlines of the same level."
2960 (interactive "p")
2961 (setq arg (prefix-numeric-value arg))
2962 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
2963 'outline-get-last-sibling))
2964 (ins-point (make-marker))
2965 (cnt (abs arg))
2966 beg end txt folded)
2967 ;; Select the tree
2968 (org-back-to-heading)
2969 (setq beg (point))
2970 (save-match-data
2971 (save-excursion (outline-end-of-heading)
2972 (setq folded (org-invisible-p)))
2973 (outline-end-of-subtree))
2974 (outline-next-heading)
2975 (setq end (point))
2976 ;; Find insertion point, with error handling
2977 (goto-char beg)
2978 (while (> cnt 0)
2979 (or (and (funcall movfunc) (looking-at outline-regexp))
2980 (progn (goto-char beg)
2981 (error "Cannot move past superior level or buffer limit")))
2982 (setq cnt (1- cnt)))
2983 (if (> arg 0)
2984 ;; Moving forward - still need to move over subtree
2985 (progn (outline-end-of-subtree)
2986 (outline-next-heading)
2987 (if (not (or (looking-at (concat "^" outline-regexp))
2988 (bolp)))
2989 (newline))))
2990 (move-marker ins-point (point))
2991 (setq txt (buffer-substring beg end))
2992 (delete-region beg end)
2993 (insert txt)
2994 (goto-char ins-point)
2995 (if folded (hide-subtree))
2996 (move-marker ins-point nil)))
2998 (defvar org-subtree-clip ""
2999 "Clipboard for cut and paste of subtrees.
3000 This is actually only a copy of the kill, because we use the normal kill
3001 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3003 (defvar org-subtree-clip-folded nil
3004 "Was the last copied subtree folded?
3005 This is used to fold the tree back after pasting.")
3007 (defun org-cut-subtree ()
3008 "Cut the current subtree into the clipboard.
3009 This is a short-hand for marking the subtree and then cutting it."
3010 (interactive)
3011 (org-copy-subtree 'cut))
3013 (defun org-copy-subtree (&optional cut)
3014 "Cut the current subtree into the clipboard.
3015 This is a short-hand for marking the subtree and then copying it.
3016 If CUT is non nil, actually cut the subtree."
3017 (interactive)
3018 (let (beg end folded)
3019 (org-back-to-heading)
3020 (setq beg (point))
3021 (save-match-data
3022 (save-excursion (outline-end-of-heading)
3023 (setq folded (org-invisible-p)))
3024 (outline-end-of-subtree))
3025 (if (equal (char-after) ?\n) (forward-char 1))
3026 (setq end (point))
3027 (goto-char beg)
3028 (when (> end beg)
3029 (setq org-subtree-clip-folded folded)
3030 (if cut (kill-region beg end) (copy-region-as-kill beg end))
3031 (setq org-subtree-clip (current-kill 0))
3032 (message "%s: Subtree with %d characters"
3033 (if cut "Cut" "Copied")
3034 (length org-subtree-clip)))))
3036 (defun org-paste-subtree (&optional level tree)
3037 "Paste the clipboard as a subtree, with modification of headline level.
3038 The entire subtree is promoted or demoted in order to match a new headline
3039 level. By default, the new level is derived from the visible headings
3040 before and after the insertion point, and taken to be the inferior headline
3041 level of the two. So if the previous visible heading is level 3 and the
3042 next is level 4 (or vice versa), level 4 will be used for insertion.
3043 This makes sure that the subtree remains an independent subtree and does
3044 not swallow low level entries.
3046 You can also force a different level, either by using a numeric prefix
3047 argument, or by inserting the heading marker by hand. For example, if the
3048 cursor is after \"*****\", then the tree will be shifted to level 5.
3050 If you want to insert the tree as is, just use \\[yank].
3052 If optional TREE is given, use this text instead of the kill ring."
3053 (interactive "P")
3054 (unless (org-kill-is-subtree-p tree)
3055 (error
3056 (substitute-command-keys
3057 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
3058 (let* ((txt (or tree (current-kill 0)))
3059 (^re (concat "^\\(" outline-regexp "\\)"))
3060 (re (concat "\\(" outline-regexp "\\)"))
3061 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3063 (old-level (if (string-match ^re txt)
3064 (- (match-end 0) (match-beginning 0))
3065 -1))
3066 (force-level (cond (level (prefix-numeric-value level))
3067 ((string-match
3068 ^re_ (buffer-substring (point-at-bol) (point)))
3069 (- (match-end 0) (match-beginning 0)))
3070 (t nil)))
3071 (previous-level (save-excursion
3072 (condition-case nil
3073 (progn
3074 (outline-previous-visible-heading 1)
3075 (if (looking-at re)
3076 (- (match-end 0) (match-beginning 0))
3078 (error 1))))
3079 (next-level (save-excursion
3080 (condition-case nil
3081 (progn
3082 (outline-next-visible-heading 1)
3083 (if (looking-at re)
3084 (- (match-end 0) (match-beginning 0))
3086 (error 1))))
3087 (new-level (or force-level (max previous-level next-level)))
3088 (shift (if (or (= old-level -1)
3089 (= new-level -1)
3090 (= old-level new-level))
3092 (- new-level old-level)))
3093 (shift1 shift)
3094 (delta (if (> shift 0) -1 1))
3095 (func (if (> shift 0) 'org-demote 'org-promote))
3096 (org-odd-levels-only nil)
3097 beg end)
3098 ;; Remove the forces level indicator
3099 (if force-level
3100 (delete-region (point-at-bol) (point)))
3101 ;; Make sure we start at the beginning of an empty line
3102 (if (not (bolp)) (insert "\n"))
3103 (if (not (looking-at "[ \t]*$"))
3104 (progn (insert "\n") (backward-char 1)))
3105 ;; Paste
3106 (setq beg (point))
3107 (insert txt)
3108 (setq end (point))
3109 (goto-char beg)
3110 ;; Shift if necessary
3111 (if (= shift 0)
3112 (message "Pasted at level %d, without shift" new-level)
3113 (save-restriction
3114 (narrow-to-region beg end)
3115 (while (not (= shift 0))
3116 (org-map-region func (point-min) (point-max))
3117 (setq shift (+ delta shift)))
3118 (goto-char (point-min))
3119 (message "Pasted at level %d, with shift by %d levels"
3120 new-level shift1)))
3121 (if (and (eq org-subtree-clip (current-kill 0))
3122 org-subtree-clip-folded)
3123 ;; The tree was folded before it was killed/copied
3124 (hide-subtree))))
3126 (defun org-kill-is-subtree-p (&optional txt)
3127 "Check if the current kill is an outline subtree, or a set of trees.
3128 Returns nil if kill does not start with a headline, or if the first
3129 headline level is not the largest headline level in the tree.
3130 So this will actually accept several entries of equal levels as well,
3131 which is OK for `org-paste-subtree'.
3132 If optional TXT is given, check this string instead of the current kill."
3133 (let* ((kill (or txt (current-kill 0) ""))
3134 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3135 (- (match-end 0) (match-beginning 0))))
3136 (re (concat "^" outline-regexp))
3137 (start 1))
3138 (if (not start-level)
3139 nil ;; does not even start with a heading
3140 (catch 'exit
3141 (while (setq start (string-match re kill (1+ start)))
3142 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3143 (throw 'exit nil)))
3144 t))))
3146 ;;; Plain list items
3148 (defun org-at-item-p ()
3149 "Is point in a line starting a hand-formatted item?"
3150 (let ((llt org-plain-list-ordered-item-terminator))
3151 (save-excursion
3152 (goto-char (point-at-bol))
3153 (looking-at
3154 (cond
3155 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3156 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3157 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3158 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3160 (defun org-get-indentation ()
3161 "Get the indentation of the current line, interpreting tabs."
3162 (save-excursion
3163 (beginning-of-line 1)
3164 (skip-chars-forward " \t")
3165 (current-column)))
3167 (defun org-beginning-of-item ()
3168 "Go to the beginning of the current hand-formatted item.
3169 If the cursor is not in an item, throw an error."
3170 (let ((pos (point))
3171 (limit (save-excursion (org-back-to-heading)
3172 (beginning-of-line 2) (point)))
3173 ind ind1)
3174 (if (org-at-item-p)
3175 (beginning-of-line 1)
3176 (beginning-of-line 1)
3177 (skip-chars-forward " \t")
3178 (setq ind (current-column))
3179 (if (catch 'exit
3180 (while t
3181 (beginning-of-line 0)
3182 (if (< (point) limit) (throw 'exit nil))
3183 (unless (looking-at " \t]*$")
3184 (skip-chars-forward " \t")
3185 (setq ind1 (current-column))
3186 (if (< ind1 ind)
3187 (throw 'exit (org-at-item-p))))))
3189 (goto-char pos)
3190 (error "Not in an item")))))
3192 (defun org-end-of-item ()
3193 "Go to the end of the current hand-formatted item.
3194 If the cursor is not in an item, throw an error."
3195 (let ((pos (point))
3196 (limit (save-excursion (outline-next-heading) (point)))
3197 (ind (save-excursion
3198 (org-beginning-of-item)
3199 (skip-chars-forward " \t")
3200 (current-column)))
3201 ind1)
3202 (if (catch 'exit
3203 (while t
3204 (beginning-of-line 2)
3205 (if (>= (point) limit) (throw 'exit t))
3206 (unless (looking-at "[ \t]*$")
3207 (skip-chars-forward " \t")
3208 (setq ind1 (current-column))
3209 (if (<= ind1 ind) (throw 'exit t)))))
3210 (beginning-of-line 1)
3211 (goto-char pos)
3212 (error "Not in an item"))))
3214 (defun org-move-item-down (arg)
3215 "Move the plain list item at point down, i.e. swap with following item.
3216 Subitems (items with larger indentation) are considered part of the item,
3217 so this really moves item trees."
3218 (interactive "p")
3219 (let (beg end ind ind1 (pos (point)) txt)
3220 (org-beginning-of-item)
3221 (setq beg (point))
3222 (setq ind (org-get-indentation))
3223 (org-end-of-item)
3224 (setq end (point))
3225 (setq ind1 (org-get-indentation))
3226 (if (and (org-at-item-p) (= ind ind1))
3227 (progn
3228 (org-end-of-item)
3229 (setq txt (buffer-substring beg end))
3230 (save-excursion
3231 (delete-region beg end))
3232 (setq pos (point))
3233 (insert txt)
3234 (goto-char pos)
3235 (org-maybe-renumber-ordered-list))
3236 (goto-char pos)
3237 (error "Cannot move this item further down"))))
3239 (defun org-move-item-up (arg)
3240 "Move the plain list item at point up, i.e. swap with previous item.
3241 Subitems (items with larger indentation) are considered part of the item,
3242 so this really moves item trees."
3243 (interactive "p")
3244 (let (beg end ind ind1 (pos (point)) txt)
3245 (org-beginning-of-item)
3246 (setq beg (point))
3247 (setq ind (org-get-indentation))
3248 (org-end-of-item)
3249 (setq end (point))
3250 (goto-char beg)
3251 (catch 'exit
3252 (while t
3253 (beginning-of-line 0)
3254 (if (looking-at "[ \t]*$")
3256 (if (<= (setq ind1 (org-get-indentation)) ind)
3257 (throw 'exit t)))))
3258 (condition-case nil
3259 (org-beginning-of-item)
3260 (error (goto-char beg)
3261 (error "Cannot move this item further up")))
3262 (setq ind1 (org-get-indentation))
3263 (if (and (org-at-item-p) (= ind ind1))
3264 (progn
3265 (setq txt (buffer-substring beg end))
3266 (save-excursion
3267 (delete-region beg end))
3268 (setq pos (point))
3269 (insert txt)
3270 (goto-char pos)
3271 (org-maybe-renumber-ordered-list))
3272 (goto-char pos)
3273 (error "Cannot move this item further up"))))
3275 (defun org-maybe-renumber-ordered-list ()
3276 "Renumber the ordered list at point if setup allows it.
3277 This tests the user option `org-auto-renumber-ordered-lists' before
3278 doing the renumbering."
3279 (and org-auto-renumber-ordered-lists
3280 (org-at-item-p)
3281 (match-beginning 3)
3282 (org-renumber-ordered-list 1)))
3284 (defun org-get-string-indentation (s)
3285 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3286 (let ((n -1) (i 0) (w tab-width) c)
3287 (catch 'exit
3288 (while (< (setq n (1+ n)) (length s))
3289 (setq c (aref s n))
3290 (cond ((= c ?\ ) (setq i (1+ i)))
3291 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3292 (t (throw 'exit t)))))
3295 (defun org-renumber-ordered-list (arg)
3296 "Renumber an ordered plain list.
3297 Cursor next to be in the first line of an item, the line that starts
3298 with something like \"1.\" or \"2)\"."
3299 (interactive "p")
3300 (unless (and (org-at-item-p)
3301 (match-beginning 3))
3302 (error "This is not an ordered list"))
3303 (let ((line (org-current-line))
3304 (col (current-column))
3305 (ind (org-get-string-indentation
3306 (buffer-substring (point-at-bol) (match-beginning 3))))
3307 ;; (term (substring (match-string 3) -1))
3308 ind1 (n (1- arg)))
3309 ;; find where this list begins
3310 (catch 'exit
3311 (while t
3312 (catch 'next
3313 (beginning-of-line 0)
3314 (if (looking-at "[ \t]*$") (throw 'next t))
3315 (skip-chars-forward " \t") (setq ind1 (current-column))
3316 (if (or (< ind1 ind)
3317 (and (= ind1 ind)
3318 (not (org-at-item-p))))
3319 (throw 'exit t)))))
3320 ;; Walk forward and replace these numbers
3321 (catch 'exit
3322 (while t
3323 (catch 'next
3324 (beginning-of-line 2)
3325 (if (eobp) (throw 'exit nil))
3326 (if (looking-at "[ \t]*$") (throw 'next nil))
3327 (skip-chars-forward " \t") (setq ind1 (current-column))
3328 (if (> ind1 ind) (throw 'next t))
3329 (if (< ind1 ind) (throw 'exit t))
3330 (if (not (org-at-item-p)) (throw 'exit nil))
3331 (if (not (match-beginning 3))
3332 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3333 (delete-region (match-beginning 3) (1- (match-end 3)))
3334 (goto-char (match-beginning 3))
3335 (insert (format "%d" (setq n (1+ n)))))))
3336 (goto-line line)
3337 (move-to-column col)))
3339 (defvar org-last-indent-begin-marker (make-marker))
3340 (defvar org-last-indent-end-marker (make-marker))
3342 (defun org-outdent-item (arg)
3343 "Outdent a local list item."
3344 (interactive "p")
3345 (org-indent-item (- arg)))
3347 (defun org-indent-item (arg)
3348 "Indent a local list item."
3349 (interactive "p")
3350 (unless (org-at-item-p)
3351 (error "Not on an item"))
3352 (let (beg end ind ind1)
3353 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3354 (setq beg org-last-indent-begin-marker
3355 end org-last-indent-end-marker)
3356 (org-beginning-of-item)
3357 (setq beg (move-marker org-last-indent-begin-marker (point)))
3358 (org-end-of-item)
3359 (setq end (move-marker org-last-indent-end-marker (point))))
3360 (goto-char beg)
3361 (skip-chars-forward " \t") (setq ind (current-column))
3362 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3363 (while (< (point) end)
3364 (beginning-of-line 1)
3365 (skip-chars-forward " \t") (setq ind1 (current-column))
3366 (delete-region (point-at-bol) (point))
3367 (indent-to-column (+ ind1 arg))
3368 (beginning-of-line 2))
3369 (goto-char beg)))
3371 ;;; Archiving
3373 (defun org-archive-subtree ()
3374 "Move the current subtree to the archive.
3375 The archive can be a certain top-level heading in the current file, or in
3376 a different file. The tree will be moved to that location, the subtree
3377 heading be marked DONE, and the current time will be added."
3378 (interactive)
3379 ;; Save all relevant TODO keyword-relatex variables
3380 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3381 (tr-org-todo-keywords org-todo-keywords)
3382 (tr-org-todo-interpretation org-todo-interpretation)
3383 (tr-org-done-string org-done-string)
3384 (tr-org-todo-regexp org-todo-regexp)
3385 (tr-org-todo-line-regexp org-todo-line-regexp)
3386 (this-buffer (current-buffer))
3387 file heading buffer level newfile-p)
3388 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3389 (progn
3390 (setq file (format (match-string 1 org-archive-location)
3391 (file-name-nondirectory buffer-file-name))
3392 heading (match-string 2 org-archive-location)))
3393 (error "Invalid `org-archive-location'"))
3394 (if (> (length file) 0)
3395 (setq newfile-p (not (file-exists-p file))
3396 buffer (find-file-noselect file))
3397 (setq buffer (current-buffer)))
3398 (unless buffer
3399 (error "Cannot access file \"%s\"" file))
3400 (if (and (> (length heading) 0)
3401 (string-match "^\\*+" heading))
3402 (setq level (match-end 0))
3403 (setq heading nil level 0))
3404 (save-excursion
3405 ;; We first only copy, in case something goes wrong
3406 ;; we need to protect this-command, to avoid kill-region sets it,
3407 ;; which would lead to duplication of subtrees
3408 (let (this-command) (org-copy-subtree))
3409 (set-buffer buffer)
3410 ;; Enforce org-mode for the archive buffer
3411 (if (not (eq major-mode 'org-mode))
3412 ;; Force the mode for future visits.
3413 (let ((org-insert-mode-line-in-empty-file t))
3414 (call-interactively 'org-mode)))
3415 (when newfile-p
3416 (goto-char (point-max))
3417 (insert (format "\nArchived entries from file %s\n\n"
3418 (buffer-file-name this-buffer))))
3419 ;; Force the TODO keywords of the original buffer
3420 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3421 (org-todo-keywords tr-org-todo-keywords)
3422 (org-todo-interpretation tr-org-todo-interpretation)
3423 (org-done-string tr-org-done-string)
3424 (org-todo-regexp tr-org-todo-regexp)
3425 (org-todo-line-regexp tr-org-todo-line-regexp))
3426 (goto-char (point-min))
3427 (if heading
3428 (progn
3429 (if (re-search-forward
3430 (concat "\\(^\\|\r\\)"
3431 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3432 nil t)
3433 (goto-char (match-end 0))
3434 ;; Heading not found, just insert it at the end
3435 (goto-char (point-max))
3436 (or (bolp) (insert "\n"))
3437 (insert "\n" heading "\n")
3438 (end-of-line 0))
3439 ;; Make the heading visible, and the following as well
3440 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3441 (if (re-search-forward
3442 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3443 nil t)
3444 (progn (goto-char (match-beginning 0)) (insert "\n")
3445 (beginning-of-line 0))
3446 (goto-char (point-max)) (insert "\n")))
3447 (goto-char (point-max)) (insert "\n"))
3448 ;; Paste
3449 (org-paste-subtree (1+ level))
3450 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3451 (if org-archive-mark-done
3452 (org-todo (length org-todo-keywords)))
3453 ;; Move cursor to right after the TODO keyword
3454 (when org-archive-stamp-time
3455 (beginning-of-line 1)
3456 (looking-at org-todo-line-regexp)
3457 (goto-char (or (match-end 2) (match-beginning 3)))
3458 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3459 (org-current-time))
3460 ")"))
3461 ;; Save the buffer, if it is not the same buffer.
3462 (if (not (eq this-buffer buffer)) (save-buffer))))
3463 ;; Here we are back in the original buffer. Everything seems to have
3464 ;; worked. So now cut the tree and finish up.
3465 (let (this-command) (org-cut-subtree))
3466 (if (looking-at "[ \t]*$") (kill-line))
3467 (message "Subtree archived %s"
3468 (if (eq this-buffer buffer)
3469 (concat "under heading: " heading)
3470 (concat "in file: " (abbreviate-file-name file))))))
3472 ;;; Completion
3474 (defun org-complete (&optional arg)
3475 "Perform completion on word at point.
3476 At the beginning of a headline, this completes TODO keywords as given in
3477 `org-todo-keywords'.
3478 If the current word is preceded by a backslash, completes the TeX symbols
3479 that are supported for HTML support.
3480 If the current word is preceded by \"#+\", completes special words for
3481 setting file options.
3482 At all other locations, this simply calls `ispell-complete-word'."
3483 (interactive "P")
3484 (catch 'exit
3485 (let* ((end (point))
3486 (beg1 (save-excursion
3487 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3488 (skip-chars-backward "a-zA-Z_@0-9")
3489 (point)))
3490 (beg (save-excursion
3491 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3492 (skip-chars-backward "a-zA-Z0-9_:$")
3493 (point)))
3494 (camel (equal (char-before beg) ?*))
3495 (tag (equal (char-before beg1) ?:))
3496 (texp (equal (char-before beg) ?\\))
3497 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3498 beg)
3499 "#+"))
3500 (completion-ignore-case opt)
3501 (type nil)
3502 (tbl nil)
3503 (table (cond
3504 (opt
3505 (setq type :opt)
3506 (mapcar (lambda (x)
3507 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3508 (cons (match-string 2 x) (match-string 1 x)))
3509 (org-split-string (org-get-current-options) "\n")))
3510 (texp
3511 (setq type :tex)
3512 org-html-entities)
3513 ((string-match "\\`\\*+[ \t]*\\'"
3514 (buffer-substring (point-at-bol) beg))
3515 (setq type :todo)
3516 (mapcar 'list org-todo-keywords))
3517 (camel
3518 (setq type :camel)
3519 (save-excursion
3520 (goto-char (point-min))
3521 (while (re-search-forward org-todo-line-regexp nil t)
3522 (push (list
3523 (if org-file-link-context-use-camel-case
3524 (org-make-org-heading-camel (match-string 3) t)
3525 (org-make-org-heading-search-string
3526 (match-string 3) t)))
3527 tbl)))
3528 tbl)
3529 (tag (setq type :tag beg beg1)
3530 (org-get-buffer-tags))
3531 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3532 (pattern (buffer-substring-no-properties beg end))
3533 (completion (try-completion pattern table)))
3534 (cond ((eq completion t)
3535 (if (equal type :opt)
3536 (insert (substring (cdr (assoc (upcase pattern) table))
3537 (length pattern)))))
3538 ((null completion)
3539 (message "Can't find completion for \"%s\"" pattern)
3540 (ding))
3541 ((not (string= pattern completion))
3542 (delete-region beg end)
3543 (if (string-match " +$" completion)
3544 (setq completion (replace-match "" t t completion)))
3545 (insert completion)
3546 (if (get-buffer-window "*Completions*")
3547 (delete-window (get-buffer-window "*Completions*")))
3548 (if (assoc completion table)
3549 (if (eq type :todo) (insert " ")
3550 (if (eq type :tag) (insert ":"))))
3551 (if (and (equal type :opt) (assoc completion table))
3552 (message "%s" (substitute-command-keys
3553 "Press \\[org-complete] again to insert example settings"))))
3555 (message "Making completion list...")
3556 (let ((list (sort (all-completions pattern table) 'string<)))
3557 (with-output-to-temp-buffer "*Completions*"
3558 (condition-case nil
3559 ;; Protection needed for XEmacs and emacs 21
3560 (display-completion-list list pattern)
3561 (error (display-completion-list list)))))
3562 (message "Making completion list...%s" "done"))))))
3564 ;;; Comments, TODO and DEADLINE
3566 (defun org-toggle-comment ()
3567 "Change the COMMENT state of an entry."
3568 (interactive)
3569 (save-excursion
3570 (org-back-to-heading)
3571 (if (looking-at (concat outline-regexp
3572 "\\( +\\<" org-comment-string "\\>\\)"))
3573 (replace-match "" t t nil 1)
3574 (if (looking-at outline-regexp)
3575 (progn
3576 (goto-char (match-end 0))
3577 (insert " " org-comment-string))))))
3579 (defvar org-last-todo-state-is-todo nil
3580 "This is non-nil when the last TODO state change led to a TODO state.
3581 If the last change removed the TODO tag or switched to DONE, then
3582 this is nil.")
3584 (defun org-todo (&optional arg)
3585 "Change the TODO state of an item.
3586 The state of an item is given by a keyword at the start of the heading,
3587 like
3588 *** TODO Write paper
3589 *** DONE Call mom
3591 The different keywords are specified in the variable `org-todo-keywords'.
3592 By default the available states are \"TODO\" and \"DONE\".
3593 So for this example: when the item starts with TODO, it is changed to DONE.
3594 When it starts with DONE, the DONE is removed. And when neither TODO nor
3595 DONE are present, add TODO at the beginning of the heading.
3597 With prefix arg, use completion to determine the new state. With numeric
3598 prefix arg, switch to that state."
3599 (interactive "P")
3600 (save-excursion
3601 (org-back-to-heading)
3602 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3603 (or (looking-at (concat " +" org-todo-regexp " *"))
3604 (looking-at " *"))
3605 (let* ((this (match-string 1))
3606 (completion-ignore-case t)
3607 (member (member this org-todo-keywords))
3608 (tail (cdr member))
3609 (state (cond
3610 ((equal arg '(4))
3611 ;; Read a state with completion
3612 (completing-read "State: " (mapcar (lambda(x) (list x))
3613 org-todo-keywords)
3614 nil t))
3615 ((eq arg 'right)
3616 (if this
3617 (if tail (car tail) nil)
3618 (car org-todo-keywords)))
3619 ((eq arg 'left)
3620 (if (equal member org-todo-keywords)
3622 (if this
3623 (nth (- (length org-todo-keywords) (length tail) 2)
3624 org-todo-keywords)
3625 org-done-string)))
3626 (arg
3627 ;; user requests a specific state
3628 (nth (1- (prefix-numeric-value arg))
3629 org-todo-keywords))
3630 ((null member) (car org-todo-keywords))
3631 ((null tail) nil) ;; -> first entry
3632 ((eq org-todo-interpretation 'sequence)
3633 (car tail))
3634 ((memq org-todo-interpretation '(type priority))
3635 (if (eq this-command last-command)
3636 (car tail)
3637 (if (> (length tail) 0) org-done-string nil)))
3638 (t nil)))
3639 (next (if state (concat " " state " ") " ")))
3640 (replace-match next t t)
3641 (setq org-last-todo-state-is-todo
3642 (not (equal state org-done-string)))
3643 (when org-log-done
3644 (if (equal state org-done-string)
3645 (org-log-done)
3646 (if (not this)
3647 (org-log-done t))))
3648 ;; Fixup tag positioning
3649 (and org-auto-align-tags (org-set-tags nil t))
3650 (run-hooks 'org-after-todo-state-change-hook)))
3651 ;; Fixup cursor location if close to the keyword
3652 (if (and (outline-on-heading-p)
3653 (not (bolp))
3654 (save-excursion (beginning-of-line 1)
3655 (looking-at org-todo-line-regexp))
3656 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3657 (progn
3658 (goto-char (or (match-end 2) (match-end 1)))
3659 (just-one-space))))
3661 (defun org-log-done (&optional undone)
3662 "Add a time stamp logging that a TODO entry has been closed.
3663 When UNDONE is non-nil, remove such a time stamp again."
3664 (interactive)
3665 (let (beg end col)
3666 (save-excursion
3667 (org-back-to-heading t)
3668 (setq beg (point))
3669 (looking-at (concat outline-regexp " *"))
3670 (goto-char (match-end 0))
3671 (setq col (current-column))
3672 (outline-next-heading)
3673 (setq end (point))
3674 (goto-char beg)
3675 (when (re-search-forward (concat
3676 "[\r\n]\\([ \t]*"
3677 (regexp-quote org-closed-string)
3678 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3679 (delete-region (match-beginning 1) (match-end 1)))
3680 (unless undone
3681 (org-back-to-heading t)
3682 (skip-chars-forward "^\n\r")
3683 (goto-char (min (1+ (point)) (point-max)))
3684 (when (not (member (char-before) '(?\r ?\n)))
3685 (insert "\n"))
3686 (indent-to col)
3687 (insert org-closed-string " "
3688 (format-time-string
3689 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3690 (org-current-time))
3691 "\n")))))
3693 (defun org-show-todo-tree (arg)
3694 "Make a compact tree which shows all headlines marked with TODO.
3695 The tree will show the lines where the regexp matches, and all higher
3696 headlines above the match.
3697 With \\[universal-argument] prefix, also show the DONE entries.
3698 With a numeric prefix N, construct a sparse tree for the Nth element
3699 of `org-todo-keywords'."
3700 (interactive "P")
3701 (let ((case-fold-search nil)
3702 (kwd-re
3703 (cond ((null arg) org-not-done-regexp)
3704 ((equal arg '(4)) org-todo-regexp)
3705 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3706 (regexp-quote (nth (1- (prefix-numeric-value arg))
3707 org-todo-keywords)))
3708 (t (error "Invalid prefix argument: %s" arg)))))
3709 (message "%d TODO entries found"
3710 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3712 (defun org-deadline ()
3713 "Insert the DEADLINE: string to make a deadline.
3714 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3715 to modify it to the correct date."
3716 (interactive)
3717 (insert
3718 org-deadline-string " "
3719 (format-time-string (car org-time-stamp-formats)
3720 (org-read-date nil 'to-time)))
3721 (message "%s" (substitute-command-keys
3722 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3724 (defun org-schedule ()
3725 "Insert the SCHEDULED: string to schedule a TODO item.
3726 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3727 to modify it to the correct date."
3728 (interactive)
3729 (insert
3730 org-scheduled-string " "
3731 (format-time-string (car org-time-stamp-formats)
3732 (org-read-date nil 'to-time)))
3733 (message "%s" (substitute-command-keys
3734 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3737 (defun org-occur (regexp &optional callback)
3738 "Make a compact tree which shows all matches of REGEXP.
3739 The tree will show the lines where the regexp matches, and all higher
3740 headlines above the match. It will also show the heading after the match,
3741 to make sure editing the matching entry is easy.
3742 If CALLBACK is non-nil, it is a function which is called to confirm
3743 that the match should indeed be shown."
3744 (interactive "sRegexp: ")
3745 (org-remove-occur-highlights nil nil t)
3746 (setq regexp (org-check-occur-regexp regexp))
3747 (let ((cnt 0))
3748 (save-excursion
3749 (goto-char (point-min))
3750 (hide-sublevels 1)
3751 (while (re-search-forward regexp nil t)
3752 (when (or (not callback)
3753 (save-match-data (funcall callback)))
3754 (setq cnt (1+ cnt))
3755 (org-highlight-new-match (match-beginning 0) (match-end 0))
3756 (org-show-hierarchy-above))))
3757 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
3758 nil 'local)
3759 (run-hooks 'org-occur-hook)
3760 (if (interactive-p)
3761 (message "%d match(es) for regexp %s" cnt regexp))
3762 cnt))
3764 (defun org-show-hierarchy-above ()
3765 "Make sure point and the headings hierarchy above is visible."
3766 (catch 'exit
3767 (if (org-on-heading-p t)
3768 (org-flag-heading nil) ; only show the heading
3769 (and (or (org-invisible-p) (org-invisible-p2))
3770 (org-show-hidden-entry))) ; show entire entry
3771 (save-excursion
3772 (and org-show-following-heading
3773 (outline-next-heading)
3774 (org-flag-heading nil))) ; show the next heading
3775 (when org-show-hierarchy-above
3776 (save-excursion ; show all higher headings
3777 (while (and (condition-case nil
3778 (progn (org-up-heading-all 1) t)
3779 (error nil))
3780 (not (bobp)))
3781 (org-flag-heading nil))))))
3783 ;; Overlay compatibility functions
3784 (defun org-make-overlay (beg end &optional buffer)
3785 (if (featurep 'xemacs)
3786 (make-extent beg end buffer)
3787 (make-overlay beg end buffer)))
3788 (defun org-delete-overlay (ovl)
3789 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
3790 (defun org-detatch-overlay (ovl)
3791 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
3792 (defun org-move-overlay (ovl beg end &optional buffer)
3793 (if (featurep 'xemacs)
3794 (set-extent-endpoints ovl beg end buffer)
3795 (move-overlay ovl beg end buffer)))
3796 (defun org-overlay-put (ovl prop value)
3797 (if (featurep 'xemacs)
3798 (set-extent-property ovl prop value)
3799 (overlay-put ovl prop value)))
3801 (defvar org-occur-highlights nil)
3802 (defun org-highlight-new-match (beg end)
3803 "Highlight from BEG to END and mark the highlight is an occur headline."
3804 (let ((ov (org-make-overlay beg end)))
3805 (org-overlay-put ov 'face 'secondary-selection)
3806 (push ov org-occur-highlights)))
3808 (defun org-remove-occur-highlights (&optional beg end noremove)
3809 "Remove the occur highlights from the buffer.
3810 BEG and END are ignored. If NOREMOVE is nil, remove this function
3811 from the `before-change-functions' in the current buffer."
3812 (interactive)
3813 (mapc 'org-delete-overlay org-occur-highlights)
3814 (setq org-occur-highlights nil)
3815 (unless noremove
3816 (remove-hook 'before-change-functions
3817 'org-remove-occur-highlights 'local)))
3819 ;;; Priorities
3821 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
3822 "Regular expression matching the priority indicator.")
3824 (defvar org-remove-priority-next-time nil)
3826 (defun org-priority-up ()
3827 "Increase the priority of the current item."
3828 (interactive)
3829 (org-priority 'up))
3831 (defun org-priority-down ()
3832 "Decrease the priority of the current item."
3833 (interactive)
3834 (org-priority 'down))
3836 (defun org-priority (&optional action)
3837 "Change the priority of an item by ARG.
3838 ACTION can be set, up, or down."
3839 (interactive)
3840 (setq action (or action 'set))
3841 (let (current new news have remove)
3842 (save-excursion
3843 (org-back-to-heading)
3844 (if (looking-at org-priority-regexp)
3845 (setq current (string-to-char (match-string 2))
3846 have t)
3847 (setq current org-default-priority))
3848 (cond
3849 ((eq action 'set)
3850 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
3851 (setq new (read-char-exclusive))
3852 (cond ((equal new ?\ ) (setq remove t))
3853 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
3854 (error "Priority must be between `%c' and `%c'"
3855 ?A org-lowest-priority))))
3856 ((eq action 'up)
3857 (setq new (1- current)))
3858 ((eq action 'down)
3859 (setq new (1+ current)))
3860 (t (error "Invalid action")))
3861 (setq new (min (max ?A (upcase new)) org-lowest-priority))
3862 (setq news (format "%c" new))
3863 (if have
3864 (if remove
3865 (replace-match "" t t nil 1)
3866 (replace-match news t t nil 2))
3867 (if remove
3868 (error "No priority cookie found in line")
3869 (looking-at org-todo-line-regexp)
3870 (if (match-end 2)
3871 (progn
3872 (goto-char (match-end 2))
3873 (insert " [#" news "]"))
3874 (goto-char (match-beginning 3))
3875 (insert "[#" news "] ")))))
3876 (if remove
3877 (message "Priority removed")
3878 (message "Priority of current item set to %s" news))))
3881 (defun org-get-priority (s)
3882 "Find priority cookie and return priority."
3883 (save-match-data
3884 (if (not (string-match org-priority-regexp s))
3885 (* 1000 (- org-lowest-priority org-default-priority))
3886 (* 1000 (- org-lowest-priority
3887 (string-to-char (match-string 2 s)))))))
3889 ;;; Timestamps
3891 (defvar org-last-changed-timestamp nil)
3893 (defun org-time-stamp (arg)
3894 "Prompt for a date/time and insert a time stamp.
3895 If the user specifies a time like HH:MM, or if this command is called
3896 with a prefix argument, the time stamp will contain date and time.
3897 Otherwise, only the date will be included. All parts of a date not
3898 specified by the user will be filled in from the current date/time.
3899 So if you press just return without typing anything, the time stamp
3900 will represent the current date/time. If there is already a timestamp
3901 at the cursor, it will be modified."
3902 (interactive "P")
3903 (let ((fmt (if arg (cdr org-time-stamp-formats)
3904 (car org-time-stamp-formats)))
3905 (org-time-was-given nil)
3906 time)
3907 (cond
3908 ((and (org-at-timestamp-p)
3909 (eq last-command 'org-time-stamp)
3910 (eq this-command 'org-time-stamp))
3911 (insert "--")
3912 (setq time (let ((this-command this-command))
3913 (org-read-date arg 'totime)))
3914 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3915 (insert (format-time-string fmt time)))
3916 ((org-at-timestamp-p)
3917 (setq time (let ((this-command this-command))
3918 (org-read-date arg 'totime)))
3919 (and (org-at-timestamp-p) (replace-match
3920 (setq org-last-changed-timestamp
3921 (format-time-string fmt time))
3922 t t))
3923 (message "Timestamp updated"))
3925 (setq time (let ((this-command this-command))
3926 (org-read-date arg 'totime)))
3927 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3928 (insert (format-time-string fmt time))))))
3930 (defun org-time-stamp-inactive (&optional arg)
3931 "Insert an inactive time stamp.
3932 An inactive time stamp is enclosed in square brackets instead of angle
3933 brackets. It is inactive in the sense that it does not trigger agenda entries,
3934 does not link to the calendar and cannot be changed with the S-cursor keys.
3935 So these are more for recording a certain time/date."
3936 ;; FIXME: Would it be better not to ask for a date/time here?
3937 (interactive "P")
3938 (let ((fmt (if arg (cdr org-time-stamp-formats)
3939 (car org-time-stamp-formats)))
3940 (org-time-was-given nil)
3941 time)
3942 (setq time (org-read-date arg 'totime))
3943 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
3944 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
3945 (insert (format-time-string fmt time))))
3947 (defvar org-date-ovl (org-make-overlay 1 1))
3948 (org-overlay-put org-date-ovl 'face 'org-warning)
3949 (org-detatch-overlay org-date-ovl)
3951 ;;; FIXME: Make the function take "Fri" as "next friday"
3952 ;;; because these are mostly being used to record the current time.
3953 (defun org-read-date (&optional with-time to-time)
3954 "Read a date and make things smooth for the user.
3955 The prompt will suggest to enter an ISO date, but you can also enter anything
3956 which will at least partially be understood by `parse-time-string'.
3957 Unrecognized parts of the date will default to the current day, month, year,
3958 hour and minute. For example,
3959 3-2-5 --> 2003-02-05
3960 feb 15 --> currentyear-02-15
3961 sep 12 9 --> 2009-09-12
3962 12:45 --> today 12:45
3963 22 sept 0:34 --> currentyear-09-22 0:34
3964 12 --> currentyear-currentmonth-12
3965 etc.
3966 The function understands only English month and weekday abbreviations,
3967 but this can be configured with the variables `parse-time-months' and
3968 `parse-time-weekdays'.
3970 While prompting, a calendar is popped up - you can also select the
3971 date with the mouse (button 1). The calendar shows a period of three
3972 months. To scroll it to other months, use the keys `>' and `<'.
3973 If you don't like the calendar, turn it off with
3974 \(setq org-popup-calendar-for-date-prompt nil)
3976 With optional argument TO-TIME, the date will immediately be converted
3977 to an internal time.
3978 With an optional argument WITH-TIME, the prompt will suggest to also
3979 insert a time. Note that when WITH-TIME is not set, you can still
3980 enter a time, and this function will inform the calling routine about
3981 this change. The calling routine may then choose to change the format
3982 used to insert the time stamp into the buffer to include the time."
3983 (require 'parse-time)
3984 (let* ((org-time-stamp-rounding-minutes
3985 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
3986 (ct (org-current-time))
3987 (default-time
3988 ;; Default time is either today, or, when entering a range,
3989 ;; the range start.
3990 (if (save-excursion
3991 (re-search-backward
3992 (concat org-ts-regexp "--\\=")
3993 (- (point) 20) t))
3994 (apply
3995 'encode-time
3996 (mapcar (lambda(x) (or x 0)) ;; FIXME: Problem with timezone?
3997 (parse-time-string (match-string 1))))
3998 ct))
3999 (calendar-move-hook nil)
4000 (view-diary-entries-initially nil)
4001 (timestr (format-time-string
4002 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
4003 (prompt (format "YYYY-MM-DD [%s]: " timestr))
4004 ans ans1 ans2
4005 second minute hour day month year tl)
4007 (if org-popup-calendar-for-date-prompt
4008 ;; Also show a calendar for date selection
4009 ;; Copied (with modifications) from planner.el by John Wiegley
4010 (save-excursion
4011 (save-window-excursion
4012 (calendar)
4013 (calendar-forward-day (- (time-to-days default-time)
4014 (calendar-absolute-from-gregorian
4015 (calendar-current-date))))
4016 (org-eval-in-calendar nil)
4017 (let* ((old-map (current-local-map))
4018 (map (copy-keymap calendar-mode-map))
4019 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
4020 (define-key map (kbd "RET") 'org-calendar-select)
4021 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
4022 'org-calendar-select-mouse)
4023 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
4024 'org-calendar-select-mouse)
4025 (define-key minibuffer-local-map [(meta shift left)]
4026 (lambda () (interactive)
4027 (org-eval-in-calendar '(calendar-backward-month 1))))
4028 (define-key minibuffer-local-map [(meta shift right)]
4029 (lambda () (interactive)
4030 (org-eval-in-calendar '(calendar-forward-month 1))))
4031 (define-key minibuffer-local-map [(shift up)]
4032 (lambda () (interactive)
4033 (org-eval-in-calendar '(calendar-backward-week 1))))
4034 (define-key minibuffer-local-map [(shift down)]
4035 (lambda () (interactive)
4036 (org-eval-in-calendar '(calendar-forward-week 1))))
4037 (define-key minibuffer-local-map [(shift left)]
4038 (lambda () (interactive)
4039 (org-eval-in-calendar '(calendar-backward-day 1))))
4040 (define-key minibuffer-local-map [(shift right)]
4041 (lambda () (interactive)
4042 (org-eval-in-calendar '(calendar-forward-day 1))))
4043 (define-key minibuffer-local-map ">"
4044 (lambda () (interactive)
4045 (org-eval-in-calendar '(scroll-calendar-left 1))))
4046 (define-key minibuffer-local-map "<"
4047 (lambda () (interactive)
4048 (org-eval-in-calendar '(scroll-calendar-right 1))))
4049 (unwind-protect
4050 (progn
4051 (use-local-map map)
4052 (setq ans (read-string prompt "" nil nil))
4053 (if (not (string-match "\\S-" ans)) (setq ans nil))
4054 (setq ans (or ans1 ans ans2)))
4055 (use-local-map old-map)))))
4056 ;; Naked prompt only
4057 (setq ans (read-string prompt "" nil timestr)))
4058 (org-detatch-overlay org-date-ovl)
4060 (if (string-match
4061 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
4062 (progn
4063 (setq year (if (match-end 2)
4064 (string-to-number (match-string 2 ans))
4065 (string-to-number (format-time-string "%Y")))
4066 month (string-to-number (match-string 3 ans))
4067 day (string-to-number (match-string 4 ans)))
4068 (if (< year 100) (setq year (+ 2000 year)))
4069 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
4070 t nil ans))))
4071 (setq tl (parse-time-string ans)
4072 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
4073 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
4074 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
4075 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
4076 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
4077 second (or (nth 0 tl) 0))
4078 (if (and (boundp 'org-time-was-given)
4079 (nth 2 tl))
4080 (setq org-time-was-given t))
4081 (if (< year 100) (setq year (+ 2000 year)))
4082 (if to-time
4083 (encode-time second minute hour day month year)
4084 (if (or (nth 1 tl) (nth 2 tl))
4085 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
4086 (format "%04d-%02d-%02d" year month day)))))
4088 (defun org-eval-in-calendar (form)
4089 "Eval FORM in the calendar window and return to current window.
4090 Also, store the cursor date in variable ans2."
4091 (let ((sw (selected-window)))
4092 (select-window (get-buffer-window "*Calendar*"))
4093 (eval form)
4094 (when (calendar-cursor-to-date)
4095 (let* ((date (calendar-cursor-to-date))
4096 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4097 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4098 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4099 (select-window sw)))
4101 (defun org-calendar-select ()
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)
4105 (when (calendar-cursor-to-date)
4106 (let* ((date (calendar-cursor-to-date))
4107 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4108 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4109 (if (active-minibuffer-window) (exit-minibuffer))))
4111 (defun org-calendar-select-mouse (ev)
4112 "Return to `org-read-date' with the date currently selected.
4113 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4114 (interactive "e")
4115 (mouse-set-point ev)
4116 (when (calendar-cursor-to-date)
4117 (let* ((date (calendar-cursor-to-date))
4118 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4119 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4120 (if (active-minibuffer-window) (exit-minibuffer))))
4122 (defun org-check-deadlines (ndays)
4123 "Check if there are any deadlines due or past due.
4124 A deadline is considered due if it happens within `org-deadline-warning-days'
4125 days from today's date. If the deadline appears in an entry marked DONE,
4126 it is not shown. The prefix arg NDAYS can be used to test that many
4127 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4128 (interactive "P")
4129 (let* ((org-warn-days
4130 (cond
4131 ((equal ndays '(4)) 100000)
4132 (ndays (prefix-numeric-value ndays))
4133 (t org-deadline-warning-days)))
4134 (case-fold-search nil)
4135 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4136 (callback
4137 (lambda ()
4138 (and (let ((d1 (time-to-days (current-time)))
4139 (d2 (time-to-days
4140 (org-time-string-to-time (match-string 1)))))
4141 (< (- d2 d1) org-warn-days))
4142 (not (org-entry-is-done-p))))))
4143 (message "%d deadlines past-due or due within %d days"
4144 (org-occur regexp callback)
4145 org-warn-days)))
4147 (defun org-evaluate-time-range (&optional to-buffer)
4148 "Evaluate a time range by computing the difference between start and end.
4149 Normally the result is just printed in the echo area, but with prefix arg
4150 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4151 If the time range is actually in a table, the result is inserted into the
4152 next column.
4153 For time difference computation, a year is assumed to be exactly 365
4154 days in order to avoid rounding problems."
4155 (interactive "P")
4156 (save-excursion
4157 (unless (org-at-date-range-p)
4158 (goto-char (point-at-bol))
4159 (re-search-forward org-tr-regexp (point-at-eol) t))
4160 (if (not (org-at-date-range-p))
4161 (error "Not at a time-stamp range, and none found in current line")))
4162 (let* ((ts1 (match-string 1))
4163 (ts2 (match-string 2))
4164 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4165 (match-end (match-end 0))
4166 (time1 (org-time-string-to-time ts1))
4167 (time2 (org-time-string-to-time ts2))
4168 (t1 (time-to-seconds time1))
4169 (t2 (time-to-seconds time2))
4170 (diff (abs (- t2 t1)))
4171 (negative (< (- t2 t1) 0))
4172 ;; (ys (floor (* 365 24 60 60)))
4173 (ds (* 24 60 60))
4174 (hs (* 60 60))
4175 (fy "%dy %dd %02d:%02d")
4176 (fy1 "%dy %dd")
4177 (fd "%dd %02d:%02d")
4178 (fd1 "%dd")
4179 (fh "%02d:%02d")
4180 y d h m align)
4181 ;; FIXME: Should I re-introduce years, make year refer to same date?
4182 ;; This would be the only useful way to have years, actually.
4183 (if havetime
4184 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4186 d (floor (/ diff ds)) diff (mod diff ds)
4187 h (floor (/ diff hs)) diff (mod diff hs)
4188 m (floor (/ diff 60)))
4189 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4191 d (floor (+ (/ diff ds) 0.5))
4192 h 0 m 0))
4193 (if (not to-buffer)
4194 (message (org-make-tdiff-string y d h m))
4195 (when (org-at-table-p)
4196 (goto-char match-end)
4197 (setq align t)
4198 (and (looking-at " *|") (goto-char (match-end 0))))
4199 (if (looking-at
4200 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4201 (replace-match ""))
4202 (if negative (insert " -"))
4203 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4204 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4205 (insert " " (format fh h m))))
4206 (if align (org-table-align))
4207 (message "Time difference inserted"))))
4209 (defun org-make-tdiff-string (y d h m)
4210 (let ((fmt "")
4211 (l nil))
4212 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4213 l (push y l)))
4214 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4215 l (push d l)))
4216 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4217 l (push h l)))
4218 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4219 l (push m l)))
4220 (apply 'format fmt (nreverse l))))
4222 (defun org-time-string-to-time (s)
4223 (apply 'encode-time (org-parse-time-string s)))
4225 (defun org-parse-time-string (s &optional nodefault)
4226 "Parse the standard Org-mode time string.
4227 This should be a lot faster than the normal `parse-time-string'.
4228 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4229 hour and minute fields will be nil if not given."
4230 (if (string-match org-ts-regexp1 s)
4231 (list 0
4232 (if (or (match-beginning 8) (not nodefault))
4233 (string-to-number (or (match-string 8 s) "0")))
4234 (if (or (match-beginning 7) (not nodefault))
4235 (string-to-number (or (match-string 7 s) "0")))
4236 (string-to-number (match-string 4 s))
4237 (string-to-number (match-string 3 s))
4238 (string-to-number (match-string 2 s))
4239 nil nil nil)
4240 (make-list 9 0)))
4242 (defun org-timestamp-up (&optional arg)
4243 "Increase the date item at the cursor by one.
4244 If the cursor is on the year, change the year. If it is on the month or
4245 the day, change that.
4246 With prefix ARG, change by that many units."
4247 (interactive "p")
4248 (org-timestamp-change (prefix-numeric-value arg)))
4250 (defun org-timestamp-down (&optional arg)
4251 "Decrease the date item at the cursor by one.
4252 If the cursor is on the year, change the year. If it is on the month or
4253 the day, change that.
4254 With prefix ARG, change by that many units."
4255 (interactive "p")
4256 (org-timestamp-change (- (prefix-numeric-value arg))))
4258 (defun org-timestamp-up-day (&optional arg)
4259 "Increase the date in the time stamp by one day.
4260 With prefix ARG, change that many days."
4261 (interactive "p")
4262 (if (and (not (org-at-timestamp-p))
4263 (org-on-heading-p))
4264 (org-todo 'up)
4265 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4267 (defun org-timestamp-down-day (&optional arg)
4268 "Decrease the date in the time stamp by one day.
4269 With prefix ARG, change that many days."
4270 (interactive "p")
4271 (if (and (not (org-at-timestamp-p))
4272 (org-on-heading-p))
4273 (org-todo 'down)
4274 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4276 (defsubst org-pos-in-match-range (pos n)
4277 (and (match-beginning n)
4278 (<= (match-beginning n) pos)
4279 (>= (match-end n) pos)))
4281 (defun org-at-timestamp-p ()
4282 "Determine if the cursor is in or at a timestamp."
4283 (interactive)
4284 (let* ((tsr org-ts-regexp2)
4285 (pos (point))
4286 (ans (or (looking-at tsr)
4287 (save-excursion
4288 (skip-chars-backward "^<\n\r\t")
4289 (if (> (point) 1) (backward-char 1))
4290 (and (looking-at tsr)
4291 (> (- (match-end 0) pos) -1))))))
4292 (and (boundp 'org-ts-what)
4293 (setq org-ts-what
4294 (cond
4295 ((org-pos-in-match-range pos 2) 'year)
4296 ((org-pos-in-match-range pos 3) 'month)
4297 ((org-pos-in-match-range pos 7) 'hour)
4298 ((org-pos-in-match-range pos 8) 'minute)
4299 ((or (org-pos-in-match-range pos 4)
4300 (org-pos-in-match-range pos 5)) 'day)
4301 (t 'day))))
4302 ans))
4304 (defun org-timestamp-change (n &optional what)
4305 "Change the date in the time stamp at point.
4306 The date will be changed by N times WHAT. WHAT can be `day', `month',
4307 `year', `minute', `second'. If WHAT is not given, the cursor position
4308 in the timestamp determines what will be changed."
4309 (let ((fmt (car org-time-stamp-formats))
4310 org-ts-what
4311 (pos (point))
4312 ts time time0)
4313 (if (not (org-at-timestamp-p))
4314 (error "Not at a timestamp"))
4315 (setq org-ts-what (or what org-ts-what))
4316 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4317 (- (match-end 0) (match-beginning 0))))
4319 (cdr org-time-stamp-formats)
4320 (car org-time-stamp-formats)))
4321 (setq ts (match-string 0))
4322 (replace-match "")
4323 (setq time0 (org-parse-time-string ts))
4324 (setq time
4325 (apply 'encode-time
4326 (append
4327 (list (or (car time0) 0))
4328 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4329 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4330 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4331 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4332 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4333 (nthcdr 6 time0))))
4334 (if (eq what 'calendar)
4335 (let ((cal-date
4336 (save-excursion
4337 (save-match-data
4338 (set-buffer "*Calendar*")
4339 (calendar-cursor-to-date)))))
4340 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4341 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4342 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4343 (setcar time0 (or (car time0) 0))
4344 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4345 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4346 (setq time (apply 'encode-time time0))))
4347 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4348 (goto-char pos)
4349 ;; Try to recenter the calendar window, if any
4350 (if (and org-calendar-follow-timestamp-change
4351 (get-buffer-window "*Calendar*" t)
4352 (memq org-ts-what '(day month year)))
4353 (org-recenter-calendar (time-to-days time)))))
4355 (defun org-recenter-calendar (date)
4356 "If the calendar is visible, recenter it to DATE."
4357 (let* ((win (selected-window))
4358 (cwin (get-buffer-window "*Calendar*" t))
4359 (calendar-move-hook nil))
4360 (when cwin
4361 (select-window cwin)
4362 (calendar-goto-date (if (listp date) date
4363 (calendar-gregorian-from-absolute date)))
4364 (select-window win))))
4366 (defun org-goto-calendar (&optional arg)
4367 "Go to the Emacs calendar at the current date.
4368 If there is a time stamp in the current line, go to that date.
4369 A prefix ARG can be used to force the current date."
4370 (interactive "P")
4371 (let ((tsr org-ts-regexp) diff
4372 (calendar-move-hook nil)
4373 (view-diary-entries-initially nil))
4374 (if (or (org-at-timestamp-p)
4375 (save-excursion
4376 (beginning-of-line 1)
4377 (looking-at (concat ".*" tsr))))
4378 (let ((d1 (time-to-days (current-time)))
4379 (d2 (time-to-days
4380 (org-time-string-to-time (match-string 1)))))
4381 (setq diff (- d2 d1))))
4382 (calendar)
4383 (calendar-goto-today)
4384 (if (and diff (not arg)) (calendar-forward-day diff))))
4386 (defun org-date-from-calendar ()
4387 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4388 If there is already a time stamp at the cursor position, update it."
4389 (interactive)
4390 (org-timestamp-change 0 'calendar))
4392 ;;; Agenda, and Diary Integration
4394 ;;; Define the mode
4396 (defvar org-agenda-mode-map (make-sparse-keymap)
4397 "Keymap for `org-agenda-mode'.")
4399 (defvar org-agenda-menu) ; defined later in this file.
4400 (defvar org-agenda-follow-mode nil)
4401 (defvar org-agenda-show-log nil)
4402 (defvar org-agenda-buffer-name "*Org Agenda*")
4403 (defvar org-agenda-redo-command nil)
4404 (defvar org-agenda-mode-hook nil)
4405 (defvar org-agenda-type nil)
4406 (defvar org-agenda-force-single-file nil)
4408 ;;;###autoload
4409 (defun org-agenda-mode ()
4410 "Mode for time-sorted view on action items in Org-mode files.
4412 The following commands are available:
4414 \\{org-agenda-mode-map}"
4415 (interactive)
4416 (kill-all-local-variables)
4417 (setq major-mode 'org-agenda-mode)
4418 (setq mode-name "Org-Agenda")
4419 (use-local-map org-agenda-mode-map)
4420 (easy-menu-add org-agenda-menu)
4421 (if org-startup-truncated (setq truncate-lines t))
4422 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4423 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4424 (unless org-agenda-keep-modes
4425 (setq org-agenda-follow-mode nil
4426 org-agenda-show-log nil))
4427 (easy-menu-change
4428 '("Agenda") "Agenda Files"
4429 (append
4430 (list
4431 (vector
4432 (if (get 'org-agenda-files 'org-restrict)
4433 "Restricted to single file"
4434 "Edit File List")
4435 '(org-edit-agenda-file-list)
4436 (not (get 'org-agenda-files 'org-restrict)))
4437 "--")
4438 (mapcar 'org-file-menu-entry (org-agenda-files))))
4439 (org-agenda-set-mode-name)
4440 (apply
4441 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4442 (list 'org-agenda-mode-hook)))
4444 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4445 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
4446 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4447 (define-key org-agenda-mode-map " " 'org-agenda-show)
4448 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4449 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4450 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4451 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4452 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4453 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4454 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4455 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4456 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4457 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4458 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4459 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4461 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4462 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4463 (while l (define-key org-agenda-mode-map
4464 (int-to-string (pop l)) 'digit-argument)))
4466 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4467 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4468 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4469 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4470 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4471 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4472 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4473 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4474 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4475 (define-key org-agenda-mode-map "n" 'next-line)
4476 (define-key org-agenda-mode-map "p" 'previous-line)
4477 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4478 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4479 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4480 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4481 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4482 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4483 (eval-after-load "calendar"
4484 '(define-key calendar-mode-map org-calendar-to-agenda-key
4485 'org-calendar-goto-agenda))
4486 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4487 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4488 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4489 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4490 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4491 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4492 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4493 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4494 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4495 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4496 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4497 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4498 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4499 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4500 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4501 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4502 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4503 "Local keymap for agenda entries from Org-mode.")
4505 (define-key org-agenda-keymap
4506 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4507 (define-key org-agenda-keymap
4508 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4509 (define-key org-agenda-keymap [follow-link] 'mouse-face)
4510 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4511 '("Agenda"
4512 ("Agenda Files")
4513 "--"
4514 ["Show" org-agenda-show t]
4515 ["Go To (other window)" org-agenda-goto t]
4516 ["Go To (one window)" org-agenda-switch-to t]
4517 ["Follow Mode" org-agenda-follow-mode
4518 :style toggle :selected org-agenda-follow-mode :active t]
4519 "--"
4520 ["Cycle TODO" org-agenda-todo t]
4521 ("Tags"
4522 ["Show all Tags" org-agenda-show-tags t]
4523 ["Set Tags" org-agenda-set-tags t])
4524 ("Reschedule"
4525 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4526 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4527 "--"
4528 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4529 ("Priority"
4530 ["Set Priority" org-agenda-priority t]
4531 ["Increase Priority" org-agenda-priority-up t]
4532 ["Decrease Priority" org-agenda-priority-down t]
4533 ["Show Priority" org-agenda-show-priority t])
4534 "--"
4535 ;; ["New agenda command" org-agenda t]
4536 ["Rebuild buffer" org-agenda-redo t]
4537 "--"
4538 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4539 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4540 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4541 "--"
4542 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4543 :style radio :selected (equal org-agenda-ndays 1)]
4544 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4545 :style radio :selected (equal org-agenda-ndays 7)]
4546 "--"
4547 ["Show Logbook entries" org-agenda-log-mode
4548 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4549 ["Include Diary" org-agenda-toggle-diary
4550 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4551 ["Use Time Grid" org-agenda-toggle-time-grid
4552 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4553 "--"
4554 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4555 ("Calendar Commands"
4556 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4557 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4558 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4559 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4560 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4561 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4562 "--"
4563 ["Quit" org-agenda-quit t]
4564 ["Exit and Release Buffers" org-agenda-exit t]
4567 ;;;###autoload
4568 (defun org-agenda (arg)
4569 "Dispatch agenda commands to collect entries to the agenda buffer.
4570 Prompts for a character to select a command. Any prefix arg will be passed
4571 on to the selected command. The default selections are:
4573 a Call `org-agenda' to display the agenda for the current day or week.
4574 t Call `org-todo-list' to display the global todo list.
4575 T Call `org-todo-list' to display the global todo list, select only
4576 entries with a specific TODO keyword (the user gets a prompt).
4577 m Call `org-tags-view' to display headlines with tags matching
4578 a condition (the user is prompted for the condition).
4579 M Like `m', but select only TODO entries, no ordinary headlines.
4581 More commands can be added by configuring the variable
4582 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4583 searches can be pre-defined in this way.
4585 If the current buffer is in Org-mode and visiting a file, you can also
4586 first press `1' to indicate that the agenda should be temporarily (until the
4587 next use of \\[org-agenda]) restricted to the current file."
4588 (interactive "P")
4589 (catch 'exit
4590 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
4591 (custom org-agenda-custom-commands)
4592 c entry key type string)
4593 (put 'org-agenda-files 'org-restrict nil)
4594 (save-window-excursion
4595 (delete-other-windows)
4596 (switch-to-buffer-other-window " *Agenda Commands*")
4597 (erase-buffer)
4598 (insert
4599 "Press key for an agenda command:
4600 --------------------------------
4601 a Agenda for current week or day
4602 t List of all TODO entries T Entries with special TODO kwd
4603 m Match a TAGS query M Like m, but only TODO entries
4604 C Configure your own agenda commands")
4605 (while (setq entry (pop custom))
4606 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4607 (insert (format "\n%-4s%-14s: %s"
4609 (cond
4610 ((eq type 'tags) "Tags query")
4611 ((eq type 'todo) "TODO keyword")
4612 ((eq type 'tags-tree) "Tags tree")
4613 ((eq type 'todo-tree) "TODO kwd tree")
4614 ((eq type 'occur-tree) "Occur tree")
4615 (t "???"))
4616 (org-string-props string 'face 'org-link))))
4617 (goto-char (point-min))
4618 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4619 (message "Press key for agenda command%s"
4620 (if restrict-ok ", or [1] to restrict to current file" ""))
4621 (setq c (read-char-exclusive))
4622 (message "")
4623 (when (equal c ?1)
4624 (if restrict-ok
4625 (put 'org-agenda-files 'org-restrict (list buffer-file-name))
4626 (error "Cannot restrict agenda to current buffer"))
4627 (message "Press key for agenda command%s"
4628 (if restrict-ok " (restricted to current file)" ""))
4629 (setq c (read-char-exclusive))
4630 (message "")))
4631 (require 'calendar) ; FIXME: can we avoid this for some commands?
4632 ;; For example the todo list should not need it (but does...)
4633 (cond
4634 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4635 ((equal c ?a) (call-interactively 'org-agenda-list))
4636 ((equal c ?t) (call-interactively 'org-todo-list))
4637 ((equal c ?T)
4638 (setq current-prefix-arg (or arg '(4)))
4639 (call-interactively 'org-todo-list))
4640 ((equal c ?m) (call-interactively 'org-tags-view))
4641 ((equal c ?M)
4642 (setq current-prefix-arg (or arg '(4)))
4643 (call-interactively 'org-tags-view))
4644 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4645 (setq type (nth 1 entry) string (nth 2 entry))
4646 (cond
4647 ((eq type 'tags)
4648 (org-tags-view current-prefix-arg string))
4649 ((eq type 'todo)
4650 (org-todo-list string))
4651 ((eq type 'tags-tree)
4652 (org-check-for-org-mode)
4653 (org-tags-sparse-tree current-prefix-arg string))
4654 ((eq type 'todo-tree)
4655 (org-check-for-org-mode)
4656 (org-occur (concat "^" outline-regexp "[ \t]*"
4657 (regexp-quote string) "\\>")))
4658 ((eq type 'occur-tree)
4659 (org-check-for-org-mode)
4660 (org-occur string))
4661 (t (error "Invalid custom agenda command type %s" type))))
4662 (t (error "Invalid key"))))))
4664 (defun org-check-for-org-mode ()
4665 "Make sure current buffer is in org-mode. Error if not."
4666 (or (eq major-mode 'org-mode)
4667 (error "Cannot execute org-mode agenda command on buffer in %s."
4668 major-mode)))
4670 (defun org-fit-agenda-window ()
4671 "Fit the window to the buffer size."
4672 (and org-fit-agenda-window
4673 (fboundp 'fit-window-to-buffer)
4674 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4675 (/ (frame-height) 2))))
4677 (defun org-agenda-files (&optional unrestricted)
4678 "Get the list of agenda files.
4679 Optional UNRESTRICTED means return the full list even if a restriction
4680 is currently in place."
4681 (cond
4682 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
4683 ((stringp org-agenda-files) (org-read-agenda-file-list))
4684 ((listp org-agenda-files) org-agenda-files)
4685 (t (error "Invalid value of `org-agenda-files'"))))
4687 (defvar org-window-configuration)
4689 (defun org-edit-agenda-file-list ()
4690 "Edit the list of agenda files.
4691 Depending on setup, this either uses customize to edit the variable
4692 `org-agenda-files', or it visits the file that is holding the list. In the
4693 latter case, the buffer is set up in a way that saving it automatically kills
4694 the buffer and restores the previous window configuration."
4695 (interactive)
4696 (if (stringp org-agenda-files)
4697 (let ((cw (current-window-configuration)))
4698 (find-file org-agenda-files)
4699 (set (make-local-variable 'org-window-configuration) cw)
4700 (org-add-hook 'after-save-hook
4701 (lambda ()
4702 (set-window-configuration
4703 (prog1 org-window-configuration
4704 (kill-buffer (current-buffer))))
4705 (org-install-agenda-files-menu)
4706 (message "New agenda file list installed"))
4707 nil 'local)
4708 (message (substitute-command-keys
4709 "Edit list and finish with \\[save-buffer]")))
4710 (customize-variable 'org-agenda-files)))
4712 (defun org-store-new-agenda-file-list (list)
4713 "Set new value for the agenda file list and save it correcly."
4714 (if (stringp org-agenda-files)
4715 (let ((f org-agenda-files) b)
4716 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
4717 (with-temp-file f
4718 (insert (mapconcat 'identity list) "\n") "\n"))
4719 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
4720 (setq org-agenda-files list)
4721 (customize-save-variable 'org-agenda-files org-agenda-files))))
4723 (defun org-read-agenda-file-list ()
4724 "Read the list of agenda files from a file."
4725 (when (stringp org-agenda-files)
4726 (with-temp-buffer
4727 (insert-file-contents org-agenda-files)
4728 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
4730 (defvar org-agenda-markers nil
4731 "List of all currently active markers created by `org-agenda'.")
4732 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4733 "Creation time of the last agenda marker.")
4735 (defun org-agenda-new-marker (&optional pos)
4736 "Return a new agenda marker.
4737 Org-mode keeps a list of these markers and resets them when they are
4738 no longer in use."
4739 (let ((m (copy-marker (or pos (point)))))
4740 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
4741 (push m org-agenda-markers)
4744 (defun org-agenda-maybe-reset-markers (&optional force)
4745 "Reset markers created by `org-agenda'. But only if they are old enough."
4746 (if (or force
4747 (> (- (time-to-seconds (current-time))
4748 org-agenda-last-marker-time)
4750 (while org-agenda-markers
4751 (move-marker (pop org-agenda-markers) nil))))
4753 (defvar org-agenda-new-buffers nil
4754 "Buffers created to visit agenda files.")
4756 (defun org-get-agenda-file-buffer (file)
4757 "Get a buffer visiting FILE. If the buffer needs to be created, add
4758 it to the list of buffers which might be released later."
4759 (let ((buf (find-buffer-visiting file)))
4760 (if buf
4761 buf ; just return it
4762 ;; Make a new buffer and remember it
4763 (setq buf (find-file-noselect file))
4764 (if buf (push buf org-agenda-new-buffers))
4765 buf)))
4767 (defun org-release-buffers (blist)
4768 "Release all buffers in list, asking the user for confirmation when needed.
4769 When a buffer is unmodified, it is just killed. When modified, it is saved
4770 \(if the user agrees) and then killed."
4771 (let (buf file)
4772 (while (setq buf (pop blist))
4773 (setq file (buffer-file-name buf))
4774 (when (and (buffer-modified-p buf)
4775 file
4776 (y-or-n-p (format "Save file %s? " file)))
4777 (with-current-buffer buf (save-buffer)))
4778 (kill-buffer buf))))
4780 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
4782 (defun org-timeline (&optional include-all keep-modes)
4783 "Show a time-sorted view of the entries in the current org file.
4784 Only entries with a time stamp of today or later will be listed. With
4785 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
4786 under the current date.
4787 If the buffer contains an active region, only check the region for
4788 dates."
4789 (interactive "P")
4790 (require 'calendar)
4791 (org-agenda-maybe-reset-markers 'force)
4792 (org-compile-prefix-format org-timeline-prefix-format)
4793 (let* ((dopast t)
4794 (dotodo include-all)
4795 (doclosed org-agenda-show-log)
4796 (org-agenda-keep-modes keep-modes)
4797 (entry buffer-file-name)
4798 (org-agenda-files (list buffer-file-name))
4799 (date (calendar-current-date))
4800 (win (selected-window))
4801 (pos1 (point))
4802 (beg (if (org-region-active-p) (region-beginning) (point-min)))
4803 (end (if (org-region-active-p) (region-end) (point-max)))
4804 (day-numbers (org-get-all-dates beg end 'no-ranges
4805 t doclosed)) ; always include today
4806 (today (time-to-days (current-time)))
4807 (org-respect-restriction t)
4808 (past t)
4809 args
4810 s e rtn d)
4811 (setq org-agenda-redo-command
4812 (list 'progn
4813 (list 'switch-to-buffer-other-window (current-buffer))
4814 (list 'org-timeline (list 'quote include-all) t)))
4815 (if (not dopast)
4816 ;; Remove past dates from the list of dates.
4817 (setq day-numbers (delq nil (mapcar (lambda(x)
4818 (if (>= x today) x nil))
4819 day-numbers))))
4820 (switch-to-buffer-other-window
4821 (get-buffer-create org-agenda-buffer-name))
4822 (setq buffer-read-only nil)
4823 (erase-buffer)
4824 (org-agenda-mode) (setq buffer-read-only nil)
4825 (set (make-local-variable 'org-agenda-type) 'timeline)
4826 (if doclosed (push :closed args))
4827 (push :timestamp args)
4828 (if dotodo (push :todo args))
4829 (while (setq d (pop day-numbers))
4830 (if (and (>= d today)
4831 dopast
4832 past)
4833 (progn
4834 (setq past nil)
4835 (insert (make-string 79 ?-) "\n")))
4836 (setq date (calendar-gregorian-from-absolute d))
4837 (setq s (point))
4838 (setq rtn (apply 'org-agenda-get-day-entries
4839 entry date args))
4840 (if (or rtn (equal d today))
4841 (progn
4842 (insert (calendar-day-name date) " "
4843 (number-to-string (extract-calendar-day date)) " "
4844 (calendar-month-name (extract-calendar-month date)) " "
4845 (number-to-string (extract-calendar-year date)) "\n")
4846 (put-text-property s (1- (point)) 'face
4847 'org-link)
4848 (if (equal d today)
4849 (put-text-property s (1- (point)) 'org-today t))
4850 (insert (org-finalize-agenda-entries rtn) "\n")
4851 (put-text-property s (1- (point)) 'day d))))
4852 (goto-char (point-min))
4853 (setq buffer-read-only t)
4854 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
4855 (point-min)))
4856 (when (not org-select-timeline-window)
4857 (select-window win)
4858 (goto-char pos1))))
4860 ;;;###autoload
4861 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
4862 "Produce a weekly view from all files in variable `org-agenda-files'.
4863 The view will be for the current week, but from the overview buffer you
4864 will be able to go to other weeks.
4865 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
4866 also be shown, under the current date.
4867 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
4868 on the days are also shown. See the variable `org-log-done' for how
4869 to turn on logging.
4870 START-DAY defaults to TODAY, or to the most recent match for the weekday
4871 given in `org-agenda-start-on-weekday'.
4872 NDAYS defaults to `org-agenda-ndays'."
4873 (interactive "P")
4874 (org-agenda-maybe-reset-markers 'force)
4875 (org-compile-prefix-format org-agenda-prefix-format)
4876 (require 'calendar)
4877 (let* ((org-agenda-start-on-weekday
4878 (if (or (equal ndays 1)
4879 (and (null ndays) (equal 1 org-agenda-ndays)))
4880 nil org-agenda-start-on-weekday))
4881 (org-agenda-keep-modes keep-modes)
4882 (thefiles (copy-sequence (org-agenda-files))) ;; FIXME: Why copy???
4883 (files thefiles)
4884 (win (selected-window))
4885 (today (time-to-days (current-time)))
4886 (sd (or start-day today))
4887 (start (if (or (null org-agenda-start-on-weekday)
4888 (< org-agenda-ndays 7))
4890 (let* ((nt (calendar-day-of-week
4891 (calendar-gregorian-from-absolute sd)))
4892 (n1 org-agenda-start-on-weekday)
4893 (d (- nt n1)))
4894 (- sd (+ (if (< d 0) 7 0) d)))))
4895 (day-numbers (list start))
4896 (inhibit-redisplay t)
4897 s e rtn rtnall file date d start-pos end-pos todayp nd)
4898 (setq org-agenda-redo-command
4899 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
4900 ;; Make the list of days
4901 (setq ndays (or ndays org-agenda-ndays)
4902 nd ndays)
4903 (while (> ndays 1)
4904 (push (1+ (car day-numbers)) day-numbers)
4905 (setq ndays (1- ndays)))
4906 (setq day-numbers (nreverse day-numbers))
4907 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
4908 (progn
4909 (delete-other-windows)
4910 (switch-to-buffer-other-window
4911 (get-buffer-create org-agenda-buffer-name))))
4912 (setq buffer-read-only nil)
4913 (erase-buffer)
4914 (org-agenda-mode) (setq buffer-read-only nil)
4915 (set (make-local-variable 'org-agenda-type) 'agenda)
4916 (set (make-local-variable 'starting-day) (car day-numbers))
4917 (set (make-local-variable 'include-all-loc) include-all)
4918 (when (and (or include-all org-agenda-include-all-todo)
4919 (member today day-numbers))
4920 (setq files thefiles
4921 rtnall nil)
4922 (while (setq file (pop files))
4923 (catch 'nextfile
4924 (org-check-agenda-file file)
4925 (setq date (calendar-gregorian-from-absolute today)
4926 rtn (org-agenda-get-day-entries
4927 file date :todo))
4928 (setq rtnall (append rtnall rtn))))
4929 (when rtnall
4930 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
4931 (add-text-properties (point-min) (1- (point))
4932 (list 'face 'org-link))
4933 (insert (org-finalize-agenda-entries rtnall) "\n")))
4934 (while (setq d (pop day-numbers))
4935 (setq date (calendar-gregorian-from-absolute d)
4936 s (point))
4937 (if (or (setq todayp (= d today))
4938 (and (not start-pos) (= d sd)))
4939 (setq start-pos (point))
4940 (if (and start-pos (not end-pos))
4941 (setq end-pos (point))))
4942 (setq files thefiles
4943 rtnall nil)
4944 (while (setq file (pop files))
4945 (catch 'nextfile
4946 (org-check-agenda-file file)
4947 (if org-agenda-show-log
4948 (setq rtn (org-agenda-get-day-entries
4949 file date
4950 :deadline :scheduled :timestamp :closed))
4951 (setq rtn (org-agenda-get-day-entries
4952 file date
4953 :deadline :scheduled :timestamp)))
4954 (setq rtnall (append rtnall rtn))))
4955 (if org-agenda-include-diary
4956 (progn
4957 (require 'diary-lib)
4958 (setq rtn (org-get-entries-from-diary date))
4959 (setq rtnall (append rtnall rtn))))
4960 (if (or rtnall org-agenda-show-all-dates)
4961 (progn
4962 (insert (format "%-9s %2d %s %4d\n"
4963 (calendar-day-name date)
4964 (extract-calendar-day date)
4965 (calendar-month-name (extract-calendar-month date))
4966 (extract-calendar-year date)))
4967 (put-text-property s (1- (point)) 'face
4968 'org-link)
4969 (if rtnall (insert
4970 (org-finalize-agenda-entries
4971 (org-agenda-add-time-grid-maybe
4972 rtnall nd todayp))
4973 "\n"))
4974 (put-text-property s (1- (point)) 'day d))))
4975 (goto-char (point-min))
4976 (setq buffer-read-only t)
4977 (org-fit-agenda-window)
4978 (unless (and (pos-visible-in-window-p (point-min))
4979 (pos-visible-in-window-p (point-max)))
4980 (goto-char (1- (point-max)))
4981 (recenter -1)
4982 (if (not (pos-visible-in-window-p (or start-pos 1)))
4983 (progn
4984 (goto-char (or start-pos 1))
4985 (recenter 1))))
4986 (goto-char (or start-pos 1))
4987 (if (not org-select-agenda-window) (select-window win))
4988 (message "")))
4990 (defvar org-select-this-todo-keyword nil)
4992 ;;;###autoload
4993 (defun org-todo-list (arg &optional keep-modes)
4994 "Show all TODO entries from all agenda file in a single list.
4995 The prefix arg can be used to select a specific TODO keyword and limit
4996 the list to these. When using \\[universal-argument], you will be prompted
4997 for a keyword. A numeric prefix directly selects the Nth keyword in
4998 `org-todo-keywords'."
4999 (interactive "P")
5000 (org-agenda-maybe-reset-markers 'force)
5001 (org-compile-prefix-format org-agenda-prefix-format)
5002 (let* ((org-agenda-keep-modes keep-modes)
5003 (today (time-to-days (current-time)))
5004 (date (calendar-gregorian-from-absolute today))
5005 (win (selected-window))
5006 (kwds org-todo-keywords)
5007 (completion-ignore-case t)
5008 (org-select-this-todo-keyword
5009 (if (stringp arg) arg
5010 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
5011 rtn rtnall files file pos)
5012 (when (equal arg '(4))
5013 (setq org-select-this-todo-keyword
5014 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
5015 nil t)))
5016 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
5017 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5018 (progn
5019 (delete-other-windows)
5020 (switch-to-buffer-other-window
5021 (get-buffer-create org-agenda-buffer-name))))
5022 (setq buffer-read-only nil)
5023 (erase-buffer)
5024 (org-agenda-mode) (setq buffer-read-only nil)
5025 (set (make-local-variable 'org-agenda-type) 'todo)
5026 (set (make-local-variable 'last-arg) arg)
5027 (set (make-local-variable 'org-todo-keywords) kwds)
5028 (set (make-local-variable 'org-agenda-redo-command)
5029 '(org-todo-list (or current-prefix-arg last-arg) t))
5030 (setq files (org-agenda-files)
5031 rtnall nil)
5032 (while (setq file (pop files))
5033 (catch 'nextfile
5034 (org-check-agenda-file file)
5035 (setq rtn (org-agenda-get-day-entries file date :todo))
5036 (setq rtnall (append rtnall rtn))))
5037 (insert "Global list of TODO items of type: ")
5038 (add-text-properties (point-min) (1- (point))
5039 (list 'face 'org-link))
5040 (setq pos (point))
5041 (insert (or org-select-this-todo-keyword "ALL") "\n")
5042 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
5043 (setq pos (point))
5044 (insert
5045 "Available with `N r': (0)ALL "
5046 (let ((n 0))
5047 (mapconcat (lambda (x)
5048 (format "(%d)%s" (setq n (1+ n)) x))
5049 org-todo-keywords " "))
5050 "\n")
5051 (add-text-properties pos (1- (point)) (list 'face 'org-link))
5052 (when rtnall
5053 (insert (org-finalize-agenda-entries rtnall) "\n"))
5054 (goto-char (point-min))
5055 (setq buffer-read-only t)
5056 (org-fit-agenda-window)
5057 (if (not org-select-agenda-window) (select-window win))))
5059 (defun org-check-agenda-file (file)
5060 "Make sure FILE exists. If not, ask user what to do."
5061 (when (not (file-exists-p file))
5062 (message "non-existent file %s. [R]emove from list or [A]bort?"
5063 (abbreviate-file-name file))
5064 (let ((r (downcase (read-char-exclusive))))
5065 (cond
5066 ((equal r ?r)
5067 (org-remove-file file)
5068 (throw 'nextfile t))
5069 (t (error "Abort"))))))
5071 (defun org-agenda-check-type (error &rest types)
5072 "Check if agenda buffer is of allowed type.
5073 If ERROR is non-nil, throw an error, otherwise just return nil."
5074 (if (memq org-agenda-type types)
5076 (if error
5077 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
5078 nil)))
5080 (defun org-agenda-quit ()
5081 "Exit agenda by removing the window or the buffer."
5082 (interactive)
5083 (let ((buf (current-buffer)))
5084 (if (not (one-window-p)) (delete-window))
5085 (kill-buffer buf)
5086 (org-agenda-maybe-reset-markers 'force)))
5088 (defun org-agenda-exit ()
5089 "Exit agenda by removing the window or the buffer.
5090 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
5091 Org-mode buffers visited directly by the user will not be touched."
5092 (interactive)
5093 (org-release-buffers org-agenda-new-buffers)
5094 (setq org-agenda-new-buffers nil)
5095 (org-agenda-quit))
5097 (defun org-agenda-redo ()
5098 "Rebuild Agenda.
5099 When this is the global TODO list, a prefix argument will be interpreted."
5100 (interactive)
5101 (message "Rebuilding agenda buffer...")
5102 (eval org-agenda-redo-command)
5103 (message "Rebuilding agenda buffer...done"))
5105 (defun org-agenda-goto-today ()
5106 "Go to today."
5107 (interactive)
5108 (org-agenda-check-type t 'timeline 'agenda)
5109 (if (boundp 'starting-day)
5110 (let ((cmd (car org-agenda-redo-command))
5111 (iall (nth 1 org-agenda-redo-command))
5112 (nday (nth 3 org-agenda-redo-command))
5113 (keep (nth 4 org-agenda-redo-command)))
5114 (eval (list cmd iall nil nday keep)))
5115 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5116 (point-min)))))
5118 (defun org-agenda-later (arg)
5119 "Go forward in time by `org-agenda-ndays' days.
5120 With prefix ARG, go forward that many times `org-agenda-ndays'."
5121 (interactive "p")
5122 (org-agenda-check-type t 'agenda)
5123 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5124 (+ starting-day (* arg org-agenda-ndays)) nil t))
5126 (defun org-agenda-earlier (arg)
5127 "Go back in time by `org-agenda-ndays' days.
5128 With prefix ARG, go back that many times `org-agenda-ndays'."
5129 (interactive "p")
5130 (org-agenda-check-type t 'agenda)
5131 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5132 (- starting-day (* arg org-agenda-ndays)) nil t))
5134 (defun org-agenda-week-view ()
5135 "Switch to weekly view for agenda."
5136 (interactive)
5137 (org-agenda-check-type t 'agenda)
5138 (setq org-agenda-ndays 7)
5139 (org-agenda-list include-all-loc
5140 (or (get-text-property (point) 'day)
5141 starting-day)
5142 nil t)
5143 (org-agenda-set-mode-name)
5144 (message "Switched to week view"))
5146 (defun org-agenda-day-view ()
5147 "Switch to daily view for agenda."
5148 (interactive)
5149 (org-agenda-check-type t 'agenda)
5150 (setq org-agenda-ndays 1)
5151 (org-agenda-list include-all-loc
5152 (or (get-text-property (point) 'day)
5153 starting-day)
5154 nil t)
5155 (org-agenda-set-mode-name)
5156 (message "Switched to day view"))
5158 (defun org-agenda-next-date-line (&optional arg)
5159 "Jump to the next line indicating a date in agenda buffer."
5160 (interactive "p")
5161 (org-agenda-check-type t 'agenda 'timeline)
5162 (beginning-of-line 1)
5163 (if (looking-at "^\\S-") (forward-char 1))
5164 (if (not (re-search-forward "^\\S-" nil t arg))
5165 (progn
5166 (backward-char 1)
5167 (error "No next date after this line in this buffer")))
5168 (goto-char (match-beginning 0)))
5170 (defun org-agenda-previous-date-line (&optional arg)
5171 "Jump to the previous line indicating a date in agenda buffer."
5172 (interactive "p")
5173 (org-agenda-check-type t 'agenda 'timeline)
5174 (beginning-of-line 1)
5175 (if (not (re-search-backward "^\\S-" nil t arg))
5176 (error "No previous date before this line in this buffer")))
5178 ;; Initialize the highlight
5179 (defvar org-hl (org-make-overlay 1 1))
5180 (org-overlay-put org-hl 'face 'highlight)
5182 (defun org-highlight (begin end &optional buffer)
5183 "Highlight a region with overlay."
5184 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
5185 org-hl begin end (or buffer (current-buffer))))
5187 (defun org-unhighlight ()
5188 "Detach overlay INDEX."
5189 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
5192 (defun org-agenda-follow-mode ()
5193 "Toggle follow mode in an agenda buffer."
5194 (interactive)
5195 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5196 (org-agenda-set-mode-name)
5197 (message "Follow mode is %s"
5198 (if org-agenda-follow-mode "on" "off")))
5200 (defun org-agenda-log-mode ()
5201 "Toggle log mode in an agenda buffer."
5202 (interactive)
5203 (org-agenda-check-type t 'agenda 'timeline)
5204 (setq org-agenda-show-log (not org-agenda-show-log))
5205 (org-agenda-set-mode-name)
5206 (org-agenda-redo)
5207 (message "Log mode is %s"
5208 (if org-agenda-show-log "on" "off")))
5210 (defun org-agenda-toggle-diary ()
5211 "Toggle diary inclusion in an agenda buffer."
5212 (interactive)
5213 (org-agenda-check-type t 'agenda)
5214 (setq org-agenda-include-diary (not org-agenda-include-diary))
5215 (org-agenda-redo)
5216 (org-agenda-set-mode-name)
5217 (message "Diary inclusion turned %s"
5218 (if org-agenda-include-diary "on" "off")))
5220 (defun org-agenda-toggle-time-grid ()
5221 "Toggle time grid in an agenda buffer."
5222 (interactive)
5223 (org-agenda-check-type t 'agenda)
5224 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5225 (org-agenda-redo)
5226 (org-agenda-set-mode-name)
5227 (message "Time-grid turned %s"
5228 (if org-agenda-use-time-grid "on" "off")))
5230 (defun org-agenda-set-mode-name ()
5231 "Set the mode name to indicate all the small mode settings."
5232 (setq mode-name
5233 (concat "Org-Agenda"
5234 (if (equal org-agenda-ndays 1) " Day" "")
5235 (if (equal org-agenda-ndays 7) " Week" "")
5236 (if org-agenda-follow-mode " Follow" "")
5237 (if org-agenda-include-diary " Diary" "")
5238 (if org-agenda-use-time-grid " Grid" "")
5239 (if org-agenda-show-log " Log" "")))
5240 (force-mode-line-update))
5242 (defun org-agenda-post-command-hook ()
5243 (and (eolp) (not (bolp)) (backward-char 1))
5244 (if (and org-agenda-follow-mode
5245 (get-text-property (point) 'org-marker))
5246 (org-agenda-show)))
5248 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5250 (defun org-get-entries-from-diary (date)
5251 "Get the (Emacs Calendar) diary entries for DATE."
5252 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5253 (diary-display-hook '(fancy-diary-display))
5254 (list-diary-entries-hook
5255 (cons 'org-diary-default-entry list-diary-entries-hook))
5256 (diary-file-name-prefix-function nil) ; turn this feature off
5257 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5258 entries
5259 (org-disable-agenda-to-diary t))
5260 (save-excursion
5261 (save-window-excursion
5262 (list-diary-entries date 1)))
5263 (if (not (get-buffer fancy-diary-buffer))
5264 (setq entries nil)
5265 (with-current-buffer fancy-diary-buffer
5266 (setq buffer-read-only nil)
5267 (if (= (point-max) 1)
5268 ;; No entries
5269 (setq entries nil)
5270 ;; Omit the date and other unnecessary stuff
5271 (org-agenda-cleanup-fancy-diary)
5272 ;; Add prefix to each line and extend the text properties
5273 (if (= (point-max) 1)
5274 (setq entries nil)
5275 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5276 (set-buffer-modified-p nil)
5277 (kill-buffer fancy-diary-buffer)))
5278 (when entries
5279 (setq entries (org-split-string entries "\n"))
5280 (setq entries
5281 (mapcar
5282 (lambda (x)
5283 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5284 ;; Extend the text properties to the beginning of the line
5285 (add-text-properties
5286 0 (length x)
5287 (text-properties-at (1- (length x)) x)
5290 entries)))))
5292 (defun org-agenda-cleanup-fancy-diary ()
5293 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5294 This gets rid of the date, the underline under the date, and
5295 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5296 date. It also removes lines that contain only whitespace."
5297 (goto-char (point-min))
5298 (if (looking-at ".*?:[ \t]*")
5299 (progn
5300 (replace-match "")
5301 (re-search-forward "\n=+$" nil t)
5302 (replace-match "")
5303 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5304 (re-search-forward "\n=+$" nil t)
5305 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5306 (goto-char (point-min))
5307 (while (re-search-forward "^ +\n" nil t)
5308 (replace-match ""))
5309 (goto-char (point-min))
5310 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5311 (replace-match "")))
5313 ;; Make sure entries from the diary have the right text properties.
5314 (eval-after-load "diary-lib"
5315 '(if (boundp 'diary-modify-entry-list-string-function)
5316 ;; We can rely on the hook, nothing to do
5318 ;; Hook not avaiable, must use advice to make this work
5319 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5320 "Make the position visible."
5321 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5322 (stringp string)
5323 buffer-file-name)
5324 (setq string (org-modify-diary-entry-string string))))))
5326 (defun org-modify-diary-entry-string (string)
5327 "Add text properties to string, allowing org-mode to act on it."
5328 (add-text-properties
5329 0 (length string)
5330 (list 'mouse-face 'highlight
5331 'keymap org-agenda-keymap
5332 'help-echo
5333 (format
5334 "mouse-2 or RET jump to diary file %s"
5335 (abbreviate-file-name buffer-file-name))
5336 'org-agenda-diary-link t
5337 'org-marker (org-agenda-new-marker (point-at-bol)))
5338 string)
5339 string)
5341 (defun org-diary-default-entry ()
5342 "Add a dummy entry to the diary.
5343 Needed to avoid empty dates which mess up holiday display."
5344 ;; Catch the error if dealing with the new add-to-diary-alist
5345 (when org-disable-agenda-to-diary
5346 (condition-case nil
5347 (add-to-diary-list original-date "Org-mode dummy" "")
5348 (error
5349 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5351 (defun org-cycle-agenda-files ()
5352 "Cycle through the files in `org-agenda-files'.
5353 If the current buffer visits an agenda file, find the next one in the list.
5354 If the current buffer does not, find the first agenda file."
5355 (interactive)
5356 (let* ((fs (org-agenda-files t))
5357 (files (append fs (list (car fs))))
5358 (tcf (if buffer-file-name (file-truename buffer-file-name)))
5359 file)
5360 (unless files (error "No agenda files"))
5361 (catch 'exit
5362 (while (setq file (pop files))
5363 (if (equal (file-truename file) tcf)
5364 (when (car files)
5365 (find-file (car files))
5366 (throw 'exit t))))
5367 (find-file (car fs)))))
5369 (defun org-agenda-file-to-end ()
5370 "Move/add the current file to the end of the agenda file list.
5371 If the file is not present in the list, it is appended to the list. If it is
5372 present, it is moved there."
5373 (interactive)
5374 (org-agenda-file-to-front 'to-end))
5376 (defun org-agenda-file-to-front (&optional to-end)
5377 "Move/add the current file to the top of the agenda file list.
5378 If the file is not present in the list, it is added to the front. If it is
5379 present, it is moved there. With optional argument TO-END, add/move to the
5380 end of the list."
5381 (interactive "P")
5382 (let ((file-alist (mapcar (lambda (x)
5383 (cons (file-truename x) x))
5384 (org-agenda-files t)))
5385 (ctf (file-truename buffer-file-name))
5386 x had)
5387 (setq x (assoc ctf file-alist) had x)
5389 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
5390 (if to-end
5391 (setq file-alist (append (delq x file-alist) (list x)))
5392 (setq file-alist (cons x (delq x file-alist))))
5393 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
5394 (org-install-agenda-files-menu)
5395 (message "File %s to %s of agenda file list"
5396 (if had "moved" "added") (if to-end "end" "front"))))
5398 (defun org-remove-file (&optional file)
5399 "Remove current file from the list of files in variable `org-agenda-files'.
5400 These are the files which are being checked for agenda entries.
5401 Optional argument FILE means, use this file instead of the current."
5402 (interactive)
5403 (let* ((file (or file buffer-file-name))
5404 (true-file (file-truename file))
5405 (afile (abbreviate-file-name file))
5406 (files (delq nil (mapcar
5407 (lambda (x)
5408 (if (equal true-file
5409 (file-truename x))
5410 nil x))
5411 (org-agenda-files t)))))
5412 (if (not (= (length files) (length (org-agenda-files t))))
5413 (progn
5414 (org-store-new-agenda-file-list files)
5415 (org-install-agenda-files-menu)
5416 (message "Removed file: %s" afile))
5417 (message "File was not in list: %s" afile))))
5419 (defun org-file-menu-entry (file)
5420 (vector file (list 'find-file file) t))
5421 ;; FIXME: Maybe we removed a buffer visited through the menu from
5422 ;; org-agenda-new-buffers, so that the buffer will not be removed
5423 ;; when exiting the agenda????
5425 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5426 "Return a list of all relevant day numbers from BEG to END buffer positions.
5427 If NO-RANGES is non-nil, include only the start and end dates of a range,
5428 not every single day in the range. If FORCE-TODAY is non-nil, make
5429 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5430 inactive time stamps (those in square brackets) are included."
5431 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5432 dates date day day1 day2 ts1 ts2)
5433 (if force-today
5434 (setq dates (list (time-to-days (current-time)))))
5435 (save-excursion
5436 (goto-char beg)
5437 (while (re-search-forward re end t)
5438 (setq day (time-to-days (org-time-string-to-time
5439 (substring (match-string 1) 0 10))))
5440 (or (memq day dates) (push day dates)))
5441 (unless no-ranges
5442 (goto-char beg)
5443 (while (re-search-forward org-tr-regexp end t)
5444 (setq ts1 (substring (match-string 1) 0 10)
5445 ts2 (substring (match-string 2) 0 10)
5446 day1 (time-to-days (org-time-string-to-time ts1))
5447 day2 (time-to-days (org-time-string-to-time ts2)))
5448 (while (< (setq day1 (1+ day1)) day2)
5449 (or (memq day1 dates) (push day1 dates)))))
5450 (sort dates '<))))
5452 ;;;###autoload
5453 (defun org-diary (&rest args)
5454 "Return diary information from org-files.
5455 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5456 It accesses org files and extracts information from those files to be
5457 listed in the diary. The function accepts arguments specifying what
5458 items should be listed. The following arguments are allowed:
5460 :timestamp List the headlines of items containing a date stamp or
5461 date range matching the selected date. Deadlines will
5462 also be listed, on the expiration day.
5464 :deadline List any deadlines past due, or due within
5465 `org-deadline-warning-days'. The listing occurs only
5466 in the diary for *today*, not at any other date. If
5467 an entry is marked DONE, it is no longer listed.
5469 :scheduled List all items which are scheduled for the given date.
5470 The diary for *today* also contains items which were
5471 scheduled earlier and are not yet marked DONE.
5473 :todo List all TODO items from the org-file. This may be a
5474 long list - so this is not turned on by default.
5475 Like deadlines, these entries only show up in the
5476 diary for *today*, not at any other date.
5478 The call in the diary file should look like this:
5480 &%%(org-diary) ~/path/to/some/orgfile.org
5482 Use a separate line for each org file to check. Or, if you omit the file name,
5483 all files listed in `org-agenda-files' will be checked automatically:
5485 &%%(org-diary)
5487 If you don't give any arguments (as in the example above), the default
5488 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5489 also be written as
5491 &%%(org-diary :deadline :timestamp :scheduled)
5493 The function expects the lisp variables `entry' and `date' to be provided
5494 by the caller, because this is how the calendar works. Don't use this
5495 function from a program - use `org-agenda-get-day-entries' instead."
5496 (org-agenda-maybe-reset-markers)
5497 (org-compile-prefix-format org-agenda-prefix-format)
5498 (setq args (or args '(:deadline :scheduled :timestamp)))
5499 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5500 (list entry)
5501 (org-agenda-files t)))
5502 file rtn results)
5503 ;; If this is called during org-agenda, don't return any entries to
5504 ;; the calendar. Org Agenda will list these entries itself.
5505 (if org-disable-agenda-to-diary (setq files nil))
5506 (while (setq file (pop files))
5507 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5508 (setq results (append results rtn)))
5509 (if results
5510 (concat (org-finalize-agenda-entries results) "\n"))))
5511 (defvar org-category-table nil)
5512 (defun org-get-category-table ()
5513 "Get the table of categories and positions in current buffer."
5514 (let (tbl)
5515 (save-excursion
5516 (goto-char (point-min))
5517 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5518 (push (cons (point) (org-trim (match-string 2))) tbl)))
5519 tbl))
5520 (defun org-get-category (&optional pos)
5521 "Get the category applying to position POS."
5522 (if (not org-category-table)
5523 (cond
5524 ((null org-category)
5525 (setq org-category
5526 (if buffer-file-name
5527 (file-name-sans-extension
5528 (file-name-nondirectory buffer-file-name))
5529 "???")))
5530 ((symbolp org-category) (symbol-name org-category))
5531 (t org-category))
5532 (let ((tbl org-category-table)
5533 (pos (or pos (point))))
5534 (while (and tbl (> (caar tbl) pos))
5535 (pop tbl))
5536 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5537 org-category-table))))))
5539 (defun org-agenda-get-day-entries (file date &rest args)
5540 "Does the work for `org-diary' and `org-agenda'.
5541 FILE is the path to a file to be checked for entries. DATE is date like
5542 the one returned by `calendar-current-date'. ARGS are symbols indicating
5543 which kind of entries should be extracted. For details about these, see
5544 the documentation of `org-diary'."
5545 (setq args (or args '(:deadline :scheduled :timestamp)))
5546 (let* ((org-startup-with-deadline-check nil)
5547 (org-startup-folded nil)
5548 (buffer (if (file-exists-p file)
5549 (org-get-agenda-file-buffer file)
5550 (error "No such file %s" file)))
5551 arg results rtn)
5552 (if (not buffer)
5553 ;; If file does not exist, make sure an error message ends up in diary
5554 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5555 (with-current-buffer buffer
5556 (unless (eq major-mode 'org-mode)
5557 (error "Agenda file %s is not in `org-mode'" file))
5558 (setq org-category-table (org-get-category-table))
5559 (let ((case-fold-search nil))
5560 (save-excursion
5561 (save-restriction
5562 (if org-respect-restriction
5563 (if (org-region-active-p)
5564 ;; Respect a region to restrict search
5565 (narrow-to-region (region-beginning) (region-end)))
5566 ;; If we work for the calendar or many files,
5567 ;; get rid of any restriction
5568 (widen))
5569 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5570 (while (setq arg (pop args))
5571 (cond
5572 ((and (eq arg :todo)
5573 (equal date (calendar-current-date)))
5574 (setq rtn (org-agenda-get-todos))
5575 (setq results (append results rtn)))
5576 ((eq arg :timestamp)
5577 (setq rtn (org-agenda-get-blocks))
5578 (setq results (append results rtn))
5579 (setq rtn (org-agenda-get-timestamps))
5580 (setq results (append results rtn)))
5581 ((eq arg :scheduled)
5582 (setq rtn (org-agenda-get-scheduled))
5583 (setq results (append results rtn)))
5584 ((eq arg :closed)
5585 (setq rtn (org-agenda-get-closed))
5586 (setq results (append results rtn)))
5587 ((and (eq arg :deadline)
5588 (equal date (calendar-current-date)))
5589 (setq rtn (org-agenda-get-deadlines))
5590 (setq results (append results rtn))))))))
5591 results))))
5593 (defun org-entry-is-done-p ()
5594 "Is the current entry marked DONE?"
5595 (save-excursion
5596 (and (re-search-backward "[\r\n]\\*" nil t)
5597 (looking-at org-nl-done-regexp))))
5599 (defun org-at-date-range-p ()
5600 "Is the cursor inside a date range?"
5601 (interactive)
5602 (save-excursion
5603 (catch 'exit
5604 (let ((pos (point)))
5605 (skip-chars-backward "^<\r\n")
5606 (skip-chars-backward "<")
5607 (and (looking-at org-tr-regexp)
5608 (>= (match-end 0) pos)
5609 (throw 'exit t))
5610 (skip-chars-backward "^<\r\n")
5611 (skip-chars-backward "<")
5612 (and (looking-at org-tr-regexp)
5613 (>= (match-end 0) pos)
5614 (throw 'exit t)))
5615 nil)))
5617 (defun org-agenda-get-todos ()
5618 "Return the TODO information for agenda display."
5619 (let* ((props (list 'face nil
5620 'done-face 'org-done
5621 'mouse-face 'highlight
5622 'keymap org-agenda-keymap
5623 'help-echo
5624 (format "mouse-2 or RET jump to org file %s"
5625 (abbreviate-file-name buffer-file-name))))
5626 (regexp (concat "[\n\r]\\*+ *\\("
5627 (if org-select-this-todo-keyword
5628 (concat "\\<\\(" org-select-this-todo-keyword
5629 "\\)\\>")
5630 org-not-done-regexp)
5631 "[^\n\r]*\\)"))
5632 marker priority category tags
5633 ee txt)
5634 (goto-char (point-min))
5635 (while (re-search-forward regexp nil t)
5636 (goto-char (match-beginning 1))
5637 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5638 category (org-get-category)
5639 tags (org-get-tags-at (point))
5640 txt (org-format-agenda-item "" (match-string 1) category tags)
5641 priority
5642 (+ (org-get-priority txt)
5643 (if org-todo-kwd-priority-p
5644 (- org-todo-kwd-max-priority -2
5645 (length
5646 (member (match-string 2) org-todo-keywords)))
5647 1)))
5648 (add-text-properties
5649 0 (length txt) (append (list 'org-marker marker 'org-hd-marker marker
5650 'priority priority 'category category)
5651 props)
5652 txt)
5653 (push txt ee)
5654 (goto-char (match-end 1)))
5655 (nreverse ee)))
5657 (defconst org-agenda-no-heading-message
5658 "No heading for this item in buffer or region.")
5660 (defun org-agenda-get-timestamps ()
5661 "Return the date stamp information for agenda display."
5662 (let* ((props (list 'face nil
5663 'mouse-face 'highlight
5664 'keymap org-agenda-keymap
5665 'help-echo
5666 (format "mouse-2 or RET jump to org file %s"
5667 (abbreviate-file-name buffer-file-name))))
5668 (regexp (regexp-quote
5669 (substring
5670 (format-time-string
5671 (car org-time-stamp-formats)
5672 (apply 'encode-time ; DATE bound by calendar
5673 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5674 0 11)))
5675 marker hdmarker deadlinep scheduledp donep tmp priority category
5676 ee txt timestr tags)
5677 (goto-char (point-min))
5678 (while (re-search-forward regexp nil t)
5679 (if (not (save-match-data (org-at-date-range-p)))
5680 (progn
5681 (setq marker (org-agenda-new-marker (match-beginning 0))
5682 category (org-get-category (match-beginning 0))
5683 tmp (buffer-substring (max (point-min)
5684 (- (match-beginning 0)
5685 org-ds-keyword-length))
5686 (match-beginning 0))
5687 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5688 deadlinep (string-match org-deadline-regexp tmp)
5689 scheduledp (string-match org-scheduled-regexp tmp)
5690 donep (org-entry-is-done-p))
5691 (if (string-match ">" timestr)
5692 ;; substring should only run to end of time stamp
5693 (setq timestr (substring timestr 0 (match-end 0))))
5694 (save-excursion
5695 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5696 (progn
5697 (goto-char (match-end 1))
5698 (setq hdmarker (org-agenda-new-marker)
5699 tags (org-get-tags-at))
5700 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5701 (setq txt (org-format-agenda-item
5702 (format "%s%s"
5703 (if deadlinep "Deadline: " "")
5704 (if scheduledp "Scheduled: " ""))
5705 (match-string 1) category tags timestr)))
5706 (setq txt org-agenda-no-heading-message))
5707 (setq priority (org-get-priority txt))
5708 (add-text-properties
5709 0 (length txt) (append (list 'org-marker marker
5710 'org-hd-marker hdmarker) props)
5711 txt)
5712 (if deadlinep
5713 (add-text-properties
5714 0 (length txt)
5715 (list 'face
5716 (if donep 'org-done 'org-warning)
5717 'undone-face 'org-warning
5718 'done-face 'org-done
5719 'category category
5720 'priority (+ 100 priority))
5721 txt)
5722 (if scheduledp
5723 (add-text-properties
5724 0 (length txt)
5725 (list 'face 'org-scheduled-today
5726 'undone-face 'org-scheduled-today
5727 'done-face 'org-done
5728 'category category
5729 priority (+ 99 priority))
5730 txt)
5731 (add-text-properties
5732 0 (length txt)
5733 (list 'priority priority 'category category) txt)))
5734 (push txt ee))
5735 (outline-next-heading))))
5736 (nreverse ee)))
5738 (defun org-agenda-get-closed ()
5739 "Return the logged TODO entries for agenda display."
5740 (let* ((props (list 'mouse-face 'highlight
5741 'keymap org-agenda-keymap
5742 'help-echo
5743 (format "mouse-2 or RET jump to org file %s"
5744 (abbreviate-file-name buffer-file-name))))
5745 (regexp (concat
5746 "\\<" org-closed-string " *\\["
5747 (regexp-quote
5748 (substring
5749 (format-time-string
5750 (car org-time-stamp-formats)
5751 (apply 'encode-time ; DATE bound by calendar
5752 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5753 1 11))))
5754 marker hdmarker priority category tags
5755 ee txt timestr)
5756 (goto-char (point-min))
5757 (while (re-search-forward regexp nil t)
5758 (if (not (save-match-data (org-at-date-range-p)))
5759 (progn
5760 (setq marker (org-agenda-new-marker (match-beginning 0))
5761 category (org-get-category (match-beginning 0))
5762 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5763 ;; donep (org-entry-is-done-p)
5765 (if (string-match "\\]" timestr)
5766 ;; substring should only run to end of time stamp
5767 (setq timestr (substring timestr 0 (match-end 0))))
5768 (save-excursion
5769 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5770 (progn
5771 (goto-char (match-end 1))
5772 (setq hdmarker (org-agenda-new-marker)
5773 tags (org-get-tags-at))
5774 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5775 (setq txt (org-format-agenda-item
5776 "Closed: "
5777 (match-string 1) category tags timestr)))
5778 (setq txt org-agenda-no-heading-message))
5779 (setq priority 100000)
5780 (add-text-properties
5781 0 (length txt) (append (list 'org-marker marker
5782 'org-hd-marker hdmarker
5783 'face 'org-done
5784 'priority priority
5785 'category category
5786 'undone-face 'org-warning
5787 'done-face 'org-done) props)
5788 txt)
5789 (push txt ee))
5790 (outline-next-heading))))
5791 (nreverse ee)))
5793 (defun org-agenda-get-deadlines ()
5794 "Return the deadline information for agenda display."
5795 (let* ((wdays org-deadline-warning-days)
5796 (props (list 'mouse-face 'highlight
5797 'keymap org-agenda-keymap
5798 'help-echo
5799 (format "mouse-2 or RET jump to org file %s"
5800 (abbreviate-file-name buffer-file-name))))
5801 (regexp org-deadline-time-regexp)
5802 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5803 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5804 d2 diff pos pos1 category tags
5805 ee txt head)
5806 (goto-char (point-min))
5807 (while (re-search-forward regexp nil t)
5808 (setq pos (1- (match-beginning 1))
5809 d2 (time-to-days
5810 (org-time-string-to-time (match-string 1)))
5811 diff (- d2 d1))
5812 ;; When to show a deadline in the calendar:
5813 ;; If the expiration is within wdays warning time.
5814 ;; Past-due deadlines are only shown on the current date
5815 (if (and (< diff wdays) todayp (not (= diff 0)))
5816 (save-excursion
5817 (setq category (org-get-category))
5818 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5819 (progn
5820 (goto-char (match-end 0))
5821 (setq pos1 (match-end 1))
5822 (setq tags (org-get-tags-at pos1))
5823 (setq head (buffer-substring-no-properties
5824 (point)
5825 (progn (skip-chars-forward "^\r\n")
5826 (point))))
5827 (if (string-match org-looking-at-done-regexp head)
5828 (setq txt nil)
5829 (setq txt (org-format-agenda-item
5830 (format "In %3d d.: " diff) head category tags))))
5831 (setq txt org-agenda-no-heading-message))
5832 (when txt
5833 (add-text-properties
5834 0 (length txt)
5835 (append
5836 (list 'org-marker (org-agenda-new-marker pos)
5837 'org-hd-marker (org-agenda-new-marker pos1)
5838 'priority (+ (- 10 diff) (org-get-priority txt))
5839 'category category
5840 'face (cond ((<= diff 0) 'org-warning)
5841 ((<= diff 5) 'org-scheduled-previously)
5842 (t nil))
5843 'undone-face (cond
5844 ((<= diff 0) 'org-warning)
5845 ((<= diff 5) 'org-scheduled-previously)
5846 (t nil))
5847 'done-face 'org-done)
5848 props)
5849 txt)
5850 (push txt ee)))))
5851 ee))
5853 (defun org-agenda-get-scheduled ()
5854 "Return the scheduled information for agenda display."
5855 (let* ((props (list 'face 'org-scheduled-previously
5856 'undone-face 'org-scheduled-previously
5857 'done-face 'org-done
5858 'mouse-face 'highlight
5859 'keymap org-agenda-keymap
5860 'help-echo
5861 (format "mouse-2 or RET jump to org file %s"
5862 (abbreviate-file-name buffer-file-name))))
5863 (regexp org-scheduled-time-regexp)
5864 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
5865 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
5866 d2 diff pos pos1 category tags
5867 ee txt head)
5868 (goto-char (point-min))
5869 (while (re-search-forward regexp nil t)
5870 (setq pos (1- (match-beginning 1))
5871 d2 (time-to-days
5872 (org-time-string-to-time (match-string 1)))
5873 diff (- d2 d1))
5874 ;; When to show a scheduled item in the calendar:
5875 ;; If it is on or past the date.
5876 (if (and (< diff 0) todayp)
5877 (save-excursion
5878 (setq category (org-get-category))
5879 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
5880 (progn
5881 (goto-char (match-end 0))
5882 (setq pos1 (match-end 1))
5883 (setq tags (org-get-tags-at))
5884 (setq head (buffer-substring-no-properties
5885 (point)
5886 (progn (skip-chars-forward "^\r\n") (point))))
5887 (if (string-match org-looking-at-done-regexp head)
5888 (setq txt nil)
5889 (setq txt (org-format-agenda-item
5890 (format "Sched.%2dx: " (- 1 diff)) head
5891 category tags))))
5892 (setq txt org-agenda-no-heading-message))
5893 (when txt
5894 (add-text-properties
5895 0 (length txt)
5896 (append (list 'org-marker (org-agenda-new-marker pos)
5897 'org-hd-marker (org-agenda-new-marker pos1)
5898 'priority (+ (- 5 diff) (org-get-priority txt))
5899 'category category)
5900 props) txt)
5901 (push txt ee)))))
5902 ee))
5904 (defun org-agenda-get-blocks ()
5905 "Return the date-range information for agenda display."
5906 (let* ((props (list 'face nil
5907 'mouse-face 'highlight
5908 'keymap org-agenda-keymap
5909 'help-echo
5910 (format "mouse-2 or RET jump to org file %s"
5911 (abbreviate-file-name buffer-file-name))))
5912 (regexp org-tr-regexp)
5913 (d0 (calendar-absolute-from-gregorian date))
5914 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
5915 (goto-char (point-min))
5916 (while (re-search-forward regexp nil t)
5917 (setq timestr (match-string 0)
5918 s1 (match-string 1)
5919 s2 (match-string 2)
5920 d1 (time-to-days (org-time-string-to-time s1))
5921 d2 (time-to-days (org-time-string-to-time s2)))
5922 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
5923 ;; Only allow days between the limits, because the normal
5924 ;; date stamps will catch the limits.
5925 (save-excursion
5926 (setq marker (org-agenda-new-marker (point)))
5927 (setq category (org-get-category))
5928 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5929 (progn
5930 (setq hdmarker (org-agenda-new-marker (match-end 1)))
5931 (goto-char (match-end 1))
5932 (setq tags (org-get-tags-at))
5933 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5934 (setq txt (org-format-agenda-item
5935 (format (if (= d1 d2) "" "(%d/%d): ")
5936 (1+ (- d0 d1)) (1+ (- d2 d1)))
5937 (match-string 1) category tags
5938 (if (= d0 d1) timestr))))
5939 (setq txt org-agenda-no-heading-message))
5940 (add-text-properties
5941 0 (length txt) (append (list 'org-marker marker
5942 'org-hd-marker hdmarker
5943 'priority (org-get-priority txt)
5944 'category category)
5945 props)
5946 txt)
5947 (push txt ee)))
5948 (outline-next-heading))
5949 ;; Sort the entries by expiration date.
5950 (nreverse ee)))
5952 (defconst org-plain-time-of-day-regexp
5953 (concat
5954 "\\(\\<[012]?[0-9]"
5955 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5956 "\\(--?"
5957 "\\(\\<[012]?[0-9]"
5958 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
5959 "\\)?")
5960 "Regular expression to match a plain time or time range.
5961 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
5962 groups carry important information:
5963 0 the full match
5964 1 the first time, range or not
5965 8 the second time, if it is a range.")
5967 (defconst org-stamp-time-of-day-regexp
5968 (concat
5969 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
5970 "\\([012][0-9]:[0-5][0-9]\\)>"
5971 "\\(--?"
5972 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
5973 "Regular expression to match a timestamp time or time range.
5974 After a match, the following groups carry important information:
5975 0 the full match
5976 1 date plus weekday, for backreferencing to make sure both times on same day
5977 2 the first time, range or not
5978 4 the second time, if it is a range.")
5980 (defvar org-prefix-has-time nil
5981 "A flag, set by `org-compile-prefix-format'.
5982 The flag is set if the currently compiled format contains a `%t'.")
5983 (defvar org-prefix-has-tag nil
5984 "A flag, set by `org-compile-prefix-format'.
5985 The flag is set if the currently compiled format contains a `%T'.")
5987 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
5988 "Format TXT to be inserted into the agenda buffer.
5989 In particular, it adds the prefix and corresponding text properties. EXTRA
5990 must be a string and replaces the `%s' specifier in the prefix format.
5991 CATEGORY (string, symbol or nil) may be used to overrule the default
5992 category taken from local variable or file name. It will replace the `%c'
5993 specifier in the format. DOTIME, when non-nil, indicates that a
5994 time-of-day should be extracted from TXT for sorting of this entry, and for
5995 the `%t' specifier in the format. When DOTIME is a string, this string is
5996 searched for a time before TXT is. NOPREFIX is a flag and indicates that
5997 only the correctly processes TXT should be returned - this is used by
5998 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
5999 (save-match-data
6000 ;; Diary entries sometimes have extra whitespace at the beginning
6001 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
6002 (let* ((category (or category
6003 org-category
6004 (if buffer-file-name
6005 (file-name-sans-extension
6006 (file-name-nondirectory buffer-file-name))
6007 "")))
6008 (tag (or (nth (1- (or (length tags) 0)) tags) ""))
6009 time ;; needed for the eval of the prefix format
6010 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
6011 (time-of-day (and dotime (org-get-time-of-day ts)))
6012 stamp plain s0 s1 s2 rtn)
6013 (when (and dotime time-of-day org-prefix-has-time)
6014 ;; Extract starting and ending time and move them to prefix
6015 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
6016 (setq plain (string-match org-plain-time-of-day-regexp ts)))
6017 (setq s0 (match-string 0 ts)
6018 s1 (match-string (if plain 1 2) ts)
6019 s2 (match-string (if plain 8 4) ts))
6021 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
6022 ;; them, we might want to remove them there to avoid duplication.
6023 ;; The user can turn this off with a variable.
6024 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
6025 (string-match (concat (regexp-quote s0) " *") txt)
6026 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
6027 (= (match-beginning 0) 0)
6029 (setq txt (replace-match "" nil nil txt))))
6030 ;; Normalize the time(s) to 24 hour
6031 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
6032 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
6034 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
6035 (and org-agenda-remove-tags-when-in-prefix
6036 org-prefix-has-tag))
6037 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
6038 (setq txt (replace-match "" t t txt)))
6040 ;; Create the final string
6041 (if noprefix
6042 (setq rtn txt)
6043 ;; Prepare the variables needed in the eval of the compiled format
6044 (setq time (cond (s2 (concat s1 "-" s2))
6045 (s1 (concat s1 "......"))
6046 (t ""))
6047 extra (or extra "")
6048 category (if (symbolp category) (symbol-name category) category))
6049 ;; Evaluate the compiled format
6050 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
6052 ;; And finally add the text properties
6053 (add-text-properties
6054 0 (length rtn) (list 'category (downcase category)
6055 'tags tags
6056 'prefix-length (- (length rtn) (length txt))
6057 'time-of-day time-of-day
6058 'dotime dotime)
6059 rtn)
6060 rtn)))
6062 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
6063 (catch 'exit
6064 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
6065 ((and todayp (member 'today (car org-agenda-time-grid))))
6066 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
6067 ((member 'weekly (car org-agenda-time-grid)))
6068 (t (throw 'exit list)))
6069 (let* ((have (delq nil (mapcar
6070 (lambda (x) (get-text-property 1 'time-of-day x))
6071 list)))
6072 (string (nth 1 org-agenda-time-grid))
6073 (gridtimes (nth 2 org-agenda-time-grid))
6074 (req (car org-agenda-time-grid))
6075 (remove (member 'remove-match req))
6076 new time)
6077 (if (and (member 'require-timed req) (not have))
6078 ;; don't show empty grid
6079 (throw 'exit list))
6080 (while (setq time (pop gridtimes))
6081 (unless (and remove (member time have))
6082 (setq time (int-to-string time))
6083 (push (org-format-agenda-item
6084 nil string "" nil ;; FIXME: put a category for the grid?
6085 (concat (substring time 0 -2) ":" (substring time -2)))
6086 new)
6087 (put-text-property
6088 1 (length (car new)) 'face 'org-time-grid (car new))))
6089 (if (member 'time-up org-agenda-sorting-strategy)
6090 (append new list)
6091 (append list new)))))
6093 (defun org-compile-prefix-format (format)
6094 "Compile the prefix format into a Lisp form that can be evaluated.
6095 The resulting form is returned and stored in the variable
6096 `org-prefix-format-compiled'."
6097 (setq org-prefix-has-time nil org-prefix-has-tag nil)
6098 (let ((start 0) varform vars var (s format)e c f opt)
6099 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
6100 s start)
6101 (setq var (cdr (assoc (match-string 4 s)
6102 '(("c" . category) ("t" . time) ("s" . extra)
6103 ("T" . tag))))
6104 c (or (match-string 3 s) "")
6105 opt (match-beginning 1)
6106 start (1+ (match-beginning 0)))
6107 (if (equal var 'time) (setq org-prefix-has-time t))
6108 (if (equal var 'tag) (setq org-prefix-has-tag t))
6109 (setq f (concat "%" (match-string 2 s) "s"))
6110 (if opt
6111 (setq varform
6112 `(if (equal "" ,var)
6114 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
6115 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
6116 (setq s (replace-match "%s" t nil s))
6117 (push varform vars))
6118 (setq vars (nreverse vars))
6119 (setq org-prefix-format-compiled `(format ,s ,@vars))))
6121 (defun org-get-time-of-day (s &optional string)
6122 "Check string S for a time of day.
6123 If found, return it as a military time number between 0 and 2400.
6124 If not found, return nil.
6125 The optional STRING argument forces conversion into a 5 character wide string
6126 HH:MM."
6127 (save-match-data
6128 (when
6130 (string-match
6131 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
6132 (string-match
6133 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
6134 (let* ((t0 (+ (* 100
6135 (+ (string-to-number (match-string 1 s))
6136 (if (and (match-beginning 4)
6137 (equal (downcase (match-string 4 s)) "pm"))
6138 12 0)))
6139 (if (match-beginning 3)
6140 (string-to-number (match-string 3 s))
6141 0)))
6142 (t1 (concat " "
6143 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6144 (int-to-string t0))))
6145 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6147 (defun org-finalize-agenda-entries (list)
6148 "Sort and concatenate the agenda items."
6149 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6151 (defsubst org-cmp-priority (a b)
6152 "Compare the priorities of string A and B."
6153 (let ((pa (or (get-text-property 1 'priority a) 0))
6154 (pb (or (get-text-property 1 'priority b) 0)))
6155 (cond ((> pa pb) +1)
6156 ((< pa pb) -1)
6157 (t nil))))
6159 (defsubst org-cmp-category (a b)
6160 "Compare the string values of categories of strings A and B."
6161 (let ((ca (or (get-text-property 1 'category a) ""))
6162 (cb (or (get-text-property 1 'category b) "")))
6163 (cond ((string-lessp ca cb) -1)
6164 ((string-lessp cb ca) +1)
6165 (t nil))))
6167 (defsubst org-cmp-time (a b)
6168 "Compare the time-of-day values of strings A and B."
6169 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6170 (ta (or (get-text-property 1 'time-of-day a) def))
6171 (tb (or (get-text-property 1 'time-of-day b) def)))
6172 (cond ((< ta tb) -1)
6173 ((< tb ta) +1)
6174 (t nil))))
6176 (defun org-entries-lessp (a b)
6177 "Predicate for sorting agenda entries."
6178 ;; The following variables will be used when the form is evaluated.
6179 (let* ((time-up (org-cmp-time a b))
6180 (time-down (if time-up (- time-up) nil))
6181 (priority-up (org-cmp-priority a b))
6182 (priority-down (if priority-up (- priority-up) nil))
6183 (category-up (org-cmp-category a b))
6184 (category-down (if category-up (- category-up) nil))
6185 (category-keep (if category-up +1 nil))) ; FIXME +1 or -1?
6186 (cdr (assoc
6187 (eval (cons 'or org-agenda-sorting-strategy))
6188 '((-1 . t) (1 . nil) (nil . nil))))))
6190 (defun org-agenda-show-priority ()
6191 "Show the priority of the current item.
6192 This priority is composed of the main priority given with the [#A] cookies,
6193 and by additional input from the age of a schedules or deadline entry."
6194 (interactive)
6195 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6196 (message "Priority is %d" (if pri pri -1000))))
6198 (defun org-agenda-show-tags ()
6199 "Show the tags applicable to the current item."
6200 (interactive)
6201 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6202 (if tags
6203 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6204 (message "No tags associated with this line"))))
6206 (defun org-agenda-goto (&optional highlight)
6207 "Go to the Org-mode file which contains the item at point."
6208 (interactive)
6209 (let* ((marker (or (get-text-property (point) 'org-marker)
6210 (org-agenda-error)))
6211 (buffer (marker-buffer marker))
6212 (pos (marker-position marker)))
6213 (switch-to-buffer-other-window buffer)
6214 (widen)
6215 (goto-char pos)
6216 (when (eq major-mode 'org-mode)
6217 (org-show-hidden-entry)
6218 (save-excursion
6219 (and (outline-next-heading)
6220 (org-flag-heading nil)))) ; show the next heading
6221 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6223 (defun org-agenda-switch-to ()
6224 "Go to the Org-mode file which contains the item at point."
6225 (interactive)
6226 (let* ((marker (or (get-text-property (point) 'org-marker)
6227 (org-agenda-error)))
6228 (buffer (marker-buffer marker))
6229 (pos (marker-position marker)))
6230 (switch-to-buffer buffer)
6231 (delete-other-windows)
6232 (widen)
6233 (goto-char pos)
6234 (when (eq major-mode 'org-mode)
6235 (org-show-hidden-entry)
6236 (save-excursion
6237 (and (outline-next-heading)
6238 (org-flag-heading nil)))))) ; show the next heading
6240 (defun org-agenda-goto-mouse (ev)
6241 "Go to the Org-mode file which contains the item at the mouse click."
6242 (interactive "e")
6243 (mouse-set-point ev)
6244 (org-agenda-goto))
6246 (defun org-agenda-show ()
6247 "Display the Org-mode file which contains the item at point."
6248 (interactive)
6249 (let ((win (selected-window)))
6250 (org-agenda-goto t)
6251 (select-window win)))
6253 (defun org-agenda-recenter (arg)
6254 "Display the Org-mode file which contains the item at point and recenter."
6255 (interactive "P")
6256 (let ((win (selected-window)))
6257 (org-agenda-goto t)
6258 (recenter arg)
6259 (select-window win)))
6261 (defun org-agenda-show-mouse (ev)
6262 "Display the Org-mode file which contains the item at the mouse click."
6263 (interactive "e")
6264 (mouse-set-point ev)
6265 (org-agenda-show))
6267 (defun org-agenda-check-no-diary ()
6268 "Check if the entry is a diary link and abort if yes."
6269 (if (get-text-property (point) 'org-agenda-diary-link)
6270 (org-agenda-error)))
6272 (defun org-agenda-error ()
6273 (error "Command not allowed in this line"))
6275 (defvar org-last-heading-marker (make-marker)
6276 "Marker pointing to the headline that last changed its TODO state
6277 by a remote command from the agenda.")
6279 (defun org-agenda-todo (&optional arg)
6280 "Cycle TODO state of line at point, also in Org-mode file.
6281 This changes the line at point, all other lines in the agenda referring to
6282 the same tree node, and the headline of the tree node in the Org-mode file."
6283 (interactive "P")
6284 (org-agenda-check-no-diary)
6285 (let* ((col (current-column))
6286 (marker (or (get-text-property (point) 'org-marker)
6287 (org-agenda-error)))
6288 (buffer (marker-buffer marker))
6289 (pos (marker-position marker))
6290 (hdmarker (get-text-property (point) 'org-hd-marker))
6291 (buffer-read-only nil)
6292 newhead)
6293 (with-current-buffer buffer
6294 (widen)
6295 (goto-char pos)
6296 (org-show-hidden-entry)
6297 (save-excursion
6298 (and (outline-next-heading)
6299 (org-flag-heading nil))) ; show the next heading
6300 (org-todo arg)
6301 (forward-char 1)
6302 (setq newhead (org-get-heading))
6303 (save-excursion
6304 (org-back-to-heading)
6305 (move-marker org-last-heading-marker (point))))
6306 (beginning-of-line 1)
6307 (save-excursion
6308 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6309 (move-to-column col)))
6311 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6312 "Change all lines in the agenda buffer which match HDMARKER.
6313 The new content of the line will be NEWHEAD (as modified by
6314 `org-format-agenda-item'). HDMARKER is checked with
6315 `equal' against all `org-hd-marker' text properties in the file.
6316 If FIXFACE is non-nil, the face of each item is modified acording to
6317 the new TODO state."
6318 (let* (props m pl undone-face done-face finish new dotime cat tags)
6319 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6320 (save-excursion
6321 (goto-char (point-max))
6322 (beginning-of-line 1)
6323 (while (not finish)
6324 (setq finish (bobp))
6325 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6326 (equal m hdmarker))
6327 (setq props (text-properties-at (point))
6328 dotime (get-text-property (point) 'dotime)
6329 cat (get-text-property (point) 'category)
6330 tags (get-text-property (point) 'tags)
6331 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6332 pl (get-text-property (point) 'prefix-length)
6333 undone-face (get-text-property (point) 'undone-face)
6334 done-face (get-text-property (point) 'done-face))
6335 (move-to-column pl)
6336 (if (looking-at ".*")
6337 (progn
6338 (replace-match new t t)
6339 (beginning-of-line 1)
6340 (add-text-properties (point-at-bol) (point-at-eol) props)
6341 (if fixface
6342 (add-text-properties
6343 (point-at-bol) (point-at-eol)
6344 (list 'face
6345 (if org-last-todo-state-is-todo
6346 undone-face done-face))))
6347 (beginning-of-line 1))
6348 (error "Line update did not work")))
6349 (beginning-of-line 0)))))
6351 (defun org-agenda-priority-up ()
6352 "Increase the priority of line at point, also in Org-mode file."
6353 (interactive)
6354 (org-agenda-priority 'up))
6356 (defun org-agenda-priority-down ()
6357 "Decrease the priority of line at point, also in Org-mode file."
6358 (interactive)
6359 (org-agenda-priority 'down))
6361 (defun org-agenda-priority (&optional force-direction)
6362 "Set the priority of line at point, also in Org-mode file.
6363 This changes the line at point, all other lines in the agenda referring to
6364 the same tree node, and the headline of the tree node in the Org-mode file."
6365 (interactive)
6366 (org-agenda-check-no-diary)
6367 (let* ((marker (or (get-text-property (point) 'org-marker)
6368 (org-agenda-error)))
6369 (buffer (marker-buffer marker))
6370 (pos (marker-position marker))
6371 (hdmarker (get-text-property (point) 'org-hd-marker))
6372 (buffer-read-only nil)
6373 newhead)
6374 (with-current-buffer buffer
6375 (widen)
6376 (goto-char pos)
6377 (org-show-hidden-entry)
6378 (save-excursion
6379 (and (outline-next-heading)
6380 (org-flag-heading nil))) ; show the next heading
6381 (funcall 'org-priority force-direction)
6382 (end-of-line 1)
6383 (setq newhead (org-get-heading)))
6384 (org-agenda-change-all-lines newhead hdmarker)
6385 (beginning-of-line 1)))
6387 (defun org-get-tags-at (&optional pos)
6388 "Get a list of all headline targs applicable at POS.
6389 POS defaults to point. If tags are inherited, the list contains
6390 the targets in the same sequence as the headlines appear, i.e.
6391 the tags of the current headline come last."
6392 (interactive)
6393 (let (tags)
6394 (save-excursion
6395 (goto-char (or pos (point)))
6396 (save-match-data
6397 (org-back-to-heading t)
6398 (condition-case nil
6399 (while t
6400 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6401 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6402 (or org-use-tag-inheritance (error ""))
6403 (org-up-heading-all 1))
6404 (error nil))))
6405 (message "%s" tags)
6406 tags))
6408 (defun org-agenda-set-tags ()
6409 "Set tags for the current headline."
6410 (interactive)
6411 (org-agenda-check-no-diary)
6412 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6413 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6414 (org-agenda-error)))
6415 (buffer (marker-buffer hdmarker))
6416 (pos (marker-position hdmarker))
6417 (buffer-read-only nil)
6418 newhead)
6419 (with-current-buffer buffer
6420 (widen)
6421 (goto-char pos)
6422 (org-show-hidden-entry)
6423 (save-excursion
6424 (and (outline-next-heading)
6425 (org-flag-heading nil))) ; show the next heading
6426 (call-interactively 'org-set-tags)
6427 (end-of-line 1)
6428 (setq newhead (org-get-heading)))
6429 (org-agenda-change-all-lines newhead hdmarker)
6430 (beginning-of-line 1)))
6432 (defun org-agenda-date-later (arg &optional what)
6433 "Change the date of this item to one day later."
6434 (interactive "p")
6435 (org-agenda-check-type t 'agenda 'timeline)
6436 (org-agenda-check-no-diary)
6437 (let* ((marker (or (get-text-property (point) 'org-marker)
6438 (org-agenda-error)))
6439 (buffer (marker-buffer marker))
6440 (pos (marker-position marker)))
6441 (with-current-buffer buffer
6442 (widen)
6443 (goto-char pos)
6444 (if (not (org-at-timestamp-p))
6445 (error "Cannot find time stamp"))
6446 (org-timestamp-change arg (or what 'day))
6447 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6449 (defun org-agenda-date-earlier (arg &optional what)
6450 "Change the date of this item to one day earlier."
6451 (interactive "p")
6452 (org-agenda-date-later (- arg) what))
6454 (defun org-agenda-date-prompt (arg)
6455 "Change the date of this item. Date is prompted for, with default today.
6456 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6457 be used to request time specification in the time stamp."
6458 (interactive "P")
6459 (org-agenda-check-type t 'agenda 'timeline)
6460 (org-agenda-check-no-diary)
6461 (let* ((marker (or (get-text-property (point) 'org-marker)
6462 (org-agenda-error)))
6463 (buffer (marker-buffer marker))
6464 (pos (marker-position marker)))
6465 (with-current-buffer buffer
6466 (widen)
6467 (goto-char pos)
6468 (if (not (org-at-timestamp-p))
6469 (error "Cannot find time stamp"))
6470 (org-time-stamp arg)
6471 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6473 (defun org-get-heading ()
6474 "Return the heading of the current entry, without the stars."
6475 (save-excursion
6476 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6477 ;;FIXME???????? (and (bolp) (end-of-line 1))
6478 (if (and (re-search-backward "[\r\n]\\*" nil t)
6479 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6480 (match-string 1)
6481 "")))
6483 (defun org-agenda-diary-entry ()
6484 "Make a diary entry, like the `i' command from the calendar.
6485 All the standard commands work: block, weekly etc."
6486 (interactive)
6487 (org-agenda-check-type t 'agenda 'timeline)
6488 (require 'diary-lib)
6489 (let* ((char (progn
6490 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6491 (read-char-exclusive)))
6492 (cmd (cdr (assoc char
6493 '((?d . insert-diary-entry)
6494 (?w . insert-weekly-diary-entry)
6495 (?m . insert-monthly-diary-entry)
6496 (?y . insert-yearly-diary-entry)
6497 (?a . insert-anniversary-diary-entry)
6498 (?b . insert-block-diary-entry)
6499 (?c . insert-cyclic-diary-entry)))))
6500 (oldf (symbol-function 'calendar-cursor-to-date))
6501 (point (point))
6502 (mark (or (mark t) (point))))
6503 (unless cmd
6504 (error "No command associated with <%c>" char))
6505 (unless (and (get-text-property point 'day)
6506 (or (not (equal ?b char))
6507 (get-text-property mark 'day)))
6508 (error "Don't know which date to use for diary entry"))
6509 ;; We implement this by hacking the `calendar-cursor-to-date' function
6510 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6511 (let ((calendar-mark-ring
6512 (list (calendar-gregorian-from-absolute
6513 (or (get-text-property mark 'day)
6514 (get-text-property point 'day))))))
6515 (unwind-protect
6516 (progn
6517 (fset 'calendar-cursor-to-date
6518 (lambda (&optional error)
6519 (calendar-gregorian-from-absolute
6520 (get-text-property point 'day))))
6521 (call-interactively cmd))
6522 (fset 'calendar-cursor-to-date oldf)))))
6525 (defun org-agenda-execute-calendar-command (cmd)
6526 "Execute a calendar command from the agenda, with the date associated to
6527 the cursor position."
6528 (org-agenda-check-type t 'agenda 'timeline)
6529 (require 'diary-lib)
6530 (unless (get-text-property (point) 'day)
6531 (error "Don't know which date to use for calendar command"))
6532 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6533 (point (point))
6534 (date (calendar-gregorian-from-absolute
6535 (get-text-property point 'day)))
6536 (displayed-day (extract-calendar-day date))
6537 (displayed-month (extract-calendar-month date))
6538 (displayed-year (extract-calendar-year date)))
6539 (unwind-protect
6540 (progn
6541 (fset 'calendar-cursor-to-date
6542 (lambda (&optional error)
6543 (calendar-gregorian-from-absolute
6544 (get-text-property point 'day))))
6545 (call-interactively cmd))
6546 (fset 'calendar-cursor-to-date oldf))))
6548 (defun org-agenda-phases-of-moon ()
6549 "Display the phases of the moon for the 3 months around the cursor date."
6550 (interactive)
6551 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6553 (defun org-agenda-holidays ()
6554 "Display the holidays for the 3 months around the cursor date."
6555 (interactive)
6556 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6558 (defun org-agenda-sunrise-sunset (arg)
6559 "Display sunrise and sunset for the cursor date.
6560 Latitude and longitude can be specified with the variables
6561 `calendar-latitude' and `calendar-longitude'. When called with prefix
6562 argument, latitude and longitude will be prompted for."
6563 (interactive "P")
6564 (let ((calendar-longitude (if arg nil calendar-longitude))
6565 (calendar-latitude (if arg nil calendar-latitude))
6566 (calendar-location-name
6567 (if arg "the given coordinates" calendar-location-name)))
6568 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6570 (defun org-agenda-goto-calendar ()
6571 "Open the Emacs calendar with the date at the cursor."
6572 (interactive)
6573 (org-agenda-check-type t 'agenda 'timeline)
6574 (let* ((day (or (get-text-property (point) 'day)
6575 (error "Don't know which date to open in calendar")))
6576 (date (calendar-gregorian-from-absolute day))
6577 (calendar-move-hook nil)
6578 (view-diary-entries-initially nil))
6579 (calendar)
6580 (calendar-goto-date date)))
6582 (defun org-calendar-goto-agenda ()
6583 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6584 This is a command that has to be installed in `calendar-mode-map'."
6585 (interactive)
6586 (org-agenda-list nil (calendar-absolute-from-gregorian
6587 (calendar-cursor-to-date))
6588 nil t))
6590 (defun org-agenda-convert-date ()
6591 (interactive)
6592 (org-agenda-check-type t 'agenda 'timeline)
6593 (let ((day (get-text-property (point) 'day))
6594 date s)
6595 (unless day
6596 (error "Don't know which date to convert"))
6597 (setq date (calendar-gregorian-from-absolute day))
6598 (setq s (concat
6599 "Gregorian: " (calendar-date-string date) "\n"
6600 "ISO: " (calendar-iso-date-string date) "\n"
6601 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6602 "Julian: " (calendar-julian-date-string date) "\n"
6603 "Astron. JD: " (calendar-astro-date-string date)
6604 " (Julian date number at noon UTC)\n"
6605 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6606 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6607 "French: " (calendar-french-date-string date) "\n"
6608 "Mayan: " (calendar-mayan-date-string date) "\n"
6609 "Coptic: " (calendar-coptic-date-string date) "\n"
6610 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6611 "Persian: " (calendar-persian-date-string date) "\n"
6612 "Chinese: " (calendar-chinese-date-string date) "\n"))
6613 (with-output-to-temp-buffer "*Dates*"
6614 (princ s))
6615 (if (fboundp 'fit-window-to-buffer)
6616 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6618 ;;; Tags
6620 (defun org-scan-tags (action matcher &optional todo-only)
6621 "Scan headline tags with inheritance and produce output ACTION.
6622 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6623 evaluated, testing if a given set of tags qualifies a headline for
6624 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
6625 are included in the output."
6626 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6627 (mapconcat 'regexp-quote
6628 (nreverse (cdr (reverse org-todo-keywords)))
6629 "\\|")
6630 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
6631 (props (list 'face nil
6632 'done-face 'org-done
6633 'undone-face nil
6634 'mouse-face 'highlight
6635 'keymap org-agenda-keymap
6636 'help-echo
6637 (format "mouse-2 or RET jump to org file %s"
6638 (abbreviate-file-name buffer-file-name))))
6639 lspos
6640 tags tags-list tags-alist (llast 0) rtn level category i txt
6641 todo marker)
6643 (save-excursion
6644 (goto-char (point-min))
6645 (when (eq action 'sparse-tree) (hide-sublevels 1))
6646 (while (re-search-forward re nil t)
6647 (setq todo (if (match-end 1) (match-string 2))
6648 tags (if (match-end 4) (match-string 4)))
6649 (goto-char (setq lspos (1+ (match-beginning 0))))
6650 (setq level (funcall outline-level)
6651 category (org-get-category))
6652 (setq i llast llast level)
6653 ;; remove tag lists from same and sublevels
6654 (while (>= i level)
6655 (when (setq entry (assoc i tags-alist))
6656 (setq tags-alist (delete entry tags-alist)))
6657 (setq i (1- i)))
6658 ;; add the nex tags
6659 (when tags
6660 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6661 tags-alist
6662 (cons (cons level tags) tags-alist)))
6663 ;; compile tags for current headline
6664 (setq tags-list
6665 (if org-use-tag-inheritance
6666 (apply 'append (mapcar 'cdr tags-alist))
6667 tags))
6668 (when (and (or (not todo-only) todo)
6669 (eval matcher))
6670 ;; list this headline
6671 (if (eq action 'sparse-tree)
6672 (progn
6673 (org-show-hierarchy-above))
6674 (setq txt (org-format-agenda-item
6676 (concat
6677 (if org-tags-match-list-sublevels
6678 (make-string (1- level) ?.) "")
6679 (org-get-heading))
6680 category tags-list))
6681 (goto-char lspos)
6682 (setq marker (org-agenda-new-marker))
6683 (add-text-properties
6684 0 (length txt)
6685 (append (list 'org-marker marker 'org-hd-marker marker
6686 'category category)
6687 props)
6688 txt)
6689 (push txt rtn))
6690 ;; if we are to skip sublevels, jump to end of subtree
6691 (point)
6692 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6693 (nreverse rtn)))
6695 (defun org-tags-sparse-tree (&optional arg match)
6696 "Create a sparse tree according to tags search string MATCH.
6697 MATCH can contain positive and negative selection of tags, like
6698 \"+WORK+URGENT-WITHBOSS\"."
6699 (interactive "P")
6700 (let ((org-show-following-heading nil)
6701 (org-show-hierarchy-above nil))
6702 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6704 (defun org-make-tags-matcher (match)
6705 "Create the TAGS matcher form for the tags-selecting string MATCH."
6706 (unless match
6707 ;; Get a new match request, with completion
6708 (setq org-last-tags-completion-table
6709 (or (org-get-buffer-tags)
6710 org-last-tags-completion-table))
6711 (setq match (completing-read
6712 "Tags: " 'org-tags-completion-function nil nil nil
6713 'org-tags-history)))
6714 ;; parse the string and create a lisp form
6715 (let ((match0 match) minus tag mm matcher orterms term orlist)
6716 (setq orterms (org-split-string match "|"))
6717 (while (setq term (pop orterms))
6718 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
6719 (setq minus (and (match-end 1)
6720 (equal (match-string 1 term) "-"))
6721 tag (match-string 2 term)
6722 term (substring term (match-end 0))
6723 mm (list 'member (downcase tag) 'tags-list)
6724 mm (if minus (list 'not mm) mm))
6725 (push mm matcher))
6726 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6727 orlist)
6728 (setq matcher nil))
6729 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6730 ;; Return the string and lisp forms of the matcher
6731 (cons match0 matcher)))
6733 ;;;###autoload
6734 (defun org-tags-view (&optional todo-only match keep-modes)
6735 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
6736 The prefix arg TODO-ONLY limits the search to TODO entries."
6737 (interactive "P")
6738 (org-agenda-maybe-reset-markers 'force)
6739 (org-compile-prefix-format org-agenda-prefix-format)
6740 (let* ((org-agenda-keep-modes keep-modes)
6741 (org-tags-match-list-sublevels
6742 (if todo-only t org-tags-match-list-sublevels))
6743 (win (selected-window))
6744 (completion-ignore-case t)
6745 rtn rtnall files file pos matcher
6746 buffer)
6747 (setq matcher (org-make-tags-matcher match)
6748 match (car matcher) matcher (cdr matcher))
6749 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6750 (progn
6751 (delete-other-windows)
6752 (switch-to-buffer-other-window
6753 (get-buffer-create org-agenda-buffer-name))))
6754 (setq buffer-read-only nil)
6755 (erase-buffer)
6756 (org-agenda-mode) (setq buffer-read-only nil)
6757 (set (make-local-variable 'org-agenda-type) 'tags)
6758 (set (make-local-variable 'org-agenda-redo-command)
6759 (list 'org-tags-view (list 'quote todo-only)
6760 (list 'if 'current-prefix-arg nil match) t))
6761 (setq files (org-agenda-files)
6762 rtnall nil)
6763 (while (setq file (pop files))
6764 (catch 'nextfile
6765 (org-check-agenda-file file)
6766 (setq buffer (if (file-exists-p file)
6767 (org-get-agenda-file-buffer file)
6768 (error "No such file %s" file)))
6769 (if (not buffer)
6770 ;; If file does not exist, merror message to agenda
6771 (setq rtn (list
6772 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6773 rtnall (append rtnall rtn))
6774 (with-current-buffer buffer
6775 (unless (eq major-mode 'org-mode)
6776 (error "Agenda file %s is not in `org-mode'" file))
6777 (save-excursion
6778 (save-restriction
6779 (if org-respect-restriction
6780 (if (org-region-active-p)
6781 ;; Respect a region to restrict search
6782 (narrow-to-region (region-beginning) (region-end)))
6783 ;; If we work for the calendar or many files,
6784 ;; get rid of any restriction
6785 (widen))
6786 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6787 (setq rtnall (append rtnall rtn))))))))
6788 (insert "Headlines with TAGS match: ")
6789 (add-text-properties (point-min) (1- (point))
6790 (list 'face 'org-link))
6791 (setq pos (point))
6792 (insert match "\n")
6793 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6794 (setq pos (point))
6795 (insert "Press `C-u r' to search again with new search string\n")
6796 (add-text-properties pos (1- (point)) (list 'face 'org-link))
6797 (when rtnall
6798 (insert (mapconcat 'identity rtnall "\n")))
6799 (goto-char (point-min))
6800 (setq buffer-read-only t)
6801 (org-fit-agenda-window)
6802 (if (not org-select-agenda-window) (select-window win))))
6804 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
6805 (defun org-set-tags (&optional arg just-align)
6806 "Set the tags for the current headline.
6807 With prefix ARG, realign all tags in headings in the current buffer."
6808 (interactive)
6809 (let* (;(inherit (org-get-inherited-tags))
6810 (re (concat "^" outline-regexp))
6811 (col (current-column))
6812 (current (org-get-tags))
6813 tags hd empty invis)
6814 (if arg
6815 (save-excursion
6816 (goto-char (point-min))
6817 (while (re-search-forward re nil t)
6818 (org-set-tags nil t))
6819 (message "All tags realigned to column %d" org-tags-column))
6820 (if just-align
6821 (setq tags current)
6822 (setq org-last-tags-completion-table
6823 (or (org-get-buffer-tags)
6824 org-last-tags-completion-table))
6825 (setq tags
6826 (let ((org-add-colon-after-tag-completion t))
6827 (completing-read "Tags: " 'org-tags-completion-function
6828 nil nil current 'org-tags-history)))
6829 (while (string-match "[-+&]+" tags)
6830 (setq tags (replace-match ":" t t tags))))
6831 ;; FIXME: still optimize this by not checking when JUST-ALIGN?
6832 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
6833 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
6834 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
6835 (if (equal current "")
6836 (progn
6837 (end-of-line 1)
6838 (or empty (insert-before-markers " ")))
6839 (beginning-of-line 1)
6840 (setq invis (org-invisible-p))
6841 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
6842 (setq hd (match-string 1))
6843 (delete-region (match-beginning 0) (match-end 0))
6844 (insert-before-markers (org-trim hd) (if empty "" " ")))
6845 ;; FIXME: What happens when adding a new tag??? Seems OK!!!
6846 (unless (equal tags "")
6847 (move-to-column (max (current-column)
6848 (if (> org-tags-column 0)
6849 org-tags-column
6850 (- (- org-tags-column) (length tags))))
6852 (insert-before-markers tags)
6853 (if (and (not invis) (org-invisible-p))
6854 (outline-flag-region (point-at-bol) (point) nil)))
6855 (move-to-column col))))
6857 (defun org-tags-completion-function (string predicate &optional flag)
6858 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
6859 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
6860 (setq s1 (match-string 1 string)
6861 s2 (match-string 2 string))
6862 (setq s1 "" s2 string))
6863 (cond
6864 ((eq flag nil)
6865 ;; try completion
6866 (setq rtn (try-completion s2 ctable))
6867 (if (stringp rtn)
6868 (concat s1 s2 (substring rtn (length s2))
6869 (if (and org-add-colon-after-tag-completion
6870 (assoc rtn ctable))
6871 ":" "")))
6873 ((eq flag t)
6874 ;; all-completions
6875 (all-completions s2 ctable)
6877 ((eq flag 'lambda)
6878 ;; exact match?
6879 (assoc s2 ctable)))
6882 (defun org-get-tags ()
6883 "Get the TAGS string in the current headline."
6884 (unless (org-on-heading-p)
6885 (error "Not on a heading"))
6886 (save-excursion
6887 (beginning-of-line 1)
6888 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
6889 (match-string 1)
6890 "")))
6892 (defun org-get-buffer-tags ()
6893 "Get a table of all tags used in the buffer, for completion."
6894 (let (tags)
6895 (save-excursion
6896 (goto-char (point-min))
6897 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
6898 (mapc (lambda (x) (add-to-list 'tags x))
6899 (org-split-string (match-string 1) ":"))))
6900 (mapcar 'list tags)))
6902 ;;; Link Stuff
6904 (defun org-find-file-at-mouse (ev)
6905 "Open file link or URL at mouse."
6906 (interactive "e")
6907 (mouse-set-point ev)
6908 (org-open-at-point 'in-emacs))
6910 (defun org-open-at-mouse (ev)
6911 "Open file link or URL at mouse."
6912 (interactive "e")
6913 (mouse-set-point ev)
6914 (org-open-at-point))
6916 (defun org-open-at-point (&optional in-emacs)
6917 "Open link at or after point.
6918 If there is no link at point, this function will search forward up to
6919 the end of the current subtree.
6920 Normally, files will be opened by an appropriate application. If the
6921 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6922 (interactive "P")
6923 (org-remove-occur-highlights nil nil t)
6924 (if (org-at-timestamp-p)
6925 (org-agenda-list nil (time-to-days (org-time-string-to-time
6926 (substring (match-string 1) 0 10)))
6928 (let (type path link line search (pos (point)))
6929 (catch 'match
6930 (save-excursion
6931 (skip-chars-forward "^]\n\r")
6932 (when (and (re-search-backward "\\[\\[" nil t)
6933 (looking-at org-bracket-link-regexp)
6934 (<= (match-beginning 0) pos)
6935 (>= (match-end 0) pos))
6936 (setq link (match-string 1))
6937 (while (string-match " *\n *" link)
6938 (setq link (replace-match " " t t link)))
6939 (if (string-match org-link-regexp link)
6940 (setq type (match-string 1 link)
6941 path (match-string 2 link))
6942 (setq type "thisfile"
6943 path link))
6944 (throw 'match t)))
6946 (when (get-text-property (point) 'org-linked-text)
6947 (setq type "thisfile"
6948 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6949 (1+ (point)) (point))
6950 path (buffer-substring
6951 (previous-single-property-change pos 'org-linked-text)
6952 (next-single-property-change pos 'org-linked-text)))
6953 (throw 'match t))
6955 (save-excursion
6956 (skip-chars-backward
6957 (concat (if org-allow-space-in-links "^" "^ ")
6958 org-non-link-chars))
6959 (when (or (looking-at org-link-regexp)
6960 (and (re-search-forward org-link-regexp (point-at-eol) t)
6961 (<= (match-beginning 0) pos)
6962 (>= (match-end 0) pos)))
6963 (setq type (match-string 1)
6964 path (match-string 2))
6965 (throw 'match t)))
6966 (save-excursion
6967 (skip-chars-backward "^ \t\n\r")
6968 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
6969 (setq type "tags"
6970 path (match-string 1))
6971 (while (string-match ":" path)
6972 (setq path (replace-match "+" t t path)))
6973 (throw 'match t)))
6974 (save-excursion
6975 (skip-chars-backward "a-zA-Z_")
6976 (when (and org-activate-camels
6977 (looking-at org-camel-regexp))
6978 (setq type "camel" path (match-string 0))
6979 (if (equal (char-before) ?*)
6980 (setq path (concat "*" path))))
6981 (throw 'match t))
6982 (save-excursion
6983 (when (re-search-forward
6984 org-link-regexp
6985 (save-excursion
6986 (condition-case nil
6987 (progn (outline-end-of-subtree) (max pos (point)))
6988 (error (end-of-line 1) (point))))
6990 (setq type (match-string 1)
6991 path (match-string 2)))))
6992 (unless path
6993 (error "No link found"))
6994 ;; Remove any trailing spaces in path
6995 (if (string-match " +\\'" path)
6996 (setq path (replace-match "" t t path)))
6998 (cond
7000 ((member type '("http" "https" "ftp" "mailto" "news"))
7001 (browse-url (concat type ":" path)))
7003 ((string= type "tags")
7004 (org-tags-view in-emacs path))
7005 ((or (string= type "camel")
7006 (string= type "thisfile"))
7007 (org-mark-ring-push)
7008 (org-link-search
7009 path
7010 (cond ((equal in-emacs '(4)) 'occur)
7011 ((equal in-emacs '(16)) 'org-occur)
7012 (t nil))))
7014 ((string= type "file")
7015 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
7016 (setq line (string-to-number (match-string 1 path))
7017 path (substring path 0 (match-beginning 0)))
7018 (if (string-match "::\\(.+\\)\\'" path)
7019 (setq search (match-string 1 path)
7020 path (substring path 0 (match-beginning 0)))))
7021 (org-open-file path in-emacs line search))
7023 ((string= type "news")
7024 (org-follow-gnus-link path))
7026 ((string= type "bbdb")
7027 (org-follow-bbdb-link path))
7029 ((string= type "gnus")
7030 (let (group article)
7031 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7032 (error "Error in Gnus link"))
7033 (setq group (match-string 1 path)
7034 article (match-string 3 path))
7035 (org-follow-gnus-link group article)))
7037 ((string= type "vm")
7038 (let (folder article)
7039 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7040 (error "Error in VM link"))
7041 (setq folder (match-string 1 path)
7042 article (match-string 3 path))
7043 ;; in-emacs is the prefix arg, will be interpreted as read-only
7044 (org-follow-vm-link folder article in-emacs)))
7046 ((string= type "wl")
7047 (let (folder article)
7048 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7049 (error "Error in Wanderlust link"))
7050 (setq folder (match-string 1 path)
7051 article (match-string 3 path))
7052 (org-follow-wl-link folder article)))
7054 ((string= type "mhe")
7055 (let (folder article)
7056 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7057 (error "Error in MHE link"))
7058 (setq folder (match-string 1 path)
7059 article (match-string 3 path))
7060 (org-follow-mhe-link folder article)))
7062 ((string= type "rmail")
7063 (let (folder article)
7064 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7065 (error "Error in RMAIL link"))
7066 (setq folder (match-string 1 path)
7067 article (match-string 3 path))
7068 (org-follow-rmail-link folder article)))
7070 ((string= type "shell")
7071 (let ((cmd path))
7072 (while (string-match "@{" cmd)
7073 (setq cmd (replace-match "<" t t cmd)))
7074 (while (string-match "@}" cmd)
7075 (setq cmd (replace-match ">" t t cmd)))
7076 (if (or (not org-confirm-shell-links)
7077 (yes-or-no-p (format "Execute \"%s\" in the shell? " cmd)))
7078 (shell-command cmd)
7079 (error "Abort"))))
7082 (browse-url-at-point))))))
7084 (defun org-link-search (s &optional type)
7085 "Search for a link search option.
7086 When S is a CamelCaseWord, search for a target, or for a sentence containing
7087 the words. If S is surrounded by forward slashes, it is interpreted as a
7088 regular expression. In org-mode files, this will create an `org-occur'
7089 sparse tree. In ordinary files, `occur' will be used to list matches.
7090 If the current buffer is in `dired-mode', grep will be used to search
7091 in all files."
7092 (let ((case-fold-search t)
7093 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7094 (pos (point))
7095 (pre "") (post "")
7096 words re0 re1 re2 re3 re4 re5 re2a reall camel)
7097 (cond ((save-excursion
7098 (goto-char (point-min))
7099 (and
7100 (re-search-forward
7101 (concat "<<" (regexp-quote s0) ">>") nil t)
7102 (setq pos (match-beginning 0))))
7103 ;; There is an exact target for this
7104 (goto-char pos))
7105 ((string-match "^/\\(.*\\)/$" s)
7106 ;; A regular expression
7107 (cond
7108 ((eq major-mode 'org-mode)
7109 (org-occur (match-string 1 s)))
7110 ;;((eq major-mode 'dired-mode)
7111 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7112 (t (org-do-occur (match-string 1 s)))))
7113 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
7115 ;; A camel or a normal search string
7116 (when (equal (string-to-char s) ?*)
7117 ;; Anchor on headlines, post may include tags.
7118 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
7119 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
7120 s (substring s 1)))
7121 (remove-text-properties
7122 0 (length s)
7123 '(face nil mouse-face nil keymap nil fontified nil) s)
7124 ;; Make a series of regular expressions to find a match
7125 (setq words
7126 (if camel
7127 (org-camel-to-words s)
7128 (org-split-string s "[ \n\r\t]+"))
7129 re0 (concat "<<" (regexp-quote s0) ">>")
7130 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
7131 re2a (concat "\\<" (mapconcat 'downcase words "[ \t\r\n]+") "\\>")
7132 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
7133 re1 (concat pre re2 post)
7134 re3 (concat pre re4 post)
7135 re5 (concat pre ".*" re4)
7136 re2 (concat pre re2)
7137 re2a (concat pre re2a)
7138 re4 (concat pre re4)
7139 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7140 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7141 re5 "\\)"
7143 (cond
7144 ((eq type 'org-occur) (org-occur reall))
7145 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7146 (t (goto-char (point-min))
7147 (if (or (org-search-not-link re0 nil t)
7148 (org-search-not-link re1 nil t)
7149 (org-search-not-link re2 nil t)
7150 (org-search-not-link re2a nil t) ;; FIXME: Right place???
7151 (org-search-not-link re3 nil t)
7152 (org-search-not-link re4 nil t)
7153 (org-search-not-link re5 nil t)
7155 (goto-char (match-beginning 0))
7156 (goto-char pos)
7157 (error "No match")))))
7159 ;; Normal string-search
7160 (goto-char (point-min))
7161 (if (search-forward s nil t)
7162 (goto-char (match-beginning 0))
7163 (error "No match"))))
7164 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
7166 (defun org-search-not-link (&rest args)
7167 "Execute `re-search-forward', but only accept matches that are not a link."
7168 (catch 'exit
7169 (let ((pos (point)) p1)
7170 (while (apply 're-search-forward args)
7171 (setq p1 (point))
7172 (if (not (save-match-data
7173 (and (re-search-backward "\\[\\[" nil t)
7174 (looking-at org-bracket-link-regexp)
7175 (<= (match-beginning 0) p1)
7176 (>= (match-end 0) p1))))
7177 (progn (goto-char (match-end 0))
7178 (throw 'exit (point)))
7179 (goto-char (match-end 0)))))))
7181 (defun org-do-occur (regexp &optional cleanup)
7182 "Call the Emacs command `occur'.
7183 If CLEANUP is non-nil, remove the printout of the regular expression
7184 in the *Occur* buffer. This is useful if the regex is long and not useful
7185 to read."
7186 (occur regexp)
7187 (when cleanup
7188 (let ((cwin (selected-window)) win beg end)
7189 (when (setq win (get-buffer-window "*Occur*"))
7190 (select-window win))
7191 (goto-char (point-min))
7192 (when (re-search-forward "match[a-z]+" nil t)
7193 (setq beg (match-end 0))
7194 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7195 (setq end (1- (match-beginning 0)))))
7196 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
7197 (goto-char (point-min))
7198 (select-window cwin))))
7200 (defvar org-mark-ring nil
7201 "Mark ring for positions before jumps in Org-mode.")
7202 (defvar org-mark-ring-last-goto nil
7203 "Last position in the mark ring used to go back.")
7204 ;; Fill and close the ring
7205 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7206 (loop for i from 1 to org-mark-ring-length do
7207 (push (make-marker) org-mark-ring))
7208 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7209 org-mark-ring)
7211 (defun org-mark-ring-push (&optional pos buffer)
7212 "Put the current position or POS into the mark ring and rotate it."
7213 (interactive)
7214 (setq pos (or pos (point)))
7215 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7216 (move-marker (car org-mark-ring)
7217 (or pos (point))
7218 (or buffer (current-buffer)))
7219 (message
7220 (substitute-command-keys
7221 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7223 (defun org-mark-ring-goto (&optional n)
7224 "Jump to the previous position in the mark ring.
7225 With prefix arg N, jump back that many stored positions. When
7226 called several times in succession, walk through the entire ring.
7227 Org-mode commands jumping to a different position in the current file,
7228 or to another Org-mode file, automatically push the old position
7229 onto the ring."
7230 (interactive "p")
7231 (let (p m)
7232 (if (eq last-command this-command)
7233 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7234 (setq p org-mark-ring))
7235 (setq org-mark-ring-last-goto p)
7236 (setq m (car p))
7237 (switch-to-buffer (marker-buffer m))
7238 (goto-char m)
7239 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7241 (defun org-camel-to-words (s)
7242 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7243 (let ((case-fold-search nil)
7244 words)
7245 (while (string-match "[a-z][A-Z]" s)
7246 (push (substring s 0 (1+ (match-beginning 0))) words)
7247 (setq s (substring s (1+ (match-beginning 0)))))
7248 (nreverse (cons s words))))
7250 (defun org-remove-angle-brackets (s)
7251 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7252 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7254 (defun org-add-angle-brackets (s)
7255 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7256 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7259 (defun org-follow-bbdb-link (name)
7260 "Follow a BBDB link to NAME."
7261 (require 'bbdb)
7262 (let ((inhibit-redisplay t)
7263 (bbdb-electric-p nil))
7264 (catch 'exit
7265 ;; Exact match on name
7266 (bbdb-name (concat "\\`" name "\\'") nil)
7267 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7268 ;; Exact match on name
7269 (bbdb-company (concat "\\`" name "\\'") nil)
7270 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7271 ;; Partial match on name
7272 (bbdb-name name nil)
7273 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7274 ;; Partial match on company
7275 (bbdb-company name nil)
7276 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7277 ;; General match including network address and notes
7278 (bbdb name nil)
7279 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7280 (delete-window (get-buffer-window "*BBDB*"))
7281 (error "No matching BBDB record")))))
7283 (defun org-follow-gnus-link (&optional group article)
7284 "Follow a Gnus link to GROUP and ARTICLE."
7285 (require 'gnus)
7286 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7287 (if group (gnus-fetch-group group))
7288 (if article
7289 (or (gnus-summary-goto-article article nil 'force)
7290 (if (fboundp 'gnus-summary-insert-cached-articles)
7291 (progn
7292 (gnus-summary-insert-cached-articles)
7293 (gnus-summary-goto-article article nil 'force))
7294 (message "Message could not be found.")))))
7296 (defun org-follow-vm-link (&optional folder article readonly)
7297 "Follow a VM link to FOLDER and ARTICLE."
7298 (require 'vm)
7299 (setq article (org-add-angle-brackets article))
7300 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7301 ;; ange-ftp or efs or tramp access
7302 (let ((user (or (match-string 1 folder) (user-login-name)))
7303 (host (match-string 2 folder))
7304 (file (match-string 3 folder)))
7305 (cond
7306 ((featurep 'tramp)
7307 ;; use tramp to access the file
7308 (if (featurep 'xemacs)
7309 (setq folder (format "[%s@%s]%s" user host file))
7310 (setq folder (format "/%s@%s:%s" user host file))))
7312 ;; use ange-ftp or efs
7313 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
7314 (setq folder (format "/%s@%s:%s" user host file))))))
7315 (when folder
7316 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7317 (sit-for 0.1)
7318 (when article
7319 (vm-select-folder-buffer)
7320 (widen)
7321 (let ((case-fold-search t))
7322 (goto-char (point-min))
7323 (if (not (re-search-forward
7324 (concat "^" "message-id: *" (regexp-quote article))))
7325 (error "Could not find the specified message in this folder"))
7326 (vm-isearch-update)
7327 (vm-isearch-narrow)
7328 (vm-beginning-of-message)
7329 (vm-summarize)))))
7331 (defun org-follow-wl-link (folder article)
7332 "Follow a Wanderlust link to FOLDER and ARTICLE."
7333 (setq article (org-add-angle-brackets article))
7334 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7335 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7336 (wl-summary-redisplay))
7338 (defun org-follow-rmail-link (folder article)
7339 "Follow an RMAIL link to FOLDER and ARTICLE."
7340 (setq article (org-add-angle-brackets article))
7341 (let (message-number)
7342 (save-excursion
7343 (save-window-excursion
7344 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7345 (setq message-number
7346 (save-restriction
7347 (widen)
7348 (goto-char (point-max))
7349 (if (re-search-backward
7350 (concat "^Message-ID:\\s-+" (regexp-quote
7351 (or article "")))
7352 nil t)
7353 (rmail-what-message))))))
7354 (if message-number
7355 (progn
7356 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7357 (rmail-show-message message-number)
7358 message-number)
7359 (error "Message not found"))))
7361 ;; mh-e integration based on planner-mode
7362 (defun org-mhe-get-message-real-folder ()
7363 "Return the name of the current message real folder, so if you use
7364 sequences, it will now work."
7365 (save-excursion
7366 (let* ((folder
7367 (if (equal major-mode 'mh-folder-mode)
7368 mh-current-folder
7369 ;; Refer to the show buffer
7370 mh-show-folder-buffer))
7371 (end-index
7372 (if (boundp 'mh-index-folder)
7373 (min (length mh-index-folder) (length folder))))
7375 ;; a simple test on mh-index-data does not work, because
7376 ;; mh-index-data is always nil in a show buffer.
7377 (if (and (boundp 'mh-index-folder)
7378 (string= mh-index-folder (substring folder 0 end-index)))
7379 (if (equal major-mode 'mh-show-mode)
7380 (save-window-excursion
7381 (when (buffer-live-p (get-buffer folder))
7382 (progn
7383 (pop-to-buffer folder)
7384 (org-mhe-get-message-folder-from-index)
7387 (org-mhe-get-message-folder-from-index)
7389 folder
7393 (defun org-mhe-get-message-folder-from-index ()
7394 "Returns the name of the message folder in a index folder buffer."
7395 (save-excursion
7396 (mh-index-previous-folder)
7397 (re-search-forward "^\\(+.*\\)$" nil t)
7398 (message (match-string 1))))
7400 (defun org-mhe-get-message-folder ()
7401 "Return the name of the current message folder. Be careful if you
7402 use sequences."
7403 (save-excursion
7404 (if (equal major-mode 'mh-folder-mode)
7405 mh-current-folder
7406 ;; Refer to the show buffer
7407 mh-show-folder-buffer)))
7409 (defun org-mhe-get-message-num ()
7410 "Return the number of the current message. Be careful if you
7411 use sequences."
7412 (save-excursion
7413 (if (equal major-mode 'mh-folder-mode)
7414 (mh-get-msg-num nil)
7415 ;; Refer to the show buffer
7416 (mh-show-buffer-message-number))))
7418 (defun org-mhe-get-header (header)
7419 "Return a header of the message in folder mode. This will create a
7420 show buffer for the corresponding message. If you have a more clever
7421 idea..."
7422 (let* ((folder (org-mhe-get-message-folder))
7423 (num (org-mhe-get-message-num))
7424 (buffer (get-buffer-create (concat "show-" folder)))
7425 (header-field))
7426 (with-current-buffer buffer
7427 (mh-display-msg num folder)
7428 (if (equal major-mode 'mh-folder-mode)
7429 (mh-header-display)
7430 (mh-show-header-display))
7431 (set-buffer buffer)
7432 (setq header-field (mh-get-header-field header))
7433 (if (equal major-mode 'mh-folder-mode)
7434 (mh-show)
7435 (mh-show-show))
7436 header-field)))
7438 (defun org-follow-mhe-link (folder article)
7439 "Follow an MHE link to FOLDER and ARTICLE.
7440 If ARTICLE is nil FOLDER is shown. If the configuration variable
7441 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
7442 ARTICLE is searched in all folders. Indexed searches (swish++,
7443 namazu, and others supported by MH-E) will always search in all
7444 folders."
7445 (require 'mh-e)
7446 (require 'mh-search)
7447 (require 'mh-utils)
7448 (mh-find-path)
7449 (if (not article)
7450 (mh-visit-folder (mh-normalize-folder-name folder))
7451 (setq article (org-add-angle-brackets article))
7452 (mh-search-choose)
7453 (if (equal mh-searcher 'pick)
7454 (progn
7455 (mh-search folder (list "--message-id" article))
7456 (when (and org-mhe-search-all-folders
7457 (not (org-mhe-get-message-real-folder)))
7458 (kill-this-buffer)
7459 (mh-search "+" (list "--message-id" article))))
7460 (mh-search "+" article))
7461 (if (org-mhe-get-message-real-folder)
7462 (mh-show-msg 1)
7463 (kill-this-buffer)
7464 (error "Message not found"))))
7466 (defun org-open-file (path &optional in-emacs line search)
7467 "Open the file at PATH.
7468 First, this expands any special file name abbreviations. Then the
7469 configuration variable `org-file-apps' is checked if it contains an
7470 entry for this file type, and if yes, the corresponding command is launched.
7471 If no application is found, Emacs simply visits the file.
7472 With optional argument IN-EMACS, Emacs will visit the file.
7473 Optional LINE specifies a line to go to, optional SEARCH a string to
7474 search for. If LINE or SEARCH is given, the file will always be
7475 opened in Emacs.
7476 If the file does not exist, an error is thrown."
7477 (setq in-emacs (or in-emacs line search))
7478 (let* ((file (if (equal path "")
7479 buffer-file-name
7480 (convert-standard-filename (org-expand-file-name path))))
7481 (dirp (file-directory-p file))
7482 (dfile (downcase file))
7483 (old-buffer (current-buffer))
7484 (old-pos (point))
7485 (old-mode major-mode)
7486 ext cmd apps)
7487 (if (and (not (file-exists-p file))
7488 (not org-open-non-existing-files))
7489 (error "No such file: %s" file))
7490 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7491 (setq ext (match-string 1 dfile))
7492 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7493 (setq ext (match-string 1 dfile))))
7494 (setq apps (append org-file-apps (org-default-apps)))
7495 (if in-emacs
7496 (setq cmd 'emacs)
7497 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7498 (cdr (assoc ext apps))
7499 (cdr (assoc t apps)))))
7500 (when (eq cmd 'mailcap)
7501 (require 'mailcap)
7502 (mailcap-parse-mailcaps)
7503 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7504 (command (mailcap-mime-info mime-type)))
7505 (if (stringp command)
7506 (setq cmd command)
7507 (setq cmd 'emacs))))
7508 (cond
7509 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7510 (setq cmd (format cmd (concat "\"" file "\"")))
7511 (save-window-excursion
7512 (shell-command (concat cmd " &"))))
7513 ((or (stringp cmd)
7514 (eq cmd 'emacs))
7515 (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
7516 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7517 (if line (goto-line line)
7518 (if search (org-link-search search))))
7519 ((consp cmd)
7520 (eval cmd))
7521 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7522 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7523 (or (not (equal old-buffer (current-buffer)))
7524 (not (equal old-pos (point))))
7525 (org-mark-ring-push old-pos old-buffer))))
7527 (defun org-default-apps ()
7528 "Return the default applications for this operating system."
7529 (cond
7530 ((eq system-type 'darwin)
7531 org-file-apps-defaults-macosx)
7532 ((eq system-type 'windows-nt)
7533 org-file-apps-defaults-windowsnt)
7534 (t org-file-apps-defaults-gnu)))
7536 (defun org-expand-file-name (path)
7537 "Replace special path abbreviations and expand the file name."
7538 (expand-file-name path))
7541 (defvar org-insert-link-history nil
7542 "Minibuffer history for links inserted with `org-insert-link'.")
7544 (defvar org-stored-links nil
7545 "Contains the links stored with `org-store-link'.")
7547 ;;;###autoload
7548 (defun org-store-link (arg)
7549 "\\<org-mode-map>Store an org-link to the current location.
7550 This link can later be inserted into an org-buffer with
7551 \\[org-insert-link].
7552 For some link types, a prefix arg is interpreted:
7553 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7554 For file links, arg negates `org-context-in-file-links'."
7555 (interactive "P")
7556 (let (link cpltxt txt (pos (point)))
7557 (cond
7559 ((eq major-mode 'bbdb-mode)
7560 (setq cpltxt (concat
7561 "bbdb:"
7562 (or (bbdb-record-name (bbdb-current-record))
7563 (bbdb-record-company (bbdb-current-record))))
7564 link (org-make-link cpltxt)))
7566 ((eq major-mode 'calendar-mode)
7567 (let ((cd (calendar-cursor-to-date)))
7568 (setq link
7569 (format-time-string
7570 (car org-time-stamp-formats)
7571 (apply 'encode-time
7572 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7573 nil nil nil))))))
7575 ((or (eq major-mode 'vm-summary-mode)
7576 (eq major-mode 'vm-presentation-mode))
7577 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7578 (vm-follow-summary-cursor)
7579 (save-excursion
7580 (vm-select-folder-buffer)
7581 (let* ((message (car vm-message-pointer))
7582 (folder buffer-file-name)
7583 (subject (vm-su-subject message))
7584 (author (vm-su-full-name message))
7585 (message-id (vm-su-message-id message)))
7586 (setq message-id (org-remove-angle-brackets message-id))
7587 (setq folder (abbreviate-file-name folder))
7588 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7589 folder)
7590 (setq folder (replace-match "" t t folder)))
7591 (setq cpltxt (concat author " on: " subject))
7592 (setq link (concat cpltxt "\n "
7593 (org-make-link
7594 "vm:" folder "#" message-id))))))
7596 ((eq major-mode 'wl-summary-mode)
7597 (let* ((msgnum (wl-summary-message-number))
7598 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7599 msgnum 'message-id))
7600 (wl-message-entity (elmo-msgdb-overview-get-entity
7601 msgnum (wl-summary-buffer-msgdb)))
7602 (author (wl-summary-line-from)) ; FIXME: how to get author name?
7603 (subject "???")) ; FIXME: How to get subject of email?
7604 (setq message-id (org-remove-angle-brackets message-id))
7605 (setq cpltxt (concat author " on: " subject))
7606 (setq link (concat cpltxt "\n "
7607 (org-make-link
7608 "wl:" wl-summary-buffer-folder-name
7609 "#" message-id)))))
7611 ((or (equal major-mode 'mh-folder-mode)
7612 (equal major-mode 'mh-show-mode))
7613 (let ((from-header (org-mhe-get-header "From:"))
7614 (to-header (org-mhe-get-header "To:"))
7615 (subject (org-mhe-get-header "Subject:")))
7616 (setq cpltxt (concat from-header " on: " subject))
7617 (setq link (concat cpltxt "\n "
7618 (org-make-link
7619 "mhe:" (org-mhe-get-message-real-folder) "#"
7620 (org-remove-angle-brackets
7621 (org-mhe-get-header "Message-Id:")))))))
7623 ((eq major-mode 'rmail-mode)
7624 (save-excursion
7625 (save-restriction
7626 (rmail-narrow-to-non-pruned-header)
7627 (let ((folder buffer-file-name)
7628 (message-id (mail-fetch-field "message-id"))
7629 (author (mail-fetch-field "from"))
7630 (subject (mail-fetch-field "subject")))
7631 (setq message-id (org-remove-angle-brackets message-id))
7632 (setq cpltxt (concat author " on: " subject))
7633 (setq link (concat cpltxt "\n "
7634 (org-make-link
7635 "rmail:" folder "#" message-id)))))))
7637 ((eq major-mode 'gnus-group-mode)
7638 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7639 (gnus-group-group-name)) ; version
7640 ((fboundp 'gnus-group-name)
7641 (gnus-group-name))
7642 (t "???"))))
7643 (setq cpltxt (concat
7644 (if (org-xor arg org-usenet-links-prefer-google)
7645 "http://groups.google.com/groups?group="
7646 "gnus:")
7647 group)
7648 link (org-make-link cpltxt))))
7650 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7651 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7652 (gnus-summary-beginning-of-article)
7653 (let* ((group (car gnus-article-current))
7654 (article (cdr gnus-article-current))
7655 (header (gnus-summary-article-header article))
7656 (author (mail-header-from header))
7657 (message-id (mail-header-id header))
7658 (date (mail-header-date header))
7659 (subject (gnus-summary-subject-string)))
7660 (setq cpltxt (concat author " on: " subject))
7661 (if (org-xor arg org-usenet-links-prefer-google)
7662 (setq link
7663 (concat
7664 cpltxt "\n "
7665 (format "http://groups.google.com/groups?as_umsgid=%s"
7666 (org-fixup-message-id-for-http message-id))))
7667 (setq link (concat cpltxt "\n"
7668 (org-make-link
7669 "gnus:" group
7670 "#" (number-to-string article)))))))
7672 ((eq major-mode 'w3-mode)
7673 (setq cpltxt (url-view-url t)
7674 link (org-make-link cpltxt)))
7675 ((eq major-mode 'w3m-mode)
7676 (setq cpltxt w3m-current-url
7677 link (org-make-link cpltxt)))
7679 ((eq major-mode 'org-mode)
7680 ;; Just link to current headline
7681 (setq cpltxt (concat "file:"
7682 (abbreviate-file-name buffer-file-name)))
7683 ;; Add a context search string
7684 (when (org-xor org-context-in-file-links arg)
7685 ;; Check if we are on a target
7686 (if (save-excursion
7687 (skip-chars-forward "^>\n\r")
7688 (and (re-search-backward "<<" nil t)
7689 (looking-at "<<\\(.*?\\)>>")
7690 (<= (match-beginning 0) pos)
7691 (>= (match-end 0) pos)))
7692 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7693 (setq txt (cond
7694 ((org-on-heading-p) nil)
7695 ((org-region-active-p)
7696 (buffer-substring (region-beginning) (region-end)))
7697 (t (buffer-substring (point-at-bol) (point-at-eol)))))
7698 (setq cpltxt
7699 (concat cpltxt "::"
7700 (if org-file-link-context-use-camel-case
7701 (org-make-org-heading-camel txt)
7702 (org-make-org-heading-search-string txt))))))
7703 (if (string-match "::\\'" cpltxt)
7704 (setq cpltxt (substring cpltxt 0 -2)))
7705 (setq link (org-make-link cpltxt)))
7707 (buffer-file-name
7708 ;; Just link to this file here.
7709 (setq cpltxt (concat "file:"
7710 (abbreviate-file-name buffer-file-name)))
7711 ;; Add a context string
7712 (when (org-xor org-context-in-file-links arg)
7713 (setq txt (if (org-region-active-p)
7714 (buffer-substring (region-beginning) (region-end))
7715 (buffer-substring (point-at-bol) (point-at-eol))))
7716 (setq cpltxt
7717 (concat cpltxt "::"
7718 (if org-file-link-context-use-camel-case
7719 (org-make-org-heading-camel txt)
7720 (org-make-org-heading-search-string txt)))))
7721 (setq link (org-make-link cpltxt)))
7723 ((interactive-p)
7724 (error "Cannot link to a buffer which is not visiting a file"))
7726 (t (setq link nil)))
7728 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7730 (if (and (interactive-p) link)
7731 (progn
7732 (setq org-stored-links
7733 (cons (cons (or cpltxt link) link) org-stored-links))
7734 (message "Stored: %s" (or cpltxt link)))
7735 link)))
7737 (defun org-make-org-heading-search-string (&optional string heading)
7738 "Make search string for STRING or current headline."
7739 (interactive)
7740 (let ((s (or string (org-get-heading))))
7741 (unless (and string (not heading))
7742 ;; We are using a headline, clean up garbage in there.
7743 (if (string-match org-todo-regexp s)
7744 (setq s (replace-match "" t t s)))
7745 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7746 (setq s (replace-match "" t t s)))
7747 (setq s (org-trim s))
7748 (if (string-match (concat "^\\(" org-quote-string "\\|"
7749 org-comment-string "\\)") s)
7750 (setq s (replace-match "" t t s)))
7751 (while (string-match org-ts-regexp s)
7752 (setq s (replace-match "" t t s))))
7753 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7754 (setq s (replace-match " " t t s)))
7755 (or string (setq s (concat "*" s))) ; Add * for headlines
7756 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7758 (defun org-make-org-heading-camel (&optional string heading)
7759 "Make a CamelCase string for STRING or the current headline."
7760 (interactive)
7761 (let ((s (or string (org-get-heading))))
7762 (unless (and string (not heading))
7763 ;; We are using a headline, clean up garbage in there.
7764 (if (string-match org-todo-regexp s)
7765 (setq s (replace-match "" t t s)))
7766 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7767 (setq s (replace-match "" t t s)))
7768 (setq s (org-trim s))
7769 (if (string-match (concat "^\\(" org-quote-string "\\|"
7770 org-comment-string "\\)") s)
7771 (setq s (replace-match "" t t s)))
7772 (while (string-match org-ts-regexp s)
7773 (setq s (replace-match "" t t s))))
7774 (while (string-match "[^a-zA-Z_ \t]+" s)
7775 (setq s (replace-match " " t t s)))
7776 (or string (setq s (concat "*" s))) ; Add * for headlines
7777 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7779 (defun org-make-link (&rest strings)
7780 "Concatenate STRINGS, format resulting string with `org-link-format'."
7781 (format org-link-format (apply 'concat strings)))
7783 (defun org-make-link2 (link &optional description)
7784 "Make a link with brackets."
7785 (concat "[[" link "]"
7786 (if description (concat "[" description "]") "")
7787 "]"))
7789 (defun org-xor (a b)
7790 "Exclusive or."
7791 (if a (not b) b))
7793 (defun org-get-header (header)
7794 "Find a header field in the current buffer."
7795 (save-excursion
7796 (goto-char (point-min))
7797 (let ((case-fold-search t) s)
7798 (cond
7799 ((eq header 'from)
7800 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
7801 (setq s (match-string 1)))
7802 (while (string-match "\"" s)
7803 (setq s (replace-match "" t t s)))
7804 (if (string-match "[<(].*" s)
7805 (setq s (replace-match "" t t s))))
7806 ((eq header 'message-id)
7807 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
7808 (setq s (match-string 1))))
7809 ((eq header 'subject)
7810 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
7811 (setq s (match-string 1)))))
7812 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
7813 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
7814 s)))
7817 (defun org-fixup-message-id-for-http (s)
7818 "Replace special characters in a message id, so it can be used in an http query."
7819 (while (string-match "<" s)
7820 (setq s (replace-match "%3C" t t s)))
7821 (while (string-match ">" s)
7822 (setq s (replace-match "%3E" t t s)))
7823 (while (string-match "@" s)
7824 (setq s (replace-match "%40" t t s)))
7827 (defun org-insert-link (&optional complete-file)
7828 "Insert a link. At the prompt, enter the link.
7830 Completion can be used to select a link previously stored with
7831 `org-store-link'. When the empty string is entered (i.e. if you just
7832 press RET at the prompt), the link defaults to the most recently
7833 stored link. As SPC triggers completion in the minibuffer, you need to
7834 use M-SPC or C-q SPC to force the insertion of a space character.
7836 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
7837 selected using completion. The path to the file will be relative to
7838 the current directory if the file is in the current directory or a
7839 subdirectory. Otherwise, the link will be the absolute path as
7840 completed in the minibuffer (i.e. normally ~/path/to/file).
7842 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
7843 is in the current directory or below."
7844 (interactive "P")
7845 (let ((link (if complete-file
7846 (read-file-name "File: ")
7847 (completing-read
7848 "Link: " org-stored-links nil nil nil
7849 org-insert-link-history
7850 (or (car (car org-stored-links))))))
7851 linktxt matched)
7852 (if (or (not link) (equal link ""))
7853 (error "No links available"))
7854 (if complete-file
7855 (let ((pwd (file-name-as-directory (expand-file-name "."))))
7856 (cond
7857 ((equal complete-file '(16))
7858 (insert
7859 (org-make-link
7860 "file:" (abbreviate-file-name (expand-file-name link)))))
7861 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7862 (expand-file-name link))
7863 (insert
7864 (org-make-link
7865 "file:" (match-string 1 (expand-file-name link)))))
7866 (t (insert (org-make-link "file:" link)))))
7867 (setq linktxt (cdr (assoc link org-stored-links)))
7868 (if (not org-keep-stored-link-after-insertion)
7869 (setq org-stored-links (delq (assoc link org-stored-links)
7870 org-stored-links)))
7871 (if (not linktxt) (setq link (org-make-link link)))
7872 (setq link (or linktxt link))
7873 (when (string-match "<\\<file:\\(.+?\\)::\\([^>]+\\)>" link)
7874 (let* ((path (match-string 1 link))
7875 (case-fold-search nil)
7876 (search (match-string 2 link)))
7877 (when (save-match-data
7878 (equal (file-truename buffer-file-name)
7879 (file-truename path)))
7880 ;; We are linking to this same file
7881 (if (and org-file-link-context-use-camel-case
7882 (save-match-data
7883 (string-match (concat "^" org-camel-regexp "$") search)))
7884 (setq link (replace-match search t t link)
7885 matched t)
7886 (setq link (replace-match (concat "[[" search "]]")
7887 t t link)
7888 matched t)))))
7889 (let ((lines (org-split-string link "\n")))
7890 (insert (car lines))
7891 (setq matched (or matched (string-match org-link-regexp (car lines))))
7892 (setq lines (cdr lines))
7893 (while lines
7894 (insert "\n")
7895 (if (save-excursion
7896 (beginning-of-line 0)
7897 (looking-at "[ \t]+\\S-"))
7898 (indent-relative))
7899 (setq matched (or matched
7900 (string-match org-link-regexp (car lines))))
7901 (insert (car lines))
7902 (setq lines (cdr lines))))
7903 (unless matched
7904 (error "Add link type: http(s),ftp,mailto,file,news,bbdb,vm,wl,rmail,gnus, or shell")))))
7906 ;;; Hooks for remember.el
7907 ;;;###autoload
7908 (defun org-remember-annotation ()
7909 "Return a link to the current location as an annotation for remember.el.
7910 If you are using Org-mode files as target for data storage with
7911 remember.el, then the annotations should include a link compatible with the
7912 conventions in Org-mode. This function returns such a link."
7913 (org-store-link nil))
7915 (defconst org-remember-help
7916 "Select a destination location for the note.
7917 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
7918 RET at beg-of-buf -> Append to file as level 2 headline
7919 RET on headline -> Store as sublevel entry to current headline
7920 <left>/<right> -> before/after current headline, same headings level")
7922 ;;;###autoload
7923 (defun org-remember-apply-template ()
7924 "Initialize *remember* buffer with template, invode `org-mode'.
7925 This function should be placed into `remember-mode-hook' and in fact requires
7926 to be run from that hook to fucntion properly."
7927 (when org-remember-templates
7928 (let* ((entry (if (= (length org-remember-templates) 1)
7929 (cdar org-remember-templates)
7930 (message "Select template: %s"
7931 (mapconcat
7932 (lambda (x) (char-to-string (car x)))
7933 org-remember-templates " "))
7934 (cdr (assoc (read-char-exclusive) org-remember-templates))))
7935 (tpl (if (consp (cdr entry)) (cadr entry) (cdr entry)))
7936 (file (if (consp (cdr entry)) (nth 2 entry)))
7937 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
7938 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
7939 (v-u (concat "[" (substring v-t 1 -1) "]"))
7940 (v-U (concat "[" (substring v-T 1 -1) "]"))
7941 (v-a annotation) ; defined in `remember-mode'
7942 (v-i initial) ; defined in `remember-mode'
7943 (v-n user-full-name)
7945 (unless tpl (setq tpl "") (message "No template") (ding))
7946 (insert tpl) (goto-char (point-min))
7947 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
7948 (when (and initial (equal (match-string 0) "%i"))
7949 (save-match-data
7950 (let* ((lead (buffer-substring
7951 (point-at-bol) (match-beginning 0))))
7952 (setq v-i (mapconcat 'identity
7953 (org-split-string initial "\n")
7954 (concat "\n" lead))))))
7955 (replace-match
7956 (or (eval (intern (concat "v-" (match-string 1)))) "")
7957 t t))
7958 (let ((org-startup-folded nil)
7959 (org-startup-with-deadline-check nil))
7960 (org-mode))
7961 ; (use-local-map org-mode-map)
7962 ; (org-set-font-lock-defaults)
7963 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
7964 (set (make-local-variable 'org-default-notes-file) file))
7965 (goto-char (point-min))
7966 (if (re-search-forward "%\\?" nil t) (replace-match "")))))
7968 ;;;###autoload
7969 (defun org-remember-handler ()
7970 "Store stuff from remember.el into an org file.
7971 First prompts for an org file. If the user just presses return, the value
7972 of `org-default-notes-file' is used.
7973 Then the command offers the headings tree of the selected file in order to
7974 file the text at a specific location.
7975 You can either immediately press RET to get the note appended to the
7976 file, or you can use vertical cursor motion and visibility cycling (TAB) to
7977 find a better place. Then press RET or <left> or <right> in insert the note.
7979 Key Cursor position Note gets inserted
7980 -----------------------------------------------------------------------------
7981 RET buffer-start as level 2 heading at end of file
7982 RET on headline as sublevel of the heading at cursor
7983 RET no heading at cursor position, level taken from context.
7984 Or use prefix arg to specify level manually.
7985 <left> on headline as same level, before current heading
7986 <right> on headline as same level, after current heading
7988 So the fastest way to store the note is to press RET RET to append it to
7989 the default file. This way your current train of thought is not
7990 interrupted, in accordance with the principles of remember.el. But with
7991 little extra effort, you can push it directly to the correct location.
7993 Before being stored away, the function ensures that the text has a
7994 headline, i.e. a first line that starts with a \"*\". If not, a headline
7995 is constructed from the current date and some additional data.
7997 If the variable `org-adapt-indentation' is non-nil, the entire text is
7998 also indented so that it starts in the same column as the headline
7999 \(i.e. after the stars).
8001 See also the variable `org-reverse-note-order'."
8002 (catch 'quit
8003 (let* ((txt (buffer-substring (point-min) (point-max)))
8004 (fastp current-prefix-arg)
8005 (file (if fastp org-default-notes-file (org-get-org-file)))
8006 (visiting (find-buffer-visiting file))
8007 (org-startup-with-deadline-check nil)
8008 (org-startup-folded nil)
8009 spos level indent reversed)
8010 ;; Modify text so that it becomes a nice subtree which can be inserted
8011 ;; into an org tree.
8012 (let* ((lines (split-string txt "\n"))
8013 first)
8014 ;; remove empty lines at the beginning
8015 (while (and lines (string-match "^[ \t]*\n" (car lines)))
8016 (setq lines (cdr lines)))
8017 (setq first (car lines) lines (cdr lines))
8018 (if (string-match "^\\*+" first)
8019 ;; Is already a headline
8020 (setq indent nil)
8021 ;; We need to add a headline: Use time and first buffer line
8022 (setq lines (cons first lines)
8023 first (concat "* " (current-time-string)
8024 " (" (remember-buffer-desc) ")")
8025 indent " "))
8026 (if (and org-adapt-indentation indent)
8027 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
8028 (setq txt (concat first "\n"
8029 (mapconcat 'identity lines "\n"))))
8030 ;; Find the file
8031 (if (not visiting)
8032 (find-file-noselect file))
8033 (with-current-buffer (get-file-buffer file)
8034 (setq reversed (org-notes-order-reversed-p))
8035 (save-excursion
8036 (save-restriction
8037 (widen)
8038 ;; Ask the User for a location
8039 (setq spos (if fastp 1 (org-get-location
8040 (current-buffer)
8041 org-remember-help)))
8042 (if (not spos) (throw 'quit nil)) ; return nil to show we did
8043 ; not handle this note
8044 (goto-char spos)
8045 (cond ((bobp)
8046 ;; Put it at the start or end, as level 2
8047 (save-restriction
8048 (widen)
8049 (goto-char (if reversed (point-min) (point-max)))
8050 (if (not (bolp)) (newline))
8051 (org-paste-subtree 2 txt)))
8052 ((and (org-on-heading-p nil) (not current-prefix-arg))
8053 ;; Put it below this entry, at the beg/end of the subtree
8054 (org-back-to-heading)
8055 (setq level (funcall outline-level))
8056 (if reversed
8057 (outline-end-of-heading)
8058 (outline-end-of-subtree))
8059 (if (not (bolp)) (newline))
8060 (beginning-of-line 1)
8061 (org-paste-subtree (1+ level) txt))
8063 ;; Put it right there, with automatic level determined by
8064 ;; org-paste-subtree or from prefix arg
8065 (org-paste-subtree current-prefix-arg txt)))
8066 (when remember-save-after-remembering
8067 (save-buffer)
8068 (if (not visiting) (kill-buffer (current-buffer)))))))))
8069 t) ;; return t to indicate that we took care of this note.
8071 (defun org-get-org-file ()
8072 "Read a filename, with default directory `org-directory'."
8073 (let ((default (or org-default-notes-file remember-data-file)))
8074 (read-file-name (format "File name [%s]: " default)
8075 (file-name-as-directory org-directory)
8076 default)))
8078 (defun org-notes-order-reversed-p ()
8079 "Check if the current file should receive notes in reversed order."
8080 (cond
8081 ((not org-reverse-note-order) nil)
8082 ((eq t org-reverse-note-order) t)
8083 ((not (listp org-reverse-note-order)) nil)
8084 (t (catch 'exit
8085 (let ((all org-reverse-note-order)
8086 entry)
8087 (while (setq entry (pop all))
8088 (if (string-match (car entry) buffer-file-name)
8089 (throw 'exit (cdr entry))))
8090 nil)))))
8092 ;;; Tables
8094 ;; Watch out: Here we are talking about two different kind of tables.
8095 ;; Most of the code is for the tables created with the Org-mode table editor.
8096 ;; Sometimes, we talk about tables created and edited with the table.el
8097 ;; Emacs package. We call the former org-type tables, and the latter
8098 ;; table.el-type tables.
8101 (defun org-before-change-function (beg end)
8102 "Every change indicates that a table might need an update."
8103 (setq org-table-may-need-update t))
8105 (defconst org-table-line-regexp "^[ \t]*|"
8106 "Detects an org-type table line.")
8107 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8108 "Detects an org-type table line.")
8109 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8110 "Detects a table line marked for automatic recalculation.")
8111 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8112 "Detects a table line marked for automatic recalculation.")
8113 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8114 "Detects a table line marked for automatic recalculation.")
8115 (defconst org-table-hline-regexp "^[ \t]*|-"
8116 "Detects an org-type table hline.")
8117 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8118 "Detects a table-type table hline.")
8119 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8120 "Detects an org-type or table-type table.")
8121 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8122 "Searching from within a table (any type) this finds the first line
8123 outside the table.")
8124 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8125 "Searching from within a table (any type) this finds the first line
8126 outside the table.")
8128 (defun org-table-create-with-table.el ()
8129 "Use the table.el package to insert a new table.
8130 If there is already a table at point, convert between Org-mode tables
8131 and table.el tables."
8132 (interactive)
8133 (require 'table)
8134 (cond
8135 ((org-at-table.el-p)
8136 (if (y-or-n-p "Convert table to Org-mode table? ")
8137 (org-table-convert)))
8138 ((org-at-table-p)
8139 (if (y-or-n-p "Convert table to table.el table? ")
8140 (org-table-convert)))
8141 (t (call-interactively 'table-insert))))
8143 (defun org-table-create (&optional size)
8144 "Query for a size and insert a table skeleton.
8145 SIZE is a string Columns x Rows like for example \"3x2\"."
8146 (interactive "P")
8147 (unless size
8148 (setq size (read-string
8149 (concat "Table size Columns x Rows [e.g. "
8150 org-table-default-size "]: ")
8151 "" nil org-table-default-size)))
8153 (let* ((pos (point))
8154 (indent (make-string (current-column) ?\ ))
8155 (split (org-split-string size " *x *"))
8156 (rows (string-to-number (nth 1 split)))
8157 (columns (string-to-number (car split)))
8158 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8159 "\n")))
8160 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8161 (point-at-bol) (point)))
8162 (beginning-of-line 1)
8163 (newline))
8164 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8165 (dotimes (i rows) (insert line))
8166 (goto-char pos)
8167 (if (> rows 1)
8168 ;; Insert a hline after the first row.
8169 (progn
8170 (end-of-line 1)
8171 (insert "\n|-")
8172 (goto-char pos)))
8173 (org-table-align)))
8175 (defun org-table-convert-region (beg0 end0 nspace)
8176 "Convert region to a table.
8177 The region goes from BEG0 to END0, but these borders will be moved
8178 slightly, to make sure a beginning of line in the first line is included.
8179 When NSPACE is non-nil, it indicates the minimum number of spaces that
8180 separate columns (default: just one space)."
8181 (let* ((beg (min beg0 end0))
8182 (end (max beg0 end0))
8183 (tabsep t)
8185 (goto-char beg)
8186 (beginning-of-line 1)
8187 (setq beg (move-marker (make-marker) (point)))
8188 (goto-char end)
8189 (if (bolp) (backward-char 1) (end-of-line 1))
8190 (setq end (move-marker (make-marker) (point)))
8191 ;; Lets see if this is tab-separated material. If every nonempty line
8192 ;; contains a tab, we will assume that it is tab-separated material
8193 (if nspace
8194 (setq tabsep nil)
8195 (goto-char beg)
8196 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
8197 (if nspace (setq tabsep nil))
8198 (if tabsep
8199 (setq re "^\\|\t")
8200 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
8201 (max 1 (prefix-numeric-value nspace)))))
8202 (goto-char beg)
8203 (while (re-search-forward re end t)
8204 (replace-match "|" t t))
8205 (goto-char beg)
8206 (insert " ")
8207 (org-table-align)))
8209 (defun org-table-import (file arg)
8210 "Import FILE as a table.
8211 The file is assumed to be tab-separated. Such files can be produced by most
8212 spreadsheet and database applications. If no tabs (at least one per line)
8213 are found, lines will be split on whitespace into fields."
8214 (interactive "f\nP")
8215 (or (bolp) (newline))
8216 (let ((beg (point))
8217 (pm (point-max)))
8218 (insert-file-contents file)
8219 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8221 (defun org-table-export ()
8222 "Export table as a tab-separated file.
8223 Such a file can be imported into a spreadsheet program like Excel."
8224 (interactive)
8225 (let* ((beg (org-table-begin))
8226 (end (org-table-end))
8227 (table (buffer-substring beg end))
8228 (file (read-file-name "Export table to: "))
8229 buf)
8230 (unless (or (not (file-exists-p file))
8231 (y-or-n-p (format "Overwrite file %s? " file)))
8232 (error "Abort"))
8233 (with-current-buffer (find-file-noselect file)
8234 (setq buf (current-buffer))
8235 (erase-buffer)
8236 (fundamental-mode)
8237 (insert table)
8238 (goto-char (point-min))
8239 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8240 (replace-match "" t t)
8241 (end-of-line 1))
8242 (goto-char (point-min))
8243 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8244 (replace-match "" t t)
8245 (goto-char (min (1+ (point)) (point-max))))
8246 (goto-char (point-min))
8247 (while (re-search-forward "^-[-+]*$" nil t)
8248 (replace-match "")
8249 (if (looking-at "\n")
8250 (delete-char 1)))
8251 (goto-char (point-min))
8252 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8253 (replace-match "\t" t t))
8254 (save-buffer))
8255 (kill-buffer buf)))
8257 (defvar org-table-aligned-begin-marker (make-marker)
8258 "Marker at the beginning of the table last aligned.
8259 Used to check if cursor still is in that table, to minimize realignment.")
8260 (defvar org-table-aligned-end-marker (make-marker)
8261 "Marker at the end of the table last aligned.
8262 Used to check if cursor still is in that table, to minimize realignment.")
8263 (defvar org-table-last-alignment nil
8264 "List of flags for flushright alignment, from the last re-alignment.
8265 This is being used to correctly align a single field after TAB or RET.")
8266 (defvar org-table-last-column-widths nil
8267 "List of max width of fields in each column.
8268 This is being used to correctly align a single field after TAB or RET.")
8270 (defvar org-last-recalc-line nil)
8272 (defun org-table-align ()
8273 "Align the table at point by aligning all vertical bars."
8274 (interactive)
8275 ;; (message "align") (sit-for 2)
8276 (let* (
8277 ;; Limits of table
8278 (beg (org-table-begin))
8279 (end (org-table-end))
8280 ;; Current cursor position
8281 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8282 (colpos (org-table-current-column))
8283 (winstart (window-start))
8284 text lines (new "") lengths l typenums ty fields maxfields i
8285 column
8286 (indent "") cnt frac
8287 rfmt hfmt
8288 (spaces (if (org-in-invisibility-spec-p '(org-table))
8289 org-table-spaces-around-invisible-separators
8290 org-table-spaces-around-separators))
8291 (sp1 (car spaces))
8292 (sp2 (cdr spaces))
8293 (rfmt1 (concat
8294 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8295 (hfmt1 (concat
8296 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8297 emptystrings)
8298 (untabify beg end)
8299 ;; (message "Aligning table...")
8300 ;; Get the rows
8301 (setq lines (org-split-string
8302 (buffer-substring-no-properties beg end) "\n"))
8303 ;; Store the indentation of the first line
8304 (if (string-match "^ *" (car lines))
8305 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8306 ;; Mark the hlines
8307 (setq lines (mapcar (lambda (l)
8308 (if (string-match "^ *|-" l)
8310 (if (string-match "[ \t]+$" l)
8311 (substring l 0 (match-beginning 0))
8312 l)))
8313 lines))
8314 ;; Get the data fields
8315 (setq fields (mapcar
8316 (lambda (l)
8317 (org-split-string l " *| *"))
8318 (delq nil (copy-sequence lines))))
8319 ;; How many fields in the longest line?
8320 (condition-case nil
8321 (setq maxfields (apply 'max (mapcar 'length fields)))
8322 (error
8323 (kill-region beg end)
8324 (org-table-create org-table-default-size)
8325 (error "Empty table - created default table")))
8326 ;; A list of empty string to fill any short rows on output
8327 (setq emptystrings (make-list maxfields ""))
8328 ;; Get the maximum length of a field and the most common datatype
8329 ;; for each column
8330 (setq i -1)
8331 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8332 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8333 ;; maximum length
8334 (push (apply 'max 1 (mapcar 'string-width column)) lengths)
8335 ;; compute the fraction stepwise, ignoring empty fields
8336 (setq cnt 0 frac 0.0)
8337 (mapcar
8338 (lambda (x)
8339 (if (equal x "")
8341 (setq frac ( / (+ (* frac cnt)
8342 (if (string-match org-table-number-regexp x) 1 0))
8343 (setq cnt (1+ cnt))))))
8344 column)
8345 (push (>= frac org-table-number-fraction) typenums))
8346 (setq lengths (nreverse lengths)
8347 typenums (nreverse typenums))
8348 (setq org-table-last-alignment typenums
8349 org-table-last-column-widths lengths)
8350 ;; Compute the formats needed for output of the table
8351 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8352 (while (setq l (pop lengths))
8353 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8354 (setq rfmt (concat rfmt (format rfmt1 ty l))
8355 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8356 (setq rfmt (concat rfmt "\n")
8357 hfmt (concat (substring hfmt 0 -1) "|\n"))
8358 ;; Produce the new table
8359 ;;(while lines
8360 ;; (setq l (pop lines))
8361 ;; (if l
8362 ;; (setq new (concat new (apply 'format rfmt
8363 ;; (append (pop fields) emptystrings))))
8364 ;; (setq new (concat new hfmt))))
8365 (setq new (mapconcat
8366 (lambda (l)
8367 (if l (apply 'format rfmt
8368 (append (pop fields) emptystrings))
8369 hfmt))
8370 lines ""))
8371 ;; Replace the old one
8372 (delete-region beg end)
8373 (move-marker end nil)
8374 (move-marker org-table-aligned-begin-marker (point))
8375 (insert new)
8376 (move-marker org-table-aligned-end-marker (point))
8377 ;; Try to move to the old location (approximately)
8378 (goto-line linepos)
8379 (set-window-start (selected-window) winstart 'noforce)
8380 (org-table-goto-column colpos)
8381 (setq org-table-may-need-update nil)
8382 (if (org-in-invisibility-spec-p '(org-table))
8383 (org-table-add-invisible-to-vertical-lines))
8386 (defun org-table-begin (&optional table-type)
8387 "Find the beginning of the table and return its position.
8388 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8389 (save-excursion
8390 (if (not (re-search-backward
8391 (if table-type org-table-any-border-regexp
8392 org-table-border-regexp)
8393 nil t))
8394 (error "Can't find beginning of table")
8395 (goto-char (match-beginning 0))
8396 (beginning-of-line 2)
8397 (point))))
8399 (defun org-table-end (&optional table-type)
8400 "Find the end of the table and return its position.
8401 With argument TABLE-TYPE, go to the end of a table.el-type table."
8402 (save-excursion
8403 (if (not (re-search-forward
8404 (if table-type org-table-any-border-regexp
8405 org-table-border-regexp)
8406 nil t))
8407 (goto-char (point-max))
8408 (goto-char (match-beginning 0)))
8409 (point-marker)))
8411 (defun org-table-justify-field-maybe (&optional new)
8412 "Justify the current field, text to left, number to right.
8413 Optional argument NEW may specify text to replace the current field content."
8414 (cond
8415 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8416 ((org-at-table-hline-p)
8417 ;; FIXME: I used to enforce realign here, but I think this is not needed.
8418 ;; (setq org-table-may-need-update t)
8420 ((and (not new)
8421 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8422 (current-buffer)))
8423 (< (point) org-table-aligned-begin-marker)
8424 (>= (point) org-table-aligned-end-marker)))
8425 ;; This is not the same table, force a full re-align
8426 (setq org-table-may-need-update t))
8427 (t ;; realign the current field, based on previous full realign
8428 (let* ((pos (point)) s
8429 (col (org-table-current-column))
8430 (num (nth (1- col) org-table-last-alignment))
8431 l f n o e)
8432 (when (> col 0)
8433 (skip-chars-backward "^|\n")
8434 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8435 (progn
8436 (setq s (match-string 1)
8437 o (match-string 0)
8438 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8439 e (not (= (match-beginning 2) (match-end 2))))
8440 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8441 l (if e "|" (setq org-table-may-need-update t) ""))
8442 n (format f s t t))
8443 (if new
8444 (if (<= (length new) l)
8445 (setq n (format f new t t)) ;; FIXME: why t t?????
8446 (setq n (concat new "|") org-table-may-need-update t)))
8447 (or (equal n o)
8448 (let (org-table-may-need-update)
8449 (replace-match n))))
8450 (setq org-table-may-need-update t))
8451 (goto-char pos))))))
8453 (defun org-table-next-field ()
8454 "Go to the next field in the current table, creating new lines as needed.
8455 Before doing so, re-align the table if necessary."
8456 (interactive)
8457 (org-table-maybe-eval-formula)
8458 (org-table-maybe-recalculate-line)
8459 (if (and org-table-automatic-realign
8460 org-table-may-need-update)
8461 (org-table-align))
8462 (let ((end (org-table-end)))
8463 (if (org-at-table-hline-p)
8464 (end-of-line 1))
8465 (condition-case nil
8466 (progn
8467 (re-search-forward "|" end)
8468 (if (looking-at "[ \t]*$")
8469 (re-search-forward "|" end))
8470 (if (and (looking-at "-")
8471 org-table-tab-jumps-over-hlines
8472 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8473 (goto-char (match-beginning 1)))
8474 (if (looking-at "-")
8475 (progn
8476 (beginning-of-line 0)
8477 (org-table-insert-row 'below))
8478 (if (looking-at " ") (forward-char 1))))
8479 (error
8480 (org-table-insert-row 'below)))))
8482 (defun org-table-previous-field ()
8483 "Go to the previous field in the table.
8484 Before doing so, re-align the table if necessary."
8485 (interactive)
8486 (org-table-justify-field-maybe)
8487 (org-table-maybe-recalculate-line)
8488 (if (and org-table-automatic-realign
8489 org-table-may-need-update)
8490 (org-table-align))
8491 (if (org-at-table-hline-p)
8492 (end-of-line 1))
8493 (re-search-backward "|" (org-table-begin))
8494 (re-search-backward "|" (org-table-begin))
8495 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8496 (re-search-backward "|" (org-table-begin)))
8497 (if (looking-at "| ?")
8498 (goto-char (match-end 0))))
8500 (defun org-table-next-row ()
8501 "Go to the next row (same column) in the current table.
8502 Before doing so, re-align the table if necessary."
8503 (interactive)
8504 (org-table-maybe-eval-formula)
8505 (org-table-maybe-recalculate-line)
8506 (if (or (looking-at "[ \t]*$")
8507 (save-excursion (skip-chars-backward " \t") (bolp)))
8508 (newline)
8509 (if (and org-table-automatic-realign
8510 org-table-may-need-update)
8511 (org-table-align))
8512 (let ((col (org-table-current-column)))
8513 (beginning-of-line 2)
8514 (if (or (not (org-at-table-p))
8515 (org-at-table-hline-p))
8516 (progn
8517 (beginning-of-line 0)
8518 (org-table-insert-row 'below)))
8519 (org-table-goto-column col)
8520 (skip-chars-backward "^|\n\r")
8521 (if (looking-at " ") (forward-char 1)))))
8523 (defun org-table-copy-down (n)
8524 "Copy a field down in the current column.
8525 If the field at the cursor is empty, copy into it the content of the nearest
8526 non-empty field above. With argument N, use the Nth non-empty field.
8527 If the current field is not empty, it is copied down to the next row, and
8528 the cursor is moved with it. Therefore, repeating this command causes the
8529 column to be filled row-by-row.
8530 If the variable `org-table-copy-increment' is non-nil and the field is an
8531 integer, it will be incremented while copying."
8532 (interactive "p")
8533 (let* ((colpos (org-table-current-column))
8534 (field (org-table-get-field))
8535 (non-empty (string-match "[^ \t]" field))
8536 (beg (org-table-begin))
8537 txt)
8538 (org-table-check-inside-data-field)
8539 (if non-empty
8540 (progn
8541 (setq txt (org-trim field))
8542 (org-table-next-row)
8543 (org-table-blank-field))
8544 (save-excursion
8545 (setq txt
8546 (catch 'exit
8547 (while (progn (beginning-of-line 1)
8548 (re-search-backward org-table-dataline-regexp
8549 beg t))
8550 (org-table-goto-column colpos t)
8551 (if (and (looking-at
8552 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8553 (= (setq n (1- n)) 0))
8554 (throw 'exit (match-string 1))))))))
8555 (if txt
8556 (progn
8557 (if (and org-table-copy-increment
8558 (string-match "^[0-9]+$" txt))
8559 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8560 (insert txt)
8561 (org-table-maybe-recalculate-line)
8562 (org-table-align))
8563 (error "No non-empty field found"))))
8565 (defun org-table-check-inside-data-field ()
8566 "Is point inside a table data field?
8567 I.e. not on a hline or before the first or after the last column?
8568 This actually throws an error, so it aborts the current command."
8569 (if (or (not (org-at-table-p))
8570 (= (org-table-current-column) 0)
8571 (org-at-table-hline-p)
8572 (looking-at "[ \t]*$"))
8573 (error "Not in table data field")))
8575 (defvar org-table-clip nil
8576 "Clipboard for table regions.")
8578 (defun org-table-blank-field ()
8579 "Blank the current table field or active region."
8580 (interactive)
8581 (org-table-check-inside-data-field)
8582 (if (and (interactive-p) (org-region-active-p))
8583 (let (org-table-clip)
8584 (org-table-cut-region (region-beginning) (region-end)))
8585 (skip-chars-backward "^|")
8586 (backward-char 1)
8587 (if (looking-at "|[^|\n]+")
8588 (let* ((pos (match-beginning 0))
8589 (match (match-string 0))
8590 (len (string-width match)))
8591 (replace-match (concat "|" (make-string (1- len) ?\ )))
8592 (goto-char (+ 2 pos))
8593 (substring match 1)))))
8595 (defun org-table-get-field (&optional n replace)
8596 "Return the value of the field in column N of current row.
8597 N defaults to current field.
8598 If REPLACE is a string, replace field with this value. The return value
8599 is always the old value."
8600 (and n (org-table-goto-column n))
8601 (skip-chars-backward "^|\n")
8602 (backward-char 1)
8603 (if (looking-at "|[^|\r\n]*")
8604 (let* ((pos (match-beginning 0))
8605 (val (buffer-substring (1+ pos) (match-end 0))))
8606 (if replace
8607 (replace-match (concat "|" replace)))
8608 (goto-char (min (point-at-eol) (+ 2 pos)))
8609 val)
8610 (forward-char 1) ""))
8612 (defun org-table-current-column ()
8613 "Find out which column we are in.
8614 When called interactively, column is also displayed in echo area."
8615 (interactive)
8616 (if (interactive-p) (org-table-check-inside-data-field))
8617 (save-excursion
8618 (let ((cnt 0) (pos (point)))
8619 (beginning-of-line 1)
8620 (while (search-forward "|" pos t)
8621 (setq cnt (1+ cnt)))
8622 (if (interactive-p) (message "This is table column %d" cnt))
8623 cnt)))
8625 (defun org-table-goto-column (n &optional on-delim force)
8626 "Move the cursor to the Nth column in the current table line.
8627 With optional argument ON-DELIM, stop with point before the left delimiter
8628 of the field.
8629 If there are less than N fields, just go to after the last delimiter.
8630 However, when FORCE is non-nil, create new columns if necessary."
8631 (interactive "p")
8632 (let ((pos (point-at-eol)))
8633 (beginning-of-line 1)
8634 (when (> n 0)
8635 (while (and (> (setq n (1- n)) -1)
8636 (or (search-forward "|" pos t)
8637 (and force
8638 (progn (end-of-line 1)
8639 (skip-chars-backward "^|")
8640 (insert " | "))))))
8641 ; (backward-char 2) t)))))
8642 (when (and force (not (looking-at ".*|")))
8643 (save-excursion (end-of-line 1) (insert " | ")))
8644 (if on-delim
8645 (backward-char 1)
8646 (if (looking-at " ") (forward-char 1))))))
8648 (defun org-at-table-p (&optional table-type)
8649 "Return t if the cursor is inside an org-type table.
8650 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8651 (if org-enable-table-editor
8652 (save-excursion
8653 (beginning-of-line 1)
8654 (looking-at (if table-type org-table-any-line-regexp
8655 org-table-line-regexp)))
8656 nil))
8658 (defun org-at-table.el-p ()
8659 "Return t if and only if we are at a table.el table."
8660 (and (org-at-table-p 'any)
8661 (save-excursion
8662 (goto-char (org-table-begin 'any))
8663 (looking-at org-table1-hline-regexp))))
8665 (defun org-table-recognize-table.el ()
8666 "If there is a table.el table nearby, recognize it and move into it."
8667 (if org-table-tab-recognizes-table.el
8668 (if (org-at-table.el-p)
8669 (progn
8670 (beginning-of-line 1)
8671 (if (looking-at org-table-dataline-regexp)
8673 (if (looking-at org-table1-hline-regexp)
8674 (progn
8675 (beginning-of-line 2)
8676 (if (looking-at org-table-any-border-regexp)
8677 (beginning-of-line -1)))))
8678 (if (re-search-forward "|" (org-table-end t) t)
8679 (progn
8680 (require 'table)
8681 (if (table--at-cell-p (point))
8683 (message "recognizing table.el table...")
8684 (table-recognize-table)
8685 (message "recognizing table.el table...done")))
8686 (error "This should not happen..."))
8688 nil)
8689 nil))
8691 (defun org-at-table-hline-p ()
8692 "Return t if the cursor is inside a hline in a table."
8693 (if org-enable-table-editor
8694 (save-excursion
8695 (beginning-of-line 1)
8696 (looking-at org-table-hline-regexp))
8697 nil))
8699 (defun org-table-insert-column ()
8700 "Insert a new column into the table."
8701 (interactive)
8702 (if (not (org-at-table-p))
8703 (error "Not at a table"))
8704 (org-table-find-dataline)
8705 (let* ((col (max 1 (org-table-current-column)))
8706 (beg (org-table-begin))
8707 (end (org-table-end))
8708 ;; Current cursor position
8709 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8710 (colpos col))
8711 (goto-char beg)
8712 (while (< (point) end)
8713 (if (org-at-table-hline-p)
8715 (org-table-goto-column col t)
8716 (insert "| "))
8717 (beginning-of-line 2))
8718 (move-marker end nil)
8719 (goto-line linepos)
8720 (org-table-goto-column colpos)
8721 (org-table-align)
8722 (org-table-modify-formulas 'insert col)))
8724 (defun org-table-find-dataline ()
8725 "Find a dataline in the current table, which is needed for column commands."
8726 (if (and (org-at-table-p)
8727 (not (org-at-table-hline-p)))
8729 (let ((col (current-column))
8730 (end (org-table-end)))
8731 (move-to-column col)
8732 (while (and (< (point) end)
8733 (or (not (= (current-column) col))
8734 (org-at-table-hline-p)))
8735 (beginning-of-line 2)
8736 (move-to-column col))
8737 (if (and (org-at-table-p)
8738 (not (org-at-table-hline-p)))
8740 (error
8741 "Please position cursor in a data line for column operations")))))
8743 (defun org-table-delete-column ()
8744 "Delete a column into the table."
8745 (interactive)
8746 (if (not (org-at-table-p))
8747 (error "Not at a table"))
8748 (org-table-find-dataline)
8749 (org-table-check-inside-data-field)
8750 (let* ((col (org-table-current-column))
8751 (beg (org-table-begin))
8752 (end (org-table-end))
8753 ;; Current cursor position
8754 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8755 (colpos col))
8756 (goto-char beg)
8757 (while (< (point) end)
8758 (if (org-at-table-hline-p)
8760 (org-table-goto-column col t)
8761 (and (looking-at "|[^|\n]+|")
8762 (replace-match "|")))
8763 (beginning-of-line 2))
8764 (move-marker end nil)
8765 (goto-line linepos)
8766 (org-table-goto-column colpos)
8767 (org-table-align)
8768 (org-table-modify-formulas 'remove col)))
8770 (defun org-table-move-column-right ()
8771 "Move column to the right."
8772 (interactive)
8773 (org-table-move-column nil))
8774 (defun org-table-move-column-left ()
8775 "Move column to the left."
8776 (interactive)
8777 (org-table-move-column 'left))
8779 (defun org-table-move-column (&optional left)
8780 "Move the current column to the right. With arg LEFT, move to the left."
8781 (interactive "P")
8782 (if (not (org-at-table-p))
8783 (error "Not at a table"))
8784 (org-table-find-dataline)
8785 (org-table-check-inside-data-field)
8786 (let* ((col (org-table-current-column))
8787 (col1 (if left (1- col) col))
8788 (beg (org-table-begin))
8789 (end (org-table-end))
8790 ;; Current cursor position
8791 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8792 (colpos (if left (1- col) (1+ col))))
8793 (if (and left (= col 1))
8794 (error "Cannot move column further left"))
8795 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
8796 (error "Cannot move column further right"))
8797 (goto-char beg)
8798 (while (< (point) end)
8799 (if (org-at-table-hline-p)
8801 (org-table-goto-column col1 t)
8802 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
8803 (replace-match "|\\2|\\1|")))
8804 (beginning-of-line 2))
8805 (move-marker end nil)
8806 (goto-line linepos)
8807 (org-table-goto-column colpos)
8808 (org-table-align)
8809 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
8811 (defun org-table-move-row-down ()
8812 "Move table row down."
8813 (interactive)
8814 (org-table-move-row nil))
8815 (defun org-table-move-row-up ()
8816 "Move table row up."
8817 (interactive)
8818 (org-table-move-row 'up))
8820 (defun org-table-move-row (&optional up)
8821 "Move the current table line down. With arg UP, move it up."
8822 (interactive "P")
8823 (let ((col (current-column))
8824 (pos (point))
8825 (tonew (if up 0 2))
8826 txt)
8827 (beginning-of-line tonew)
8828 (if (not (org-at-table-p))
8829 (progn
8830 (goto-char pos)
8831 (error "Cannot move row further")))
8832 (goto-char pos)
8833 (beginning-of-line 1)
8834 (setq pos (point))
8835 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
8836 (delete-region (point) (1+ (point-at-eol)))
8837 (beginning-of-line tonew)
8838 (insert txt)
8839 (beginning-of-line 0)
8840 (move-to-column col)))
8842 (defun org-table-insert-row (&optional arg)
8843 "Insert a new row above the current line into the table.
8844 With prefix ARG, insert below the current line."
8845 (interactive "P")
8846 (if (not (org-at-table-p))
8847 (error "Not at a table"))
8848 (let* ((line
8849 (org-expand-wide-chars
8850 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8851 new)
8852 (if (string-match "^[ \t]*|-" line)
8853 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
8854 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
8855 ;; Fix the first field if necessary
8856 (setq new (concat new))
8857 (if (string-match "^[ \t]*| *[#$] *|" line)
8858 (setq new (replace-match (match-string 0 line) t t new)))
8859 (beginning-of-line (if arg 2 1))
8860 (let (org-table-may-need-update)
8861 (insert-before-markers new)
8862 (insert-before-markers "\n"))
8863 (beginning-of-line 0)
8864 (re-search-forward "| ?" (point-at-eol) t)
8865 (and org-table-may-need-update (org-table-align))))
8867 (defun org-table-insert-hline (&optional arg)
8868 "Insert a horizontal-line below the current line into the table.
8869 With prefix ARG, insert above the current line."
8870 (interactive "P")
8871 (if (not (org-at-table-p))
8872 (error "Not at a table"))
8873 (let ((line
8874 (org-expand-wide-chars
8875 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
8876 (col (current-column))
8877 start)
8878 (if (string-match "^[ \t]*|-" line)
8879 (setq line
8880 (mapcar (lambda (x) (if (member x '(?| ?+))
8881 (prog1 (if start ?+ ?|) (setq start t))
8882 (if start ?- ?\ )))
8883 line))
8884 (setq line
8885 (mapcar (lambda (x) (if (equal x ?|)
8886 (prog1 (if start ?+ ?|) (setq start t))
8887 (if start ?- ?\ )))
8888 line)))
8889 (beginning-of-line (if arg 1 2))
8890 (apply 'insert line)
8891 (if (equal (char-before (point)) ?+)
8892 (progn (backward-delete-char 1) (insert "|")))
8893 (insert "\n")
8894 (beginning-of-line (if arg 1 -1))
8895 (move-to-column col)))
8897 (defun org-expand-wide-chars (s)
8898 "Expand wide characters to spaces."
8899 (let (w a)
8900 (mapconcat
8901 (lambda (x)
8902 (if (> (setq w (string-width (setq a (char-to-string x)))) 1)
8903 (make-string w ?\ )
8905 s "")))
8907 (defun org-table-kill-row ()
8908 "Delete the current row or horizontal line from the table."
8909 (interactive)
8910 (if (not (org-at-table-p))
8911 (error "Not at a table"))
8912 (let ((col (current-column)))
8913 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
8914 (if (not (org-at-table-p)) (beginning-of-line 0))
8915 (move-to-column col)))
8917 (defun org-table-sort-lines (beg end numericp)
8918 "Sort table lines in region.
8919 Point and mark define the first and last line to include. Both point and
8920 mark should be in the column that is used for sorting. For example, to
8921 sort according to column 3, put the mark in the first line to sort, in
8922 table column 3. Put point into the last line to be included in the sorting,
8923 also in table column 3. The command will prompt for the sorting method
8924 \(n for numerical, a for alphanumeric)."
8925 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
8926 (setq numericp (string-match "[nN]" numericp))
8927 (org-table-align) ;; Just to be safe
8928 (let* (bcol ecol cmp column lns)
8929 (goto-char beg)
8930 (org-table-check-inside-data-field)
8931 (setq column (org-table-current-column)
8932 beg (move-marker (make-marker) (point-at-bol)))
8933 (goto-char end)
8934 (org-table-check-inside-data-field)
8935 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
8936 (untabify beg end)
8937 (goto-char beg)
8938 (org-table-goto-column column)
8939 (skip-chars-backward "^|")
8940 (setq bcol (current-column))
8941 (org-table-goto-column (1+ column))
8942 (skip-chars-backward "^|")
8943 (setq ecol (1- (current-column)))
8944 (setq cmp (if numericp
8945 (lambda (a b) (< (car a) (car b)))
8946 (lambda (a b) (string< (car a) (car b)))))
8947 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
8948 (split-string (buffer-substring beg end) "\n")))
8949 (if numericp
8950 (setq lns (mapcar (lambda(x)
8951 (cons (string-to-number (car x)) (cdr x)))
8952 lns)))
8953 (delete-region beg end)
8954 (move-marker beg nil)
8955 (move-marker end nil)
8956 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
8957 (message "%d lines sorted %s based on column %d"
8958 (length lns)
8959 (if numericp "numerically" "alphabetically") column)))
8961 (defun org-table-cut-region (beg end)
8962 "Copy region in table to the clipboard and blank all relevant fields."
8963 (interactive "r")
8964 (org-table-copy-region beg end 'cut))
8966 (defun org-table-copy-region (beg end &optional cut)
8967 "Copy rectangular region in table to clipboard.
8968 A special clipboard is used which can only be accessed
8969 with `org-table-paste-rectangle'."
8970 (interactive "rP")
8971 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
8972 region cols
8973 (rpl (if cut " " nil)))
8974 (goto-char beg)
8975 (org-table-check-inside-data-field)
8976 (setq l01 (count-lines (point-min) (point))
8977 c01 (org-table-current-column))
8978 (goto-char end)
8979 (org-table-check-inside-data-field)
8980 (setq l02 (count-lines (point-min) (point))
8981 c02 (org-table-current-column))
8982 (setq l1 (min l01 l02) l2 (max l01 l02)
8983 c1 (min c01 c02) c2 (max c01 c02))
8984 (catch 'exit
8985 (while t
8986 (catch 'nextline
8987 (if (> l1 l2) (throw 'exit t))
8988 (goto-line l1)
8989 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
8990 (setq cols nil ic1 c1 ic2 c2)
8991 (while (< ic1 (1+ ic2))
8992 (push (org-table-get-field ic1 rpl) cols)
8993 (setq ic1 (1+ ic1)))
8994 (push (nreverse cols) region)
8995 (setq l1 (1+ l1)))))
8996 (setq org-table-clip (nreverse region))
8997 (if cut (org-table-align))
8998 org-table-clip))
9000 (defun org-table-paste-rectangle ()
9001 "Paste a rectangular region into a table.
9002 The upper right corner ends up in the current field. All involved fields
9003 will be overwritten. If the rectangle does not fit into the present table,
9004 the table is enlarged as needed. The process ignores horizontal separator
9005 lines."
9006 (interactive)
9007 (unless (and org-table-clip (listp org-table-clip))
9008 (error "First cut/copy a region to paste!"))
9009 (org-table-check-inside-data-field)
9010 (let* ((clip org-table-clip)
9011 (line (count-lines (point-min) (point)))
9012 (col (org-table-current-column))
9013 (org-enable-table-editor t)
9014 (org-table-automatic-realign nil)
9015 c cols field)
9016 (while (setq cols (pop clip))
9017 (while (org-at-table-hline-p) (beginning-of-line 2))
9018 (if (not (org-at-table-p))
9019 (progn (end-of-line 0) (org-table-next-field)))
9020 (setq c col)
9021 (while (setq field (pop cols))
9022 (org-table-goto-column c nil 'force)
9023 (org-table-get-field nil field)
9024 (setq c (1+ c)))
9025 (beginning-of-line 2))
9026 (goto-line line)
9027 (org-table-goto-column col)
9028 (org-table-align)))
9030 (defun org-table-convert ()
9031 "Convert from `org-mode' table to table.el and back.
9032 Obviously, this only works within limits. When an Org-mode table is
9033 converted to table.el, all horizontal separator lines get lost, because
9034 table.el uses these as cell boundaries and has no notion of horizontal lines.
9035 A table.el table can be converted to an Org-mode table only if it does not
9036 do row or column spanning. Multiline cells will become multiple cells.
9037 Beware, Org-mode does not test if the table can be successfully converted - it
9038 blindly applies a recipe that works for simple tables."
9039 (interactive)
9040 (require 'table)
9041 (if (org-at-table.el-p)
9042 ;; convert to Org-mode table
9043 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9044 (end (move-marker (make-marker) (org-table-end t))))
9045 (table-unrecognize-region beg end)
9046 (goto-char beg)
9047 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9048 (replace-match ""))
9049 (goto-char beg))
9050 (if (org-at-table-p)
9051 ;; convert to table.el table
9052 (let ((beg (move-marker (make-marker) (org-table-begin)))
9053 (end (move-marker (make-marker) (org-table-end))))
9054 ;; first, get rid of all horizontal lines
9055 (goto-char beg)
9056 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9057 (replace-match ""))
9058 ;; insert a hline before first
9059 (goto-char beg)
9060 (org-table-insert-hline 'above)
9061 (beginning-of-line -1)
9062 ;; insert a hline after each line
9063 (while (progn (beginning-of-line 3) (< (point) end))
9064 (org-table-insert-hline))
9065 (goto-char beg)
9066 (setq end (move-marker end (org-table-end)))
9067 ;; replace "+" at beginning and ending of hlines
9068 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9069 (replace-match "\\1+-"))
9070 (goto-char beg)
9071 (while (re-search-forward "-|[ \t]*$" end t)
9072 (replace-match "-+"))
9073 (goto-char beg)))))
9075 (defun org-table-wrap-region (arg)
9076 "Wrap several fields in a column like a paragraph.
9077 This is useful if you'd like to spread the contents of a field over several
9078 lines, in order to keep the table compact.
9080 If there is an active region, and both point and mark are in the same column,
9081 the text in the column is wrapped to minimum width for the given number of
9082 lines. Generally, this makes the table more compact. A prefix ARG may be
9083 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9084 formats the selected text to two lines. If the region was longer than two
9085 lines, the remaining lines remain empty. A negative prefix argument reduces
9086 the current number of lines by that amount. The wrapped text is pasted back
9087 into the table. If you formatted it to more lines than it was before, fields
9088 further down in the table get overwritten - so you might need to make space in
9089 the table first.
9091 If there is no region, the current field is split at the cursor position and
9092 the text fragment to the right of the cursor is prepended to the field one
9093 line down.
9095 If there is no region, but you specify a prefix ARG, the current field gets
9096 blank, and the content is appended to the field above."
9097 (interactive "P")
9098 (org-table-check-inside-data-field)
9099 (if (org-region-active-p)
9100 ;; There is a region: fill as a paragraph
9101 (let ((beg (region-beginning))
9102 nlines)
9103 (org-table-cut-region (region-beginning) (region-end))
9104 (if (> (length (car org-table-clip)) 1)
9105 (error "Region must be limited to single column"))
9106 (setq nlines (if arg
9107 (if (< arg 1)
9108 (+ (length org-table-clip) arg)
9109 arg)
9110 (length org-table-clip)))
9111 (setq org-table-clip
9112 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9113 nil nlines)))
9114 (goto-char beg)
9115 (org-table-paste-rectangle))
9116 ;; No region, split the current field at point
9117 (if arg
9118 ;; combine with field above
9119 (let ((s (org-table-blank-field))
9120 (col (org-table-current-column)))
9121 (beginning-of-line 0)
9122 (while (org-at-table-hline-p) (beginning-of-line 0))
9123 (org-table-goto-column col)
9124 (skip-chars-forward "^|")
9125 (skip-chars-backward " ")
9126 (insert " " (org-trim s))
9127 (org-table-align))
9128 ;; split field
9129 (when (looking-at "\\([^|]+\\)+|")
9130 (let ((s (match-string 1)))
9131 (replace-match " |")
9132 (goto-char (match-beginning 0))
9133 (org-table-next-row)
9134 (insert (org-trim s) " ")
9135 (org-table-align))))))
9137 (defun org-trim (s)
9138 "Remove whitespace at beginning and end of string."
9139 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
9140 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
9143 (defun org-wrap (string &optional width lines)
9144 "Wrap string to either a number of lines, or a width in characters.
9145 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9146 that costs. If there is a word longer than WIDTH, the text is actually
9147 wrapped to the length of that word.
9148 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9149 many lines, whatever width that takes.
9150 The return value is a list of lines, without newlines at the end."
9151 (let* ((words (org-split-string string "[ \t\n]+"))
9152 (maxword (apply 'max (mapcar 'string-width words)))
9153 w ll)
9154 (cond (width
9155 (org-do-wrap words (max maxword width)))
9156 (lines
9157 (setq w maxword)
9158 (setq ll (org-do-wrap words maxword))
9159 (if (<= (length ll) lines)
9161 (setq ll words)
9162 (while (> (length ll) lines)
9163 (setq w (1+ w))
9164 (setq ll (org-do-wrap words w)))
9165 ll))
9166 (t (error "Cannot wrap this")))))
9169 (defun org-do-wrap (words width)
9170 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9171 (let (lines line)
9172 (while words
9173 (setq line (pop words))
9174 (while (and words (< (+ (length line) (length (car words))) width))
9175 (setq line (concat line " " (pop words))))
9176 (setq lines (push line lines)))
9177 (nreverse lines)))
9179 ;; FIXME: I think I can make this more efficient
9180 (defun org-split-string (string &optional separators)
9181 "Splits STRING into substrings at SEPARATORS.
9182 No empty strings are returned if there are matches at the beginning
9183 and end of string."
9184 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9185 (start 0)
9186 notfirst
9187 (list nil))
9188 (while (and (string-match rexp string
9189 (if (and notfirst
9190 (= start (match-beginning 0))
9191 (< start (length string)))
9192 (1+ start) start))
9193 (< (match-beginning 0) (length string)))
9194 (setq notfirst t)
9195 (or (eq (match-beginning 0) 0)
9196 (and (eq (match-beginning 0) (match-end 0))
9197 (eq (match-beginning 0) start))
9198 (setq list
9199 (cons (substring string start (match-beginning 0))
9200 list)))
9201 (setq start (match-end 0)))
9202 (or (eq start (length string))
9203 (setq list
9204 (cons (substring string start)
9205 list)))
9206 (nreverse list)))
9208 (defun org-table-add-invisible-to-vertical-lines ()
9209 "Add an `invisible' property to vertical lines of current table."
9210 (interactive)
9211 (let* ((beg (org-table-begin))
9212 (end (org-table-end))
9213 (end1))
9214 (save-excursion
9215 (goto-char beg)
9216 (while (< (point) end)
9217 (setq end1 (point-at-eol))
9218 (if (looking-at org-table-dataline-regexp)
9219 (while (re-search-forward "|" end1 t)
9220 (add-text-properties (1- (point)) (point)
9221 '(invisible org-table)))
9222 (while (re-search-forward "[+|]" end1 t)
9223 (add-text-properties (1- (point)) (point)
9224 '(invisible org-table))))
9225 (beginning-of-line 2)))))
9227 (defun org-table-toggle-vline-visibility (&optional arg)
9228 "Toggle the visibility of table vertical lines.
9229 The effect is immediate and on all tables in the file.
9230 With prefix ARG, make lines invisible when ARG is positive, make lines
9231 visible when ARG is not positive."
9232 (interactive "P")
9233 (let ((action (cond
9234 ((and arg (> (prefix-numeric-value arg) 0)) 'on)
9235 ((and arg (< (prefix-numeric-value arg) 1)) 'off)
9236 (t (if (org-in-invisibility-spec-p '(org-table))
9237 'off
9238 'on)))))
9239 (if (eq action 'off)
9240 (progn
9241 (org-remove-from-invisibility-spec '(org-table))
9242 (org-table-map-tables 'org-table-align)
9243 (message "Vertical table lines visible")
9244 (if (org-at-table-p)
9245 (org-table-align)))
9246 (org-add-to-invisibility-spec '(org-table))
9247 (org-table-map-tables 'org-table-align)
9248 (message "Vertical table lines invisible"))
9249 (redraw-frame (selected-frame))))
9251 (defun org-table-map-tables (function)
9252 "Apply FUNCTION to the start of all tables in the buffer."
9253 (save-excursion
9254 (save-restriction
9255 (widen)
9256 (goto-char (point-min))
9257 (while (re-search-forward org-table-any-line-regexp nil t)
9258 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9259 (beginning-of-line 1)
9260 (if (looking-at org-table-line-regexp)
9261 (save-excursion (funcall function)))
9262 (re-search-forward org-table-any-border-regexp nil 1)))))
9264 (defun org-table-sum (&optional beg end nlast)
9265 "Sum numbers in region of current table column.
9266 The result will be displayed in the echo area, and will be available
9267 as kill to be inserted with \\[yank].
9269 If there is an active region, it is interpreted as a rectangle and all
9270 numbers in that rectangle will be summed. If there is no active
9271 region and point is located in a table column, sum all numbers in that
9272 column.
9274 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9275 numbers are assumed to be times as well (in decimal hours) and the
9276 numbers are added as such.
9278 If NLAST is a number, only the NLAST fields will actually be summed."
9279 (interactive)
9280 (save-excursion
9281 (let (col (timecnt 0) diff h m s org-table-clip)
9282 (cond
9283 ((and beg end)) ; beg and end given explicitly
9284 ((org-region-active-p)
9285 (setq beg (region-beginning) end (region-end)))
9287 (setq col (org-table-current-column))
9288 (goto-char (org-table-begin))
9289 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9290 (error "No table data"))
9291 (org-table-goto-column col)
9292 ;not needed? (skip-chars-backward "^|")
9293 (setq beg (point))
9294 (goto-char (org-table-end))
9295 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9296 (error "No table data"))
9297 (org-table-goto-column col)
9298 ;not needed? (skip-chars-forward "^|")
9299 (setq end (point))))
9300 (let* ((items (apply 'append (org-table-copy-region beg end)))
9301 (items1 (cond ((not nlast) items)
9302 ((>= nlast (length items)) items)
9303 (t (setq items (reverse items))
9304 (setcdr (nthcdr (1- nlast) items) nil)
9305 (nreverse items))))
9306 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9307 items1)))
9308 (res (apply '+ numbers))
9309 (sres (if (= timecnt 0)
9310 (format "%g" res)
9311 (setq diff (* 3600 res)
9312 h (floor (/ diff 3600)) diff (mod diff 3600)
9313 m (floor (/ diff 60)) diff (mod diff 60)
9314 s diff)
9315 (format "%d:%02d:%02d" h m s))))
9316 (kill-new sres)
9317 (if (interactive-p)
9318 (message "%s"
9319 (substitute-command-keys
9320 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9321 (length numbers) sres))))
9322 sres))))
9324 (defun org-table-get-number-for-summing (s)
9325 (let (n)
9326 (if (string-match "^ *|? *" s)
9327 (setq s (replace-match "" nil nil s)))
9328 (if (string-match " *|? *$" s)
9329 (setq s (replace-match "" nil nil s)))
9330 (setq n (string-to-number s))
9331 (cond
9332 ((and (string-match "0" s)
9333 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9334 ((string-match "\\`[ \t]+\\'" s) nil)
9335 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9336 (let ((h (string-to-number (or (match-string 1 s) "0")))
9337 (m (string-to-number (or (match-string 2 s) "0")))
9338 (s (string-to-number (or (match-string 4 s) "0"))))
9339 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9340 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9341 ((equal n 0) nil)
9342 (t n))))
9344 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9345 "Get a calc vector from a column, accorting to descriptor DESC.
9346 Optional arguments TBEG and COL can give the beginning of the table and
9347 the current column, to avoid unnecessary parsing."
9348 (save-excursion
9349 (or tbeg (setq tbeg (org-table-begin)))
9350 (or col (setq col (org-table-current-column)))
9351 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9352 (cond
9353 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9354 (setq n1 (- (match-end 1) (match-beginning 1)))
9355 (if (match-beginning 3)
9356 (setq n2 (- (match-end 2) (match-beginning 3))))
9357 (setq n (if n2 (max n1 n2) n1))
9358 (setq n1 (if n2 (min n1 n2)))
9359 (setq nn n)
9360 (while (and (> nn 0)
9361 (re-search-backward org-table-hline-regexp tbeg t))
9362 (push (org-current-line) hline-list)
9363 (setq nn (1- nn)))
9364 (setq hline-list (nreverse hline-list))
9365 (goto-line (nth (1- n) hline-list))
9366 (when (re-search-forward org-table-dataline-regexp)
9367 (org-table-goto-column col)
9368 (setq beg (point)))
9369 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9370 (when (re-search-backward org-table-dataline-regexp)
9371 (org-table-goto-column col)
9372 (setq end (point)))
9373 (setq l (apply 'append (org-table-copy-region beg end)))
9374 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9375 (if (equal x "") "0" x))
9376 l ",") "]"))
9377 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9378 (setq n1 (string-to-number (match-string 1 desc))
9379 n2 (string-to-number (match-string 2 desc)))
9380 (beginning-of-line 1)
9381 (save-excursion
9382 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9383 (org-table-goto-column col)
9384 (setq beg (point))))
9385 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9386 (org-table-goto-column col)
9387 (setq end (point)))
9388 (setq l (apply 'append (org-table-copy-region beg end)))
9389 (concat "[" (mapconcat
9390 (lambda (x) (setq x (org-trim x))
9391 (if (equal x "") "0" x))
9392 l ",") "]"))
9393 ((string-match "\\([0-9]+\\)" desc)
9394 (beginning-of-line 1)
9395 (when (re-search-backward org-table-dataline-regexp tbeg t
9396 (string-to-number (match-string 0 desc)))
9397 (org-table-goto-column col)
9398 (org-trim (org-table-get-field))))))))
9400 (defvar org-table-formula-history nil)
9402 (defvar org-table-column-names nil
9403 "Alist with column names, derived from the `!' line.")
9404 (defvar org-table-column-name-regexp nil
9405 "Regular expression matching the current column names.")
9406 (defvar org-table-local-parameters nil
9407 "Alist with parameter names, derived from the `$' line.")
9408 (defvar org-table-named-field-locations nil
9409 "Alist with locations of named fields.")
9411 (defun org-table-get-formula (&optional equation named)
9412 "Read a formula from the minibuffer, offer stored formula as default."
9413 (let* ((name (car (rassoc (list (org-current-line)
9414 (org-table-current-column))
9415 org-table-named-field-locations)))
9416 (scol (if named
9417 (if name name
9418 (error "Not in a named field"))
9419 (int-to-string (org-table-current-column))))
9420 (dummy (and name (not named)
9421 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9422 (error "Abort")))
9423 (org-table-may-need-update nil)
9424 (stored-list (org-table-get-stored-formulas))
9425 (stored (cdr (assoc scol stored-list)))
9426 (eq (cond
9427 ((and stored equation (string-match "^ *=? *$" equation))
9428 stored)
9429 ((stringp equation)
9430 equation)
9431 (t (read-string
9432 (format "%s formula $%s=" (if named "Field" "Column") scol)
9433 (or stored "") 'org-table-formula-history
9434 ;stored
9435 ))))
9436 mustsave)
9437 (when (not (string-match "\\S-" eq))
9438 ;; remove formula
9439 (setq stored-list (delq (assoc scol stored-list) stored-list))
9440 (org-table-store-formulas stored-list)
9441 (error "Formula removed"))
9442 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9443 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9444 (if (and name (not named))
9445 ;; We set the column equation, delete the named one.
9446 (setq stored-list (delq (assoc name stored-list) stored-list)
9447 mustsave t))
9448 (if stored
9449 (setcdr (assoc scol stored-list) eq)
9450 (setq stored-list (cons (cons scol eq) stored-list)))
9451 (if (or mustsave (not (equal stored eq)))
9452 (org-table-store-formulas stored-list))
9453 eq))
9455 (defun org-table-store-formulas (alist)
9456 "Store the list of formulas below the current table."
9457 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9458 (save-excursion
9459 (goto-char (org-table-end))
9460 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9461 (delete-region (point) (match-end 0)))
9462 (insert "#+TBLFM: "
9463 (mapconcat (lambda (x)
9464 (concat "$" (car x) "=" (cdr x)))
9465 alist "::")
9466 "\n")))
9468 (defun org-table-get-stored-formulas ()
9469 "Return an alist with the t=stored formulas directly after current table."
9470 (interactive)
9471 (let (scol eq eq-alist strings string seen)
9472 (save-excursion
9473 (goto-char (org-table-end))
9474 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9475 (setq strings (org-split-string (match-string 2) " *:: *"))
9476 (while (setq string (pop strings))
9477 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9478 (setq scol (match-string 1 string)
9479 eq (match-string 2 string)
9480 eq-alist (cons (cons scol eq) eq-alist))
9481 (if (member scol seen)
9482 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9483 (push scol seen))))))
9484 (nreverse eq-alist)))
9486 (defun org-table-modify-formulas (action &rest columns)
9487 "Modify the formulas stored below the current table.
9488 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
9489 expected, for the other actions only a single column number is needed."
9490 (let ((list (org-table-get-stored-formulas))
9491 (nmax (length (org-split-string
9492 (buffer-substring (point-at-bol) (point-at-eol))
9493 "|")))
9494 col col1 col2 scol si sc1 sc2)
9495 (cond
9496 ((null list)) ; No action needed if there are no stored formulas
9497 ((eq action 'remove)
9498 (setq col (car columns)
9499 scol (int-to-string col))
9500 (org-table-replace-in-formulas list scol "INVALID")
9501 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
9502 (loop for i from (1+ col) upto nmax by 1 do
9503 (setq si (int-to-string i))
9504 (org-table-replace-in-formulas list si (int-to-string (1- i)))
9505 (if (assoc si list) (setcar (assoc si list)
9506 (int-to-string (1- i))))))
9507 ((eq action 'insert)
9508 (setq col (car columns))
9509 (loop for i from nmax downto col by 1 do
9510 (setq si (int-to-string i))
9511 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
9512 (if (assoc si list) (setcar (assoc si list)
9513 (int-to-string (1+ i))))))
9514 ((eq action 'swap)
9515 (setq col1 (car columns) col2 (nth 1 columns)
9516 sc1 (int-to-string col1) sc2 (int-to-string col2))
9517 ;; Hopefully, ZqZ will never be a name in a table... FIXME:
9518 (org-table-replace-in-formulas list sc1 "ZqZ")
9519 (org-table-replace-in-formulas list sc2 sc1)
9520 (org-table-replace-in-formulas list "ZqZ" sc2)
9521 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZ"))
9522 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
9523 (if (assoc "ZqZ" list) (setcar (assoc "ZqZ" list) sc2)))
9524 (t (error "Invalid action in `org-table-modify-formulas'")))
9525 (if list (org-table-store-formulas list))))
9527 (defun org-table-replace-in-formulas (list s1 s2)
9528 (let (elt re s)
9529 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
9530 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
9531 re (concat (regexp-quote s1) "\\>"))
9532 (while (setq elt (pop list))
9533 (setq s (cdr elt))
9534 (while (string-match re s)
9535 (setq s (replace-match s2 t t s)))
9536 (setcdr elt s))))
9538 (defun org-table-get-specials ()
9539 "Get the column names and local parameters for this table."
9540 (save-excursion
9541 (let ((beg (org-table-begin)) (end (org-table-end))
9542 names name fields fields1 field cnt c v line col)
9543 (setq org-table-column-names nil
9544 org-table-local-parameters nil
9545 org-table-named-field-locations nil)
9546 (goto-char beg)
9547 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9548 (setq names (org-split-string (match-string 1) " *| *")
9549 cnt 1)
9550 (while (setq name (pop names))
9551 (setq cnt (1+ cnt))
9552 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9553 (push (cons name (int-to-string cnt)) org-table-column-names))))
9554 (setq org-table-column-names (nreverse org-table-column-names))
9555 (setq org-table-column-name-regexp
9556 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9557 (goto-char beg)
9558 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9559 (setq fields (org-split-string (match-string 1) " *| *"))
9560 (while (setq field (pop fields))
9561 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9562 (push (cons (match-string 1 field) (match-string 2 field))
9563 org-table-local-parameters))))
9564 (goto-char beg)
9565 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9566 (setq c (match-string 1)
9567 fields (org-split-string (match-string 2) " *| *"))
9568 (save-excursion
9569 (beginning-of-line (if (equal c "_") 2 0))
9570 (setq line (org-current-line) col 1)
9571 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9572 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9573 (while (and fields1 (setq field (pop fields)))
9574 (setq v (pop fields1) col (1+ col))
9575 (when (and (stringp field) (stringp v)
9576 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9577 (push (cons field v) org-table-local-parameters)
9578 (push (list field line col) org-table-named-field-locations)))))))
9580 (defun org-this-word ()
9581 ;; Get the current word
9582 (save-excursion
9583 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
9584 (end (progn (skip-chars-forward "^ \t\n") (point))))
9585 (buffer-substring-no-properties beg end))))
9587 (defun org-table-maybe-eval-formula ()
9588 "Check if the current field starts with \"=\" or \":=\".
9589 If yes, store the formula and apply it."
9590 ;; We already know we are in a table. Get field will only return a formula
9591 ;; when appropriate. It might return a separator line, but no problem.
9592 (when org-table-formula-evaluate-inline
9593 (let* ((field (org-trim (or (org-table-get-field) "")))
9594 named eq)
9595 (when (string-match "^:?=\\(.*\\)" field)
9596 (setq named (equal (string-to-char field) ?:)
9597 eq (match-string 1 field))
9598 (if (fboundp 'calc-eval)
9599 (org-table-eval-formula (if named '(4) nil) eq))))))
9601 (defvar org-recalc-commands nil
9602 "List of commands triggering the recalculation of a line.
9603 Will be filled automatically during use.")
9605 (defvar org-recalc-marks
9606 '((" " . "Unmarked: no special line, no automatic recalculation")
9607 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9608 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9609 ("!" . "Column name definition line. Reference in formula as $name.")
9610 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9611 ("_" . "Names for values in row below this one.")
9612 ("^" . "Names for values in row above this one.")))
9614 (defun org-table-rotate-recalc-marks (&optional newchar)
9615 "Rotate the recalculation mark in the first column.
9616 If in any row, the first field is not consistent with a mark,
9617 insert a new column for the markers.
9618 When there is an active region, change all the lines in the region,
9619 after prompting for the marking character.
9620 After each change, a message will be displayed indicating the meaning
9621 of the new mark."
9622 (interactive)
9623 (unless (org-at-table-p) (error "Not at a table"))
9624 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9625 (beg (org-table-begin))
9626 (end (org-table-end))
9627 (l (org-current-line))
9628 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9629 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9630 (have-col
9631 (save-excursion
9632 (goto-char beg)
9633 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9634 (col (org-table-current-column))
9635 (forcenew (car (assoc newchar org-recalc-marks)))
9636 epos new)
9637 (when l1
9638 (message "Change region to what mark? Type # * ! $ or SPC: ")
9639 (setq newchar (char-to-string (read-char-exclusive))
9640 forcenew (car (assoc newchar org-recalc-marks))))
9641 (if (and newchar (not forcenew))
9642 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9643 newchar))
9644 (if l1 (goto-line l1))
9645 (save-excursion
9646 (beginning-of-line 1)
9647 (unless (looking-at org-table-dataline-regexp)
9648 (error "Not at a table data line")))
9649 (unless have-col
9650 (org-table-goto-column 1)
9651 (org-table-insert-column)
9652 (org-table-goto-column (1+ col)))
9653 (setq epos (point-at-eol))
9654 (save-excursion
9655 (beginning-of-line 1)
9656 (org-table-get-field
9657 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9658 (concat " "
9659 (setq new (or forcenew
9660 (cadr (member (match-string 1) marks))))
9661 " ")
9662 " # ")))
9663 (if (and l1 l2)
9664 (progn
9665 (goto-line l1)
9666 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9667 (and (looking-at org-table-dataline-regexp)
9668 (org-table-get-field 1 (concat " " new " "))))
9669 (goto-line l1)))
9670 (if (not (= epos (point-at-eol))) (org-table-align))
9671 (goto-line l)
9672 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9674 (defun org-table-maybe-recalculate-line ()
9675 "Recompute the current line if marked for it, and if we haven't just done it."
9676 (interactive)
9677 (and org-table-allow-automatic-line-recalculation
9678 (not (and (memq last-command org-recalc-commands)
9679 (equal org-last-recalc-line (org-current-line))))
9680 (save-excursion (beginning-of-line 1)
9681 (looking-at org-table-auto-recalculate-regexp))
9682 (fboundp 'calc-eval)
9683 (org-table-recalculate) t))
9685 (defvar org-table-formula-debug nil
9686 "Non-nil means, debug table formulas.
9687 When nil, simply write \"#ERROR\" in corrupted fields.")
9689 (defvar modes)
9690 (defsubst org-set-calc-mode (var &optional value)
9691 (if (stringp var)
9692 (setq var (assoc var '(("D" calc-angle-mode deg)
9693 ("R" calc-angle-mode rad)
9694 ("F" calc-prefer-frac t)
9695 ("S" calc-symbolic-mode t)))
9696 value (nth 2 var) var (nth 1 var)))
9697 (if (memq var modes)
9698 (setcar (cdr (memq var modes)) value)
9699 (cons var (cons value modes)))
9700 modes)
9702 (defun org-table-eval-formula (&optional arg equation
9703 suppress-align suppress-const
9704 suppress-store)
9705 "Replace the table field value at the cursor by the result of a calculation.
9707 This function makes use of Dave Gillespie's Calc package, in my view the
9708 most exciting program ever written for GNU Emacs. So you need to have Calc
9709 installed in order to use this function.
9711 In a table, this command replaces the value in the current field with the
9712 result of a formula. It also installs the formula as the \"current\" column
9713 formula, by storing it in a special line below the table. When called
9714 with a `C-u' prefix, the current field must ba a named field, and the
9715 formula is installed as valid in only this specific field.
9717 When called, the command first prompts for a formula, which is read in
9718 the minibuffer. Previously entered formulas are available through the
9719 history list, and the last used formula is offered as a default.
9720 These stored formulas are adapted correctly when moving, inserting, or
9721 deleting columns with the corresponding commands.
9723 The formula can be any algebraic expression understood by the Calc package.
9724 For details, see the Org-mode manual.
9726 This function can also be called from Lisp programs and offers
9727 additional arguments: EQUATION can be the formula to apply. If this
9728 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
9729 used to speed-up recursive calls by by-passing unnecessary aligns.
9730 SUPPRESS-CONST suppresses the interpretation of constants in the
9731 formula, assuming that this has been done already outside the function.
9732 SUPPRESS-STORE means the formula should not be stored, either because
9733 it is already stored, or because it is a modified equation that should
9734 not overwrite the stored one."
9735 (interactive "P")
9736 (require 'calc)
9737 (org-table-check-inside-data-field)
9738 (org-table-get-specials)
9739 (let* (fields
9740 (ndown (if (integerp arg) arg 1))
9741 (org-table-automatic-realign nil)
9742 (case-fold-search nil)
9743 (down (> ndown 1))
9744 (formula (if (and equation suppress-store)
9745 equation
9746 (org-table-get-formula equation (equal arg '(4)))))
9747 (n0 (org-table-current-column))
9748 (modes (copy-sequence org-calc-default-modes))
9749 n form fmt x ev orig c)
9750 ;; Parse the format string. Since we have a lot of modes, this is
9751 ;; a lot of work. However, I think calc still uses most of the time.
9752 (if (string-match ";" formula)
9753 (let ((tmp (org-split-string formula ";")))
9754 (setq formula (car tmp)
9755 fmt (concat (cdr (assoc "%" org-table-local-parameters))
9756 (nth 1 tmp)))
9757 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
9758 (setq c (string-to-char (match-string 1 fmt))
9759 n (string-to-number (or (match-string 1 fmt) "")))
9760 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
9761 (setq modes (org-set-calc-mode
9762 'calc-float-format
9763 (list (cdr (assoc c '((?n . float) (?f . fix)
9764 (?s . sci) (?e . eng))))
9765 n))))
9766 (setq fmt (replace-match "" t t fmt)))
9767 (while (string-match "[DRFS]" fmt)
9768 (setq modes (org-set-calc-mode (match-string 0 fmt)))
9769 (setq fmt (replace-match "" t t fmt)))
9770 (unless (string-match "\\S-" fmt)
9771 (setq fmt nil))))
9772 (if (and (not suppress-const) org-table-formula-use-constants)
9773 (setq formula (org-table-formula-substitute-names formula)))
9774 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
9775 (while (> ndown 0)
9776 (setq fields (org-split-string
9777 (buffer-substring
9778 (point-at-bol) (point-at-eol)) " *| *"))
9779 (if org-table-formula-numbers-only
9780 (setq fields (mapcar
9781 (lambda (x) (number-to-string (string-to-number x)))
9782 fields)))
9783 (setq ndown (1- ndown))
9784 (setq form (copy-sequence formula))
9785 ;; Insert the references to fields in same row
9786 (while (string-match "\\$\\([0-9]+\\)?" form)
9787 (setq n (if (match-beginning 1)
9788 (string-to-number (match-string 1 form))
9790 x (nth (1- n) fields))
9791 (unless x (error "Invalid field specifier \"%s\""
9792 (match-string 0 form)))
9793 (if (equal x "") (setq x "0"))
9794 (setq form (replace-match (concat "(" x ")") t t form)))
9795 ;; Insert ranges in current column
9796 (while (string-match "\\&[-I0-9]+" form)
9797 (setq form (replace-match
9798 (save-match-data
9799 (org-table-get-vertical-vector (match-string 0 form)
9800 nil n0))
9801 t t form)))
9802 (setq ev (calc-eval (cons form modes)
9803 (if org-table-formula-numbers-only 'num)))
9805 (when org-table-formula-debug
9806 (with-output-to-temp-buffer "*Help*"
9807 (princ (format "Substitution history of formula
9808 Orig: %s
9809 $xyz-> %s
9810 $1-> %s\n" orig formula form))
9811 (if (listp ev)
9812 (princ (format " %s^\nError: %s"
9813 (make-string (car ev) ?\-) (nth 1 ev)))
9814 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
9815 ev (or fmt "NONE")
9816 (if fmt (format fmt (string-to-number ev)) ev)))))
9817 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
9818 (unless (and (interactive-p) (not ndown))
9819 (unless (let (inhibit-redisplay)
9820 (y-or-n-p "Debugging Formula. Continue to next? "))
9821 (org-table-align)
9822 (error "Abort"))
9823 (delete-window (get-buffer-window "*Help*"))
9824 (message "")))
9825 (if (listp ev) (setq fmt nil ev "#ERROR"))
9826 (org-table-justify-field-maybe
9827 (if fmt (format fmt (string-to-number ev)) ev))
9828 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
9829 (call-interactively 'org-return)
9830 (setq ndown 0)))
9831 (and down (org-table-maybe-recalculate-line))
9832 (or suppress-align (and org-table-may-need-update
9833 (org-table-align)))))
9835 (defun org-table-recalculate (&optional all noalign)
9836 "Recalculate the current table line by applying all stored formulas."
9837 (interactive "P")
9838 (or (memq this-command org-recalc-commands)
9839 (setq org-recalc-commands (cons this-command org-recalc-commands)))
9840 (unless (org-at-table-p) (error "Not at a table"))
9841 (org-table-get-specials)
9842 (let* ((eqlist (sort (org-table-get-stored-formulas)
9843 (lambda (a b) (string< (car a) (car b)))))
9844 (inhibit-redisplay t)
9845 (line-re org-table-dataline-regexp)
9846 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9847 (thiscol (org-table-current-column))
9848 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
9849 ;; Insert constants in all formulas
9850 (setq eqlist
9851 (mapcar (lambda (x)
9852 (setcdr x (org-table-formula-substitute-names (cdr x)))
9854 eqlist))
9855 ;; Split the equation list
9856 (while (setq eq (pop eqlist))
9857 (if (<= (string-to-char (car eq)) ?9)
9858 (push eq eqlnum)
9859 (push eq eqlname)))
9860 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
9861 (if all
9862 (progn
9863 (setq end (move-marker (make-marker) (1+ (org-table-end))))
9864 (goto-char (setq beg (org-table-begin)))
9865 (if (re-search-forward org-table-calculate-mark-regexp end t)
9866 ;; This is a table with marked lines, only compute selected lines
9867 (setq line-re org-table-recalculate-regexp)
9868 ;; Move forward to the first non-header line
9869 (if (and (re-search-forward org-table-dataline-regexp end t)
9870 (re-search-forward org-table-hline-regexp end t)
9871 (re-search-forward org-table-dataline-regexp end t))
9872 (setq beg (match-beginning 0))
9873 nil))) ;; just leave beg where it is
9874 (setq beg (point-at-bol)
9875 end (move-marker (make-marker) (1+ (point-at-eol)))))
9876 (goto-char beg)
9877 (and all (message "Re-applying formulas to full table..."))
9878 (while (re-search-forward line-re end t)
9879 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
9880 ;; Unprotected line, recalculate
9881 (and all (message "Re-applying formulas to full table...(line %d)"
9882 (setq cnt (1+ cnt))))
9883 (setq org-last-recalc-line (org-current-line))
9884 (setq eql eqlnum)
9885 (while (setq entry (pop eql))
9886 (goto-line org-last-recalc-line)
9887 (org-table-goto-column (string-to-number (car entry)) nil 'force)
9888 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
9889 (goto-line thisline)
9890 (org-table-goto-column thiscol)
9891 (or noalign (and org-table-may-need-update (org-table-align))
9892 (and all (message "Re-applying formulas to %d lines...done" cnt)))
9893 ;; Now do the names fields
9894 (while (setq eq (pop eqlname))
9895 (setq name (car eq)
9896 a (assoc name org-table-named-field-locations))
9897 (when a
9898 (message "Re-applying formula to named field: %s" name)
9899 (goto-line (nth 1 a))
9900 (org-table-goto-column (nth 2 a))
9901 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
9902 ;; back to initial position
9903 (goto-line thisline)
9904 (org-table-goto-column thiscol)
9905 (or noalign (and org-table-may-need-update (org-table-align))
9906 (and all (message "Re-applying formulas...done")))))
9908 (defun org-table-formula-substitute-names (f)
9909 "Replace $const with values in string F."
9910 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
9911 ;; First, check for column names
9912 (while (setq start (string-match org-table-column-name-regexp f start))
9913 (setq start (1+ start))
9914 (setq a (assoc (match-string 1 f) org-table-column-names))
9915 (setq f (replace-match (concat "$" (cdr a)) t t f)))
9916 ;; Expand ranges to vectors
9917 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
9918 (setq n1 (string-to-number (match-string 1 f))
9919 n2 (string-to-number (match-string 2 f))
9920 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
9921 s (concat "[($" (number-to-string (1- nn1)) ")"))
9922 (loop for i from nn1 upto nn2 do
9923 (setq s (concat s ",($" (int-to-string i) ")")))
9924 (setq s (concat s "]"))
9925 (if (< n2 n1) (setq s (concat "rev(" s ")")))
9926 (setq f (replace-match s t t f)))
9927 ;; Parameters and constants
9928 (setq start 0)
9929 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
9930 (setq start (1+ start))
9931 (if (setq a (save-match-data
9932 (org-table-get-constant (match-string 1 f))))
9933 (setq f (replace-match (concat "(" a ")") t t f))))
9934 (if org-table-formula-debug
9935 (put-text-property 0 (length f) :orig-formula f1 f))
9938 (defun org-table-get-constant (const)
9939 "Find the value for a parameter or constant in a formula.
9940 Parameters get priority."
9941 (or (cdr (assoc const org-table-local-parameters))
9942 (cdr (assoc const org-table-formula-constants))
9943 (and (fboundp 'constants-get) (constants-get const))
9944 "#UNDEFINED_NAME"))
9946 (defvar org-edit-formulas-map (make-sparse-keymap))
9947 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
9948 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
9949 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
9951 (defvar org-pos)
9953 (defun org-table-edit-formulas ()
9954 "Edit the formulas of the current table in a separate buffer."
9955 (interactive)
9956 (unless (org-at-table-p)
9957 (error "Not at a table"))
9958 (org-table-get-specials)
9959 (let ((eql (org-table-get-stored-formulas))
9960 (pos (move-marker (make-marker) (point)))
9961 (wc (current-window-configuration))
9962 entry loc s)
9963 (switch-to-buffer-other-window "*Edit Formulas*")
9964 (erase-buffer)
9965 (fundamental-mode)
9966 (set (make-local-variable 'org-pos) pos)
9967 (set (make-local-variable 'org-window-configuration) wc)
9968 (use-local-map org-edit-formulas-map)
9969 (setq s "# Edit formulas and finish with `C-c C-c'.
9970 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
9971 # Use `C-c ?' to get information about $name at point.
9972 # To cancel editing, press `C-c C-q'.\n")
9973 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9974 (insert s)
9975 (while (setq entry (pop eql))
9976 (when (setq loc (assoc (car entry) org-table-named-field-locations))
9977 (setq s (format "# Named formula, referring to column %d in line %d\n"
9978 (nth 2 loc) (nth 1 loc)))
9979 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
9980 (insert s))
9981 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
9982 (remove-text-properties 0 (length s) '(face nil) s)
9983 (insert s))
9984 (goto-char (point-min))
9985 (message "Edit formulas and finish with `C-c C-c'.")))
9987 (defun org-show-variable ()
9988 "Show the location/value of the $ expression at point."
9989 (interactive)
9990 (let (var (pos org-pos) (win (selected-window)) e)
9991 (save-excursion
9992 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
9993 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
9994 (setq var (match-string 1))
9995 (error "No variable at point")))
9996 (cond
9997 ((setq e (assoc var org-table-named-field-locations))
9998 (switch-to-buffer-other-window (marker-buffer pos))
9999 (goto-line (nth 1 e))
10000 (org-table-goto-column (nth 2 e))
10001 (select-window win)
10002 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10003 ((setq e (assoc var org-table-column-names))
10004 (switch-to-buffer-other-window (marker-buffer pos))
10005 (goto-char pos)
10006 (goto-char (org-table-begin))
10007 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10008 (org-table-end) t)
10009 (progn
10010 (goto-char (match-beginning 1))
10011 (message "Named column (column %s)" (cdr e)))
10012 (error "Column name not found"))
10013 (select-window win))
10014 ((string-match "^[0-9]$" var)
10015 ;; column number
10016 (switch-to-buffer-other-window (marker-buffer pos))
10017 (goto-char pos)
10018 (goto-char (org-table-begin))
10019 (recenter 1)
10020 (if (re-search-forward org-table-dataline-regexp
10021 (org-table-end) t)
10022 (progn
10023 (goto-char (match-beginning 0))
10024 (org-table-goto-column (string-to-number var))
10025 (message "Column %s" var))
10026 (error "Column name not found"))
10027 (select-window win))
10028 ((setq e (assoc var org-table-local-parameters))
10029 (switch-to-buffer-other-window (marker-buffer pos))
10030 (goto-char pos)
10031 (goto-char (org-table-begin))
10032 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10033 (progn
10034 (goto-char (match-beginning 1))
10035 (message "Local parameter."))
10036 (error "Parameter not found"))
10037 (select-window win))
10039 (cond
10040 ((setq e (assoc var org-table-formula-constants))
10041 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
10042 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10043 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
10044 (t (error "Undefined name $%s" var)))))))
10046 (defun org-finish-edit-formulas (&optional arg)
10047 "Parse the buffer for formula definitions and install them.
10048 With prefix ARG, apply the new formulas to the table."
10049 (interactive "P")
10050 (let ((pos org-pos) eql)
10051 (goto-char (point-min))
10052 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
10053 (push (cons (match-string 1) (match-string 2)) eql))
10054 (set-window-configuration org-window-configuration)
10055 (select-window (get-buffer-window (marker-buffer pos)))
10056 (goto-char pos)
10057 (unless (org-at-table-p)
10058 (error "Lost table position - cannot install formulae"))
10059 (org-table-store-formulas eql)
10060 (move-marker pos nil)
10061 (kill-buffer "*Edit Formulas*")
10062 (if arg
10063 (org-table-recalculate 'all)
10064 (message "New formulas installed - press C-u C-c C-c to apply."))))
10066 (defun org-abort-edit-formulas ()
10067 "Abort editing formulas, without installing the changes."
10068 (interactive)
10069 (let ((pos org-pos))
10070 (set-window-configuration org-window-configuration)
10071 (select-window (get-buffer-window (marker-buffer pos)))
10072 (goto-char pos)
10073 (message "Formula editing aborted without installing changes")))
10075 ;;; The orgtbl minor mode
10077 ;; Define a minor mode which can be used in other modes in order to
10078 ;; integrate the org-mode table editor.
10080 ;; This is really a hack, because the org-mode table editor uses several
10081 ;; keys which normally belong to the major mode, for example the TAB and
10082 ;; RET keys. Here is how it works: The minor mode defines all the keys
10083 ;; necessary to operate the table editor, but wraps the commands into a
10084 ;; function which tests if the cursor is currently inside a table. If that
10085 ;; is the case, the table editor command is executed. However, when any of
10086 ;; those keys is used outside a table, the function uses `key-binding' to
10087 ;; look up if the key has an associated command in another currently active
10088 ;; keymap (minor modes, major mode, global), and executes that command.
10089 ;; There might be problems if any of the keys used by the table editor is
10090 ;; otherwise used as a prefix key.
10092 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10093 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10094 ;; addresses this by checking explicitly for both bindings.
10096 ;; The optimized version (see variable `orgtbl-optimized') takes over
10097 ;; all keys which are bound to `self-insert-command' in the *global map*.
10098 ;; Some modes bind other commands to simple characters, for example
10099 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10100 ;; active, this binding is ignored inside tables and replaced with a
10101 ;; modified self-insert.
10103 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
10104 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
10105 In the optimized version, the table editor takes over all simple keys that
10106 normally just insert a character. In tables, the characters are inserted
10107 in a way to minimize disturbing the table structure (i.e. in overwrite mode
10108 for empty fields). Outside tables, the correct binding of the keys is
10109 restored.
10111 The default for this option is t if the optimized version is also used in
10112 Org-mode. See the variable `org-enable-table-editor' for details. Changing
10113 this variable requires a restart of Emacs to become effective."
10114 :group 'org-table
10115 :type 'boolean)
10117 (defvar orgtbl-mode nil
10118 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10119 table editor in arbitrary modes.")
10120 (make-variable-buffer-local 'orgtbl-mode)
10122 (defvar orgtbl-mode-map (make-keymap)
10123 "Keymap for `orgtbl-mode'.")
10125 ;;;###autoload
10126 (defun turn-on-orgtbl ()
10127 "Unconditionally turn on `orgtbl-mode'."
10128 (orgtbl-mode 1))
10130 ;;;###autoload
10131 (defun orgtbl-mode (&optional arg)
10132 "The `org-mode' table editor as a minor mode for use in other modes."
10133 (interactive)
10134 (if (eq major-mode 'org-mode)
10135 ;; Exit without error, in case some hook functions calls this
10136 ;; by accident in org-mode.
10137 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10138 (setq orgtbl-mode
10139 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10140 (if orgtbl-mode
10141 (progn
10142 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10143 ;; Make sure we are first in minor-mode-map-alist
10144 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10145 (and c (setq minor-mode-map-alist
10146 (cons c (delq c minor-mode-map-alist)))))
10147 (set (make-local-variable (quote org-table-may-need-update)) t)
10148 (org-add-hook 'before-change-functions 'org-before-change-function
10149 nil 'local)
10150 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
10151 auto-fill-inhibit-regexp)
10152 (set (make-local-variable 'auto-fill-inhibit-regexp)
10153 (if auto-fill-inhibit-regexp
10154 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
10155 "[ \t]*|"))
10156 (easy-menu-add orgtbl-mode-menu)
10157 (run-hooks 'orgtbl-mode-hook))
10158 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10159 (remove-hook 'before-change-functions 'org-before-change-function t)
10160 (easy-menu-remove orgtbl-mode-menu)
10161 (force-mode-line-update 'all))))
10163 ;; Install it as a minor mode.
10164 (put 'orgtbl-mode :included t)
10165 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10166 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10168 (defun orgtbl-make-binding (fun n &rest keys)
10169 "Create a function for binding in the table minor mode.
10170 FUN is the command to call inside a table. N is used to create a unique
10171 command name. KEYS are keys that should be checked in for a command
10172 to execute outside of tables."
10173 (eval
10174 (list 'defun
10175 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10176 '(arg)
10177 (concat "In tables, run `" (symbol-name fun) "'.\n"
10178 "Outside of tables, run the binding of `"
10179 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10180 "'.")
10181 '(interactive "p")
10182 (list 'if
10183 '(org-at-table-p)
10184 (list 'call-interactively (list 'quote fun))
10185 (list 'let '(orgtbl-mode)
10186 (list 'call-interactively
10187 (append '(or)
10188 (mapcar (lambda (k)
10189 (list 'key-binding k))
10190 keys)
10191 '('orgtbl-error))))))))
10193 (defun orgtbl-error ()
10194 "Error when there is no default binding for a table key."
10195 (interactive)
10196 (error "This key is has no function outside tables"))
10198 (defun orgtbl-setup ()
10199 "Setup orgtbl keymaps."
10200 (let ((nfunc 0)
10201 (bindings
10202 (list
10203 '([(meta shift left)] org-table-delete-column)
10204 '([(meta left)] org-table-move-column-left)
10205 '([(meta right)] org-table-move-column-right)
10206 '([(meta shift right)] org-table-insert-column)
10207 '([(meta shift up)] org-table-kill-row)
10208 '([(meta shift down)] org-table-insert-row)
10209 '([(meta up)] org-table-move-row-up)
10210 '([(meta down)] org-table-move-row-down)
10211 '("\C-c\C-w" org-table-cut-region)
10212 '("\C-c\M-w" org-table-copy-region)
10213 '("\C-c\C-y" org-table-paste-rectangle)
10214 '("\C-c-" org-table-insert-hline)
10215 ; '([(shift tab)] org-table-previous-field)
10216 '("\C-m" org-table-next-row)
10217 (list (org-key 'S-return) 'org-table-copy-down)
10218 '([(meta return)] org-table-wrap-region)
10219 '("\C-c\C-q" org-table-wrap-region)
10220 '("\C-c?" org-table-current-column)
10221 '("\C-c " org-table-blank-field)
10222 '("\C-c+" org-table-sum)
10223 '("\C-c|" org-table-toggle-vline-visibility)
10224 '("\C-c=" org-table-eval-formula)
10225 '("\C-c'" org-table-edit-formulas)
10226 '("\C-c*" org-table-recalculate)
10227 '("\C-c^" org-table-sort-lines)
10228 '([(control ?#)] org-table-rotate-recalc-marks)))
10229 elt key fun cmd)
10230 (while (setq elt (pop bindings))
10231 (setq nfunc (1+ nfunc))
10232 (setq key (car elt)
10233 fun (nth 1 elt)
10234 cmd (orgtbl-make-binding fun nfunc key))
10235 (define-key orgtbl-mode-map key cmd))
10236 ;; Special treatment needed for TAB and RET
10237 (define-key orgtbl-mode-map [(return)]
10238 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10239 (define-key orgtbl-mode-map "\C-m"
10240 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10241 (define-key orgtbl-mode-map [(tab)]
10242 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10243 (define-key orgtbl-mode-map "\C-i"
10244 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
10245 (define-key orgtbl-mode-map "\C-i"
10246 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
10247 (define-key orgtbl-mode-map "\C-c\C-c"
10248 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
10249 (when orgtbl-optimized
10250 ;; If the user wants maximum table support, we need to hijack
10251 ;; some standard editing functions
10252 (org-remap orgtbl-mode-map
10253 'self-insert-command 'orgtbl-self-insert-command
10254 'delete-char 'orgtbl-delete-char
10255 'delete-backward-char 'orgtbl-delete-backward-char)
10256 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
10257 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10258 '("OrgTbl"
10259 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10260 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10261 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10262 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10263 "--"
10264 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10265 ["Copy Field from Above"
10266 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10267 "--"
10268 ("Column"
10269 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10270 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10271 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10272 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"])
10273 ("Row"
10274 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10275 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10276 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10277 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10278 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10279 "--"
10280 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10281 ("Rectangle"
10282 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10283 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10284 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10285 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10286 "--"
10287 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10288 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10289 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10290 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10291 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10292 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10293 ["Sum Column/Rectangle" org-table-sum
10294 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10295 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10296 ["Debug Formulas"
10297 (setq org-table-formula-debug (not org-table-formula-debug))
10298 :style toggle :selected org-table-formula-debug]
10302 (defun orgtbl-tab ()
10303 "Justification and field motion for `orgtbl-mode'."
10304 (interactive)
10305 (org-table-justify-field-maybe)
10306 (org-table-next-field))
10308 (defun orgtbl-ret ()
10309 "Justification and field motion for `orgtbl-mode'."
10310 (interactive)
10311 (org-table-justify-field-maybe)
10312 (org-table-next-row))
10314 (defun orgtbl-self-insert-command (N)
10315 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10316 If the cursor is in a table looking at whitespace, the whitespace is
10317 overwritten, and the table is not marked as requiring realignment."
10318 (interactive "p")
10319 (if (and (org-at-table-p)
10321 (and org-table-auto-blank-field
10322 (member last-command
10323 '(orgtbl-hijacker-command-100
10324 orgtbl-hijacker-command-101
10325 orgtbl-hijacker-command-102
10326 orgtbl-hijacker-command-103
10327 orgtbl-hijacker-command-104
10328 orgtbl-hijacker-command-105))
10329 (org-table-blank-field))
10331 (eq N 1)
10332 (looking-at "[^|\n]* +|"))
10333 (let (org-table-may-need-update)
10334 (goto-char (1- (match-end 0)))
10335 (delete-backward-char 1)
10336 (goto-char (match-beginning 0))
10337 (self-insert-command N))
10338 (setq org-table-may-need-update t)
10339 (let (orgtbl-mode)
10340 (call-interactively (key-binding (vector last-input-event))))))
10342 (defun org-force-self-insert (N)
10343 "Needed to enforce self-insert under remapping."
10344 (interactive "p")
10345 (self-insert-command N))
10347 (defun orgtbl-delete-backward-char (N)
10348 "Like `delete-backward-char', insert whitespace at field end in tables.
10349 When deleting backwards, in tables this function will insert whitespace in
10350 front of the next \"|\" separator, to keep the table aligned. The table will
10351 still be marked for re-alignment, because a narrow field may lead to a
10352 reduced column width."
10353 (interactive "p")
10354 (if (and (org-at-table-p)
10355 (eq N 1)
10356 (string-match "|" (buffer-substring (point-at-bol) (point)))
10357 (looking-at ".*?|"))
10358 (let ((pos (point)))
10359 (backward-delete-char N)
10360 (skip-chars-forward "^|")
10361 (insert " ")
10362 (goto-char (1- pos)))
10363 (delete-backward-char N)))
10365 (defun orgtbl-delete-char (N)
10366 "Like `delete-char', but insert whitespace at field end in tables.
10367 When deleting characters, in tables this function will insert whitespace in
10368 front of the next \"|\" separator, to keep the table aligned. The table
10369 will still be marked for re-alignment, because a narrow field may lead to
10370 a reduced column width."
10371 (interactive "p")
10372 (if (and (org-at-table-p)
10373 (not (bolp))
10374 (not (= (char-after) ?|))
10375 (eq N 1))
10376 (if (looking-at ".*?|")
10377 (let ((pos (point)))
10378 (replace-match (concat
10379 (substring (match-string 0) 1 -1)
10380 " |"))
10381 (goto-char pos)))
10382 (delete-char N)))
10384 ;;; Exporting
10386 (defconst org-level-max 20)
10388 (defun org-export-find-first-heading-line (list)
10389 "Remove all lines from LIST which are before the first headline."
10390 (let ((orig-list list)
10391 (re (concat "^" outline-regexp)))
10392 (while (and list
10393 (not (string-match re (car list))))
10394 (pop list))
10395 (or list orig-list)))
10397 (defun org-skip-comments (lines)
10398 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10399 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10400 (re2 "^\\(\\*+\\)[ \t\n\r]")
10401 rtn line level)
10402 (while (setq line (pop lines))
10403 (cond
10404 ((and (string-match re1 line)
10405 (setq level (- (match-end 1) (match-beginning 1))))
10406 ;; Beginning of a COMMENT subtree. Skip it.
10407 (while (and (setq line (pop lines))
10408 (or (not (string-match re2 line))
10409 (> (- (match-end 1) (match-beginning 1)) level))))
10410 (setq lines (cons line lines)))
10411 ((string-match "^#" line)
10412 ;; an ordinary comment line
10414 ((and org-export-table-remove-special-lines
10415 (string-match "^[ \t]*| *[!_^] *|" line))
10416 ;; a special table line that should be removed
10418 (t (setq rtn (cons line rtn)))))
10419 (nreverse rtn)))
10421 ;; ASCII
10423 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10424 "Characters for underlining headings in ASCII export.")
10426 (defconst org-html-entities
10427 '(("nbsp")
10428 ("iexcl")
10429 ("cent")
10430 ("pound")
10431 ("curren")
10432 ("yen")
10433 ("brvbar")
10434 ("sect")
10435 ("uml")
10436 ("copy")
10437 ("ordf")
10438 ("laquo")
10439 ("not")
10440 ("shy")
10441 ("reg")
10442 ("macr")
10443 ("deg")
10444 ("plusmn")
10445 ("sup2")
10446 ("sup3")
10447 ("acute")
10448 ("micro")
10449 ("para")
10450 ("middot")
10451 ("odot"."o")
10452 ("star"."*")
10453 ("cedil")
10454 ("sup1")
10455 ("ordm")
10456 ("raquo")
10457 ("frac14")
10458 ("frac12")
10459 ("frac34")
10460 ("iquest")
10461 ("Agrave")
10462 ("Aacute")
10463 ("Acirc")
10464 ("Atilde")
10465 ("Auml")
10466 ("Aring") ("AA"."&Aring;")
10467 ("AElig")
10468 ("Ccedil")
10469 ("Egrave")
10470 ("Eacute")
10471 ("Ecirc")
10472 ("Euml")
10473 ("Igrave")
10474 ("Iacute")
10475 ("Icirc")
10476 ("Iuml")
10477 ("ETH")
10478 ("Ntilde")
10479 ("Ograve")
10480 ("Oacute")
10481 ("Ocirc")
10482 ("Otilde")
10483 ("Ouml")
10484 ("times")
10485 ("Oslash")
10486 ("Ugrave")
10487 ("Uacute")
10488 ("Ucirc")
10489 ("Uuml")
10490 ("Yacute")
10491 ("THORN")
10492 ("szlig")
10493 ("agrave")
10494 ("aacute")
10495 ("acirc")
10496 ("atilde")
10497 ("auml")
10498 ("aring")
10499 ("aelig")
10500 ("ccedil")
10501 ("egrave")
10502 ("eacute")
10503 ("ecirc")
10504 ("euml")
10505 ("igrave")
10506 ("iacute")
10507 ("icirc")
10508 ("iuml")
10509 ("eth")
10510 ("ntilde")
10511 ("ograve")
10512 ("oacute")
10513 ("ocirc")
10514 ("otilde")
10515 ("ouml")
10516 ("divide")
10517 ("oslash")
10518 ("ugrave")
10519 ("uacute")
10520 ("ucirc")
10521 ("uuml")
10522 ("yacute")
10523 ("thorn")
10524 ("yuml")
10525 ("fnof")
10526 ("Alpha")
10527 ("Beta")
10528 ("Gamma")
10529 ("Delta")
10530 ("Epsilon")
10531 ("Zeta")
10532 ("Eta")
10533 ("Theta")
10534 ("Iota")
10535 ("Kappa")
10536 ("Lambda")
10537 ("Mu")
10538 ("Nu")
10539 ("Xi")
10540 ("Omicron")
10541 ("Pi")
10542 ("Rho")
10543 ("Sigma")
10544 ("Tau")
10545 ("Upsilon")
10546 ("Phi")
10547 ("Chi")
10548 ("Psi")
10549 ("Omega")
10550 ("alpha")
10551 ("beta")
10552 ("gamma")
10553 ("delta")
10554 ("epsilon")
10555 ("varepsilon"."&epsilon;")
10556 ("zeta")
10557 ("eta")
10558 ("theta")
10559 ("iota")
10560 ("kappa")
10561 ("lambda")
10562 ("mu")
10563 ("nu")
10564 ("xi")
10565 ("omicron")
10566 ("pi")
10567 ("rho")
10568 ("sigmaf") ("varsigma"."&sigmaf;")
10569 ("sigma")
10570 ("tau")
10571 ("upsilon")
10572 ("phi")
10573 ("chi")
10574 ("psi")
10575 ("omega")
10576 ("thetasym") ("vartheta"."&thetasym;")
10577 ("upsih")
10578 ("piv")
10579 ("bull") ("bullet"."&bull;")
10580 ("hellip") ("dots"."&hellip;")
10581 ("prime")
10582 ("Prime")
10583 ("oline")
10584 ("frasl")
10585 ("weierp")
10586 ("image")
10587 ("real")
10588 ("trade")
10589 ("alefsym")
10590 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
10591 ("uarr") ("uparrow"."&uarr;")
10592 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
10593 ("darr")("downarrow"."&darr;")
10594 ("harr") ("leftrightarrow"."&harr;")
10595 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
10596 ("lArr") ("Leftarrow"."&lArr;")
10597 ("uArr") ("Uparrow"."&uArr;")
10598 ("rArr") ("Rightarrow"."&rArr;")
10599 ("dArr") ("Downarrow"."&dArr;")
10600 ("hArr") ("Leftrightarrow"."&hArr;")
10601 ("forall")
10602 ("part") ("partial"."&part;")
10603 ("exist") ("exists"."&exist;")
10604 ("empty") ("emptyset"."&empty;")
10605 ("nabla")
10606 ("isin") ("in"."&isin;")
10607 ("notin")
10608 ("ni")
10609 ("prod")
10610 ("sum")
10611 ("minus")
10612 ("lowast") ("ast"."&lowast;")
10613 ("radic")
10614 ("prop") ("proptp"."&prop;")
10615 ("infin") ("infty"."&infin;")
10616 ("ang") ("angle"."&ang;")
10617 ("and") ("vee"."&and;")
10618 ("or") ("wedge"."&or;")
10619 ("cap")
10620 ("cup")
10621 ("int")
10622 ("there4")
10623 ("sim")
10624 ("cong") ("simeq"."&cong;")
10625 ("asymp")("approx"."&asymp;")
10626 ("ne") ("neq"."&ne;")
10627 ("equiv")
10628 ("le")
10629 ("ge")
10630 ("sub") ("subset"."&sub;")
10631 ("sup") ("supset"."&sup;")
10632 ("nsub")
10633 ("sube")
10634 ("supe")
10635 ("oplus")
10636 ("otimes")
10637 ("perp")
10638 ("sdot") ("cdot"."&sdot;")
10639 ("lceil")
10640 ("rceil")
10641 ("lfloor")
10642 ("rfloor")
10643 ("lang")
10644 ("rang")
10645 ("loz") ("Diamond"."&loz;")
10646 ("spades") ("spadesuit"."&spades;")
10647 ("clubs") ("clubsuit"."&clubs;")
10648 ("hearts") ("diamondsuit"."&hearts;")
10649 ("diams") ("diamondsuit"."&diams;")
10650 ("quot")
10651 ("amp")
10652 ("lt")
10653 ("gt")
10654 ("OElig")
10655 ("oelig")
10656 ("Scaron")
10657 ("scaron")
10658 ("Yuml")
10659 ("circ")
10660 ("tilde")
10661 ("ensp")
10662 ("emsp")
10663 ("thinsp")
10664 ("zwnj")
10665 ("zwj")
10666 ("lrm")
10667 ("rlm")
10668 ("ndash")
10669 ("mdash")
10670 ("lsquo")
10671 ("rsquo")
10672 ("sbquo")
10673 ("ldquo")
10674 ("rdquo")
10675 ("bdquo")
10676 ("dagger")
10677 ("Dagger")
10678 ("permil")
10679 ("lsaquo")
10680 ("rsaquo")
10681 ("euro")
10683 ("arccos"."arccos")
10684 ("arcsin"."arcsin")
10685 ("arctan"."arctan")
10686 ("arg"."arg")
10687 ("cos"."cos")
10688 ("cosh"."cosh")
10689 ("cot"."cot")
10690 ("coth"."coth")
10691 ("csc"."csc")
10692 ("deg"."deg")
10693 ("det"."det")
10694 ("dim"."dim")
10695 ("exp"."exp")
10696 ("gcd"."gcd")
10697 ("hom"."hom")
10698 ("inf"."inf")
10699 ("ker"."ker")
10700 ("lg"."lg")
10701 ("lim"."lim")
10702 ("liminf"."liminf")
10703 ("limsup"."limsup")
10704 ("ln"."ln")
10705 ("log"."log")
10706 ("max"."max")
10707 ("min"."min")
10708 ("Pr"."Pr")
10709 ("sec"."sec")
10710 ("sin"."sin")
10711 ("sinh"."sinh")
10712 ("sup"."sup")
10713 ("tan"."tan")
10714 ("tanh"."tanh")
10716 "Entities for TeX->HTML translation.
10717 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
10718 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
10719 In that case, \"\\ent\" will be translated to \"&other;\".
10720 The list contains HTML entities for Latin-1, Greek and other symbols.
10721 It is supplemented by a number of commonly used TeX macros with appropriate
10722 translations. There is currently no way for users to extend this.")
10724 (defun org-cleaned-string-for-export (string)
10725 "Cleanup a buffer substring so that links can be created safely."
10726 (interactive)
10727 (let* ((cb (current-buffer))
10728 (re-radio (and org-target-link-regexp
10729 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
10730 rtn)
10731 (save-excursion
10732 (set-buffer (get-buffer-create " org-mode-tmp"))
10733 (erase-buffer)
10734 (insert string)
10735 (org-mode)
10736 ;; Find targets in comments and move them out of comments,
10737 ;; but mark them as targets that should be invisible
10738 (goto-char (point-min))
10739 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
10740 (replace-match "\\1(INVISIBLE)"))
10741 ;; Find matches for radio targets and turn them into links
10742 (goto-char (point-min))
10743 (when re-radio
10744 (while (re-search-forward re-radio nil t)
10745 (replace-match "\\1[[\\2]]")))
10746 ;; Find all links that contain a newline and put them into a single line
10747 (goto-char (point-min))
10748 (while (re-search-forward "\\(\\[\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\]\\)" nil t)
10749 (replace-match "\\1 \\2")
10750 (goto-char (match-beginning 0)))
10751 ;; Remove comments
10752 (goto-char (point-min))
10753 (while (re-search-forward "^#.*\n?" nil t)
10754 (replace-match ""))
10755 (setq rtn (buffer-string)))
10756 (kill-buffer " org-mode-tmp")
10757 rtn))
10759 (defun org-solidify-link-text (s &optional alist)
10760 "Take link text and make a safe target out of it."
10761 (save-match-data
10762 (let* ((rtn
10763 (mapconcat
10764 'identity
10765 (org-split-string s "[ \t\r\n]+") "--"))
10766 (a (assoc rtn alist)))
10767 (or (cdr a) rtn))))
10769 (defun org-convert-to-odd-levels ()
10770 "Convert an org-mode file with all levels allowed to one with odd levels.
10771 This will leave level 1 alone, convert level 2 to level 3, level 3 to
10772 level 5 etc."
10773 (interactive)
10774 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
10775 (let ((org-odd-levels-only nil) n)
10776 (save-excursion
10777 (goto-char (point-min))
10778 (while (re-search-forward "^\\*\\*+" nil t)
10779 (setq n (1- (length (match-string 0))))
10780 (while (>= (setq n (1- n)) 0)
10781 (org-demote))
10782 (end-of-line 1))))))
10785 (defun org-convert-to-oddeven-levels ()
10786 "Convert an org-mode file with only odd levels to one with odd and even levels.
10787 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
10788 section with an even level, conversion would destroy the structure of the file. An error
10789 is signaled in this case."
10790 (interactive)
10791 (goto-char (point-min))
10792 ;; First check if there are no even levels
10793 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
10794 (org-show-hierarchy-above)
10795 (error "Not all levels are odd in this file. Conversion not possible."))
10796 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
10797 (let ((org-odd-levels-only nil) n)
10798 (save-excursion
10799 (goto-char (point-min))
10800 (while (re-search-forward "^\\*\\*+" nil t)
10801 (setq n (/ (length (match-string 0)) 2))
10802 (while (>= (setq n (1- n)) 0)
10803 (org-promote))
10804 (end-of-line 1))))))
10806 (defun org-tr-level (n)
10807 "Make N odd if required."
10808 (if org-odd-levels-only (1+ (/ n 2)) n))
10810 (defvar org-last-level nil) ; dynamically scoped variable
10812 (defun org-export-as-ascii (arg)
10813 "Export the outline as a pretty ASCII file.
10814 If there is an active region, export only the region.
10815 The prefix ARG specifies how many levels of the outline should become
10816 underlined headlines. The default is 3."
10817 (interactive "P")
10818 (setq-default org-todo-line-regexp org-todo-line-regexp)
10819 (let* ((region
10820 (buffer-substring
10821 (if (org-region-active-p) (region-beginning) (point-min))
10822 (if (org-region-active-p) (region-end) (point-max))))
10823 (lines (org-export-find-first-heading-line
10824 (org-skip-comments
10825 (org-split-string
10826 (org-cleaned-string-for-export region)
10827 "[\r\n]"))))
10828 (org-startup-with-deadline-check nil)
10829 (level 0) line txt
10830 (umax nil)
10831 (case-fold-search nil)
10832 (filename (concat (file-name-sans-extension buffer-file-name)
10833 ".txt"))
10834 (buffer (find-file-noselect filename))
10835 (levels-open (make-vector org-level-max nil))
10836 (date (format-time-string "%Y/%m/%d" (current-time)))
10837 (time (format-time-string "%X" (org-current-time)))
10838 (author user-full-name)
10839 (title (buffer-name))
10840 (options nil)
10841 (email user-mail-address)
10842 (language org-export-default-language)
10843 (text nil)
10844 (todo nil)
10845 (lang-words nil))
10847 (setq org-last-level 1)
10848 (org-init-section-numbers)
10850 (find-file-noselect filename)
10852 ;; Search for the export key lines
10853 (org-parse-key-lines)
10855 (setq lang-words (or (assoc language org-export-language-setup)
10856 (assoc "en" org-export-language-setup)))
10857 (if org-export-ascii-show-new-buffer
10858 (switch-to-buffer-other-window buffer)
10859 (set-buffer buffer))
10860 (erase-buffer)
10861 (fundamental-mode)
10862 (if options (org-parse-export-options options))
10863 (setq umax (if arg (prefix-numeric-value arg)
10864 org-export-headline-levels))
10866 ;; File header
10867 (if title (org-insert-centered title ?=))
10868 (insert "\n")
10869 (if (or author email)
10870 (insert (concat (nth 1 lang-words) ": " (or author "")
10871 (if email (concat " <" email ">") "")
10872 "\n")))
10873 (if (and date time)
10874 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
10875 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
10877 (insert "\n\n")
10879 (if org-export-with-toc
10880 (progn
10881 (insert (nth 3 lang-words) "\n"
10882 (make-string (length (nth 3 lang-words)) ?=) "\n")
10883 (mapcar '(lambda (line)
10884 (if (string-match org-todo-line-regexp
10885 line)
10886 ;; This is a headline
10887 (progn
10888 (setq level (- (match-end 1) (match-beginning 1))
10889 level (org-tr-level level)
10890 txt (match-string 3 line)
10891 todo
10892 (or (and (match-beginning 2)
10893 (not (equal (match-string 2 line)
10894 org-done-string)))
10895 ; TODO, not DONE
10896 (and (= level umax)
10897 (org-search-todo-below
10898 line lines level))))
10899 (setq txt (org-html-expand-for-ascii txt))
10901 (if org-export-with-section-numbers
10902 (setq txt (concat (org-section-number level)
10903 " " txt)))
10904 (if (<= level umax)
10905 (progn
10906 (insert
10907 (make-string (* (1- level) 4) ?\ )
10908 (format (if todo "%s (*)\n" "%s\n") txt))
10909 (setq org-last-level level))
10910 ))))
10911 lines)))
10913 (org-init-section-numbers)
10914 (while (setq line (pop lines))
10915 ;; Remove the quoted HTML tags.
10916 (setq line (org-html-expand-for-ascii line))
10917 ;; Remove targets
10918 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
10919 (setq line (replace-match "" t t line)))
10920 ;; Replace internal links
10921 (while (string-match org-bracket-link-regexp line)
10922 (setq line (replace-match
10923 (if (match-end 3) "[\\3]" "[\\1]")
10924 t nil line)))
10925 (cond
10926 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
10927 ;; a Headline
10928 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
10929 txt (match-string 2 line))
10930 (org-ascii-level-start level txt umax))
10931 (t (insert line "\n"))))
10932 (normal-mode)
10933 (save-buffer)
10934 (goto-char (point-min))))
10936 (defun org-search-todo-below (line lines level)
10937 "Search the subtree below LINE for any TODO entries."
10938 (let ((rest (cdr (memq line lines)))
10939 (re org-todo-line-regexp)
10940 line lv todo)
10941 (catch 'exit
10942 (while (setq line (pop rest))
10943 (if (string-match re line)
10944 (progn
10945 (setq lv (- (match-end 1) (match-beginning 1))
10946 todo (and (match-beginning 2)
10947 (not (equal (match-string 2 line)
10948 org-done-string))))
10949 ; TODO, not DONE
10950 (if (<= lv level) (throw 'exit nil))
10951 (if todo (throw 'exit t))))))))
10953 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
10954 ;; FIXME: Can I implement *bold*,/italic/ and _underline_ for ASCII export?
10955 (defun org-html-expand-for-ascii (line)
10956 "Handle quoted HTML for ASCII export."
10957 (if org-export-html-expand
10958 (while (string-match "@<[^<>\n]*>" line)
10959 ;; We just remove the tags for now.
10960 (setq line (replace-match "" nil nil line))))
10961 line)
10963 (defun org-insert-centered (s &optional underline)
10964 "Insert the string S centered and underline it with character UNDERLINE."
10965 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
10966 (insert (make-string ind ?\ ) s "\n")
10967 (if underline
10968 (insert (make-string ind ?\ )
10969 (make-string (string-width s) underline)
10970 "\n"))))
10972 (defun org-ascii-level-start (level title umax)
10973 "Insert a new level in ASCII export."
10974 (let (char)
10975 (if (> level umax)
10976 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
10977 (if (or (not (equal (char-before) ?\n))
10978 (not (equal (char-before (1- (point))) ?\n)))
10979 (insert "\n"))
10980 (setq char (nth (- umax level) (reverse org-ascii-underline)))
10981 (if org-export-with-section-numbers
10982 (setq title (concat (org-section-number level) " " title)))
10983 (insert title "\n" (make-string (string-width title) char) "\n"))))
10985 (defun org-export-copy-visible ()
10986 "Copy the visible part of the buffer to another buffer, for printing.
10987 Also removes the first line of the buffer if it specifies a mode,
10988 and all options lines."
10989 (interactive)
10990 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
10991 ".txt"))
10992 (buffer (find-file-noselect filename))
10993 (ore (concat
10994 (org-make-options-regexp
10995 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
10996 "STARTUP" "ARCHIVE"
10997 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
10998 (if org-noutline-p "\\(\n\\|$\\)" "")))
10999 s e)
11000 (with-current-buffer buffer
11001 (erase-buffer)
11002 (text-mode))
11003 (save-excursion
11004 (setq s (goto-char (point-min)))
11005 (while (not (= (point) (point-max)))
11006 (goto-char (org-find-invisible))
11007 (append-to-buffer buffer s (point))
11008 (setq s (goto-char (org-find-visible)))))
11009 (switch-to-buffer-other-window buffer)
11010 (newline)
11011 (goto-char (point-min))
11012 (if (looking-at ".*-\\*- mode:.*\n")
11013 (replace-match ""))
11014 (while (re-search-forward ore nil t)
11015 (replace-match ""))
11016 (goto-char (point-min))))
11018 (defun org-find-visible ()
11019 (if (featurep 'noutline)
11020 (let ((s (point)))
11021 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11022 (get-char-property s 'invisible)))
11024 (skip-chars-forward "^\n")
11025 (point)))
11026 (defun org-find-invisible ()
11027 (if (featurep 'noutline)
11028 (let ((s (point)))
11029 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11030 (not (get-char-property s 'invisible))))
11032 (skip-chars-forward "^\r")
11033 (point)))
11035 ;; HTML
11037 (defun org-get-current-options ()
11038 "Return a string with current options as keyword options.
11039 Does include HTML export options as well as TODO and CATEGORY stuff."
11040 (format
11041 "#+TITLE: %s
11042 #+AUTHOR: %s
11043 #+EMAIL: %s
11044 #+LANGUAGE: %s
11045 #+TEXT: Some descriptive text to be emitted. Several lines OK.
11046 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
11047 #+CATEGORY: %s
11048 #+SEQ_TODO: %s
11049 #+TYP_TODO: %s
11050 #+STARTUP: %s %s %s %s
11051 #+ARCHIVE: %s
11053 (buffer-name) (user-full-name) user-mail-address org-export-default-language
11054 org-export-headline-levels
11055 org-export-with-section-numbers
11056 org-export-with-toc
11057 org-export-preserve-breaks
11058 org-export-html-expand
11059 org-export-with-fixed-width
11060 org-export-with-tables
11061 org-export-with-sub-superscripts
11062 org-export-with-emphasize
11063 org-export-with-TeX-macros
11064 (file-name-nondirectory buffer-file-name)
11065 (if (equal org-todo-interpretation 'sequence)
11066 (mapconcat 'identity org-todo-keywords " ")
11067 "TODO FEEDBACK VERIFY DONE")
11068 (if (equal org-todo-interpretation 'type)
11069 (mapconcat 'identity org-todo-keywords " ")
11070 "Me Jason Marie DONE")
11071 (cdr (assoc org-startup-folded
11072 '((nil . "nofold")(t . "fold")(content . "content"))))
11073 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
11074 (if org-odd-levels-only "odd" "oddeven")
11075 (if org-hide-leading-stars "hidestars" "showstars")
11076 org-archive-location
11079 (defun org-insert-export-options-template ()
11080 "Insert into the buffer a template with information for exporting."
11081 (interactive)
11082 (if (not (bolp)) (newline))
11083 (let ((s (org-get-current-options)))
11084 (and (string-match "#\\+CATEGORY" s)
11085 (setq s (substring s 0 (match-beginning 0))))
11086 (insert s)))
11088 (defun org-toggle-fixed-width-section (arg)
11089 "Toggle the fixed-width export.
11090 If there is no active region, the QUOTE keyword at the current headline is
11091 inserted or removed. When present, it causes the text between this headline
11092 and the next to be exported as fixed-width text, and unmodified.
11093 If there is an active region, this command adds or removes a colon as the
11094 first character of this line. If the first character of a line is a colon,
11095 this line is also exported in fixed-width font."
11096 (interactive "P")
11097 (let* ((cc 0)
11098 (regionp (org-region-active-p))
11099 (beg (if regionp (region-beginning) (point)))
11100 (end (if regionp (region-end)))
11101 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
11102 (re "[ \t]*\\(:\\)")
11103 off)
11104 (if regionp
11105 (save-excursion
11106 (goto-char beg)
11107 (setq cc (current-column))
11108 (beginning-of-line 1)
11109 (setq off (looking-at re))
11110 (while (> nlines 0)
11111 (setq nlines (1- nlines))
11112 (beginning-of-line 1)
11113 (cond
11114 (arg
11115 (move-to-column cc t)
11116 (insert ":\n")
11117 (forward-line -1))
11118 ((and off (looking-at re))
11119 (replace-match "" t t nil 1))
11120 ((not off) (move-to-column cc t) (insert ":")))
11121 (forward-line 1)))
11122 (save-excursion
11123 (org-back-to-heading)
11124 (if (looking-at (concat outline-regexp
11125 "\\( +\\<" org-quote-string "\\>\\)"))
11126 (replace-match "" t t nil 1)
11127 (if (looking-at outline-regexp)
11128 (progn
11129 (goto-char (match-end 0))
11130 (insert " " org-quote-string))))))))
11132 (defun org-export-as-html-and-open (arg)
11133 "Export the outline as HTML and immediately open it with a browser.
11134 If there is an active region, export only the region.
11135 The prefix ARG specifies how many levels of the outline should become
11136 headlines. The default is 3. Lower levels will become bulleted lists."
11137 (interactive "P")
11138 (org-export-as-html arg 'hidden)
11139 (org-open-file buffer-file-name))
11141 (defun org-export-as-html-batch ()
11142 "Call `org-export-as-html', may be used in batch processing as
11143 emacs --batch
11144 --load=$HOME/lib/emacs/org.el
11145 --eval \"(setq org-export-headline-levels 2)\"
11146 --visit=MyFile --funcall org-export-as-html-batch"
11147 (org-export-as-html org-export-headline-levels 'hidden))
11149 (defun org-export-as-html (arg &optional hidden)
11150 "Export the outline as a pretty HTML file.
11151 If there is an active region, export only the region.
11152 The prefix ARG specifies how many levels of the outline should become
11153 headlines. The default is 3. Lower levels will become bulleted lists."
11154 (interactive "P")
11155 (setq-default org-todo-line-regexp org-todo-line-regexp)
11156 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
11157 (setq-default org-done-string org-done-string)
11158 (let* ((style org-export-html-style)
11159 (odd org-odd-levels-only)
11160 (region-p (org-region-active-p))
11161 (region
11162 (buffer-substring
11163 (if region-p (region-beginning) (point-min))
11164 (if region-p (region-end) (point-max))))
11165 (all_lines
11166 (org-skip-comments (org-split-string
11167 (org-cleaned-string-for-export region)
11168 "[\r\n]")))
11169 (lines (org-export-find-first-heading-line all_lines))
11170 (level 0) (line "") (origline "") txt todo
11171 (umax nil)
11172 (filename (concat (file-name-sans-extension buffer-file-name)
11173 ".html"))
11174 (buffer (find-file-noselect filename))
11175 (levels-open (make-vector org-level-max nil))
11176 (date (format-time-string "%Y/%m/%d" (current-time)))
11177 (time (format-time-string "%X" (org-current-time)))
11178 (author user-full-name)
11179 (title (buffer-name))
11180 (options nil)
11181 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
11182 (inquote nil)
11183 (infixed nil)
11184 (in-local-list nil)
11185 (local-list-num nil)
11186 (local-list-indent nil)
11187 (llt org-plain-list-ordered-item-terminator)
11188 (email user-mail-address)
11189 (language org-export-default-language)
11190 (text nil)
11191 (lang-words nil)
11192 (target-alist nil) tg
11193 (head-count 0) cnt
11194 (start 0)
11195 ;; FIXME: The following returns always nil under XEmacs
11196 (coding-system (and (fboundp 'coding-system-get)
11197 (boundp 'buffer-file-coding-system)
11198 buffer-file-coding-system))
11199 (coding-system-for-write (or coding-system coding-system-for-write))
11200 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
11201 (charset (and coding-system
11202 (coding-system-get coding-system 'mime-charset)))
11203 table-open type
11204 table-buffer table-orig-buffer
11205 ind start-is-num starter
11207 (message "Exporting...")
11209 (setq org-last-level 1)
11210 (org-init-section-numbers)
11212 ;; Search for the export key lines
11213 (org-parse-key-lines)
11214 (setq lang-words (or (assoc language org-export-language-setup)
11215 (assoc "en" org-export-language-setup)))
11217 ;; Switch to the output buffer
11218 (if (or hidden (not org-export-html-show-new-buffer))
11219 (set-buffer buffer)
11220 (switch-to-buffer-other-window buffer))
11221 (erase-buffer)
11222 (fundamental-mode)
11223 (let ((case-fold-search nil)
11224 (org-odd-levels-only odd))
11225 (if options (org-parse-export-options options))
11226 (setq umax (if arg (prefix-numeric-value arg)
11227 org-export-headline-levels))
11229 ;; File header
11230 (insert (format
11231 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
11232 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
11233 <html lang=\"%s\"><head>
11234 <title>%s</title>
11235 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
11236 <meta name=generator content=\"Org-mode\">
11237 <meta name=generated content=\"%s %s\">
11238 <meta name=author content=\"%s\">
11240 </head><body>
11242 language (org-html-expand title) (or charset "iso-8859-1")
11243 date time author style))
11244 (if title (insert (concat "<H1 class=\"title\">"
11245 (org-html-expand title) "</H1>\n")))
11246 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
11247 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
11248 email "&gt;</a>\n")))
11249 (if (or author email) (insert "<br>\n"))
11250 (if (and date time) (insert (concat (nth 2 lang-words) ": "
11251 date " " time "<br>\n")))
11252 (if text (insert (concat "<p>\n" (org-html-expand text))))
11253 (if org-export-with-toc
11254 (progn
11255 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
11256 (insert "<ul>\n")
11257 (setq lines
11258 (mapcar '(lambda (line)
11259 (if (string-match org-todo-line-regexp line)
11260 ;; This is a headline
11261 (progn
11262 (setq level (- (match-end 1) (match-beginning 1))
11263 level (org-tr-level level)
11264 txt (save-match-data
11265 (org-html-expand
11266 (match-string 3 line)))
11267 todo
11268 (or (and (match-beginning 2)
11269 (not (equal (match-string 2 line)
11270 org-done-string)))
11271 ; TODO, not DONE
11272 (and (= level umax)
11273 (org-search-todo-below
11274 line lines level))))
11275 (if org-export-with-section-numbers
11276 (setq txt (concat (org-section-number level)
11277 " " txt)))
11278 (if (<= level umax)
11279 (progn
11280 (setq head-count (+ head-count 1))
11281 (if (> level org-last-level)
11282 (progn
11283 (setq cnt (- level org-last-level))
11284 (while (>= (setq cnt (1- cnt)) 0)
11285 (insert "<ul>"))
11286 (insert "\n")))
11287 (if (< level org-last-level)
11288 (progn
11289 (setq cnt (- org-last-level level))
11290 (while (>= (setq cnt (1- cnt)) 0)
11291 (insert "</ul>"))
11292 (insert "\n")))
11293 ;; Check for targets
11294 (while (string-match org-target-regexp line)
11295 (setq tg (match-string 1 line)
11296 line (replace-match
11297 (concat "@<span class=\"target\">" tg "@</span> ")
11298 t t line))
11299 (push (cons (org-solidify-link-text tg)
11300 (format "sec-%d" head-count))
11301 target-alist))
11302 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
11303 (setq txt (replace-match "" t t txt)))
11304 (insert
11305 (format
11306 (if todo
11307 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
11308 "<li><a href=\"#sec-%d\">%s</a>\n")
11309 head-count txt))
11311 (setq org-last-level level))
11313 line)
11314 lines))
11315 (while (> org-last-level 0)
11316 (setq org-last-level (1- org-last-level))
11317 (insert "</ul>\n"))
11319 (setq head-count 0)
11320 (org-init-section-numbers)
11322 (while (setq line (pop lines) origline line)
11323 (catch 'nextline
11325 ;; end of quote section?
11326 (when (and inquote (string-match "^\\*+" line))
11327 (insert "</pre>\n")
11328 (setq inquote nil))
11329 ;; inside a quote section?
11330 (when inquote
11331 (insert (org-html-protect line) "\n")
11332 (throw 'nextline nil))
11334 ;; verbatim lines
11335 (when (and org-export-with-fixed-width
11336 (string-match "^[ \t]*:\\(.*\\)" line))
11337 (when (not infixed)
11338 (setq infixed t)
11339 (insert "<pre>\n"))
11340 (insert (org-html-protect (match-string 1 line)) "\n")
11341 (when (and lines
11342 (not (string-match "^[ \t]*\\(:.*\\)"
11343 (car lines))))
11344 (setq infixed nil)
11345 (insert "</pre>\n"))
11346 (throw 'nextline nil))
11349 ;; make targets to anchors
11350 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
11351 (cond
11352 ((match-end 2)
11353 (setq line (replace-match
11354 (concat "@<a name=\""
11355 (org-solidify-link-text (match-string 1 line))
11356 "\">\\nbsp@</a>")
11357 t t line)))
11358 ((and org-export-with-toc (equal (string-to-char line) ?*))
11359 (setq line (replace-match
11360 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
11361 ; (concat "@<i>" (match-string 1 line) "@</i> ")
11362 t t line)))
11364 (setq line (replace-match
11365 (concat "@<a name=\""
11366 (org-solidify-link-text (match-string 1 line))
11367 "\" class=\"target\">" (match-string 1 line) "@</a> ")
11368 t t line)))))
11369 ;; Replace internal links
11370 (while (string-match org-bracket-link-regexp line)
11371 (setq line (replace-match
11372 (concat
11373 "@<a href=\"#"
11374 (org-solidify-link-text (match-string 1 line) target-alist)
11375 "\">"
11376 (match-string (if (match-end 3) 3 1) line)
11377 "@</a>")
11378 t t line)))
11380 ;; Protect the external links
11381 (setq start 0)
11382 (while (string-match org-link-maybe-angles-regexp line start)
11383 (setq start (match-end 0))
11384 (setq line (replace-match
11385 (concat "\000" (match-string 1 line) "\000")
11386 t t line)))
11388 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
11389 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
11390 (setq line (org-html-expand line))
11392 ;; Format the links
11393 (setq start 0)
11394 (while (string-match org-protected-link-regexp line start)
11395 (setq start (- (match-end 0) 2))
11396 (setq type (match-string 1 line))
11397 (cond
11398 ((member type '("http" "https" "ftp" "mailto" "news"))
11399 ;; standard URL
11400 (setq line (replace-match
11401 ; "<a href=\"\\1:\\2\">&lt;\\1:\\2&gt;</a>"
11402 "<a href=\"\\1:\\2\">\\1:\\2</a>"
11403 nil nil line)))
11404 ((string= type "file")
11405 ;; FILE link
11406 (let* ((filename (match-string 2 line))
11407 (abs-p (file-name-absolute-p filename))
11408 (thefile (if abs-p (expand-file-name filename) filename))
11409 (thefile (save-match-data
11410 (if (string-match ":[0-9]+$" thefile)
11411 (replace-match "" t t thefile)
11412 thefile)))
11413 (file-is-image-p
11414 (save-match-data
11415 (string-match (org-image-file-name-regexp) thefile))))
11416 (setq line (replace-match
11417 (if (and org-export-html-inline-images
11418 file-is-image-p)
11419 (concat "<img src=\"" thefile "\"/>")
11420 (concat "<a href=\"" thefile "\">\\1:\\2</a>"))
11421 nil nil line))))
11423 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11424 (setq line (replace-match
11425 "<i>&lt;\\1:\\2&gt;</i>" nil nil line)))))
11427 ;; TODO items
11428 (if (and (string-match org-todo-line-regexp line)
11429 (match-beginning 2))
11430 (if (equal (match-string 2 line) org-done-string)
11431 (setq line (replace-match
11432 "<span class=\"done\">\\2</span>"
11433 nil nil line 2))
11434 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11435 nil nil line 2))))
11437 ;; DEADLINES
11438 (if (string-match org-deadline-line-regexp line)
11439 (progn
11440 (if (save-match-data
11441 (string-match "<a href"
11442 (substring line 0 (match-beginning 0))))
11443 nil ; Don't do the replacement - it is inside a link
11444 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11445 nil nil line 1)))))
11446 (cond
11447 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11448 ;; This is a headline
11449 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11450 txt (match-string 2 line))
11451 (if (<= level umax) (setq head-count (+ head-count 1)))
11452 (when in-local-list
11453 ;; Close any local lists before inserting a new header line
11454 (while local-list-num
11455 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11456 (pop local-list-num))
11457 (setq local-list-indent nil
11458 in-local-list nil))
11459 (org-html-level-start level txt umax
11460 (and org-export-with-toc (<= level umax))
11461 head-count)
11462 ;; QUOTES
11463 (when (string-match quote-re line)
11464 (insert "<pre>")
11465 (setq inquote t)))
11467 ((and org-export-with-tables
11468 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11469 (if (not table-open)
11470 ;; New table starts
11471 (setq table-open t table-buffer nil table-orig-buffer nil))
11472 ;; Accumulate lines
11473 (setq table-buffer (cons line table-buffer)
11474 table-orig-buffer (cons origline table-orig-buffer))
11475 (when (or (not lines)
11476 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11477 (car lines))))
11478 (setq table-open nil
11479 table-buffer (nreverse table-buffer)
11480 table-orig-buffer (nreverse table-orig-buffer))
11481 (insert (org-format-table-html table-buffer table-orig-buffer))))
11483 ;; Normal lines
11484 (when (and (> org-export-plain-list-max-depth 0)
11485 (string-match
11486 (cond
11487 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11488 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11489 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11490 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
11491 line))
11492 (setq ind (org-get-string-indentation line)
11493 start-is-num (match-beginning 4)
11494 starter (if (match-beginning 2) (match-string 2 line))
11495 line (substring line (match-beginning 5)))
11496 (unless (string-match "[^ \t]" line)
11497 ;; empty line. Pretend indentation is large.
11498 (setq ind (1+ (or (car local-list-indent) 1))))
11499 (while (and in-local-list
11500 (or (and (= ind (car local-list-indent))
11501 (not starter))
11502 (< ind (car local-list-indent))))
11503 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11504 (pop local-list-num) (pop local-list-indent)
11505 (setq in-local-list local-list-indent))
11506 (cond
11507 ((and starter
11508 (or (not in-local-list)
11509 (> ind (car local-list-indent)))
11510 (< (length local-list-indent)
11511 org-export-plain-list-max-depth))
11512 ;; Start new (level of ) list
11513 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
11514 (push start-is-num local-list-num)
11515 (push ind local-list-indent)
11516 (setq in-local-list t))
11517 (starter
11518 ;; continue current list
11519 (insert "<li>\n"))))
11520 ;; Empty lines start a new paragraph. If hand-formatted lists
11521 ;; are not fully interpreted, lines starting with "-", "+", "*"
11522 ;; also start a new paragraph.
11523 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
11524 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
11526 (if org-export-html-with-timestamp
11527 (insert org-export-html-html-helper-timestamp))
11528 (insert "</body>\n</html>\n")
11529 (normal-mode)
11530 (save-buffer)
11531 (goto-char (point-min)))))
11533 (defun org-format-table-html (lines olines)
11534 "Find out which HTML converter to use and return the HTML code."
11535 (if (string-match "^[ \t]*|" (car lines))
11536 ;; A normal org table
11537 (org-format-org-table-html lines)
11538 ;; Table made by table.el - test for spanning
11539 (let* ((hlines (delq nil (mapcar
11540 (lambda (x)
11541 (if (string-match "^[ \t]*\\+-" x) x
11542 nil))
11543 lines)))
11544 (first (car hlines))
11545 (ll (and (string-match "\\S-+" first)
11546 (match-string 0 first)))
11547 (re (concat "^[ \t]*" (regexp-quote ll)))
11548 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
11549 hlines))))
11550 (if (and (not spanning)
11551 (not org-export-prefer-native-exporter-for-tables))
11552 ;; We can use my own converter with HTML conversions
11553 (org-format-table-table-html lines)
11554 ;; Need to use the code generator in table.el, with the original text.
11555 (org-format-table-table-html-using-table-generate-source olines)))))
11557 (defun org-format-org-table-html (lines)
11558 "Format a table into HTML."
11559 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11560 (setq lines (nreverse lines))
11561 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11562 (setq lines (nreverse lines))
11563 (when org-export-table-remove-special-lines
11564 ;; Check if the table has a marking column. If yes remove the
11565 ;; column and the special lines
11566 (let* ((special
11567 (not
11568 (memq nil
11569 (mapcar
11570 (lambda (x)
11571 (or (string-match "^[ \t]*|-" x)
11572 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
11573 lines)))))
11574 (if special
11575 (setq lines
11576 (delq nil
11577 (mapcar
11578 (lambda (x)
11579 (if (string-match "^[ \t]*| *[!_^] *|" x)
11580 nil ; ignore this line
11581 (and (or (string-match "^[ \t]*|-+\\+" x)
11582 (string-match "^[ \t]*|[^|]*|" x))
11583 (replace-match "|" t t x))))
11584 lines))))))
11586 (let ((head (and org-export-highlight-first-table-line
11587 (delq nil (mapcar
11588 (lambda (x) (string-match "^[ \t]*|-" x))
11589 (cdr lines)))))
11590 line fields html)
11591 (setq html (concat org-export-html-table-tag "\n"))
11592 (while (setq line (pop lines))
11593 (catch 'next-line
11594 (if (string-match "^[ \t]*|-" line)
11595 (progn
11596 (setq head nil) ;; head ends here, first time around
11597 ;; ignore this line
11598 (throw 'next-line t)))
11599 ;; Break the line into fields
11600 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11601 (setq html (concat
11602 html
11603 "<tr>"
11604 (mapconcat (lambda (x)
11605 (if head
11606 (concat "<th>" x "</th>")
11607 (concat "<td>" x "</td>")))
11608 fields "")
11609 "</tr>\n"))))
11610 (setq html (concat html "</table>\n"))
11611 html))
11613 (defun org-fake-empty-table-line (line)
11614 "Replace everything except \"|\" with spaces."
11615 (let ((i (length line))
11616 (newstr (copy-sequence line)))
11617 (while (> i 0)
11618 (setq i (1- i))
11619 (if (not (eq (aref newstr i) ?|))
11620 (aset newstr i ?\ )))
11621 newstr))
11623 (defun org-format-table-table-html (lines)
11624 "Format a table generated by table.el into HTML.
11625 This conversion does *not* use `table-generate-source' from table.el.
11626 This has the advantage that Org-mode's HTML conversions can be used.
11627 But it has the disadvantage, that no cell- or row-spanning is allowed."
11628 (let (line field-buffer
11629 (head org-export-highlight-first-table-line)
11630 fields html empty)
11631 (setq html (concat org-export-html-table-tag "\n"))
11632 (while (setq line (pop lines))
11633 (setq empty "&nbsp")
11634 (catch 'next-line
11635 (if (string-match "^[ \t]*\\+-" line)
11636 (progn
11637 (if field-buffer
11638 (progn
11639 (setq html (concat
11640 html
11641 "<tr>"
11642 (mapconcat
11643 (lambda (x)
11644 (if (equal x "") (setq x empty))
11645 (if head
11646 (concat "<th>" x "</th>\n")
11647 (concat "<td>" x "</td>\n")))
11648 field-buffer "\n")
11649 "</tr>\n"))
11650 (setq head nil)
11651 (setq field-buffer nil)))
11652 ;; Ignore this line
11653 (throw 'next-line t)))
11654 ;; Break the line into fields and store the fields
11655 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11656 (if field-buffer
11657 (setq field-buffer (mapcar
11658 (lambda (x)
11659 (concat x "<br>" (pop fields)))
11660 field-buffer))
11661 (setq field-buffer fields))))
11662 (setq html (concat html "</table>\n"))
11663 html))
11665 (defun org-format-table-table-html-using-table-generate-source (lines)
11666 "Format a table into html, using `table-generate-source' from table.el.
11667 This has the advantage that cell- or row-spanning is allowed.
11668 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
11669 (require 'table)
11670 (with-current-buffer (get-buffer-create " org-tmp1 ")
11671 (erase-buffer)
11672 (insert (mapconcat 'identity lines "\n"))
11673 (goto-char (point-min))
11674 (if (not (re-search-forward "|[^+]" nil t))
11675 (error "Error processing table"))
11676 (table-recognize-table)
11677 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
11678 (table-generate-source 'html " org-tmp2 ")
11679 (set-buffer " org-tmp2 ")
11680 (buffer-substring (point-min) (point-max))))
11682 (defun org-html-protect (s)
11683 ;; convert & to &amp;, < to &lt; and > to &gt;
11684 (let ((start 0))
11685 (while (string-match "&" s start)
11686 (setq s (replace-match "&amp;" t t s)
11687 start (1+ (match-beginning 0))))
11688 (while (string-match "<" s)
11689 (setq s (replace-match "&lt;" t t s)))
11690 (while (string-match ">" s)
11691 (setq s (replace-match "&gt;" t t s))))
11694 (defun org-html-expand (string)
11695 "Prepare STRING for HTML export. Applies all active conversions."
11696 ;; First check if there is a link in the line - if yes, apply conversions
11697 ;; only before the start of the link.
11698 ;; FIXME: This is no longer correct, because links now have an end.
11699 (let* ((m (string-match org-link-regexp string))
11700 (s (if m (substring string 0 m) string))
11701 (r (if m (substring string m) "")))
11702 ;; convert & to &amp;, < to &lt; and > to &gt;
11703 (setq s (org-html-protect s))
11704 (if org-export-html-expand
11705 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
11706 (setq s (replace-match "<\\1>" nil nil s))))
11707 (if org-export-with-emphasize
11708 (setq s (org-export-html-convert-emphasize s)))
11709 (if org-export-with-sub-superscripts
11710 (setq s (org-export-html-convert-sub-super s)))
11711 (if org-export-with-TeX-macros
11712 (let ((start 0) wd ass)
11713 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
11714 (setq wd (match-string 1 s))
11715 (if (setq ass (assoc wd org-html-entities))
11716 (setq s (replace-match (or (cdr ass)
11717 (concat "&" (car ass) ";"))
11718 t t s))
11719 (setq start (+ start (length wd)))))))
11720 (concat s r)))
11722 (defun org-create-multibrace-regexp (left right n)
11723 "Create a regular expression which will match a balanced sexp.
11724 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
11725 as single character strings.
11726 The regexp returned will match the entire expression including the
11727 delimiters. It will also define a single group which contains the
11728 match except for the outermost delimiters. The maximum depth of
11729 stacked delimiters is N. Escaping delimiters is not possible."
11730 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
11731 (or "\\|")
11732 (re nothing)
11733 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
11734 (while (> n 1)
11735 (setq n (1- n)
11736 re (concat re or next)
11737 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
11738 (concat left "\\(" re "\\)" right)))
11740 (defvar org-match-substring-regexp
11741 (concat
11742 "\\([^\\]\\)\\([_^]\\)\\("
11743 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
11744 "\\|"
11745 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
11746 "\\|"
11747 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
11748 "The regular expression matching a sub- or superscript.")
11750 (defun org-export-html-convert-sub-super (string)
11751 "Convert sub- and superscripts in STRING to HTML."
11752 (let (key c)
11753 (while (string-match org-match-substring-regexp string)
11754 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
11755 (setq c (or (match-string 8 string)
11756 (match-string 6 string)
11757 (match-string 5 string)))
11758 (setq string (replace-match
11759 (concat (match-string 1 string)
11760 "<" key ">" c "</" key ">")
11761 t t string)))
11762 (while (string-match "\\\\\\([_^]\\)" string)
11763 (setq string (replace-match (match-string 1 string) t t string))))
11764 string)
11766 (defun org-export-html-convert-emphasize (string)
11767 (let (c (s 0))
11768 (while (string-match "\\(\\W\\|^\\)\\([*/_]\\)\\(\\w+\\)\\2\\(\\W\\|$\\)" string s)
11769 (setq c (cdr (assoc (match-string 2 string)
11770 '(("*" . "b") ("/" . "i") ("_" . "u"))))
11771 s (+ (match-end 0) 3)
11772 string (replace-match
11773 (concat "\\1<" c ">\\3</" c ">\\4") t nil string)))
11774 string))
11776 (defun org-parse-key-lines ()
11777 "Find the special key lines with the information for exporters."
11778 (save-excursion
11779 (goto-char 0)
11780 (let ((re (org-make-options-regexp
11781 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
11782 key)
11783 (while (re-search-forward re nil t)
11784 (setq key (match-string 1))
11785 (cond ((string-equal key "TITLE")
11786 (setq title (match-string 2)))
11787 ((string-equal key "AUTHOR")
11788 (setq author (match-string 2)))
11789 ((string-equal key "EMAIL")
11790 (setq email (match-string 2)))
11791 ((string-equal key "LANGUAGE")
11792 (setq language (match-string 2)))
11793 ((string-equal key "TEXT")
11794 (setq text (concat text "\n" (match-string 2))))
11795 ((string-equal key "OPTIONS")
11796 (setq options (match-string 2))))))))
11798 (defun org-parse-export-options (s)
11799 "Parse the export options line."
11800 (let ((op '(("H" . org-export-headline-levels)
11801 ("num" . org-export-with-section-numbers)
11802 ("toc" . org-export-with-toc)
11803 ("\\n" . org-export-preserve-breaks)
11804 ("@" . org-export-html-expand)
11805 (":" . org-export-with-fixed-width)
11806 ("|" . org-export-with-tables)
11807 ("^" . org-export-with-sub-superscripts)
11808 ("*" . org-export-with-emphasize)
11809 ("TeX" . org-export-with-TeX-macros)))
11811 (while (setq o (pop op))
11812 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
11814 (set (make-local-variable (cdr o))
11815 (car (read-from-string (match-string 1 s))))))))
11817 (defun org-html-level-start (level title umax with-toc head-count)
11818 "Insert a new level in HTML export."
11819 (let ((l (1+ (max level umax))))
11820 (while (<= l org-level-max)
11821 (if (aref levels-open (1- l))
11822 (progn
11823 (org-html-level-close l)
11824 (aset levels-open (1- l) nil)))
11825 (setq l (1+ l)))
11826 (if (> level umax)
11827 (progn
11828 (if (aref levels-open (1- level))
11829 (insert "<li>" title "<p>\n")
11830 (aset levels-open (1- level) t)
11831 (insert "<ul><li>" title "<p>\n")))
11832 (if org-export-with-section-numbers
11833 (setq title (concat (org-section-number level) " " title)))
11834 (setq level (+ level 1))
11835 (if with-toc
11836 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
11837 level head-count title level))
11838 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
11840 (defun org-html-level-close (&rest args)
11841 "Terminate one level in HTML export."
11842 (insert "</ul>"))
11844 ;; Variable holding the vector with section numbers
11845 (defvar org-section-numbers (make-vector org-level-max 0))
11847 (defun org-init-section-numbers ()
11848 "Initialize the vector for the section numbers."
11849 (let* ((level -1)
11850 (numbers (nreverse (org-split-string "" "\\.")))
11851 (depth (1- (length org-section-numbers)))
11852 (i depth) number-string)
11853 (while (>= i 0)
11854 (if (> i level)
11855 (aset org-section-numbers i 0)
11856 (setq number-string (or (car numbers) "0"))
11857 (if (string-match "\\`[A-Z]\\'" number-string)
11858 (aset org-section-numbers i
11859 (- (string-to-char number-string) ?A -1))
11860 (aset org-section-numbers i (string-to-number number-string)))
11861 (pop numbers))
11862 (setq i (1- i)))))
11864 (defun org-section-number (&optional level)
11865 "Return a string with the current section number.
11866 When LEVEL is non-nil, increase section numbers on that level."
11867 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
11868 (when level
11869 (when (> level -1)
11870 (aset org-section-numbers
11871 level (1+ (aref org-section-numbers level))))
11872 (setq idx (1+ level))
11873 (while (<= idx depth)
11874 (if (not (= idx 1))
11875 (aset org-section-numbers idx 0))
11876 (setq idx (1+ idx))))
11877 (setq idx 0)
11878 (while (<= idx depth)
11879 (setq n (aref org-section-numbers idx))
11880 (setq string (concat string (if (not (string= string "")) "." "")
11881 (int-to-string n)))
11882 (setq idx (1+ idx)))
11883 (save-match-data
11884 (if (string-match "\\`\\([@0]\\.\\)+" string)
11885 (setq string (replace-match "" nil nil string)))
11886 (if (string-match "\\(\\.0\\)+\\'" string)
11887 (setq string (replace-match "" nil nil string))))
11888 string))
11891 (defun org-export-icalendar-this-file ()
11892 "Export current file as an iCalendar file.
11893 The iCalendar file will be located in the same directory as the Org-mode
11894 file, but with extension `.ics'."
11895 (interactive)
11896 (org-export-icalendar nil buffer-file-name))
11898 ;;;###autoload
11899 (defun org-export-icalendar-all-agenda-files ()
11900 "Export all files in `org-agenda-files' to iCalendar .ics files.
11901 Each iCalendar file will be located in the same directory as the Org-mode
11902 file, but with extension `.ics'."
11903 (interactive)
11904 (apply 'org-export-icalendar nil (org-agenda-files t)))
11906 ;;;###autoload
11907 (defun org-export-icalendar-combine-agenda-files ()
11908 "Export all files in `org-agenda-files' to a single combined iCalendar file.
11909 The file is stored under the name `org-combined-agenda-icalendar-file'."
11910 (interactive)
11911 (apply 'org-export-icalendar t (org-agenda-files t)))
11913 (defun org-export-icalendar (combine &rest files)
11914 "Create iCalendar files for all elements of FILES.
11915 If COMBINE is non-nil, combine all calendar entries into a single large
11916 file and store it under the name `org-combined-agenda-icalendar-file'."
11917 (save-excursion
11918 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
11919 (when combine
11920 (setq ical-file org-combined-agenda-icalendar-file
11921 ical-buffer (org-get-agenda-file-buffer ical-file))
11922 (set-buffer ical-buffer) (erase-buffer))
11923 (while (setq file (pop files))
11924 (catch 'nextfile
11925 (org-check-agenda-file file)
11926 (unless combine
11927 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
11928 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
11929 (set-buffer ical-buffer) (erase-buffer))
11930 (set-buffer (org-get-agenda-file-buffer file))
11931 (setq category (or org-category
11932 (file-name-sans-extension
11933 (file-name-nondirectory buffer-file-name))))
11934 (if (symbolp category) (setq category (symbol-name category)))
11935 (let ((standard-output ical-buffer))
11936 (if combine
11937 (and (not started) (setq started t)
11938 (org-start-icalendar-file org-icalendar-combined-name))
11939 (org-start-icalendar-file category))
11940 (org-print-icalendar-entries combine category)
11941 (when (or (and combine (not files)) (not combine))
11942 (org-finish-icalendar-file)
11943 (set-buffer ical-buffer)
11944 (save-buffer)
11945 (run-hooks 'org-after-save-iCalendar-file-hook)))))
11946 (org-release-buffers org-agenda-new-buffers))))
11948 (defvar org-after-save-iCalendar-file-hook nil
11949 "Hook run after an iCalendar file has been saved.
11950 The iCalendar buffer is still current when this hook is run.
11951 A good way to use this is to tell a desktop calenndar application to re-read
11952 the iCalendar file.")
11954 (defun org-print-icalendar-entries (&optional combine category)
11955 "Print iCalendar entries for the current Org-mode file to `standard-output'.
11956 When COMBINE is non nil, add the category to each line."
11957 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
11958 (dts (org-ical-ts-to-string
11959 (format-time-string (cdr org-time-stamp-formats) (current-time))
11960 "DTSTART"))
11961 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
11962 (save-excursion
11963 (goto-char (point-min))
11964 (while (re-search-forward org-ts-regexp nil t)
11965 (setq pos (match-beginning 0)
11966 ts (match-string 0)
11967 inc t
11968 hd (org-get-heading))
11969 (if (looking-at re2)
11970 (progn
11971 (goto-char (match-end 0))
11972 (setq ts2 (match-string 1) inc nil))
11973 (setq ts2 ts
11974 tmp (buffer-substring (max (point-min)
11975 (- pos org-ds-keyword-length))
11976 pos)
11977 deadlinep (string-match org-deadline-regexp tmp)
11978 scheduledp (string-match org-scheduled-regexp tmp)
11979 ;; donep (org-entry-is-done-p)
11981 (if (or (string-match org-tr-regexp hd)
11982 (string-match org-ts-regexp hd))
11983 (setq hd (replace-match "" t t hd)))
11984 (if combine
11985 (setq hd (concat hd " (category " category ")")))
11986 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
11987 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
11988 (princ (format "BEGIN:VEVENT
11991 SUMMARY:%s
11992 END:VEVENT\n"
11993 (org-ical-ts-to-string ts "DTSTART")
11994 (org-ical-ts-to-string ts2 "DTEND" inc)
11995 hd)))
11996 (when org-icalendar-include-todo
11997 (goto-char (point-min))
11998 (while (re-search-forward org-todo-line-regexp nil t)
11999 (setq state (match-string 1))
12000 (unless (equal state org-done-string)
12001 (setq hd (match-string 3))
12002 (if (string-match org-priority-regexp hd)
12003 (setq pri (string-to-char (match-string 2 hd))
12004 hd (concat (substring hd 0 (match-beginning 1))
12005 (substring hd (- (match-end 1)))))
12006 (setq pri org-default-priority))
12007 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
12008 (- org-lowest-priority ?A))))))
12010 (princ (format "BEGIN:VTODO
12012 SUMMARY:%s
12013 SEQUENCE:1
12014 PRIORITY:%d
12015 END:VTODO\n"
12016 dts hd pri))))))))
12018 (defun org-start-icalendar-file (name)
12019 "Start an iCalendar file by inserting the header."
12020 (let ((user user-full-name)
12021 (name (or name "unknown"))
12022 (timezone (cadr (current-time-zone))))
12023 (princ
12024 (format "BEGIN:VCALENDAR
12025 VERSION:2.0
12026 X-WR-CALNAME:%s
12027 PRODID:-//%s//Emacs with Org-mode//EN
12028 X-WR-TIMEZONE:%s
12029 CALSCALE:GREGORIAN\n" name user timezone))))
12031 (defun org-finish-icalendar-file ()
12032 "Finish an iCalendar file by inserting the END statement."
12033 (princ "END:VCALENDAR\n"))
12035 (defun org-ical-ts-to-string (s keyword &optional inc)
12036 "Take a time string S and convert it to iCalendar format.
12037 KEYWORD is added in front, to make a complete line like DTSTART....
12038 When INC is non-nil, increase the hour by two (if time string contains
12039 a time), or the day by one (if it does not contain a time)."
12040 (let ((t1 (org-parse-time-string s 'nodefault))
12041 t2 fmt have-time time)
12042 (if (and (car t1) (nth 1 t1) (nth 2 t1))
12043 (setq t2 t1 have-time t)
12044 (setq t2 (org-parse-time-string s)))
12045 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
12046 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
12047 (when inc
12048 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
12049 (setq time (encode-time s mi h d m y)))
12050 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
12051 (concat keyword (format-time-string fmt time))))
12054 ;;; Key bindings
12056 ;; - Bindings in Org-mode map are currently
12057 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
12058 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
12059 ;; e (?) useful from outline-mode
12060 ;; i k @ expendable from outline-mode
12061 ;; 0123456789 % & ()_{} " ` free
12063 ;; Make `C-c C-x' a prefix key
12064 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
12066 ;; TAB key with modifiers
12067 (define-key org-mode-map "\C-i" 'org-cycle)
12068 (define-key org-mode-map [(tab)] 'org-cycle)
12069 (define-key org-mode-map [(meta tab)] 'org-complete)
12070 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
12071 ;; The following line is necessary under Suse GNU/Linux
12072 (unless (featurep 'xemacs)
12073 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
12074 (define-key org-mode-map [(shift tab)] 'org-shifttab)
12076 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
12077 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
12078 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12079 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
12080 (define-key org-mode-map [(meta return)] 'org-meta-return)
12081 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
12082 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
12084 ;; Cursor keys with modifiers
12085 (define-key org-mode-map [(meta left)] 'org-metaleft)
12086 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
12087 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
12088 (define-key org-mode-map [(meta right)] 'org-metaright)
12089 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
12090 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
12091 (define-key org-mode-map [(meta up)] 'org-metaup)
12092 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
12093 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
12094 (define-key org-mode-map [(meta down)] 'org-metadown)
12095 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
12096 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
12098 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12099 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
12100 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
12101 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
12102 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
12103 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
12104 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
12105 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
12106 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
12107 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
12108 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
12109 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
12110 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
12111 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
12112 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
12113 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
12115 ;; All the other keys
12116 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
12117 (define-key org-mode-map "\C-c\C-j" 'org-goto)
12118 (define-key org-mode-map "\C-c\C-t" 'org-todo)
12119 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
12120 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
12121 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
12122 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12123 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
12124 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
12125 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12126 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
12127 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
12128 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
12129 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
12130 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
12131 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
12132 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
12133 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12134 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12135 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12136 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12137 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
12138 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
12139 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12140 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
12141 (define-key org-mode-map "\C-c]" 'org-remove-file)
12142 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
12143 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
12144 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
12145 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12146 (define-key org-mode-map "\C-m" 'org-return)
12147 (define-key org-mode-map "\C-c?" 'org-table-current-column)
12148 (define-key org-mode-map "\C-c " 'org-table-blank-field)
12149 (define-key org-mode-map "\C-c+" 'org-table-sum)
12150 (define-key org-mode-map "\C-c|" 'org-table-toggle-vline-visibility)
12151 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
12152 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
12153 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
12154 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12155 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
12156 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12157 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
12158 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
12159 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
12160 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
12161 ;; OPML support is only an option for the future
12162 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
12163 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
12164 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
12165 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
12166 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
12167 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
12168 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
12169 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12170 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
12171 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
12172 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
12174 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12175 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12176 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12177 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12179 (defsubst org-table-p () (org-at-table-p))
12181 (defun org-self-insert-command (N)
12182 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12183 If the cursor is in a table looking at whitespace, the whitespace is
12184 overwritten, and the table is not marked as requiring realignment."
12185 (interactive "p")
12186 (if (and (org-table-p)
12188 (and org-table-auto-blank-field
12189 (member last-command
12190 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12191 (org-table-blank-field))
12193 (eq N 1)
12194 (looking-at "[^|\n]* +|"))
12195 (let (org-table-may-need-update)
12196 (goto-char (1- (match-end 0)))
12197 (delete-backward-char 1)
12198 (goto-char (match-beginning 0))
12199 (self-insert-command N))
12200 (setq org-table-may-need-update t)
12201 (self-insert-command N)))
12203 ;; FIXME:
12204 ;; The following two functions might still be optimized to trigger
12205 ;; re-alignment less frequently.
12207 (defun org-delete-backward-char (N)
12208 "Like `delete-backward-char', insert whitespace at field end in tables.
12209 When deleting backwards, in tables this function will insert whitespace in
12210 front of the next \"|\" separator, to keep the table aligned. The table will
12211 still be marked for re-alignment, because a narrow field may lead to a
12212 reduced column width."
12213 (interactive "p")
12214 (if (and (org-table-p)
12215 (eq N 1)
12216 (string-match "|" (buffer-substring (point-at-bol) (point)))
12217 (looking-at ".*?|"))
12218 (let ((pos (point)))
12219 (backward-delete-char N)
12220 (skip-chars-forward "^|")
12221 (insert " ")
12222 (goto-char (1- pos)))
12223 (backward-delete-char N)))
12225 (defun org-delete-char (N)
12226 "Like `delete-char', but insert whitespace at field end in tables.
12227 When deleting characters, in tables this function will insert whitespace in
12228 front of the next \"|\" separator, to keep the table aligned. The table
12229 will still be marked for re-alignment, because a narrow field may lead to
12230 a reduced column width."
12231 (interactive "p")
12232 (if (and (org-table-p)
12233 (not (bolp))
12234 (not (= (char-after) ?|))
12235 (eq N 1))
12236 (if (looking-at ".*?|")
12237 (let ((pos (point)))
12238 (replace-match (concat
12239 (substring (match-string 0) 1 -1)
12240 " |"))
12241 (goto-char pos)))
12242 (delete-char N)))
12244 ;; How to do this: Measure non-white length of current string
12245 ;; If equal to column width, we should realign.
12247 (defun org-remap (map &rest commands)
12248 "In MAP, remap the functions given in COMMANDS.
12249 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12250 (let (new old)
12251 (while commands
12252 (setq old (pop commands) new (pop commands))
12253 (if (fboundp 'command-remapping)
12254 (define-key map (vector 'remap old) new)
12255 (substitute-key-definition old new map global-map)))))
12257 (when (eq org-enable-table-editor 'optimized)
12258 ;; If the user wants maximum table support, we need to hijack
12259 ;; some standard editing functions
12260 (org-remap org-mode-map
12261 'self-insert-command 'org-self-insert-command
12262 'delete-char 'org-delete-char
12263 'delete-backward-char 'org-delete-backward-char)
12264 (define-key org-mode-map "|" 'org-force-self-insert))
12266 (defun org-shiftcursor-error ()
12267 "Throw an error because Shift-Cursor command was applied in wrong context."
12268 (error "This command is active in special context like tables, headlines or timestamps"))
12270 (defun org-shifttab ()
12271 "Global visibility cycling or move to previous table field.
12272 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
12273 See the individual commands for more information."
12274 (interactive)
12275 (cond
12276 ((org-at-table-p) (org-table-previous-field))
12277 (t (org-cycle '(4)))))
12279 (defun org-shiftmetaleft ()
12280 "Promote subtree or delete table column.
12281 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
12282 See the individual commands for more information."
12283 (interactive)
12284 (cond
12285 ((org-at-table-p) (org-table-delete-column))
12286 ((org-on-heading-p) (org-promote-subtree))
12287 ((org-at-item-p) (call-interactively 'org-outdent-item))
12288 (t (org-shiftcursor-error))))
12290 (defun org-shiftmetaright ()
12291 "Demote subtree or insert table column.
12292 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
12293 See the individual commands for more information."
12294 (interactive)
12295 (cond
12296 ((org-at-table-p) (org-table-insert-column))
12297 ((org-on-heading-p) (org-demote-subtree))
12298 ((org-at-item-p) (call-interactively 'org-indent-item))
12299 (t (org-shiftcursor-error))))
12301 (defun org-shiftmetaup (&optional arg)
12302 "Move subtree up or kill table row.
12303 Calls `org-move-subtree-up' or `org-table-kill-row' or
12304 `org-move-item-up' depending on context. See the individual commands
12305 for more information."
12306 (interactive "P")
12307 (cond
12308 ((org-at-table-p) (org-table-kill-row))
12309 ((org-on-heading-p) (org-move-subtree-up arg))
12310 ((org-at-item-p) (org-move-item-up arg))
12311 (t (org-shiftcursor-error))))
12312 (defun org-shiftmetadown (&optional arg)
12313 "Move subtree down or insert table row.
12314 Calls `org-move-subtree-down' or `org-table-insert-row' or
12315 `org-move-item-down', depending on context. See the individual
12316 commands for more information."
12317 (interactive "P")
12318 (cond
12319 ((org-at-table-p) (org-table-insert-row arg))
12320 ((org-on-heading-p) (org-move-subtree-down arg))
12321 ((org-at-item-p) (org-move-item-down arg))
12322 (t (org-shiftcursor-error))))
12324 (defun org-metaleft (&optional arg)
12325 "Promote heading or move table column to left.
12326 Calls `org-do-promote' or `org-table-move-column', depending on context.
12327 With no specific context, calls the Emacs default `backward-word'.
12328 See the individual commands for more information."
12329 (interactive "P")
12330 (cond
12331 ((org-at-table-p) (org-table-move-column 'left))
12332 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
12333 (t (backward-word (prefix-numeric-value arg)))))
12335 (defun org-metaright (&optional arg)
12336 "Demote subtree or move table column to right.
12337 Calls `org-do-demote' or `org-table-move-column', depending on context.
12338 With no specific context, calls the Emacs default `forward-word'.
12339 See the individual commands for more information."
12340 (interactive "P")
12341 (cond
12342 ((org-at-table-p) (org-table-move-column nil))
12343 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
12344 (t (forward-word (prefix-numeric-value arg)))))
12346 (defun org-metaup (&optional arg)
12347 "Move subtree up or move table row up.
12348 Calls `org-move-subtree-up' or `org-table-move-row' or
12349 `org-move-item-up', depending on context. See the individual commands
12350 for more information."
12351 (interactive "P")
12352 (cond
12353 ((org-at-table-p) (org-table-move-row 'up))
12354 ((org-on-heading-p) (org-move-subtree-up arg))
12355 ((org-at-item-p) (org-move-item-up arg))
12356 (t (org-shiftcursor-error))))
12358 (defun org-metadown (&optional arg)
12359 "Move subtree down or move table row down.
12360 Calls `org-move-subtree-down' or `org-table-move-row' or
12361 `org-move-item-down', depending on context. See the individual
12362 commands for more information."
12363 (interactive "P")
12364 (cond
12365 ((org-at-table-p) (org-table-move-row nil))
12366 ((org-on-heading-p) (org-move-subtree-down arg))
12367 ((org-at-item-p) (org-move-item-down arg))
12368 (t (org-shiftcursor-error))))
12370 (defun org-shiftup (&optional arg)
12371 "Increase item in timestamp or increase priority of current item.
12372 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12373 See the individual commands for more information."
12374 (interactive "P")
12375 (cond
12376 ((org-at-timestamp-p) (org-timestamp-up arg))
12377 (t (org-priority-up))))
12379 (defun org-shiftdown (&optional arg)
12380 "Decrease item in timestamp or decrease priority of current item.
12381 Calls `org-timestamp-down' or `org-priority-down', depending on context.
12382 See the individual commands for more information."
12383 (interactive "P")
12384 (cond
12385 ((org-at-timestamp-p) (org-timestamp-down arg))
12386 (t (org-priority-down))))
12388 (defun org-shiftright ()
12389 "Next TODO keyword or timestamp one day later, depending on context."
12390 (interactive)
12391 (cond
12392 ((org-at-timestamp-p) (org-timestamp-up-day))
12393 ((org-on-heading-p) (org-todo 'right))
12394 (t (org-shiftcursor-error))))
12396 (defun org-shiftleft ()
12397 "Previous TODO keyword or timestamp one day earlier, depending on context."
12398 (interactive)
12399 (cond
12400 ((org-at-timestamp-p) (org-timestamp-down-day))
12401 ((org-on-heading-p) (org-todo 'left))
12402 (t (org-shiftcursor-error))))
12404 (defun org-copy-special ()
12405 "Copy region in table or copy current subtree.
12406 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12407 See the individual commands for more information."
12408 (interactive)
12409 (call-interactively
12410 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12412 (defun org-cut-special ()
12413 "Cut region in table or cut current subtree.
12414 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12415 See the individual commands for more information."
12416 (interactive)
12417 (call-interactively
12418 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12420 (defun org-paste-special (arg)
12421 "Paste rectangular region into table, or past subtree relative to level.
12422 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12423 See the individual commands for more information."
12424 (interactive "P")
12425 (if (org-at-table-p)
12426 (org-table-paste-rectangle)
12427 (org-paste-subtree arg)))
12429 (defun org-ctrl-c-ctrl-c (&optional arg)
12430 "Call realign table, or recognize a table.el table, or update keywords.
12431 When the cursor is inside a table created by the table.el package,
12432 activate that table. Otherwise, if the cursor is at a normal table
12433 created with org.el, re-align that table. This command works even if
12434 the automatic table editor has been turned off.
12436 If the cursor is in a headline, prompt for tags and insert them into
12437 the current line, aligned to `org-tags-column'. When in a headline and
12438 called with prefix arg, realign all tags in the current buffer.
12440 If the cursor is in one of the special #+KEYWORD lines, this triggers
12441 scanning the buffer for these lines and updating the information.
12442 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
12443 (interactive "P")
12444 (let ((org-enable-table-editor t))
12445 (cond
12446 ((and (boundp 'remember-buffer) (equal (buffer-name) remember-buffer))
12447 (remember-buffer))
12448 ((org-on-target-p) (org-update-radio-target-regexp))
12449 ((org-on-heading-p) (org-set-tags arg))
12450 ((org-at-table.el-p)
12451 (require 'table)
12452 (beginning-of-line 1)
12453 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12454 (table-recognize-table))
12455 ((org-at-table-p)
12456 (org-table-maybe-eval-formula)
12457 (if arg
12458 (org-table-recalculate t)
12459 (org-table-maybe-recalculate-line))
12460 (org-table-align))
12461 ((org-at-item-p)
12462 (org-renumber-ordered-list (prefix-numeric-value arg)))
12463 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12464 (cond
12465 ((equal (match-string 1) "TBLFM")
12466 ;; Recalculate the table before this line
12467 (save-excursion
12468 (beginning-of-line 1)
12469 (skip-chars-backward " \r\n\t")
12470 (if (org-at-table-p) (org-table-recalculate t))))
12472 (org-mode-restart))))
12473 ((org-region-active-p)
12474 (org-table-convert-region (region-beginning) (region-end) arg))
12475 ((condition-case nil
12476 (and (region-beginning) (region-end))
12477 (error nil))
12478 (if (y-or-n-p "Convert inactive region to table? ")
12479 (org-table-convert-region (region-beginning) (region-end) arg)
12480 (error "Abort")))
12481 (t (error "C-c C-c can do nothing useful at this location.")))))
12483 (defun org-mode-restart ()
12484 "Restart Org-mode, to scan again for special lines.
12485 Also updates the keyword regular expressions."
12486 (interactive)
12487 (let ((org-inhibit-startup t)) (org-mode))
12488 (message "Org-mode restarted to refresh keyword and special line setup"))
12490 (defun org-return ()
12491 "Goto next table row or insert a newline.
12492 Calls `org-table-next-row' or `newline', depending on context.
12493 See the individual commands for more information."
12494 (interactive)
12495 (cond
12496 ((org-at-table-p)
12497 (org-table-justify-field-maybe)
12498 (org-table-next-row))
12499 (t (newline))))
12501 (defun org-meta-return (&optional arg)
12502 "Insert a new heading or wrap a region in a table.
12503 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12504 See the individual commands for more information."
12505 (interactive "P")
12506 (cond
12507 ((org-at-table-p)
12508 (org-table-wrap-region arg))
12509 (t (org-insert-heading arg))))
12511 ;;; Menu entries
12513 ;; Define the Org-mode menus
12514 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12515 '("Tbl"
12516 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
12517 ["Next Field" org-cycle (org-at-table-p)]
12518 ["Previous Field" org-shifttab (org-at-table-p)]
12519 ["Next Row" org-return (org-at-table-p)]
12520 "--"
12521 ["Blank Field" org-table-blank-field (org-at-table-p)]
12522 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12523 "--"
12524 ("Column"
12525 ["Move Column Left" org-metaleft (org-at-table-p)]
12526 ["Move Column Right" org-metaright (org-at-table-p)]
12527 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12528 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12529 ("Row"
12530 ["Move Row Up" org-metaup (org-at-table-p)]
12531 ["Move Row Down" org-metadown (org-at-table-p)]
12532 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12533 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12534 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12535 "--"
12536 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
12537 ("Rectangle"
12538 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12539 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12540 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12541 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12542 "--"
12543 ("Calculate"
12544 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12545 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12546 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12547 "--"
12548 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12549 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12550 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12551 "--"
12552 ["Sum Column/Rectangle" org-table-sum
12553 (or (org-at-table-p) (org-region-active-p))]
12554 ["Which Column?" org-table-current-column (org-at-table-p)])
12555 ["Debug Formulas"
12556 (setq org-table-formula-debug (not org-table-formula-debug))
12557 :style toggle :selected org-table-formula-debug]
12558 "--"
12559 ["Invisible Vlines" org-table-toggle-vline-visibility
12560 :style toggle :selected (org-in-invisibility-spec-p '(org-table))]
12561 "--"
12562 ["Create" org-table-create (and (not (org-at-table-p))
12563 org-enable-table-editor)]
12564 ["Convert Region" org-ctrl-c-ctrl-c (not (org-at-table-p 'any))]
12565 ["Import from File" org-table-import (not (org-at-table-p))]
12566 ["Export to File" org-table-export (org-at-table-p)]
12567 "--"
12568 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12570 (easy-menu-define org-org-menu org-mode-map "Org menu"
12571 '("Org"
12572 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
12573 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
12574 ["Sparse Tree" org-occur t]
12575 ["Show All" show-all t]
12576 "--"
12577 ["New Heading" org-insert-heading t]
12578 ("Navigate Headings"
12579 ["Up" outline-up-heading t]
12580 ["Next" outline-next-visible-heading t]
12581 ["Previous" outline-previous-visible-heading t]
12582 ["Next Same Level" outline-forward-same-level t]
12583 ["Previous Same Level" outline-backward-same-level t]
12584 "--"
12585 ["Jump" org-goto t])
12586 ("Edit Structure"
12587 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12588 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12589 "--"
12590 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12591 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12592 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12593 "--"
12594 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12595 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12596 ["Demote Heading" org-metaright (not (org-at-table-p))]
12597 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12598 "--"
12599 ["Archive Subtree" org-archive-subtree t]
12600 "--"
12601 ["Convert to odd levels" org-convert-to-odd-levels t]
12602 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12603 "--"
12604 ("TODO Lists"
12605 ["TODO/DONE/-" org-todo t]
12606 ["Show TODO Tree" org-show-todo-tree t]
12607 ["Global TODO list" org-todo-list t]
12608 "--"
12609 ["Set Priority" org-priority t]
12610 ["Priority Up" org-shiftup t]
12611 ["Priority Down" org-shiftdown t])
12612 ("Dates and Scheduling"
12613 ["Timestamp" org-time-stamp t]
12614 ["Timestamp (inactive)" org-time-stamp-inactive t]
12615 ("Change Date"
12616 ["1 Day Later" org-timestamp-up-day t]
12617 ["1 Day Earlier" org-timestamp-down-day t]
12618 ["1 ... Later" org-shiftup t]
12619 ["1 ... Earlier" org-shiftdown t])
12620 ["Compute Time Range" org-evaluate-time-range t]
12621 ["Schedule Item" org-schedule t]
12622 ["Deadline" org-deadline t]
12623 "--"
12624 ["Goto Calendar" org-goto-calendar t]
12625 ["Date from Calendar" org-date-from-calendar t])
12626 "--"
12627 ["Agenda Command" org-agenda t]
12628 ("File List for Agenda")
12629 ("Special views current file"
12630 ["TODO Tree" org-show-todo-tree t]
12631 ["Check Deadlines" org-check-deadlines t]
12632 ["Timeline" org-timeline t]
12633 ["Tags Tree" org-tags-sparse-tree t])
12634 "--"
12635 ("Hyperlinks"
12636 ["Store Link (Global)" org-store-link t]
12637 ["Insert Link" org-insert-link t]
12638 ["Follow Link" org-open-at-point t])
12639 "--"
12640 ("Export"
12641 ["ASCII" org-export-as-ascii t]
12642 ["Extract Visible Text" org-export-copy-visible t]
12643 ["HTML" org-export-as-html t]
12644 ["HTML and Open" org-export-as-html-and-open t]
12645 ; ["OPML" org-export-as-opml nil]
12646 "--"
12647 ["iCalendar this file" org-export-icalendar-this-file t]
12648 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
12649 :active t :keys "C-c C-x C-i"]
12650 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
12651 "--"
12652 ["Option Template" org-insert-export-options-template t]
12653 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
12654 "--"
12655 ("Documentation"
12656 ["Show Version" org-version t]
12657 ["Info Documentation" org-info t])
12658 ("Customize"
12659 ["Browse Org Group" org-customize t]
12660 "--"
12661 ["Build Full Customize Menu" org-create-customize-menu
12662 (fboundp 'customize-menu-create)])
12663 "--"
12664 ["Refresh setup" org-mode-restart t]
12667 (defun org-info (&optional node)
12668 "Read documentation for Org-mode in the info system.
12669 With optional NODE, go directly to that node."
12670 (interactive)
12671 (require 'info)
12672 (Info-goto-node (format "(org)%s" (or node ""))))
12674 (defun org-install-agenda-files-menu ()
12675 (let ((bl (buffer-list)))
12676 (save-excursion
12677 (while bl
12678 (set-buffer (pop bl))
12679 (if (eq major-mode 'org-mode) (setq bl nil)))
12680 (when (eq major-mode 'org-mode)
12681 (easy-menu-change
12682 '("Org") "File List for Agenda"
12683 (append
12684 (list
12685 ["Edit File List" (org-edit-agenda-file-list) t]
12686 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12687 ["Remove Current File from List" org-remove-file t]
12688 ["Cycle through agenda files" org-cycle-agenda-files t]
12689 "--")
12690 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12692 ;;; Documentation
12694 (defun org-customize ()
12695 "Call the customize function with org as argument."
12696 (interactive)
12697 (customize-browse 'org))
12699 (defun org-create-customize-menu ()
12700 "Create a full customization menu for Org-mode, insert it into the menu."
12701 (interactive)
12702 (if (fboundp 'customize-menu-create)
12703 (progn
12704 (easy-menu-change
12705 '("Org") "Customize"
12706 `(["Browse Org group" org-customize t]
12707 "--"
12708 ,(customize-menu-create 'org)
12709 ["Set" Custom-set t]
12710 ["Save" Custom-save t]
12711 ["Reset to Current" Custom-reset-current t]
12712 ["Reset to Saved" Custom-reset-saved t]
12713 ["Reset to Standard Settings" Custom-reset-standard t]))
12714 (message "\"Org\"-menu now contains full customization menu"))
12715 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12717 ;;; Miscellaneous stuff
12719 (defun org-move-line-down (arg)
12720 "Move the current line down. With prefix argument, move it past ARG lines."
12721 (interactive "p")
12722 (let ((col (current-column))
12723 beg end pos)
12724 (beginning-of-line 1) (setq beg (point))
12725 (beginning-of-line 2) (setq end (point))
12726 (beginning-of-line (+ 1 arg))
12727 (setq pos (move-marker (make-marker) (point)))
12728 (insert (delete-and-extract-region beg end))
12729 (goto-char pos)
12730 (move-to-column col)))
12732 (defun org-move-line-up (arg)
12733 "Move the current line up. With prefix argument, move it past ARG lines."
12734 (interactive "p")
12735 (let ((col (current-column))
12736 beg end pos)
12737 (beginning-of-line 1) (setq beg (point))
12738 (beginning-of-line 2) (setq end (point))
12739 (beginning-of-line (- arg))
12740 (setq pos (move-marker (make-marker) (point)))
12741 (insert (delete-and-extract-region beg end))
12742 (goto-char pos)
12743 (move-to-column col)))
12745 ;; Paragraph filling stuff.
12746 ;; We want this to be just right, so use the full arsenal.
12747 ;; FIXME: This very likely does not work correctly for XEmacs, because the
12748 ;; filladapt package works slightly differently.
12750 (defun org-set-autofill-regexps ()
12751 (interactive)
12752 ;; In the paragraph separator we include headlines, because filling
12753 ;; text in a line directly attached to a headline would otherwise
12754 ;; fill the headline as well.
12755 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
12756 ;; The paragraph starter includes hand-formatted lists.
12757 (set (make-local-variable 'paragraph-start)
12758 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
12759 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
12760 ;; But only if the user has not turned off tables or fixed-width regions
12761 (set (make-local-variable 'auto-fill-inhibit-regexp)
12762 (concat "\\*\\|#"
12763 (if (or org-enable-table-editor org-enable-fixed-width-editor)
12764 (concat
12765 "\\|[ \t]*["
12766 (if org-enable-table-editor "|" "")
12767 (if org-enable-fixed-width-editor ":" "")
12768 "]"))))
12769 ;; We use our own fill-paragraph function, to make sure that tables
12770 ;; and fixed-width regions are not wrapped. That function will pass
12771 ;; through to `fill-paragraph' when appropriate.
12772 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
12773 ;; Adaptive filling: To get full control, first make sure that
12774 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
12775 (setq adaptive-fill-regexp "\000")
12776 (setq adaptive-fill-function 'org-adaptive-fill-function))
12778 (defun org-fill-paragraph (&optional justify)
12779 "Re-align a table, pass through to fill-paragraph if no table."
12780 (let ((table-p (org-at-table-p))
12781 (table.el-p (org-at-table.el-p)))
12782 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
12783 (table.el-p t) ; skip table.el tables
12784 (table-p (org-table-align) t) ; align org-mode tables
12785 (t nil)))) ; call paragraph-fill
12787 ;; For reference, this is the default value of adaptive-fill-regexp
12788 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
12790 (defun org-adaptive-fill-function ()
12791 "Return a fill prefix for org-mode files.
12792 In particular, this makes sure hanging paragraphs for hand-formatted lists
12793 work correctly."
12794 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
12795 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
12797 ;; Functions needed for Emacs/XEmacs region compatibility
12799 (defun org-add-hook (hook function &optional append local)
12800 "Add-hook, compatible with both Emacsen."
12801 (if (and local (featurep 'xemacs))
12802 (add-local-hook hook function append)
12803 (add-hook hook function append local)))
12805 (defun org-region-active-p ()
12806 "Is `transient-mark-mode' on and the region active?
12807 Works on both Emacs and XEmacs."
12808 (if org-ignore-region
12810 (if (featurep 'xemacs)
12811 (and zmacs-regions (region-active-p))
12812 (and transient-mark-mode mark-active))))
12814 (defun org-add-to-invisibility-spec (arg)
12815 "Add elements to `buffer-invisibility-spec'.
12816 See documentation for `buffer-invisibility-spec' for the kind of elements
12817 that can be added."
12818 (cond
12819 ((fboundp 'add-to-invisibility-spec)
12820 (add-to-invisibility-spec arg))
12821 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
12822 (setq buffer-invisibility-spec (list arg)))
12824 (setq buffer-invisibility-spec
12825 (cons arg buffer-invisibility-spec)))))
12827 (defun org-remove-from-invisibility-spec (arg)
12828 "Remove elements from `buffer-invisibility-spec'."
12829 (if (fboundp 'remove-from-invisibility-spec)
12830 (remove-from-invisibility-spec arg)
12831 (if (consp buffer-invisibility-spec)
12832 (setq buffer-invisibility-spec
12833 (delete arg buffer-invisibility-spec)))))
12835 (defun org-in-invisibility-spec-p (arg)
12836 "Is ARG a member of `buffer-invisibility-spec'?"
12837 (if (consp buffer-invisibility-spec)
12838 (member arg buffer-invisibility-spec)
12839 nil))
12841 (defun org-image-file-name-regexp ()
12842 "Return regexp matching the file names of images."
12843 (if (fboundp 'image-file-name-regexp)
12844 (image-file-name-regexp)
12845 (let ((image-file-name-extensions
12846 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
12847 "xbm" "xpm" "pbm" "pgm" "ppm")))
12848 (concat "\\."
12849 (regexp-opt (nconc (mapcar 'upcase
12850 image-file-name-extensions)
12851 image-file-name-extensions)
12853 "\\'"))))
12855 ;; Functions needed for compatibility with old outline.el.
12857 ;; Programming for the old outline.el (that uses selective display
12858 ;; instead of `invisible' text properties) is a nightmare, mostly
12859 ;; because regular expressions can no longer be anchored at
12860 ;; beginning/end of line. Therefore a number of function need special
12861 ;; treatment when the old outline.el is being used.
12863 ;; The following functions capture almost the entire compatibility code
12864 ;; between the different versions of outline-mode. The only other
12865 ;; places where this is important are the font-lock-keywords, and in
12866 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
12868 ;; C-a should go to the beginning of a *visible* line, also in the
12869 ;; new outline.el. I guess this should be patched into Emacs?
12870 (defun org-beginning-of-line ()
12871 "Go to the beginning of the current line. If that is invisible, continue
12872 to a visible line beginning. This makes the function of C-a more intuitive."
12873 (interactive)
12874 (beginning-of-line 1)
12875 (if (bobp)
12877 (backward-char 1)
12878 (if (org-invisible-p)
12879 (while (and (not (bobp)) (org-invisible-p))
12880 (backward-char 1)
12881 (beginning-of-line 1))
12882 (forward-char 1))))
12884 (when org-noutline-p
12885 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
12886 ;; FIXME: should I use substitute-key-definition to reach other bindings
12887 ;; of beginning-of-line?
12889 (defun org-invisible-p ()
12890 "Check if point is at a character currently not visible."
12891 (if org-noutline-p
12892 ;; Early versions of noutline don't have `outline-invisible-p'.
12893 (if (fboundp 'outline-invisible-p)
12894 (outline-invisible-p)
12895 (get-char-property (point) 'invisible))
12896 (save-excursion
12897 (skip-chars-backward "^\r\n")
12898 (equal (char-before) ?\r))))
12900 (defun org-invisible-p2 ()
12901 "Check if point is at a character currently not visible."
12902 (save-excursion
12903 (if org-noutline-p
12904 (progn
12905 (if (and (eolp) (not (bobp))) (backward-char 1))
12906 ;; Early versions of noutline don't have `outline-invisible-p'.
12907 (if (fboundp 'outline-invisible-p)
12908 (outline-invisible-p)
12909 (get-char-property (point) 'invisible)))
12910 (skip-chars-backward "^\r\n")
12911 (equal (char-before) ?\r))))
12913 (defun org-back-to-heading (&optional invisible-ok)
12914 "Move to previous heading line, or beg of this line if it's a heading.
12915 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
12916 (if org-noutline-p
12917 (outline-back-to-heading invisible-ok)
12918 (if (and (memq (char-before) '(?\n ?\r))
12919 (looking-at outline-regexp))
12921 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
12922 outline-regexp)
12923 nil t)
12924 (if invisible-ok
12925 (progn (goto-char (match-end 1))
12926 (looking-at outline-regexp)))
12927 (error "Before first heading")))))
12929 (defun org-on-heading-p (&optional invisible-ok)
12930 "Return t if point is on a (visible) heading line.
12931 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
12932 (if org-noutline-p
12933 (outline-on-heading-p 'invisible-ok)
12934 (save-excursion
12935 (skip-chars-backward "^\n\r")
12936 (and (looking-at outline-regexp)
12937 (or invisible-ok
12938 (bobp)
12939 (equal (char-before) ?\n))))))
12941 (defun org-on-target-p ()
12942 (let ((pos (point)))
12943 (save-excursion
12944 (skip-chars-forward "<")
12945 (and (re-search-backward "<<" nil t)
12946 (or (looking-at org-target-regexp)
12947 (looking-at org-radio-target-regexp))
12948 (<= (match-beginning 0) pos)
12949 (>= (match-end 0) pos)))))
12951 (defun org-up-heading-all (arg)
12952 "Move to the heading line of which the present line is a subheading.
12953 This function considers both visible and invisible heading lines.
12954 With argument, move up ARG levels."
12955 (if org-noutline-p
12956 (if (fboundp 'outline-up-heading-all)
12957 (outline-up-heading-all arg) ; emacs 21 version of outline.el
12958 (outline-up-heading arg t)) ; emacs 22 version of outline.el
12959 (org-back-to-heading t)
12960 (looking-at outline-regexp)
12961 (if (<= (- (match-end 0) (match-beginning 0)) arg)
12962 (error "Cannot move up %d levels" arg)
12963 (re-search-backward
12964 (concat "[\n\r]" (regexp-quote
12965 (make-string (- (match-end 0) (match-beginning 0) arg)
12966 ?*))
12967 "[^*]"))
12968 (forward-char 1))))
12970 (defun org-show-hidden-entry ()
12971 "Show an entry where even the heading is hidden."
12972 (save-excursion
12973 (if (not org-noutline-p)
12974 (progn
12975 (org-back-to-heading t)
12976 (org-flag-heading nil)))
12977 (org-show-entry)))
12979 (defun org-check-occur-regexp (regexp)
12980 "If REGEXP starts with \"^\", modify it to check for \\r as well.
12981 Of course, only for the old outline mode."
12982 (if org-noutline-p
12983 regexp
12984 (if (string-match "^\\^" regexp)
12985 (concat "[\n\r]" (substring regexp 1))
12986 regexp)))
12988 (defun org-flag-heading (flag &optional entry)
12989 "Flag the current heading. FLAG non-nil means make invisible.
12990 When ENTRY is non-nil, show the entire entry."
12991 (save-excursion
12992 (org-back-to-heading t)
12993 (if (not org-noutline-p)
12994 ;; Make the current headline visible
12995 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
12996 ;; Check if we should show the entire entry
12997 (if entry
12998 (progn
12999 (org-show-entry)
13000 (save-excursion ;; FIXME: Is this the fix for points in the -|
13001 ;; middle of text? |
13002 (and (outline-next-heading) ;; |
13003 (org-flag-heading nil)))) ; show the next heading _|
13004 (outline-flag-region (max 1 (1- (point)))
13005 (save-excursion (outline-end-of-heading) (point))
13006 (if org-noutline-p
13007 flag
13008 (if flag ?\r ?\n))))))
13010 (defun org-end-of-subtree (&optional invisible-OK)
13011 ;; This is an exact copy of the original function, but it uses
13012 ;; `org-back-to-heading', to make it work also in invisible
13013 ;; trees. And is uses an invisible-OK argument.
13014 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13015 (org-back-to-heading invisible-OK)
13016 (let ((first t)
13017 (level (funcall outline-level)))
13018 (while (and (not (eobp))
13019 (or first (> (funcall outline-level) level)))
13020 (setq first nil)
13021 (outline-next-heading))
13022 (if (memq (preceding-char) '(?\n ?\^M))
13023 (progn
13024 ;; Go to end of line before heading
13025 (forward-char -1)
13026 (if (memq (preceding-char) '(?\n ?\^M))
13027 ;; leave blank line before heading
13028 (forward-char -1))))))
13030 (defun org-show-subtree ()
13031 "Show everything after this heading at deeper levels."
13032 (outline-flag-region
13033 (point)
13034 (save-excursion
13035 (outline-end-of-subtree) (outline-next-heading) (point))
13036 (if org-noutline-p nil ?\n)))
13038 (defun org-show-entry ()
13039 "Show the body directly following this heading.
13040 Show the heading too, if it is currently invisible."
13041 (interactive)
13042 (save-excursion
13043 (org-back-to-heading t)
13044 (outline-flag-region
13045 (1- (point))
13046 (save-excursion
13047 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13048 (or (match-beginning 1) (point-max)))
13049 (if org-noutline-p nil ?\n))))
13052 (defun org-make-options-regexp (kwds)
13053 "Make a regular expression for keyword lines."
13054 (concat
13055 (if org-noutline-p "^" "[\n\r]")
13056 "#?[ \t]*\\+\\("
13057 (mapconcat 'regexp-quote kwds "\\|")
13058 "\\):[ \t]*"
13059 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
13061 ;; Make `bookmark-jump' show the jump location if it was hidden.
13062 (eval-after-load "bookmark"
13063 '(if (boundp 'bookmark-after-jump-hook)
13064 ;; We can use the hook
13065 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13066 ;; Hook not available, use advice
13067 (defadvice bookmark-jump (after org-make-visible activate)
13068 "Make the position visible."
13069 (org-bookmark-jump-unhide))))
13071 (defun org-bookmark-jump-unhide ()
13072 "Unhide the current position, to show the bookmark location."
13073 (and (eq major-mode 'org-mode)
13074 (or (org-invisible-p)
13075 (save-excursion (goto-char (max (point-min) (1- (point))))
13076 (org-invisible-p)))
13077 (org-show-hierarchy-above)))
13079 ;;; Finish up
13081 (provide 'org)
13083 (run-hooks 'org-load-hook)
13085 ;; Experimental code
13088 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13089 ;;; org.el ends here