Release 4.20
[org-mode.git] / org.el
blobd58d851122b6a0add661c63b7b95856f18a7ec9f
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.20
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.20
85 ;; - Links use now the [[link][description]] format by default.
86 ;; When inserting links, the user is prompted for a description.
87 ;; - If a link has a description, only the description is displayed
88 ;; the link part is hidden. Use C-c C-l to edit the link part.
89 ;; - TAGS are now bold, but in the same color as the headline.
90 ;; - The width of a table column can be limited by using a field "<N>".
91 ;; - New structure for the customization tree.
92 ;; - Bug fixes.
94 ;; Version 4.13
95 ;; - The list of agenda files can be maintainted in an external file.
96 ;; - Bug fixes.
98 ;; Version 4.12
99 ;; - Templates for remember buffer. Note that the remember setup changes.
100 ;; To set up templates, see `org-remember-templates'.
101 ;; - The time in new time stamps can be rounded, see new option
102 ;; `org-time-stamp-rounding-minutes'.
103 ;; - Bug fixes (there are *always* more bugs).
105 ;; Version 4.10
106 ;; - Bug fixes.
108 ;; Version 4.09
109 ;; - Bug fixes.
110 ;; - Small improvements to font-lock support.
111 ;; - MHE support finalized.
113 ;; Version 4.08
114 ;; - Bug fixes.
115 ;; - Improved MHE support
117 ;; Version 4.07
118 ;; - Bug fixes.
119 ;; - Leading stars in headlines can be hidden, so make the outline look
120 ;; cleaner.
121 ;; - Mouse-1 can be used to follow links.
123 ;; Version 4.06
124 ;; - HTML exporter treats targeted internal links.
125 ;; - Bug fixes.
127 ;; Version 4.05
128 ;; - Changes to internal link system (thanks to David Wainberg for ideas).
129 ;; - in-file links: [[Search String]] instead of <file:::Search String>
130 ;; - automatic links to "radio targets".
131 ;; - CamelCase not longer active by default, configure org-activate-camels
132 ;; if you want to turn it back on.
133 ;; - After following a link, `C-c &' jumps back to it.
134 ;; - MH-E link support (thanks to Thomas Baumann).
135 ;; - Special table lines are no longer exported.
136 ;; - Bug fixes and minor improvements.
138 ;; Version 4.04
139 ;; - Cleanup tags display in agenda.
140 ;; - Bug fixes.
142 ;; Version 4.03
143 ;; - Table alignment fixed for use with wide characters.
144 ;; - `C-c -' leaves cursor in current table line.
145 ;; - The current TAG can be incorporated into the agenda prefix.
146 ;; See option `org-agenda-prefix-format' for details.
148 ;; Version 4.02
149 ;; - Minor bug fixes and improvements around tag searches.
150 ;; - XEmacs compatibility fixes.
152 ;; Version 4.01
153 ;; - Tags can also be set remotely from agenda buffer.
154 ;; - Boolean logic for tag searches.
155 ;; - Additional agenda commands can be configured through the variable
156 ;; `org-agenda-custom-commands'.
157 ;; - Minor bug fixes.
159 ;;; Code:
161 (eval-when-compile
162 (require 'cl)
163 (require 'calendar))
164 (require 'outline)
165 (require 'time-date)
166 (require 'easymenu)
168 (defvar calc-embedded-close-formula) ; defined by the calc package
169 (defvar calc-embedded-open-formula) ; defined by the calc package
170 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
172 ;;; Customization variables
174 (defvar org-version "4.20"
175 "The version number of the file org.el.")
176 (defun org-version ()
177 (interactive)
178 (message "Org-mode version %s" org-version))
180 ;; The following constant is for compatibility with different versions
181 ;; of outline.el.
182 (defconst org-noutline-p (featurep 'noutline)
183 "Are we using the new outline mode?")
184 (defconst org-xemacs-p (featurep 'xemacs))
185 (defconst org-format-transports-properties-p
186 (let ((x "a"))
187 (add-text-properties 0 1 '(test t) x)
188 (get-text-property 0 'test (format "%s" x)))
189 "Does format transport text properties?")
191 (defgroup org nil
192 "Outline-based notes management and organizer."
193 :tag "Org"
194 :group 'outlines
195 :group 'hypermedia
196 :group 'calendar)
198 (defgroup org-startup nil
199 "Options concerning startup of Org-mode."
200 :tag "Org Startup"
201 :group 'org)
203 (defcustom org-startup-folded t
204 "Non-nil means, entering Org-mode will switch to OVERVIEW.
205 This can also be configured on a per-file basis by adding one of
206 the following lines anywhere in the buffer:
208 #+STARTUP: fold
209 #+STARTUP: nofold
210 #+STARTUP: content"
211 :group 'org-startup
212 :type '(choice
213 (const :tag "nofold: show all" nil)
214 (const :tag "fold: overview" t)
215 (const :tag "content: all headlines" content)))
217 (defcustom org-startup-truncated t
218 "Non-nil means, entering Org-mode will set `truncate-lines'.
219 This is useful since some lines containing links can be very long and
220 uninteresting. Also tables look terrible when wrapped."
221 :group 'org-startup
222 :type 'boolean)
224 (defcustom org-startup-align-all-tables nil
225 "Non-nil means, align all tables when visiting a file.
226 This is useful when the column width in tables is forced with <N> cookies
227 in table fields. Such tables will look correct only after the first re-align."
228 :group 'org-startup
229 :type 'boolean)
231 (defcustom org-startup-with-deadline-check nil
232 "Non-nil means, entering Org-mode will run the deadline check.
233 This means, if you start editing an org file, you will get an
234 immediate reminder of any due deadlines.
235 This can also be configured on a per-file basis by adding one of
236 the following lines anywhere in the buffer:
238 #+STARTUP: dlcheck
239 #+STARTUP: nodlcheck"
240 :group 'org-startup
241 :type 'boolean)
243 (defcustom org-insert-mode-line-in-empty-file nil
244 "Non-nil means insert the first line setting Org-mode in empty files.
245 When the function `org-mode' is called interactively in an empty file, this
246 normally means that the file name does not automatically trigger Org-mode.
247 To ensure that the file will always be in Org-mode in the future, a
248 line enforcing Org-mode will be inserted into the buffer, if this option
249 has been set."
250 :group 'org-startup
251 :type 'boolean)
253 (defcustom org-CUA-compatible nil
254 "Non-nil means use alternative key bindings for S-<cursor movement>.
255 Org-mode used S-<cursor movement> for changing timestamps and priorities.
256 S-<cursor movement> is also used for example by `CUA-mode' to select text.
257 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
258 alternative bindings. Setting this variable to t will replace the following
259 keys both in Org-mode and in the Org-agenda buffer.
261 S-RET -> C-S-RET
262 S-up -> M-p
263 S-down -> M-n
264 S-left -> M--
265 S-right -> M-+
267 If you do not like the alternative keys, take a look at the variable
268 `org-disputed-keys'.
270 This option is only relevant at load-time of Org-mode. Changing it requires
271 a restart of Emacs to become effective."
272 :group 'org-startup
273 :type 'boolean)
275 (defvar org-disputed-keys
276 '((S-up [(shift up)] [(meta ?p)])
277 (S-down [(shift down)] [(meta ?n)])
278 (S-left [(shift left)] [(meta ?-)])
279 (S-right [(shift right)] [(meta ?+)])
280 (S-return [(shift return)] [(control shift return)]))
281 "Keys for which Org-mode and other modes compete.
282 This is an alist, cars are symbols for lookup, 1st element is the default key,
283 second element will be used when `org-CUA-compatible' is t.")
285 (defun org-key (key)
286 "Select a key according to `org-CUA-compatible'."
287 (nth (if org-CUA-compatible 2 1)
288 (or (assq key org-disputed-keys)
289 (error "Invalid Key %s in `org-key'" key))))
291 (defcustom org-ellipsis nil
292 "The ellipsis to use in the Org-mode outline.
293 When nil, just use the standard three dots. When a string, use that instead,
294 and just in Org-mode (which will then use its own display table).
295 Changing this requires executing `M-x org-mode' in a buffer to become
296 effective."
297 :group 'org-startup
298 :type '(choice (const :tag "Default" nil)
299 (string :tag "String" :value "...#")))
301 (defvar org-display-table nil
302 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
304 (defgroup org-keywords nil
305 "Keywords in Org-mode."
306 :tag "Org Keywords"
307 :group 'org)
309 (defcustom org-deadline-string "DEADLINE:"
310 "String to mark deadline entries.
311 A deadline is this string, followed by a time stamp. Should be a word,
312 terminated by a colon. You can insert a schedule keyword and
313 a timestamp with \\[org-deadline].
314 Changes become only effective after restarting Emacs."
315 :group 'org-keywords
316 :type 'string)
318 (defcustom org-scheduled-string "SCHEDULED:"
319 "String to mark scheduled TODO entries.
320 A schedule is this string, followed by a time stamp. Should be a word,
321 terminated by a colon. You can insert a schedule keyword and
322 a timestamp with \\[org-schedule].
323 Changes become only effective after restarting Emacs."
324 :group 'org-keywords
325 :type 'string)
327 (defcustom org-closed-string "CLOSED:"
328 "String used as the prefix for timestamps logging closing a TODO entry."
329 :group 'org-keywords
330 :type 'string)
332 (defcustom org-comment-string "COMMENT"
333 "Entries starting with this keyword will never be exported.
334 An entry can be toggled between COMMENT and normal with
335 \\[org-toggle-comment].
336 Changes become only effective after restarting Emacs."
337 :group 'org-keywords
338 :type 'string)
340 (defcustom org-quote-string "QUOTE"
341 "Entries starting with this keyword will be exported in fixed-width font.
342 Quoting applies only to the text in the entry following the headline, and does
343 not extend beyond the next headline, even if that is lower level.
344 An entry can be toggled between QUOTE and normal with
345 \\[org-toggle-fixed-width-section]."
346 :group 'org-keywords
347 :type 'string)
349 (defgroup org-structure nil
350 "Options concerning the general structure of Org-mode files."
351 :tag "Org Structure"
352 :group 'org)
354 (defgroup org-cycle nil
355 "Options concerning visibility cycling in Org-mode."
356 :tag "Org Cycle"
357 :group 'org-structure)
359 (defcustom org-cycle-emulate-tab t
360 "Where should `org-cycle' emulate TAB.
361 nil Never
362 white Only in completely white lines
363 t Everywhere except in headlines"
364 :group 'org-cycle
365 :type '(choice (const :tag "Never" nil)
366 (const :tag "Only in completely white lines" white)
367 (const :tag "Everywhere except in headlines" t)
370 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
371 "Hook that is run after `org-cycle' has changed the buffer visibility.
372 The function(s) in this hook must accept a single argument which indicates
373 the new state that was set by the most recent `org-cycle' command. The
374 argument is a symbol. After a global state change, it can have the values
375 `overview', `content', or `all'. After a local state change, it can have
376 the values `folded', `children', or `subtree'."
377 :group 'org-cycle
378 :type 'hook)
380 (defgroup org-edit-structure nil
381 "Options concerning structure editing in Org-mode."
382 :tag "Org Edit Structure"
383 :group 'org-structure)
385 (defcustom org-odd-levels-only nil
386 "Non-nil means, skip even levels and only use odd levels for the outline.
387 This has the effect that two stars are being added/taken away in
388 promotion/demotion commands. It also influences how levels are
389 handled by the exporters.
390 Changing it requires restart of `font-lock-mode' to become effective
391 for fontification also in regions already fontified."
392 :group 'org-edit-structure
393 :group 'org-font-lock
394 :type 'boolean)
396 (defcustom org-adapt-indentation t
397 "Non-nil means, adapt indentation when promoting and demoting.
398 When this is set and the *entire* text in an entry is indented, the
399 indentation is increased by one space in a demotion command, and
400 decreased by one in a promotion command. If any line in the entry
401 body starts at column 0, indentation is not changed at all."
402 :group 'org-edit-structure
403 :type 'boolean)
405 (defcustom org-enable-fixed-width-editor t
406 "Non-nil means, lines starting with \":\" are treated as fixed-width.
407 This currently only means, they are never auto-wrapped.
408 When nil, such lines will be treated like ordinary lines.
409 See also the QUOTE keyword."
410 :group 'org-edit-structure
411 :type 'boolean)
413 (defgroup org-sparse-trees nil
414 "Options concerning sparse trees in Org-mode."
415 :tag "Org Sparse Trees"
416 :group 'org-structure)
418 (defcustom org-highlight-sparse-tree-matches t
419 "Non-nil means, highlight all matches that define a sparse tree.
420 The highlights will automatically disappear the next time the buffer is
421 changed by an edit command."
422 :group 'org-sparse-trees
423 :type 'boolean)
425 (defcustom org-show-hierarchy-above t
426 "Non-nil means, show full hierarchy when showing a spot in the tree.
427 Turning this off makes sparse trees more compact, but also less clear."
428 :group 'org-sparse-trees
429 :type 'boolean)
431 (defcustom org-show-following-heading t
432 "Non-nil means, show heading following match in `org-occur'.
433 When doing an `org-occur' it is useful to show the headline which
434 follows the match, even if they do not match the regexp. This makes it
435 easier to edit directly inside the sparse tree. However, if you use
436 `org-occur' mainly as an overview, the following headlines are
437 unnecessary clutter."
438 :group 'org-sparse-trees
439 :type 'boolean)
441 (defcustom org-occur-hook '(org-first-headline-recenter)
442 "Hook that is run after `org-occur' has constructed a sparse tree.
443 This can be used to recenter the window to show as much of the structure
444 as possible."
445 :group 'org-sparse-trees
446 :type 'hook)
448 (defgroup org-plain-lists nil
449 "Options concerning plain lists in Org-mode."
450 :tag "Org Plain lists"
451 :group 'org-structure)
453 (defcustom org-cycle-include-plain-lists nil
454 "Non-nil means, include plain lists into visibility cycling.
455 This means that during cycling, plain list items will *temporarily* be
456 interpreted as outline headlines with a level given by 1000+i where i is the
457 indentation of the bullet. In all other operations, plain list items are
458 not seen as headlines. For example, you cannot assign a TODO keyword to
459 such an item."
460 :group 'org-plain-lists
461 :type 'boolean)
464 (defcustom org-plain-list-ordered-item-terminator t
465 "The character that makes a line with leading number an ordered list item.
466 Valid values are ?. and ?\). To get both terminators, use t. While
467 ?. may look nicer, it creates the danger that a line with leading
468 number may be incorrectly interpreted as an item. ?\) therefore is
469 the safe choice."
470 :group 'org-plain-lists
471 :type '(choice (const :tag "dot like in \"2.\"" ?.)
472 (const :tag "paren like in \"2)\"" ?\))
473 (const :tab "both" t)))
475 (defcustom org-auto-renumber-ordered-lists t
476 "Non-nil means, automatically renumber ordered plain lists.
477 Renumbering happens when the sequence have been changed with
478 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
479 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
480 :group 'org-plain-lists
481 :type 'boolean)
483 (defgroup org-archive nil
484 "Options concerning archiving in Org-mode."
485 :tag "Org Archive"
486 :group 'org-structure)
488 (defcustom org-archive-location "%s_archive::"
489 "The location where subtrees should be archived.
490 This string consists of two parts, separated by a double-colon.
492 The first part is a file name - when omitted, archiving happens in the same
493 file. %s will be replaced by the current file name (without directory part).
494 Archiving to a different file is useful to keep archived entries from
495 contributing to the Org-mode Agenda.
497 The part after the double colon is a headline. The archived entries will be
498 filed under that headline. When omitted, the subtrees are simply filed away
499 at the end of the file, as top-level entries.
501 Here are a few examples:
502 \"%s_archive::\"
503 If the current file is Projects.org, archive in file
504 Projects.org_archive, as top-level trees. This is the default.
506 \"::* Archived Tasks\"
507 Archive in the current file, under the top-level headline
508 \"* Archived Tasks\".
510 \"~/org/archive.org::\"
511 Archive in file ~/org/archive.org (absolute path), as top-level trees.
513 \"basement::** Finished Tasks\"
514 Archive in file ./basement (relative path), as level 3 trees
515 below the level 2 heading \"** Finished Tasks\".
517 You may set this option on a per-file basis by adding to the buffer a
518 line like
520 #+ARCHIVE: basement::** Finished Tasks"
521 :group 'org-archive
522 :type 'string)
524 (defcustom org-archive-mark-done t
525 "Non-nil means, mark archived entries as DONE."
526 :group 'org-archive
527 :type 'boolean)
529 (defcustom org-archive-stamp-time t
530 "Non-nil means, add a time stamp to archived entries.
531 The time stamp will be added directly after the TODO state keyword in the
532 first line, so it is probably best to use this in combinations with
533 `org-archive-mark-done'."
534 :group 'org-archive
535 :type 'boolean)
537 (defgroup org-table nil
538 "Options concerning tables in Org-mode."
539 :tag "Org Table"
540 :group 'org)
542 (defcustom org-enable-table-editor 'optimized
543 "Non-nil means, lines starting with \"|\" are handled by the table editor.
544 When nil, such lines will be treated like ordinary lines.
546 When equal to the symbol `optimized', the table editor will be optimized to
547 do the following:
548 - Use automatic overwrite mode in front of whitespace in table fields.
549 This make the structure of the table stay in tact as long as the edited
550 field does not exceed the column width.
551 - Minimize the number of realigns. Normally, the table is aligned each time
552 TAB or RET are pressed to move to another field. With optimization this
553 happens only if changes to a field might have changed the column width.
554 Optimization requires replacing the functions `self-insert-command',
555 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
556 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
557 very good at guessing when a re-align will be necessary, but you can always
558 force one with \\[org-ctrl-c-ctrl-c].
560 If you would like to use the optimized version in Org-mode, but the
561 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
563 This variable can be used to turn on and off the table editor during a session,
564 but in order to toggle optimization, a restart is required.
566 See also the variable `org-table-auto-blank-field'."
567 :group 'org-table
568 :type '(choice
569 (const :tag "off" nil)
570 (const :tag "on" t)
571 (const :tag "on, optimized" optimized)))
573 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
574 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
575 In the optimized version, the table editor takes over all simple keys that
576 normally just insert a character. In tables, the characters are inserted
577 in a way to minimize disturbing the table structure (i.e. in overwrite mode
578 for empty fields). Outside tables, the correct binding of the keys is
579 restored.
581 The default for this option is t if the optimized version is also used in
582 Org-mode. See the variable `org-enable-table-editor' for details. Changing
583 this variable requires a restart of Emacs to become effective."
584 :group 'org-table
585 :type 'boolean)
587 (defgroup org-table-settings nil
588 "Settings for tables in Org-mode."
589 :tag "Org Table Settings"
590 :group 'org-table)
592 (defcustom org-table-default-size "5x2"
593 "The default size for newly created tables, Columns x Rows."
594 :group 'org-table-settings
595 :type 'string)
597 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
598 "Regular expression for recognizing numbers in table columns.
599 If a table column contains mostly numbers, it will be aligned to the
600 right. If not, it will be aligned to the left.
602 The default value of this option is a regular expression which allows
603 anything which looks remotely like a number as used in scientific
604 context. For example, all of the following will be considered a
605 number:
606 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
608 Other options offered by the customize interface are more restrictive."
609 :group 'org-table-settings
610 :type '(choice
611 (const :tag "Positive Integers"
612 "^[0-9]+$")
613 (const :tag "Integers"
614 "^[-+]?[0-9]+$")
615 (const :tag "Floating Point Numbers"
616 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
617 (const :tag "Floating Point Number or Integer"
618 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
619 (const :tag "Exponential, Floating point, Integer"
620 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
621 (const :tag "Very General Number-Like"
622 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
623 (string :tag "Regexp:")))
625 (defcustom org-table-number-fraction 0.5
626 "Fraction of numbers in a column required to make the column align right.
627 In a column all non-white fields are considered. If at least this
628 fraction of fields is matched by `org-table-number-fraction',
629 alignment to the right border applies."
630 :group 'org-table-settings
631 :type 'number)
633 (defgroup org-table-editing nil
634 "Bahavior of tables during editing in Org-mode."
635 :tag "Org Table Editing"
636 :group 'org-table)
638 (defcustom org-table-automatic-realign t
639 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
640 When nil, aligning is only done with \\[org-table-align], or after column
641 removal/insertion."
642 :group 'org-table-editing
643 :type 'boolean)
645 (defcustom org-table-limit-column-width t ;kw
646 "Non-nil means, allow to limit the width of table columns with <N> fields."
647 :group 'org-table-editing
648 :type 'boolean)
650 (defcustom org-table-auto-blank-field t
651 "Non-nil means, automatically blank table field when starting to type into it.
652 This only happens when typing immediately after a field motion
653 command (TAB, S-TAB or RET).
654 Only relevant when `org-enable-table-editor' is equal to `optimized'."
655 :group 'org-table-editing
656 :type 'boolean)
658 (defcustom org-table-tab-jumps-over-hlines t
659 "Non-nil means, tab in the last column of a table with jump over a hline.
660 If a horizontal separator line is following the current line,
661 `org-table-next-field' can either create a new row before that line, or jump
662 over the line. When this option is nil, a new line will be created before
663 this line."
664 :group 'org-table-editing
665 :type 'boolean)
667 (defcustom org-table-tab-recognizes-table.el t
668 "Non-nil means, TAB will automatically notice a table.el table.
669 When it sees such a table, it moves point into it and - if necessary -
670 calls `table-recognize-table'."
671 :group 'org-table-editing
672 :type 'boolean)
674 (defgroup org-table-calculation nil
675 "Options concerning tables in Org-mode."
676 :tag "Org Table Calculation"
677 :group 'org-table)
679 (defcustom org-table-copy-increment t
680 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
681 :group 'org-table-calculation
682 :type 'boolean)
684 (defcustom org-calc-default-modes
685 '(calc-internal-prec 12
686 calc-float-format (float 5)
687 calc-angle-mode deg
688 calc-prefer-frac nil
689 calc-symbolic-mode nil
690 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
691 calc-display-working-message t
693 "List with Calc mode settings for use in calc-eval for table formulas.
694 The list must contain alternating symbols (Calc modes variables and values).
695 Don't remove any of the default settings, just change the values. Org-mode
696 relies on the variables to be present in the list."
697 :group 'org-table-calculation
698 :type 'plist)
700 (defcustom org-table-formula-evaluate-inline t
701 "Non-nil means, TAB and RET evaluate a formula in current table field.
702 If the current field starts with an equal sign, it is assumed to be a formula
703 which should be evaluated as described in the manual and in the documentation
704 string of the command `org-table-eval-formula'. This feature requires the
705 Emacs calc package.
706 When this variable is nil, formula calculation is only available through
707 the command \\[org-table-eval-formula]."
708 :group 'org-table-calculation
709 :type 'boolean)
712 (defcustom org-table-formula-use-constants t
713 "Non-nil means, interpret constants in formulas in tables.
714 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
715 by the value given in `org-table-formula-constants', or by a value obtained
716 from the `constants.el' package."
717 :group 'org-table-calculation
718 :type 'boolean)
720 (defcustom org-table-formula-constants nil
721 "Alist with constant names and values, for use in table formulas.
722 The car of each element is a name of a constant, without the `$' before it.
723 The cdr is the value as a string. For example, if you'd like to use the
724 speed of light in a formula, you would configure
726 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
728 and then use it in an equation like `$1*$c'."
729 :group 'org-table-calculation
730 :type '(repeat
731 (cons (string :tag "name")
732 (string :tag "value"))))
734 (defcustom org-table-formula-numbers-only nil
735 "Non-nil means, calculate only with numbers in table formulas.
736 Then all input fields will be converted to a number, and the result
737 must also be a number. When nil, calc's full potential is available
738 in table calculations, including symbolics etc."
739 :group 'org-table-calculation
740 :type 'boolean)
742 (defcustom org-table-allow-automatic-line-recalculation t
743 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
744 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
745 :group 'org-table-calculation
746 :type 'boolean)
748 (defgroup org-link nil
749 "Options concerning links in Org-mode."
750 :tag "Org Link"
751 :group 'org)
753 (defcustom org-descriptive-links t
754 "Non-nil means, hide link part and only show description of bracket links.
755 Bracket links are like [[link][descritpion]]. This variable sets the initial
756 state in new org-mode buffers. The setting can then be toggled on a
757 per-buffer basis from the Org->Hyperlinks menu."
758 :group 'org-link
759 :type 'boolean)
761 (defcustom org-link-style 'bracket
762 "The style of links to be inserted with \\[org-insert-link].
763 Possible values are:
764 bracket [[link][description]]. This is recommended
765 plain Description \\n link. The old way, no longer recommended."
766 :group 'org-link
767 :type '(choice
768 (const :tag "Bracket (recommended)" bracket)
769 (const :tag "Plain (no longer recommended)" plain)))
771 (defcustom org-link-format "%s"
772 "Default format for external, URL-like linkes in the buffer.
773 This is a format string for printf, %s will be replaced by the link text.
774 The recommended value is just \"%s\", since links will be protected by
775 enclosing them in double brackets. If you prefer plain links (see variable
776 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
777 additional URL: prefix, so the format would be \"<URL:%s>\"."
778 :group 'org-link
779 :type '(choice
780 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
781 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
782 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
783 (string :tag "Other" :value "<%s>")))
785 (defcustom org-activate-links '(bracket angle plain radio tag date)
786 "Types of links that should be activated in Org-mode files.
787 This is a list of symbols, each leading to the activation of a certain link
788 type. In principle, it does not hurt to turn on most link types - there may
789 be a small gain when turning off unused link types. The types are:
791 bracket The recommended [[link][description]] or [[link]] links with hiding.
792 angular Links in angular brackes that may contain whitespace like
793 <bbdb:Carsten Dominik>.
794 plain Plain links in normal text, no whitespace, like http://google.com.
795 radio Text that is matched by a radio target, see manual for details.
796 tag Tag settings in a headline (link to tag search).
797 date Time stamps (link to calendar).
798 camel CamelCase words defining text searches.
800 Changing this variable requires a restart of Emacs to become effective."
801 :group 'org-link
802 :type '(set (const :tag "Double bracket links (new style)" bracket)
803 (const :tag "Angular bracket links (old style)" angular)
804 (const :tag "plain text links" plain)
805 (const :tag "Radio target matches" radio)
806 (const :tag "Tags" tag)
807 (const :tag "Timestamps" date)
808 (const :tag "CamelCase words" camel)))
810 (defgroup org-link-store nil
811 "Options concerning storing links in Org-mode"
812 :tag "Org Store Link"
813 :group 'org-link)
815 (defcustom org-context-in-file-links t
816 "Non-nil means, file links from `org-store-link' contain context.
817 A search string will be added to the file name with :: as separator and
818 used to find the context when the link is activated by the command
819 `org-open-at-point'.
820 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
821 negates this setting for the duration of the command."
822 :group 'org-link-store
823 :type 'boolean)
825 (defcustom org-file-link-context-use-camel-case nil
826 "Non-nil means, use CamelCase to store a search context in a file link.
827 When nil, the search string simply consists of the words of the string.
828 CamelCase is deprecated, and support for it may be dropped in the future."
829 :group 'org-link-store
830 :type 'boolean)
832 (defcustom org-keep-stored-link-after-insertion nil
833 "Non-nil means, keep link in list for entire session.
835 The command `org-store-link' adds a link pointing to the current
836 location to an internal list. These links accumulate during a session.
837 The command `org-insert-link' can be used to insert links into any
838 Org-mode file (offering completion for all stored links). When this
839 option is nil, every link which has been inserted once using \\[org-insert-link]
840 will be removed from the list, to make completing the unused links
841 more efficient."
842 :group 'org-link-store
843 :type 'boolean)
845 (defcustom org-usenet-links-prefer-google nil
846 "Non-nil means, `org-store-link' will create web links to Google groups.
847 When nil, Gnus will be used for such links.
848 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
849 negates this setting for the duration of the command."
850 :group 'org-link-store
851 :type 'boolean)
853 (defgroup org-link-follow nil
854 "Options concerning following links in Org-mode"
855 :tag "Org Follow Link"
856 :group 'org-link)
858 (defcustom org-tab-follows-link nil
859 "Non-nil means, on links TAB will follow the link.
860 Needs to be set before org.el is loaded."
861 :group 'org-link-follow
862 :type 'boolean)
864 (defcustom org-return-follows-link nil
865 "Non-nil means, on links RET will follow the link.
866 Needs to be set before org.el is loaded."
867 :group 'org-link-follow
868 :type 'boolean)
870 (defcustom org-mark-ring-length 4
871 "Number of different positions to be recorded in the ring
872 Changing this requires a restart of Emacs to work correctly."
873 :group 'org-link-follow
874 :type 'interger)
876 (defcustom org-link-frame-setup
877 '((vm . vm-visit-folder-other-frame)
878 (gnus . gnus-other-frame)
879 (file . find-file-other-window))
880 "Setup the frame configuration for following links.
881 When following a link with Emacs, it may often be useful to display
882 this link in another window or frame. This variable can be used to
883 set this up for the different types of links.
884 For VM, use any of
885 `vm-visit-folder'
886 `vm-visit-folder-other-frame'
887 For Gnus, use any of
888 `gnus'
889 `gnus-other-frame'
890 For FILE, use any of
891 `find-file'
892 `find-file-other-window'
893 `find-file-other-frame'
894 For the calendar, use the variable `calendar-setup'.
895 For BBDB, it is currently only possible to display the matches in
896 another window."
897 :group 'org-link-follow
898 :type '(list
899 (cons (const vm)
900 (choice
901 (const vm-visit-folder)
902 (const vm-visit-folder-other-window)
903 (const vm-visit-folder-other-frame)))
904 (cons (const gnus)
905 (choice
906 (const gnus)
907 (const gnus-other-frame)))
908 (cons (const file)
909 (choice
910 (const find-file)
911 (const find-file-other-window)
912 (const find-file-other-frame)))))
914 (defcustom org-open-non-existing-files nil
915 "Non-nil means, `org-open-file' will open non-existing file.
916 When nil, an error will be generated."
917 :group 'org-link-follow
918 :type 'boolean)
920 (defcustom org-confirm-shell-links 'yes-or-no-p
921 "Non-nil means, ask for confirmation before executing shell links.
922 Shell links can be dangerous, just thing about a link
924 [[shell:rm -rf ~/*][Google Search]]
926 This link would show up in your Org-mode document as \"Google Search\"
927 but really it would remove your entire home directory. Dangerous indeed.
928 Therefore I *definitely* advise agains setting this varaiable to nil.
929 Just change it to `y-or-n-p' of you want to confirm with a single key press
930 rather than having to type \"yes\"."
931 :group 'org-link-follow
932 :type '(choice
933 (const :tag "with yes-or-no (safer)" yes-or-no-p)
934 (const :tag "with y-or-n (faster)" y-or-n-p)
935 (const :tag "no confirmation (dangerous)" nil)))
937 (defconst org-file-apps-defaults-gnu
938 '((t . mailcap))
939 "Default file applications on a UNIX or GNU/Linux system.
940 See `org-file-apps'.")
942 (defconst org-file-apps-defaults-macosx
943 '((t . "open %s")
944 ("ps" . "gv %s")
945 ("ps.gz" . "gv %s")
946 ("eps" . "gv %s")
947 ("eps.gz" . "gv %s")
948 ("dvi" . "xdvi %s")
949 ("fig" . "xfig %s"))
950 "Default file applications on a MacOS X system.
951 The system \"open\" is known as a default, but we use X11 applications
952 for some files for which the OS does not have a good default.
953 See `org-file-apps'.")
955 (defconst org-file-apps-defaults-windowsnt
956 '((t . (w32-shell-execute "open" file)))
957 "Default file applications on a Windows NT system.
958 The system \"open\" is used for most files.
959 See `org-file-apps'.")
961 (defcustom org-file-apps
963 ("txt" . emacs)
964 ("tex" . emacs)
965 ("ltx" . emacs)
966 ("org" . emacs)
967 ("el" . emacs)
969 "External applications for opening `file:path' items in a document.
970 Org-mode uses system defaults for different file types, but
971 you can use this variable to set the application for a given file
972 extension. The entries in this list are cons cells with a file extension
973 and the corresponding command. Possible values for the command are:
974 `emacs' The file will be visited by the current Emacs process.
975 `default' Use the default application for this file type.
976 string A command to be executed by a shell; %s will be replaced
977 by the path to the file.
978 sexp A Lisp form which will be evaluated. The file path will
979 be available in the Lisp variable `file'.
980 For more examples, see the system specific constants
981 `org-file-apps-defaults-macosx'
982 `org-file-apps-defaults-windowsnt'
983 `org-file-apps-defaults-gnu'."
984 :group 'org-link-follow
985 :type '(repeat
986 (cons (choice :value ""
987 (string :tag "Extension")
988 (const :tag "Default for unrecognized files" t)
989 (const :tag "Links to a directory" directory))
990 (choice :value ""
991 (const :tag "Visit with Emacs" emacs)
992 (const :tag "Use system default" default)
993 (string :tag "Command")
994 (sexp :tag "Lisp form")))))
996 (defcustom org-mhe-search-all-folders nil
997 "Non-nil means, that the search for the mh-message will be extended to
998 all folders if the message cannot be found in the folder given in the link.
999 Searching all folders is very effective with one of the search engines
1000 supported by MH-E, but will be slow with pick."
1001 :group 'org-link-follow
1002 :type 'boolean)
1004 (defgroup org-remember nil
1005 "Options concerning interaction with remember.el."
1006 :tag "Org Remember"
1007 :group 'org)
1009 (defcustom org-directory "~/org"
1010 "Directory with org files.
1011 This directory will be used as default to prompt for org files.
1012 Used by the hooks for remember.el."
1013 :group 'org-remember
1014 :type 'directory)
1016 (defcustom org-default-notes-file "~/.notes"
1017 "Default target for storing notes.
1018 Used by the hooks for remember.el. This can be a string, or nil to mean
1019 the value of `remember-data-file'."
1020 :group 'org-remember
1021 :type '(choice
1022 (const :tag "Default from remember-data-file" nil)
1023 file))
1025 (defcustom org-remember-templates nil
1026 "Templates for the creation of remember buffers.
1027 When nil, just let remember make the buffer.
1028 When not nil, this is a list of 3-element lists. In each entry, the first
1029 element is a character, a unique key to select this template.
1030 The second element is the template. The third element is optional and can
1031 specify a destination file for remember items created with this template.
1032 The default file is given by `org-default-notes-file'.
1034 The template specifies the structure of the remember buffer. It should have
1035 a first line starting with a star, to act as the org-mode headline.
1036 Furthermore, the following %-escapes will be replaced with content:
1037 %t time stamp, date only
1038 %T time stamp with date and time
1039 %u inactive time stamp, date only
1040 %U inactive time stamp with date and time
1041 %n user name
1042 %a annotation, normally the link created with org-store-link
1043 %i initial content, the region when remember is called with C-u.
1044 If %i is indented, the entire inserted text will be indented as well.
1045 %? This will be removed, and the cursor placed at this position."
1046 :group 'org-remember
1047 :type '(repeat :tag "enabled"
1048 (list :value (?a "\n" nil)
1049 (character :tag "Selection Key")
1050 (string :tag "Template")
1051 (file :tag "Destination file (optional)"))))
1053 (defcustom org-reverse-note-order nil
1054 "Non-nil means, store new notes at the beginning of a file or entry.
1055 When nil, new notes will be filed to the end of a file or entry."
1056 :group 'org-remember
1057 :type '(choice
1058 (const :tag "Reverse always" t)
1059 (const :tag "Reverse never" nil)
1060 (repeat :tag "By file name regexp"
1061 (cons regexp boolean))))
1063 (defgroup org-todo nil
1064 "Options concerning TODO items in Org-mode."
1065 :tag "Org TODO"
1066 :group 'org)
1068 (defcustom org-todo-keywords '("TODO" "DONE")
1069 "List of TODO entry keywords.
1070 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1071 considered to mean that the entry is \"done\". All the other mean that
1072 action is required, and will make the entry show up in todo lists, diaries
1073 etc.
1074 The command \\[org-todo] cycles an entry through these states, and an
1075 additional state where no keyword is present. For details about this
1076 cycling, see also the variable `org-todo-interpretation'
1077 Changes become only effective after restarting Emacs."
1078 :group 'org-todo
1079 :group 'org-keywords
1080 :type '(repeat (string :tag "Keyword")))
1082 (defcustom org-todo-interpretation 'sequence
1083 "Controls how TODO keywords are interpreted.
1084 This variable is only relevant if `org-todo-keywords' contains more than two
1085 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1087 When `sequence', \\[org-todo] will always switch to the next state in the
1088 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1089 to state when executed several times in direct succession. Otherwise, it
1090 switches directly to DONE from any state.
1091 See the manual for more information."
1092 :group 'org-todo
1093 :group 'org-keywords
1094 :type '(choice (const sequence)
1095 (const type)))
1097 (defcustom org-after-todo-state-change-hook nil
1098 "Hook which is run after the state of a TODO item was changed.
1099 The new state (a string with a TODO keyword, or nil) is available in the
1100 Lisp variable `state'."
1101 :group 'org-todo
1102 :type 'hook)
1104 (defcustom org-log-done nil
1105 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1106 When the state of an entry is changed from nothing to TODO, remove a previous
1107 closing date."
1108 :group 'org-todo
1109 :type 'boolean)
1111 (defgroup org-priorities nil
1112 "Keywords in Org-mode."
1113 :tag "Org Priorities"
1114 :group 'org-todo)
1116 (defcustom org-default-priority ?B
1117 "The default priority of TODO items.
1118 This is the priority an item get if no explicit priority is given."
1119 :group 'org-priorities
1120 :type 'character)
1122 (defcustom org-lowest-priority ?C
1123 "The lowest priority of TODO items. A character like ?A, ?B etc."
1124 :group 'org-priorities
1125 :type 'character)
1127 (defgroup org-time nil
1128 "Options concerning time stamps and deadlines in Org-mode."
1129 :tag "Org Time"
1130 :group 'org)
1132 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1133 "Formats for `format-time-string' which are used for time stamps.
1134 It is not recommended to change this constant.")
1136 (defcustom org-time-stamp-rounding-minutes 0
1137 "Number of minutes to round time stamps to upon insertion.
1138 When zero, insert the time unmodified. Useful rounding numbers
1139 should be factors of 60, so for example 5, 10, 15.
1140 When this is not zero, you can still force an exact time-stamp by using
1141 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1142 :group 'org-time
1143 :type 'integer)
1145 (defcustom org-deadline-warning-days 30
1146 "No. of days before expiration during which a deadline becomes active.
1147 This variable governs the display in the org file."
1148 :group 'org-time
1149 :type 'number)
1151 (defcustom org-popup-calendar-for-date-prompt t
1152 "Non-nil means, pop up a calendar when prompting for a date.
1153 In the calendar, the date can be selected with mouse-1. However, the
1154 minibuffer will also be active, and you can simply enter the date as well.
1155 When nil, only the minibuffer will be available."
1156 :group 'org-time
1157 :type 'boolean)
1159 (defcustom org-calendar-follow-timestamp-change t
1160 "Non-nil means, make the calendar window follow timestamp changes.
1161 When a timestamp is modified and the calendar window is visible, it will be
1162 moved to the new date."
1163 :group 'org-time
1164 :type 'boolean)
1166 (defgroup org-tags nil
1167 "Options concerning startup of Org-mode."
1168 :tag "Org Tags"
1169 :group 'org)
1171 (defcustom org-tags-column 48
1172 "The column to which tags should be indented in a headline.
1173 If this number is positive, it specifies the column. If it is negative,
1174 it means that the tags should be flushright to that column. For example,
1175 -79 works well for a normal 80 character screen."
1176 :group 'org-tags
1177 :type 'integer)
1179 (defcustom org-auto-align-tags t
1180 "Non-nil means, realign tags after pro/demotion of TODO state change.
1181 These operations change the length of a headline and therefore shift
1182 the tags around. With this options turned on, after each such operation
1183 the tags are again aligned to `org-tags-column'."
1184 :group 'org-tags
1185 :type 'boolean)
1187 (defcustom org-use-tag-inheritance t
1188 "Non-nil means, tags in levels apply also for sublevels.
1189 When nil, only the tags directly given in a specific line apply there.
1190 If you turn off this option, you very likely want to turn on the
1191 companion option `org-tags-match-list-sublevels'."
1192 :group 'org-tags
1193 :type 'boolean)
1195 (defcustom org-tags-match-list-sublevels nil
1196 "Non-nil means list also sublevels of headlines matching tag search.
1197 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1198 the sublevels of a headline matching a tag search often also match
1199 the same search. Listing all of them can create very long lists.
1200 Setting this variable to nil causes subtrees of a match to be skipped.
1201 This option is off by default, because inheritance in on. If you turn
1202 inheritance off, you very likely want to turn this option on.
1204 As a special case, if the tag search is restricted to TODO items, the
1205 value of this variable is ignored and sublevels are always checked, to
1206 make sure all corresponding TODO items find their way into the list."
1207 :group 'org-tags
1208 :type 'boolean)
1210 (defvar org-tags-history nil
1211 "History of minibuffer reads for tags.")
1212 (defvar org-last-tags-completion-table nil
1213 "The last used completion table for tags.")
1215 (defgroup org-agenda nil
1216 "Options concerning agenda display Org-mode."
1217 :tag "Org Agenda"
1218 :group 'org)
1220 (defvar org-category nil
1221 "Variable used by org files to set a category for agenda display.
1222 Such files should use a file variable to set it, for example
1224 -*- mode: org; org-category: \"ELisp\"
1226 or contain a special line
1228 #+CATEGORY: ELisp
1230 If the file does not specify a category, then file's base name
1231 is used instead.")
1232 (make-variable-buffer-local 'org-category)
1234 (defcustom org-agenda-files nil
1235 "The files to be used for agenda display.
1236 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1237 \\[org-remove-file]. You can also use customize to edit the list.
1239 If the value of the variable is not a list but a single file name, then
1240 the list of agenda files is actually stored and maintained in that file, one
1241 agenda file per line."
1242 :group 'org-agenda
1243 :type '(choice
1244 (repeat :tag "List of files" file)
1245 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1247 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1248 "Custom commands for the agenda.
1249 These commands will be offered on the splash screen displayed by the
1250 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1252 key The key (a single char as a string) to be associated with the command.
1253 type The command type, any of the following symbols:
1254 todo Entries with a specific TODO keyword, in all agenda files.
1255 tags Tags match in all agenda files.
1256 todo-tree Sparse tree of specific TODO keyword in *current* file.
1257 tags-tree Sparse tree with all tags matches in *current* file.
1258 occur-tree Occur sparse tree for current file.
1259 match What to search for:
1260 - a single keyword for TODO keyword searches
1261 - a tags match expression for tags searches
1262 - a regular expression for occur searches"
1263 :group 'org-agenda
1264 :type '(repeat
1265 (list (string :tag "Key")
1266 (choice :tag "Type"
1267 (const :tag "Tags search in all agenda files" tags)
1268 (const :tag "TODO keyword search in all agenda files" todo)
1269 (const :tag "Tags sparse tree in current buffer" tags-tree)
1270 (const :tag "TODO keyword tree in current buffer" todo-tree)
1271 (const :tag "Occur tree in current buffer" occur-tree))
1272 (string :tag "Match"))))
1274 (defcustom org-agenda-include-all-todo t
1275 "Non-nil means, the agenda will always contain all TODO entries.
1276 When nil, date-less entries will only be shown if `org-agenda' is called
1277 with a prefix argument.
1278 When non-nil, the TODO entries will be listed at the top of the agenda, before
1279 the entries for specific days."
1280 :group 'org-agenda
1281 :type 'boolean)
1283 (defcustom org-agenda-include-diary nil
1284 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1285 :group 'org-agenda
1286 :type 'boolean)
1288 (defcustom org-calendar-to-agenda-key [?c]
1289 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1290 The command `org-calendar-goto-agenda' will be bound to this key. The
1291 default is the character `c' because then `c' can be used to switch back and
1292 forth between agenda and calendar."
1293 :group 'org-agenda
1294 :type 'sexp)
1296 (defgroup org-agenda-window-setup nil
1297 "Options concerning setting up the Agenda window in Org Mode."
1298 :tag "Org Agenda Window Setup"
1299 :group 'org-agenda)
1301 (defcustom org-select-timeline-window t
1302 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1303 When nil, cursor will remain in the current window."
1304 :group 'org-agenda-window-setup
1305 :type 'boolean)
1307 (defcustom org-select-agenda-window t
1308 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1309 When nil, cursor will remain in the current window."
1310 :group 'org-agenda-window-setup
1311 :type 'boolean)
1313 (defcustom org-fit-agenda-window t
1314 "Non-nil means, change window size of agenda to fit content."
1315 :group 'org-agenda-window-setup
1316 :type 'boolean)
1318 (defgroup org-agenda-display nil
1319 "Options concerning what to display initially in Agenda."
1320 :tag "Org Agenda Display"
1321 :group 'org-agenda)
1323 (defcustom org-agenda-show-all-dates t
1324 "Non-nil means, `org-agenda' shows every day in the selected range.
1325 When nil, only the days which actually have entries are shown."
1326 :group 'org-agenda-display
1327 :type 'boolean)
1329 (defcustom org-agenda-start-on-weekday 1
1330 "Non-nil means, start the overview always on the specified weekday.
1331 0 denotes Sunday, 1 denotes Monday etc.
1332 When nil, always start on the current day."
1333 :group 'org-agenda-display
1334 :type '(choice (const :tag "Today" nil)
1335 (number :tag "Weekday No.")))
1337 (defcustom org-agenda-ndays 7
1338 "Number of days to include in overview display.
1339 Should be 1 or 7."
1340 :group 'org-agenda-display
1341 :type 'number)
1343 (defcustom org-agenda-use-time-grid t
1344 "Non-nil means, show a time grid in the agenda schedule.
1345 A time grid is a set of lines for specific times (like every two hours between
1346 8:00 and 20:00). The items scheduled for a day at specific times are
1347 sorted in between these lines.
1348 For details about when the grid will be shown, and what it will look like, see
1349 the variable `org-agenda-time-grid'."
1350 :group 'org-agenda-display
1351 :type 'boolean)
1353 (defcustom org-agenda-time-grid
1354 '((daily today require-timed)
1355 "----------------"
1356 (800 1000 1200 1400 1600 1800 2000))
1358 "The settings for time grid for agenda display.
1359 This is a list of three items. The first item is again a list. It contains
1360 symbols specifying conditions when the grid should be displayed:
1362 daily if the agenda shows a single day
1363 weekly if the agenda shows an entire week
1364 today show grid on current date, independent of daily/weekly display
1365 require-timed show grid only if at least on item has a time specification
1367 The second item is a string which will be places behing the grid time.
1369 The third item is a list of integers, indicating the times that should have
1370 a grid line."
1371 :group 'org-agenda-display
1372 :type
1373 '(list
1374 (set :greedy t :tag "Grid Display Options"
1375 (const :tag "Show grid in single day agenda display" daily)
1376 (const :tag "Show grid in weekly agenda display" weekly)
1377 (const :tag "Always show grid for today" today)
1378 (const :tag "Show grid only if any timed entries are present"
1379 require-timed)
1380 (const :tag "Skip grid times already present in an entry"
1381 remove-match))
1382 (string :tag "Grid String")
1383 (repeat :tag "Grid Times" (integer :tag "Time"))))
1385 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1386 "Sorting structure for the agenda items of a single day.
1387 This is a list of symbols which will be used in sequence to determine
1388 if an entry should be listed before another entry. The following
1389 symbols are recognized:
1391 time-up Put entries with time-of-day indications first, early first
1392 time-down Put entries with time-of-day indications first, late first
1393 category-keep Keep the default order of categories, corresponding to the
1394 sequence in `org-agenda-files'.
1395 category-up Sort alphabetically by category, A-Z.
1396 category-down Sort alphabetically by category, Z-A.
1397 priority-up Sort numerically by priority, high priority last.
1398 priority-down Sort numerically by priority, high priority first.
1400 The different possibilities will be tried in sequence, and testing stops
1401 if one comparison returns a \"not-equal\". For example, the default
1402 '(time-up category-keep priority-down)
1403 means: Pull out all entries having a specified time of day and sort them,
1404 in order to make a time schedule for the current day the first thing in the
1405 agenda listing for the day. Of the entries without a time indication, keep
1406 the grouped in categories, don't sort the categories, but keep them in
1407 the sequence given in `org-agenda-files'. Within each category sort by
1408 priority.
1410 Leaving out `category-keep' would mean that items will be sorted across
1411 categories by priority."
1412 :group 'org-agenda-display
1413 :type '(repeat
1414 (choice
1415 (const time-up)
1416 (const time-down)
1417 (const category-keep)
1418 (const category-up)
1419 (const category-down)
1420 (const priority-up)
1421 (const priority-down))))
1423 (defcustom org-sort-agenda-notime-is-late t
1424 "Non-nil means, items without time are considered late.
1425 This is only relevant for sorting. When t, items which have no explicit
1426 time like 15:30 will be considered as 24:01, i.e. later than any items which
1427 do have a time. When nil, the default time is before 0:00. You can use this
1428 option to decide if the schedule for today should come before or after timeless
1429 agenda entries."
1430 :group 'org-agenda-display
1431 :type 'boolean)
1434 (defgroup org-agenda-prefix nil
1435 "Options concerning the entry prefix in the Org-mode agenda display."
1436 :tag "Org Agenda Prefix"
1437 :group 'org-agenda)
1439 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1440 "Format specification for the prefix of items in the agenda buffer.
1441 This format works similar to a printf format, with the following meaning:
1443 %c the category of the item, \"Diary\" for entries from the diary, or
1444 as given by the CATEGORY keyword or derived from the file name.
1445 %T the first tag of the item.
1446 %t the time-of-day specification if one applies to the entry, in the
1447 format HH:MM
1448 %s Scheduling/Deadline information, a short string
1450 All specifiers work basically like the standard `%s' of printf, but may
1451 contain two additional characters: A question mark just after the `%' and
1452 a whitespace/punctuation character just before the final letter.
1454 If the first character after `%' is a question mark, the entire field
1455 will only be included if the corresponding value applies to the
1456 current entry. This is useful for fields which should have fixed
1457 width when present, but zero width when absent. For example,
1458 \"%?-12t\" will result in a 12 character time field if a time of the
1459 day is specified, but will completely disappear in entries which do
1460 not contain a time.
1462 If there is punctuation or whitespace character just before the final
1463 format letter, this character will be appended to the field value if
1464 the value is not empty. For example, the format \"%-12:c\" leads to
1465 \"Diary: \" if the category is \"Diary\". If the category were be
1466 empty, no additional colon would be interted.
1468 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1469 - Indent the line with two space characters
1470 - Give the category in a 12 chars wide field, padded with whitespace on
1471 the right (because of `-'). Append a colon if there is a category
1472 (because of `:').
1473 - If there is a time-of-day, put it into a 12 chars wide field. If no
1474 time, don't put in an empty field, just skip it (because of '?').
1475 - Finally, put the scheduling information and append a whitespace.
1477 As another example, if you don't want the time-of-day of entries in
1478 the prefix, you could use:
1480 (setq org-agenda-prefix-format \" %-11:c% s\")
1482 See also the variables `org-agenda-remove-times-when-in-prefix' and
1483 `org-agenda-remove-tags-when-in-prefix'."
1484 :type 'string
1485 :group 'org-agenda-prefix)
1487 (defcustom org-timeline-prefix-format " % s"
1488 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1489 :type 'string
1490 :group 'org-agenda-prefix)
1492 (defvar org-prefix-format-compiled nil
1493 "The compiled version of the most recently used prefix format.
1494 Depending on which command was used last, this may be the compiled version
1495 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1497 ;; FIXME: There seem to be situations where this does no work.
1498 (defcustom org-agenda-remove-times-when-in-prefix t
1499 "Non-nil means, remove duplicate time specifications in agenda items.
1500 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1501 time-of-day specification in a headline or diary entry is extracted and
1502 placed into the prefix. If this option is non-nil, the original specification
1503 \(a timestamp or -range, or just a plain time(range) specification like
1504 11:30-4pm) will be removed for agenda display. This makes the agenda less
1505 cluttered.
1506 The option can be t or nil. It may also be the symbol `beg', indicating
1507 that the time should only be removed what it is located at the beginning of
1508 the headline/diary entry."
1509 :group 'org-agenda-prefix
1510 :type '(choice
1511 (const :tag "Always" t)
1512 (const :tag "Never" nil)
1513 (const :tag "When at beginning of entry" beg)))
1515 (defcustom org-agenda-remove-tags-when-in-prefix nil
1516 "Non-nil means, remove the tags from the headline copy in the agenda.
1517 When this is the symbol `prefix', only remove tags when
1518 `org-agenda-prefix-format' contains a `%T' specifier."
1519 :group 'org-agenda-prefix
1520 :type '(choice
1521 (const :tag "Always" t)
1522 (const :tag "Never" nil)
1523 (const :tag "When prefix format contains %T" prefix)))
1525 (defgroup org-export nil
1526 "Options for exporting org-listings."
1527 :tag "Org Export"
1528 :group 'org)
1530 (defgroup org-export-general nil
1531 "General options for exporting Org-mode files."
1532 :tag "Org Export General"
1533 :group 'org-export)
1535 (defcustom org-export-language-setup
1536 '(("en" "Author" "Date" "Table of Contents")
1537 ("da" "Ophavsmand" "Dato" "Indhold")
1538 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1539 ("es" "Autor" "Fecha" "\xccndice")
1540 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1541 ("it" "Autore" "Data" "Indice")
1542 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1543 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1544 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1545 "Terms used in export text, translated to different languages.
1546 Use the variable `org-export-default-language' to set the language,
1547 or use the +OPTION lines for a per-file setting."
1548 :group 'org-export-general
1549 :type '(repeat
1550 (list
1551 (string :tag "HTML language tag")
1552 (string :tag "Author")
1553 (string :tag "Date")
1554 (string :tag "Table of Contents"))))
1556 (defcustom org-export-default-language "en"
1557 "The default language of HTML export, as a string.
1558 This should have an association in `org-export-language-setup'."
1559 :group 'org-export-general
1560 :type 'string)
1562 (defcustom org-export-headline-levels 3
1563 "The last level which is still exported as a headline.
1564 Inferior levels will produce itemize lists when exported.
1565 Note that a numeric prefix argument to an exporter function overrides
1566 this setting.
1568 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1569 :group 'org-export-general
1570 :type 'number)
1572 (defcustom org-export-with-section-numbers t
1573 "Non-nil means, add section numbers to headlines when exporting.
1575 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1576 :group 'org-export-general
1577 :type 'boolean)
1579 (defcustom org-export-with-toc t
1580 "Non-nil means, create a table of contents in exported files.
1581 The TOC contains headlines with levels up to`org-export-headline-levels'.
1583 Headlines which contain any TODO items will be marked with \"(*)\" in
1584 ASCII export, and with red color in HTML output.
1586 In HTML output, the TOC will be clickable.
1588 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1589 :group 'org-export-general
1590 :type 'boolean)
1592 (defcustom org-export-mark-todo-in-toc nil
1593 "Non-nil means, mark TOC lines that contain any open TODO items."
1594 :group 'org-export-general
1595 :type 'boolean)
1597 (defcustom org-export-preserve-breaks nil
1598 "Non-nil means, preserve all line breaks when exporting.
1599 Normally, in HTML output paragraphs will be reformatted. In ASCII
1600 export, line breaks will always be preserved, regardless of this variable.
1602 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1603 :group 'org-export-general
1604 :type 'boolean)
1606 (defgroup org-export-translation nil
1607 "Options for translating special ascii sequences for the export backends."
1608 :tag "Org Export Translation"
1609 :group 'org-export)
1611 (defcustom org-export-with-emphasize t
1612 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1613 If the export target supports emphasizing text, the word will be
1614 typeset in bold, italic, or underlined, respectively. Works only for
1615 single words, but you can say: I *really* *mean* *this*.
1616 Not all export backends support this.
1618 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1619 :group 'org-export-translation
1620 :type 'boolean)
1622 (defcustom org-export-with-sub-superscripts t
1623 "Non-nil means, interpret \"_\" and \"^\" for export.
1624 When this option is turned on, you can use TeX-like syntax for sub- and
1625 superscripts. Several characters after \"_\" or \"^\" will be
1626 considered as a single item - so grouping with {} is normally not
1627 needed. For example, the following things will be parsed as single
1628 sub- or superscripts.
1630 10^24 or 10^tau several digits will be considered 1 item.
1631 10^-12 or 10^-tau a leading sign with digits or a word
1632 x^2-y^3 will be read as x^2 - y^3, because items are
1633 terminated by almost any nonword/nondigit char.
1634 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1636 Still, ambiguity is possible - so when in doubt use {} to enclose the
1637 sub/superscript.
1638 Not all export backends support this, but HTML does.
1640 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1641 :group 'org-export-translation
1642 :type 'boolean)
1644 (defcustom org-export-with-TeX-macros t
1645 "Non-nil means, interpret simple TeX-like macros when exporting.
1646 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1647 No only real TeX macros will work here, but the standard HTML entities
1648 for math can be used as macro names as well. For a list of supported
1649 names in HTML export, see the constant `org-html-entities'.
1650 Not all export backends support this.
1652 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1653 :group 'org-export-translation
1654 :type 'boolean)
1656 (defcustom org-export-with-fixed-width t
1657 "Non-nil means, lines starting with \":\" will be in fixed width font.
1658 This can be used to have pre-formatted text, fragments of code etc. For
1659 example:
1660 : ;; Some Lisp examples
1661 : (while (defc cnt)
1662 : (ding))
1663 will be looking just like this in also HTML. See also the QUOTE keyword.
1664 Not all export backends support this.
1666 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1667 :group 'org-export-translation
1668 :type 'boolean)
1670 (defcustom org-match-sexp-depth 3
1671 "Number of stacked braces for sub/superscript matching.
1672 This has to be set before loading org.el to be effective."
1673 :group 'org-export-translation
1674 :type 'integer)
1676 (defgroup org-export-tables nil
1677 "Options for exporting tables in Org-mode."
1678 :tag "Org Export Tables"
1679 :group 'org-export)
1681 (defcustom org-export-with-tables t
1682 "If non-nil, lines starting with \"|\" define a table.
1683 For example:
1685 | Name | Address | Birthday |
1686 |-------------+----------+-----------|
1687 | Arthur Dent | England | 29.2.2100 |
1689 Not all export backends support this.
1691 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1692 :group 'org-export-tables
1693 :type 'boolean)
1695 (defcustom org-export-highlight-first-table-line t
1696 "Non-nil means, highlight the first table line.
1697 In HTML export, this means use <th> instead of <td>.
1698 In tables created with table.el, this applies to the first table line.
1699 In Org-mode tables, all lines before the first horizontal separator
1700 line will be formatted with <th> tags."
1701 :group 'org-export-tables
1702 :type 'boolean)
1704 (defcustom org-export-table-remove-special-lines t
1705 "Remove special lines and marking characters in calculating tables.
1706 This removes the special marking character column from tables that are set
1707 up for spreadsheet calculations. It also removes the entire lines
1708 marked with `!', `_', or `^'. The lines with `$' are kept, because
1709 the values of constants may be useful to have."
1710 :group 'org-export-tables
1711 :type 'boolean)
1713 (defcustom org-export-prefer-native-exporter-for-tables nil
1714 "Non-nil means, always export tables created with table.el natively.
1715 Natively means, use the HTML code generator in table.el.
1716 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1717 the table does not use row- or column-spanning). This has the
1718 advantage, that the automatic HTML conversions for math symbols and
1719 sub/superscripts can be applied. Org-mode's HTML generator is also
1720 much faster."
1721 :group 'org-export-tables
1722 :type 'boolean)
1724 (defgroup org-export-ascii nil
1725 "Options specific for ASCII export of Org-mode files."
1726 :tag "Org Export ASCII"
1727 :group 'org-export)
1729 (defcustom org-export-ascii-show-new-buffer t
1730 "Non-nil means, popup buffer containing the exported ASCII text.
1731 Otherwise the buffer will just be saved to a file and stay hidden."
1732 :group 'org-export-ascii
1733 :type 'boolean)
1735 (defgroup org-export-xml nil
1736 "Options specific for XML export of Org-mode files."
1737 :tag "Org Export XML"
1738 :group 'org-export)
1740 (defcustom org-export-xml-type 'xoxo ;kw, if we have only one.
1741 "The kind of XML to be produced by the XML exporter.
1742 Allowed values are:
1743 xoxo The XOXO exporter."
1744 :group 'org-export-xml
1745 :type '(choice
1746 (const :tag "XOXO" xoxo)))
1748 (defgroup org-export-html nil
1749 "Options specific for HTML export of Org-mode files."
1750 :tag "Org Export HTML"
1751 :group 'org-export)
1753 (defcustom org-export-html-style
1754 "<style type=\"text/css\">
1755 html {
1756 font-family: Times, serif;
1757 font-size: 12pt;
1759 .title { text-align: center; }
1760 .todo, .deadline { color: red; }
1761 .done { color: green; }
1762 .target { background-color: lavender; }
1763 pre {
1764 border: 1pt solid #AEBDCC;
1765 background-color: #F3F5F7;
1766 padding: 5pt;
1767 font-family: courier, monospace;
1769 table { border-collapse: collapse; }
1770 td, th {
1771 vertical-align: top;
1772 border: 1pt solid #ADB9CC;
1774 </style>"
1775 "The default style specification for exported HTML files.
1776 Since there are different ways of setting style information, this variable
1777 needs to contain the full HTML structure to provide a style, including the
1778 surrounding HTML tags. The style specifications should include definitions
1779 for new classes todo, done, title, and deadline. For example, legal values
1780 would be:
1782 <style type=\"text/css\">
1783 p { font-weight: normal; color: gray; }
1784 h1 { color: black; }
1785 .title { text-align: center; }
1786 .todo, .deadline { color: red; }
1787 .done { color: green; }
1788 </style>
1790 or, if you want to keep the style in a file,
1792 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1794 As the value of this option simply gets inserted into the HTML <head> header,
1795 you can \"misuse\" it to add arbitrary text to the header."
1796 :group 'org-export-html
1797 :type 'string)
1799 (defcustom org-export-html-inline-images t
1800 "Non-nil means, inline images into exported HTML pages.
1801 The link will still be to the original location of the image file.
1802 So if you are moving the page, lets say to your public HTML site,
1803 you will have to move the image and maybe change the link."
1804 :group 'org-export-html
1805 :type 'boolean)
1807 (defcustom org-export-html-expand t
1808 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1809 When nil, these tags will be exported as plain text and therefore
1810 not be interpreted by a browser.
1812 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1813 :group 'org-export-html
1814 :type 'boolean)
1816 (defcustom org-export-html-table-tag
1817 "<table border=1 cellspacing=0 cellpadding=6>"
1818 "The HTML tag used to start a table.
1819 This must be a <table> tag, but you may change the options like
1820 borders and spacing."
1821 :group 'org-export-html
1822 :type 'string)
1824 (defcustom org-export-html-with-timestamp nil
1825 "If non-nil, write `org-export-html-html-helper-timestamp'
1826 into the exported HTML text. Otherwise, the buffer will just be saved
1827 to a file."
1828 :group 'org-export-html
1829 :type 'boolean)
1831 (defcustom org-export-html-html-helper-timestamp
1832 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1833 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1834 :group 'org-export-html
1835 :type 'string)
1837 (defcustom org-export-html-show-new-buffer nil
1838 "Non-nil means, popup buffer containing the exported html text.
1839 Otherwise, the buffer will just be saved to a file and stay hidden."
1840 :group 'org-export-html
1841 :type 'boolean)
1843 (defgroup org-export-icalendar nil
1844 "Options specific for iCalendar export of Org-mode files."
1845 :tag "Org Export iCalendar"
1846 :group 'org-export)
1848 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1849 "The file name for the iCalendar file covering all agenda files.
1850 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1851 :group 'org-export-icalendar
1852 :type 'file)
1854 (defcustom org-icalendar-include-todo nil
1855 "Non-nil means, export to iCalendar files should also cover TODO items."
1856 :group 'org-export-icalendar
1857 :type 'boolean)
1859 (defcustom org-icalendar-combined-name "OrgMode"
1860 "Calendar name for the combined iCalendar representing all agenda files."
1861 :group 'org-export-icalendar
1862 :type 'string)
1864 (defgroup org-font-lock nil
1865 "Font-lock settings for highlighting in Org-mode."
1866 :tag "Org Font Lock"
1867 :group 'org)
1869 (defcustom org-level-color-stars-only nil
1870 "Non-nil means fontify only the stars in each headline.
1871 When nil, the entire headline is fontified.
1872 Changing it requires restart of `font-lock-mode' to become effective
1873 also in regions already fontified."
1874 :group 'org-font-lock
1875 :type 'boolean)
1877 (defcustom org-hide-leading-stars nil
1878 "Non-nil means, hide the first N-1 stars in a headline.
1879 This works by using the face `org-hide' for these stars. This
1880 face is white for a light background, and black for a dark
1881 background. You may have to customize the face `org-hide' to
1882 make this work.
1883 Changing it requires restart of `font-lock-mode' to become effective
1884 also in regions already fontified."
1885 :group 'org-font-lock
1886 :type 'boolean)
1888 (defcustom org-fontify-done-headline nil
1889 "Non-nil means, change the face of a headline if it is marked DONE.
1890 Normally, only the TODO/DONE keyword indicates the state of a headline.
1891 When this is non-nil, the headline after the keyword is set to the
1892 `org-headline-done' as an additional indication."
1893 :group 'org-font-lock
1894 :type 'boolean)
1896 (defcustom org-fontify-emphasized-text t
1897 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
1898 Changing this variable requires a restart of Emacs to take effect."
1899 :group 'org-font-lock
1900 :type 'boolean)
1902 (defgroup org-faces nil
1903 "Faces in Org-mode."
1904 :tag "Org Faces"
1905 :group 'org-font-lock)
1907 (defface org-hide
1909 (((type tty) (class color)) (:foreground "white"))
1910 (((class color) (background light)) (:foreground "white"))
1911 (((class color) (background dark)) (:foreground "black"))
1912 (t (:inverse-video nil)))
1913 "Face used for level 1 headlines."
1914 :group 'org-faces)
1916 (defface org-level-1 ;; font-lock-function-name-face
1917 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1918 (((class color) (background light)) (:foreground "Blue"))
1919 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1920 (t (:inverse-video t :bold t)))
1921 "Face used for level 1 headlines."
1922 :group 'org-faces)
1924 (defface org-level-2 ;; font-lock-variable-name-face
1925 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1926 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1927 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1928 (t (:bold t :italic t)))
1929 "Face used for level 2 headlines."
1930 :group 'org-faces)
1932 (defface org-level-3 ;; font-lock-keyword-face
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 used for level 3 headlines."
1938 :group 'org-faces)
1940 (defface org-level-4 ;; font-lock-comment-face
1941 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1942 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1943 (((class color) (background light)) (:foreground "Firebrick"))
1944 (((class color) (background dark)) (:foreground "chocolate1"))
1945 (t (:bold t :italic t)))
1946 "Face used for level 4 headlines."
1947 :group 'org-faces)
1949 (defface org-level-5 ;; font-lock-type-face
1950 '((((type tty) (class color)) (:foreground "green"))
1951 (((class color) (background light)) (:foreground "ForestGreen"))
1952 (((class color) (background dark)) (:foreground "PaleGreen"))
1953 (t (:bold t :underline t)))
1954 "Face used for level 5 headlines."
1955 :group 'org-faces)
1957 (defface org-level-6 ;; font-lock-constant-face
1958 '((((type tty) (class color)) (:foreground "magenta"))
1959 (((class color) (background light)) (:foreground "CadetBlue"))
1960 (((class color) (background dark)) (:foreground "Aquamarine"))
1961 (t (:bold t :underline t)))
1962 "Face used for level 6 headlines."
1963 :group 'org-faces)
1965 (defface org-level-7 ;; font-lock-builtin-face
1966 '((((type tty) (class color)) (:foreground "blue" :weight light))
1967 (((class color) (background light)) (:foreground "Orchid"))
1968 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1969 (t (:bold t)))
1970 "Face used for level 7 headlines."
1971 :group 'org-faces)
1973 (defface org-level-8 ;; font-lock-string-face
1974 '((((type tty) (class color)) (:foreground "green"))
1975 (((class color) (background light)) (:foreground "RosyBrown"))
1976 (((class color) (background dark)) (:foreground "LightSalmon"))
1977 (t (:italic t)))
1978 "Face used for level 8 headlines."
1979 :group 'org-faces)
1981 (defface org-special-keyword ;; font-lock-string-face
1982 '((((type tty) (class color)) (:foreground "green"))
1983 (((class color) (background light)) (:foreground "RosyBrown"))
1984 (((class color) (background dark)) (:foreground "LightSalmon"))
1985 (t (:italic t)))
1986 "Face used for special keywords."
1987 :group 'org-faces)
1989 (defface org-warning ;; font-lock-warning-face
1990 '((((type tty) (class color)) (:foreground "red"))
1991 (((class color) (background light)) (:foreground "Red" :bold t))
1992 (((class color) (background dark)) (:foreground "Red1" :bold t))
1993 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1994 (t (:inverse-video t :bold t)))
1995 "Face for deadlines and TODO keywords."
1996 :group 'org-faces)
1998 (defface org-headline-done ;; font-lock-string-face
1999 '((((type tty) (class color)) (:foreground "green"))
2000 (((class color) (background light)) (:foreground "RosyBrown"))
2001 (((class color) (background dark)) (:foreground "LightSalmon"))
2002 (t (:italic t)))
2003 "Face used to indicate that a headline is DONE. See also the variable
2004 `org-fontify-done-headline'."
2005 :group 'org-faces)
2007 ;; Inheritance does not work for xemacs. So we just copy...
2009 (defface org-deadline-announce
2010 '((((type tty) (class color)) (:foreground "blue" :weight bold))
2011 (((class color) (background light)) (:foreground "Blue"))
2012 (((class color) (background dark)) (:foreground "LightSkyBlue"))
2013 (t (:inverse-video t :bold t)))
2014 "Face for upcoming deadlines."
2015 :group 'org-faces)
2017 (defface org-scheduled-today
2018 '((((type tty) (class color)) (:foreground "green"))
2019 (((class color) (background light)) (:foreground "DarkGreen"))
2020 (((class color) (background dark)) (:foreground "PaleGreen"))
2021 (t (:bold t :underline t)))
2022 "Face for items scheduled for a certain day."
2023 :group 'org-faces)
2025 (defface org-scheduled-previously
2026 '((((type tty pc) (class color) (background light)) (:foreground "red"))
2027 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
2028 (((class color) (background light)) (:foreground "Firebrick"))
2029 (((class color) (background dark)) (:foreground "chocolate1"))
2030 (t (:bold t :italic t)))
2031 "Face for items scheduled previously, and not yet done."
2032 :group 'org-faces)
2034 (defface org-formula
2035 '((((type tty pc) (class color) (background light)) (:foreground "red"))
2036 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
2037 (((class color) (background light)) (:foreground "Firebrick"))
2038 (((class color) (background dark)) (:foreground "chocolate1"))
2039 (t (:bold t :italic t)))
2040 "Face for formulas."
2041 :group 'org-faces)
2043 (defface org-link
2044 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
2045 (((class color) (background light)) (:foreground "Purple" :underline t))
2046 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2047 (t (:bold t)))
2048 "Face for links."
2049 :group 'org-faces)
2051 (defface org-tag
2052 '((((type tty) (class color)) (:weight bold))
2053 (((class color) (background light)) (:weight bold))
2054 (((class color) (background dark)) (:weight bold))
2055 (t (:bold t)))
2056 "Face for tags."
2057 :group 'org-faces)
2059 (defface org-done ;; font-lock-type-face
2060 '((((type tty) (class color)) (:foreground "green"))
2061 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
2062 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
2063 (t (:bold t :underline t)))
2064 "Face used for DONE."
2065 :group 'org-faces)
2067 (defface org-table ;; font-lock-function-name-face
2068 '((((type tty) (class color)) (:foreground "blue" :weight bold))
2069 (((class color) (background light)) (:foreground "Blue"))
2070 (((class color) (background dark)) (:foreground "LightSkyBlue"))
2071 (t (:inverse-video t :bold t)))
2072 "Face used for tables."
2073 :group 'org-faces)
2075 (defface org-time-grid ;; font-lock-variable-name-face
2076 '((((type tty) (class color)) (:foreground "yellow" :weight light))
2077 (((class color) (background light)) (:foreground "DarkGoldenrod"))
2078 (((class color) (background dark)) (:foreground "LightGoldenrod"))
2079 (t (:bold t :italic t)))
2080 "Face used for time grids."
2081 :group 'org-faces)
2083 (defvar org-level-faces
2084 '(org-level-1 org-level-2 org-level-3 org-level-4
2085 org-level-5 org-level-6 org-level-7 org-level-8
2087 (defvar org-n-levels (length org-level-faces))
2090 ;; Variables for pre-computed regular expressions, all buffer local
2091 (defvar org-done-string nil
2092 "The last string in `org-todo-keywords', indicating an item is DONE.")
2093 (make-variable-buffer-local 'org-done-string)
2094 (defvar org-todo-regexp nil
2095 "Matches any of the TODO state keywords.")
2096 (make-variable-buffer-local 'org-todo-regexp)
2097 (defvar org-not-done-regexp nil
2098 "Matches any of the TODO state keywords except the last one.")
2099 (make-variable-buffer-local 'org-not-done-regexp)
2100 (defvar org-todo-line-regexp nil
2101 "Matches a headline and puts TODO state into group 2 if present.")
2102 (make-variable-buffer-local 'org-todo-line-regexp)
2103 (defvar org-nl-done-regexp nil
2104 "Matches newline followed by a headline with the DONE keyword.")
2105 (make-variable-buffer-local 'org-nl-done-regexp)
2106 (defvar org-looking-at-done-regexp nil
2107 "Matches the DONE keyword a point.")
2108 (make-variable-buffer-local 'org-looking-at-done-regexp)
2109 (defvar org-todo-kwd-priority-p nil
2110 "Do TODO items have priorities?")
2111 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2112 (defvar org-todo-kwd-max-priority nil
2113 "Maximum priority of TODO items.")
2114 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2115 (defvar org-ds-keyword-length 12
2116 "Maximum length of the Deadline and SCHEDULED keywords.")
2117 (make-variable-buffer-local 'org-ds-keyword-length)
2118 (defvar org-deadline-regexp nil
2119 "Matches the DEADLINE keyword.")
2120 (make-variable-buffer-local 'org-deadline-regexp)
2121 (defvar org-deadline-time-regexp nil
2122 "Matches the DEADLINE keyword together with a time stamp.")
2123 (make-variable-buffer-local 'org-deadline-time-regexp)
2124 (defvar org-deadline-line-regexp nil
2125 "Matches the DEADLINE keyword and the rest of the line.")
2126 (make-variable-buffer-local 'org-deadline-line-regexp)
2127 (defvar org-scheduled-regexp nil
2128 "Matches the SCHEDULED keyword.")
2129 (make-variable-buffer-local 'org-scheduled-regexp)
2130 (defvar org-scheduled-time-regexp nil
2131 "Matches the SCHEDULED keyword together with a time stamp.")
2132 (make-variable-buffer-local 'org-scheduled-time-regexp)
2134 (defun org-set-regexps-and-options ()
2135 "Precompute regular expressions for current buffer."
2136 (when (eq major-mode 'org-mode)
2137 (let ((re (org-make-options-regexp
2138 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2139 "STARTUP" "ARCHIVE")))
2140 (splitre "[ \t]+")
2141 kwds int key value cat arch)
2142 (save-excursion
2143 (save-restriction
2144 (widen)
2145 (goto-char (point-min))
2146 (while (re-search-forward re nil t)
2147 (setq key (match-string 1) value (match-string 2))
2148 (cond
2149 ((equal key "CATEGORY")
2150 (if (string-match "[ \t]+$" value)
2151 (setq value (replace-match "" t t value)))
2152 (setq cat (intern value)))
2153 ((equal key "SEQ_TODO")
2154 (setq int 'sequence
2155 kwds (append kwds (org-split-string value splitre))))
2156 ((equal key "PRI_TODO")
2157 (setq int 'priority
2158 kwds (append kwds (org-split-string value splitre))))
2159 ((equal key "TYP_TODO")
2160 (setq int 'type
2161 kwds (append kwds (org-split-string value splitre))))
2162 ((equal key "STARTUP")
2163 (let ((opts (org-split-string value splitre))
2164 (set '(("fold" org-startup-folded t)
2165 ("nofold" org-startup-folded nil)
2166 ("content" org-startup-folded content)
2167 ("hidestars" org-hide-leading-stars t)
2168 ("showstars" org-hide-leading-stars nil)
2169 ("odd" org-odd-levels-only t)
2170 ("oddeven" org-odd-levels-only nil)
2171 ("align" org-startup-align-all-tables t)
2172 ("noalign" org-startup-align-all-tables nil)
2173 ("dlcheck" org-startup-with-deadline-check t)
2174 ("nodlcheck" org-startup-with-deadline-check nil)))
2175 l var val)
2176 (while (setq l (assoc (pop opts) set))
2177 (setq var (nth 1 l) val (nth 2 l))
2178 (set (make-local-variable var) val))))
2179 ((equal key "ARCHIVE")
2180 (string-match " *$" value)
2181 (setq arch (replace-match "" t t value))
2182 (remove-text-properties 0 (length arch)
2183 '(face t fontified t) arch)))
2185 (and cat (set (make-local-variable 'org-category) cat))
2186 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2187 (and arch (set (make-local-variable 'org-archive-location) arch))
2188 (and int (set (make-local-variable 'org-todo-interpretation) int)))
2189 ;; Compute the regular expressions and other local variables
2190 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2191 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2192 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2193 (length org-scheduled-string)))
2194 org-done-string
2195 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2196 org-todo-regexp
2197 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2198 "\\|") "\\)\\>")
2199 org-not-done-regexp
2200 (concat "\\<\\("
2201 (mapconcat 'regexp-quote
2202 (nreverse (cdr (reverse org-todo-keywords)))
2203 "\\|")
2204 "\\)\\>")
2205 org-todo-line-regexp
2206 (concat "^\\(\\*+\\)[ \t]*\\("
2207 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2208 "\\)? *\\(.*\\)")
2209 org-nl-done-regexp
2210 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2211 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2212 org-deadline-regexp (concat "\\<" org-deadline-string)
2213 org-deadline-time-regexp
2214 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2215 org-deadline-line-regexp
2216 (concat "\\<\\(" org-deadline-string "\\).*")
2217 org-scheduled-regexp
2218 (concat "\\<" org-scheduled-string)
2219 org-scheduled-time-regexp
2220 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
2221 (org-set-font-lock-defaults)))
2223 ;; Tell the compiler about dynamically scoped variables,
2224 ;; and variables from other packages
2225 (defvar zmacs-regions) ; XEmacs regions
2226 (defvar original-date) ; dynamically scoped in calendar
2227 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2228 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2229 (defvar org-html-entities) ; defined later in this file
2230 (defvar org-goto-start-pos) ; dynamically scoped parameter
2231 (defvar org-time-was-given) ; dynamically scoped parameter
2232 (defvar org-ts-what) ; dynamically scoped parameter
2233 (defvar mark-active) ; Emacs only, not available in XEmacs.
2234 (defvar timecnt) ; dynamically scoped parameter
2235 (defvar levels-open) ; dynamically scoped parameter
2236 (defvar title) ; dynamically scoped parameter
2237 (defvar author) ; dynamically scoped parameter
2238 (defvar email) ; dynamically scoped parameter
2239 (defvar text) ; dynamically scoped parameter
2240 (defvar entry) ; dynamically scoped parameter
2241 (defvar date) ; dynamically scoped parameter
2242 (defvar language) ; dynamically scoped parameter
2243 (defvar options) ; dynamically scoped parameter
2244 (defvar ans1) ; dynamically scoped parameter
2245 (defvar ans2) ; dynamically scoped parameter
2246 (defvar starting-day) ; local variable
2247 (defvar include-all-loc) ; local variable
2248 (defvar vm-message-pointer) ; from vm
2249 (defvar vm-folder-directory) ; from vm
2250 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2251 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2252 (defvar gnus-group-name) ; from gnus
2253 (defvar gnus-article-current) ; from gnus
2254 (defvar w3m-current-url) ; from w3m
2255 (defvar mh-progs) ; from MH-E
2256 (defvar mh-current-folder) ; from MH-E
2257 (defvar mh-show-folder-buffer) ; from MH-E
2258 (defvar mh-index-folder) ; from MH-E
2259 (defvar mh-searcher) ; from MH-E
2260 (defvar org-selected-point) ; dynamically scoped parameter
2261 (defvar calendar-mode-map) ; from calendar.el
2262 (defvar last-arg) ; local variable
2263 (defvar remember-save-after-remembering) ; from remember.el
2264 (defvar remember-data-file) ; from remember.el
2265 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2266 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2267 (defvar orgtbl-mode) ; defined later in this file
2268 ;;; Define the mode
2270 (defvar org-mode-map (copy-keymap outline-mode-map)
2271 "Keymap for Org-mode.")
2273 (defvar org-struct-menu) ; defined later in this file
2274 (defvar org-org-menu) ; defined later in this file
2275 (defvar org-tbl-menu) ; defined later in this file
2277 ;; We use a before-change function to check if a table might need
2278 ;; an update.
2279 (defvar org-table-may-need-update t
2280 "Indicates that a table might need an update.
2281 This variable is set by `org-before-change-function'.
2282 `org-table-align' sets it back to nil.")
2283 (defvar org-mode-hook nil)
2284 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2285 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2288 ;;;###autoload
2289 (define-derived-mode org-mode outline-mode "Org"
2290 "Outline-based notes management and organizer, alias
2291 \"Carsten's outline-mode for keeping track of everything.\"
2293 Org-mode develops organizational tasks around a NOTES file which
2294 contains information about projects as plain text. Org-mode is
2295 implemented on top of outline-mode, which is ideal to keep the content
2296 of large files well structured. It supports ToDo items, deadlines and
2297 time stamps, which magically appear in the diary listing of the Emacs
2298 calendar. Tables are easily created with a built-in table editor.
2299 Plain text URL-like links connect to websites, emails (VM), Usenet
2300 messages (Gnus), BBDB entries, and any files related to the project.
2301 For printing and sharing of notes, an Org-mode file (or a part of it)
2302 can be exported as a structured ASCII or HTML file.
2304 The following commands are available:
2306 \\{org-mode-map}"
2307 (easy-menu-add org-org-menu)
2308 (easy-menu-add org-tbl-menu)
2309 (org-install-agenda-files-menu)
2310 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2311 (org-add-to-invisibility-spec '(org-cwidth))
2312 (setq outline-regexp "\\*+")
2313 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2314 (setq outline-level 'org-outline-level)
2315 (when (and org-ellipsis (stringp org-ellipsis))
2316 (unless org-display-table
2317 (setq org-display-table (make-display-table)))
2318 (set-display-table-slot org-display-table
2319 4 (string-to-vector org-ellipsis))
2320 (setq buffer-display-table org-display-table))
2321 (org-set-regexps-and-options)
2322 (if org-startup-truncated (setq truncate-lines t))
2323 (set (make-local-variable 'font-lock-unfontify-region-function)
2324 'org-unfontify-region)
2325 ;; Activate before-change-function
2326 (set (make-local-variable 'org-table-may-need-update) t)
2327 (org-add-hook 'before-change-functions 'org-before-change-function nil
2328 'local)
2329 ;; Paragraphs and auto-filling
2330 (org-set-autofill-regexps)
2331 (org-update-radio-target-regexp)
2332 ;; Settings for Calc embedded mode
2333 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2334 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2335 (if (and org-insert-mode-line-in-empty-file
2336 (interactive-p)
2337 (= (point-min) (point-max)))
2338 (insert " -*- mode: org -*-\n\n"))
2340 ;; Get rid of Outline menus, they are not needed
2341 ;; Need to do this here because define-derived-mode sets up
2342 ;; the keymap so late.
2343 (if (featurep 'xemacs)
2344 (progn
2345 (delete-menu-item '("Headings"))
2346 (delete-menu-item '("Show"))
2347 (delete-menu-item '("Hide"))
2348 (set-menubar-dirty-flag))
2349 (define-key org-mode-map [menu-bar headings] 'undefined)
2350 (define-key org-mode-map [menu-bar hide] 'undefined)
2351 (define-key org-mode-map [menu-bar show] 'undefined))
2353 (unless org-inhibit-startup
2354 (if org-startup-align-all-tables
2355 (org-table-map-tables 'org-table-align))
2356 (if org-startup-with-deadline-check
2357 (call-interactively 'org-check-deadlines)
2358 (cond
2359 ((eq org-startup-folded t)
2360 (org-cycle '(4)))
2361 ((eq org-startup-folded 'content)
2362 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2363 (org-cycle '(4)) (org-cycle '(4))))))))
2365 (defsubst org-current-line (&optional pos)
2366 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2368 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2369 mouse-map t)
2370 "Properties to remove when a string without properties is wanted.")
2372 (defsubst org-match-string-no-properties (num &optional string)
2373 (if (featurep 'xemacs)
2374 (let ((s (match-string num string)))
2375 (remove-text-properties 0 (length s) org-rm-props s)
2377 (match-string-no-properties num string)))
2379 (defun org-current-time ()
2380 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2381 (if (> org-time-stamp-rounding-minutes 0)
2382 (let ((r org-time-stamp-rounding-minutes)
2383 (time (decode-time)))
2384 (apply 'encode-time
2385 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2386 (nthcdr 2 time))))
2387 (current-time)))
2389 (defun org-add-props (string plist &rest props)
2390 "Add text properties to entire string, from beginning to end.
2391 PLIST may be a list of properties, PROPS are individual properties and values
2392 that will be added to PLIST. Returns the string that was modified."
2393 (add-text-properties
2394 0 (length string) (if props (append plist props) plist) string)
2395 string)
2396 (put 'org-add-props 'lisp-indent-function 2)
2399 ;;; Font-Lock stuff
2401 (defvar org-mouse-map (make-sparse-keymap))
2402 (define-key org-mouse-map
2403 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
2404 (define-key org-mouse-map
2405 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
2406 (define-key org-mouse-map [follow-link] 'mouse-face)
2407 (when org-tab-follows-link
2408 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2409 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2410 (when org-return-follows-link
2411 (define-key org-mouse-map [(return)] 'org-open-at-point)
2412 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2414 (require 'font-lock)
2416 (defconst org-non-link-chars "]\t\n\r<>")
2417 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
2418 "wl" "mhe" "rmail" "gnus" "shell"))
2419 (defconst org-link-re-with-space
2420 (concat
2421 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2422 "\\([^" org-non-link-chars " ]"
2423 "[^" org-non-link-chars "]*"
2424 "[^" org-non-link-chars " ]\\)>?")
2425 "Matches a link with spaces, optional angular brackets around it.")
2427 (defconst org-link-re-with-space2
2428 (concat
2429 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2430 "\\([^" org-non-link-chars " ]"
2431 "[^]\t\n\r]*"
2432 "[^" org-non-link-chars " ]\\)>?")
2433 "Matches a link with spaces, optional angular brackets around it.")
2435 (defconst org-angle-link-re
2436 (concat
2437 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2438 "\\([^" org-non-link-chars " ]"
2439 "[^" org-non-link-chars "]*"
2440 "\\)>")
2441 "Matches link with angular brackets, spaces are allowed.")
2442 (defconst org-plain-link-re
2443 (concat
2444 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2445 "\\([^]\t\n\r<>,;() ]+\\)")
2446 "Matches plain link, without spaces.")
2448 (defconst org-bracket-link-regexp
2449 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2450 "Matches a link in double brackets.")
2452 (defconst org-bracket-link-analytic-regexp
2453 (concat
2454 "\\[\\["
2455 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
2456 "\\([^]]+\\)"
2457 "\\]"
2458 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
2459 "\\]"))
2460 ; 1: http:
2461 ; 2: http
2462 ; 3: path
2463 ; 4: [desc]
2464 ; 5: desc
2467 (defconst org-ts-lengths
2468 (cons (length (format-time-string (car org-time-stamp-formats)))
2469 (length (format-time-string (cdr org-time-stamp-formats))))
2470 "This holds the lengths of the two different time formats.")
2471 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2472 "Regular expression for fast time stamp matching.")
2473 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2474 "Regular expression for fast time stamp matching.")
2475 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2476 "Regular expression matching time strings for analysis.")
2477 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2478 "Regular expression matching time stamps, with groups.")
2479 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2480 "Regular expression matching a time stamp range.")
2481 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2482 org-ts-regexp "\\)?")
2483 "Regular expression matching a time stamp or time stamp range.")
2485 (defun org-activate-plain-links (limit)
2486 "Run through the buffer and add overlays to links."
2487 (if (re-search-forward org-plain-link-re limit t)
2488 (progn
2489 (add-text-properties (match-beginning 0) (match-end 0)
2490 (list 'mouse-face 'highlight
2491 'keymap org-mouse-map
2493 t)))
2495 (defun org-activate-angle-links (limit)
2496 "Run through the buffer and add overlays to links."
2497 (if (re-search-forward org-angle-link-re limit t)
2498 (progn
2499 (add-text-properties (match-beginning 0) (match-end 0)
2500 (list 'mouse-face 'highlight
2501 'keymap org-mouse-map
2503 t)))
2505 (defun org-activate-bracket-links (limit)
2506 "Run through the buffer and add overlays to bracketed links."
2507 (if (re-search-forward org-bracket-link-regexp limit t)
2508 (let* ((help (concat "LINK: " (org-match-string-no-properties 1)))
2509 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
2510 'keymap org-mouse-map 'mouse-face 'highlight
2511 'help-echo help))
2512 (vp (list 'rear-nonsticky t
2513 'keymap org-mouse-map 'mouse-face 'highlight
2514 'help-echo help)))
2515 ;; We need to remove the invisible property here. Table narrowing
2516 ;; may have made some of this invisible.
2517 (remove-text-properties (match-beginning 0) (match-end 0)
2518 '(invisible nil))
2519 (if (match-end 3)
2520 (progn
2521 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
2522 (add-text-properties (match-beginning 3) (match-end 3) vp)
2523 (add-text-properties (match-end 3) (match-end 0) ip))
2524 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
2525 (add-text-properties (match-beginning 1) (match-end 1) vp)
2526 (add-text-properties (match-end 1) (match-end 0) ip))
2527 t)))
2529 (defun org-activate-dates (limit)
2530 "Run through the buffer and add overlays to dates."
2531 (if (re-search-forward org-tsr-regexp limit t)
2532 (progn
2533 (add-text-properties (match-beginning 0) (match-end 0)
2534 (list 'mouse-face 'highlight
2535 'keymap org-mouse-map))
2536 t)))
2538 (defvar org-target-link-regexp nil
2539 "Regular expression matching radio targets in plain text.")
2540 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2541 "Regular expression matching a link target.")
2542 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2543 "Regular expression matching a link target.")
2545 (defun org-activate-target-links (limit)
2546 "Run through the buffer and add overlays to target matches."
2547 (when org-target-link-regexp
2548 (let ((case-fold-search t))
2549 (if (re-search-forward org-target-link-regexp limit t)
2550 (progn
2551 (add-text-properties (match-beginning 0) (match-end 0)
2552 (list 'mouse-face 'highlight
2553 'keymap org-mouse-map
2554 'help-echo "Radio target link"
2555 'org-linked-text t))
2556 t)))))
2558 (defun org-update-radio-target-regexp ()
2559 "Find all radio targets in this file and update the regular expression."
2560 (interactive)
2561 (when (memq 'radio org-activate-links)
2562 (setq org-target-link-regexp
2563 (org-make-target-link-regexp (org-all-targets 'radio)))
2564 (org-restart-font-lock)))
2566 (defun org-hide-wide-columns (limit)
2567 (let (s e)
2568 (setq s (text-property-any (point) (or limit (point-max))
2569 'org-cwidth t))
2570 (when s
2571 (setq e (next-single-property-change s 'org-cwidth))
2572 (add-text-properties s e '(invisible org-cwidth intangible t))
2573 (goto-char e)
2574 t)))
2576 (defun org-restart-font-lock ()
2577 "Restart font-lock-mode, to force refontification."
2578 (when (and (boundp 'font-lock-mode) font-lock-mode)
2579 (font-lock-mode -1)
2580 (font-lock-mode 1)))
2582 (defun org-all-targets (&optional radio)
2583 "Return a list of all targets in this file.
2584 With optional argument RADIO, only find radio targets."
2585 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2586 rtn)
2587 (save-excursion
2588 (goto-char (point-min))
2589 (while (re-search-forward re nil t)
2590 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
2591 rtn)))
2593 (defun org-make-target-link-regexp (targets)
2594 "Make regular expression matching all strings in TARGETS.
2595 The regular expression finds the targets also if there is a line break
2596 between words."
2597 (and targets
2598 (concat
2599 "\\<\\("
2600 (mapconcat
2601 (lambda (x)
2602 (while (string-match " +" x)
2603 (setq x (replace-match "\\s-+" t t x)))
2605 targets
2606 "\\|")
2607 "\\)\\>")))
2609 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2610 "Matches CamelCase words, possibly with a star before it.")
2612 (defun org-activate-camels (limit)
2613 "Run through the buffer and add overlays to dates."
2614 (if (re-search-forward org-camel-regexp limit t)
2615 (progn
2616 (add-text-properties (match-beginning 0) (match-end 0)
2617 (list 'mouse-face 'highlight
2618 'keymap org-mouse-map))
2619 t)))
2621 (defun org-activate-tags (limit)
2622 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2623 (progn
2624 (add-text-properties (match-beginning 1) (match-end 1)
2625 (list 'mouse-face 'highlight
2626 'keymap org-mouse-map))
2627 t)))
2629 (defun org-font-lock-level ()
2630 (save-excursion
2631 (org-back-to-heading t)
2632 (- (match-end 0) (match-beginning 0))))
2634 (defun org-outline-level ()
2635 (save-excursion
2636 (looking-at outline-regexp)
2637 (if (match-beginning 1)
2638 (+ (org-get-string-indentation (match-string 1)) 1000)
2639 (- (match-end 0) (match-beginning 0)))))
2641 (defvar org-font-lock-keywords nil)
2643 (defun org-set-font-lock-defaults ()
2644 (let* ((em org-fontify-emphasized-text)
2645 (lk org-activate-links)
2646 (org-font-lock-extra-keywords
2647 (list
2648 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
2649 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
2650 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2651 (1 'org-table))
2652 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
2653 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
2654 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
2655 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
2656 (if (memq 'date lk) '(org-activate-dates (0 'org-link t)))
2657 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
2658 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
2659 (if org-table-limit-column-width
2660 '(org-hide-wide-columns (0 nil append)))
2661 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2662 '(1 'org-warning t))
2663 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2664 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2665 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2666 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2667 (if em '("\\(\\W\\|^\\)\\(\\*\\w+\\*\\)\\(\\W\\|$\\)" 2 'bold prepend))
2668 (if em '("\\(\\W\\|^\\)\\(/\\w+/\\)\\(\\W\\|$\\)" 2 'italic prepend))
2669 (if em '("\\(\\W\\|^\\)\\(_\\w+_\\)\\(\\W\\|$\\)" 2 'underline prepend))
2670 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2671 "\\|" org-quote-string "\\)\\>")
2672 '(1 'org-special-keyword t))
2673 '("^#.*" (0 'font-lock-comment-face t))
2674 (if org-fontify-done-headline
2675 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2676 '(1 'org-done t) '(2 'org-headline-done t))
2677 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2678 '(1 'org-done t)))
2679 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2680 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2681 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2682 (if org-format-transports-properties-p
2683 '("| *\\(<[0-9]+>\\) *|" (1 'org-formula t)))
2685 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
2686 ;; Now set the full font-lock-keywords
2687 (set (make-local-variable 'org-font-lock-keywords)
2688 org-font-lock-extra-keywords)
2689 (set (make-local-variable 'font-lock-defaults)
2690 '(org-font-lock-keywords t nil nil backward-paragraph))
2691 (kill-local-variable 'font-lock-keywords) nil))
2693 (defvar org-m nil)
2694 (defvar org-l nil)
2695 (defvar org-f nil)
2696 (defun org-get-level-face (n)
2697 "Get the right face for match N in font-lock matching of healdines."
2698 (setq org-l (- (match-end 2) (match-beginning 1)))
2699 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
2700 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
2701 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
2702 (cond
2703 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
2704 ((eq n 2) org-f)
2705 (t (if org-level-color-stars-only nil org-f))))
2707 (defun org-unfontify-region (beg end &optional maybe_loudly)
2708 "Remove fontification and activation overlays from links."
2709 (font-lock-default-unfontify-region beg end)
2710 (let* ((buffer-undo-list t)
2711 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2712 (inhibit-modification-hooks t)
2713 deactivate-mark buffer-file-name buffer-file-truename)
2714 (remove-text-properties beg end
2715 '(mouse-face nil keymap nil org-linked-text nil
2716 invisible nil intangible nil))))
2717 ;;; Visibility cycling
2719 (defvar org-cycle-global-status nil)
2720 (defvar org-cycle-subtree-status nil)
2721 (defun org-cycle (&optional arg)
2722 "Visibility cycling for Org-mode.
2724 - When this function is called with a prefix argument, rotate the entire
2725 buffer through 3 states (global cycling)
2726 1. OVERVIEW: Show only top-level headlines.
2727 2. CONTENTS: Show all headlines of all levels, but no body text.
2728 3. SHOW ALL: Show everything.
2730 - When point is at the beginning of a headline, rotate the subtree started
2731 by this line through 3 different states (local cycling)
2732 1. FOLDED: Only the main headline is shown.
2733 2. CHILDREN: The main headline and the direct children are shown.
2734 From this state, you can move to one of the children
2735 and zoom in further.
2736 3. SUBTREE: Show the entire subtree, including body text.
2738 - When there is a numeric prefix, go up to a heading with level ARG, do
2739 a `show-subtree' and return to the previous cursor position. If ARG
2740 is negative, go up that many levels.
2742 - When point is not at the beginning of a headline, execute
2743 `indent-relative', like TAB normally does. See the option
2744 `org-cycle-emulate-tab' for details.
2746 - Special case: if point is the the beginning of the buffer and there is
2747 no headline in line 1, this function will act as if called with prefix arg."
2748 (interactive "P")
2750 (if (or (and (bobp) (not (looking-at outline-regexp)))
2751 (equal arg '(4)))
2752 ;; special case: use global cycling
2753 (setq arg t))
2755 (let ((outline-regexp
2756 (if org-cycle-include-plain-lists
2757 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2758 outline-regexp)))
2760 (cond
2762 ((org-at-table-p 'any)
2763 ;; Enter the table or move to the next field in the table
2764 (or (org-table-recognize-table.el)
2765 (progn
2766 (if arg (org-table-edit-field t)
2767 (org-table-justify-field-maybe)
2768 (org-table-next-field)))))
2770 ((eq arg t) ;; Global cycling
2772 (cond
2773 ((and (eq last-command this-command)
2774 (eq org-cycle-global-status 'overview))
2775 ;; We just created the overview - now do table of contents
2776 ;; This can be slow in very large buffers, so indicate action
2777 (message "CONTENTS...")
2778 (save-excursion
2779 ;; Visit all headings and show their offspring
2780 (goto-char (point-max))
2781 (catch 'exit
2782 (while (and (progn (condition-case nil
2783 (outline-previous-visible-heading 1)
2784 (error (goto-char (point-min))))
2786 (looking-at outline-regexp))
2787 (show-branches)
2788 (if (bobp) (throw 'exit nil))))
2789 (message "CONTENTS...done"))
2790 (setq org-cycle-global-status 'contents)
2791 (run-hook-with-args 'org-cycle-hook 'contents))
2793 ((and (eq last-command this-command)
2794 (eq org-cycle-global-status 'contents))
2795 ;; We just showed the table of contents - now show everything
2796 (show-all)
2797 (message "SHOW ALL")
2798 (setq org-cycle-global-status 'all)
2799 (run-hook-with-args 'org-cycle-hook 'all))
2802 ;; Default action: go to overview
2803 (hide-sublevels 1)
2804 (message "OVERVIEW")
2805 (setq org-cycle-global-status 'overview)
2806 (run-hook-with-args 'org-cycle-hook 'overview))))
2808 ((integerp arg)
2809 ;; Show-subtree, ARG levels up from here.
2810 (save-excursion
2811 (org-back-to-heading)
2812 (outline-up-heading (if (< arg 0) (- arg)
2813 (- (funcall outline-level) arg)))
2814 (org-show-subtree)))
2816 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2817 ;; At a heading: rotate between three different views
2818 (org-back-to-heading)
2819 (let ((goal-column 0) eoh eol eos)
2820 ;; First, some boundaries
2821 (save-excursion
2822 (org-back-to-heading)
2823 (save-excursion
2824 (beginning-of-line 2)
2825 (while (and (not (eobp)) ;; this is like `next-line'
2826 (get-char-property (1- (point)) 'invisible))
2827 (beginning-of-line 2)) (setq eol (point)))
2828 (outline-end-of-heading) (setq eoh (point))
2829 (org-end-of-subtree t) (setq eos (point))
2830 (outline-next-heading))
2831 ;; Find out what to do next and set `this-command'
2832 (cond
2833 ((= eos eoh)
2834 ;; Nothing is hidden behind this heading
2835 (message "EMPTY ENTRY")
2836 (setq org-cycle-subtree-status nil))
2837 ((>= eol eos)
2838 ;; Entire subtree is hidden in one line: open it
2839 (org-show-entry)
2840 (show-children)
2841 (message "CHILDREN")
2842 (setq org-cycle-subtree-status 'children)
2843 (run-hook-with-args 'org-cycle-hook 'children))
2844 ((and (eq last-command this-command)
2845 (eq org-cycle-subtree-status 'children))
2846 ;; We just showed the children, now show everything.
2847 (org-show-subtree)
2848 (message "SUBTREE")
2849 (setq org-cycle-subtree-status 'subtree)
2850 (run-hook-with-args 'org-cycle-hook 'subtree))
2852 ;; Default action: hide the subtree.
2853 (hide-subtree)
2854 (message "FOLDED")
2855 (setq org-cycle-subtree-status 'folded)
2856 (run-hook-with-args 'org-cycle-hook 'folded)))))
2858 ;; TAB emulation
2859 (buffer-read-only (org-back-to-heading))
2860 ((if (and (eq org-cycle-emulate-tab 'white)
2861 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2863 (eq org-cycle-emulate-tab t))
2864 (if (and (looking-at "[ \n\r\t]")
2865 (string-match "^[ \t]*$" (buffer-substring
2866 (point-at-bol) (point))))
2867 (progn
2868 (beginning-of-line 1)
2869 (and (looking-at "[ \t]+") (replace-match ""))))
2870 (indent-relative))
2872 (t (save-excursion
2873 (org-back-to-heading)
2874 (org-cycle))))))
2876 (defun org-optimize-window-after-visibility-change (state)
2877 "Adjust the window after a change in outline visibility.
2878 This function is the default value of the hook `org-cycle-hook'."
2879 (when (get-buffer-window (current-buffer))
2880 (cond
2881 ((eq state 'overview) (org-first-headline-recenter 1))
2882 ((eq state 'content) nil)
2883 ((eq state 'all) nil)
2884 ((eq state 'folded) nil)
2885 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2886 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
2888 (defun org-subtree-end-visible-p ()
2889 "Is the end of the current subtree visible?"
2890 (pos-visible-in-window-p
2891 (save-excursion (org-end-of-subtree t) (point))))
2893 (defun org-first-headline-recenter (&optional N)
2894 "Move cursor to the first headline and recenter the headline.
2895 Optional argument N means, put the headline into the Nth line of the window."
2896 (goto-char (point-min))
2897 (when (re-search-forward (concat "^" outline-regexp) nil t)
2898 (beginning-of-line)
2899 (recenter (prefix-numeric-value N))))
2901 (defvar org-goto-window-configuration nil)
2902 (defvar org-goto-marker nil)
2903 (defvar org-goto-map (make-sparse-keymap))
2904 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2905 (while (setq cmd (pop cmds))
2906 (substitute-key-definition cmd cmd org-goto-map global-map)))
2907 (define-key org-goto-map "\C-m" 'org-goto-ret)
2908 (define-key org-goto-map [(left)] 'org-goto-left)
2909 (define-key org-goto-map [(right)] 'org-goto-right)
2910 (define-key org-goto-map [(?q)] 'org-goto-quit)
2911 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2912 (define-key org-goto-map "\C-i" 'org-cycle)
2913 (define-key org-goto-map [(tab)] 'org-cycle)
2914 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2915 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2916 (define-key org-goto-map "n" 'outline-next-visible-heading)
2917 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2918 (define-key org-goto-map "f" 'outline-forward-same-level)
2919 (define-key org-goto-map "b" 'outline-backward-same-level)
2920 (define-key org-goto-map "u" 'outline-up-heading)
2921 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2922 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2923 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2924 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2925 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2926 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2927 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2929 (defconst org-goto-help
2930 "Select a location to jump to, press RET
2931 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2933 (defun org-goto ()
2934 "Go to a different location of the document, keeping current visibility.
2936 When you want to go to a different location in a document, the fastest way
2937 is often to fold the entire buffer and then dive into the tree. This
2938 method has the disadvantage, that the previous location will be folded,
2939 which may not be what you want.
2941 This command works around this by showing a copy of the current buffer in
2942 overview mode. You can dive into the tree in that copy, to find the
2943 location you want to reach. When pressing RET, the command returns to the
2944 original buffer in which the visibility is still unchanged. It then jumps
2945 to the new location, making it and the headline hierarchy above it visible."
2946 (interactive)
2947 (let* ((org-goto-start-pos (point))
2948 (selected-point
2949 (org-get-location (current-buffer) org-goto-help)))
2950 (if selected-point
2951 (progn
2952 (org-mark-ring-push org-goto-start-pos)
2953 (goto-char selected-point)
2954 (if (or (org-invisible-p) (org-invisible-p2))
2955 (org-show-hierarchy-above)))
2956 (error "Quit"))))
2958 (defun org-get-location (buf help)
2959 "Let the user select a location in the Org-mode buffer BUF.
2960 This function uses a recursive edit. It returns the selected position
2961 or nil."
2962 (let (org-selected-point)
2963 (save-excursion
2964 (save-window-excursion
2965 (delete-other-windows)
2966 (switch-to-buffer (get-buffer-create "*org-goto*"))
2967 (with-output-to-temp-buffer "*Help*"
2968 (princ help))
2969 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2970 (setq buffer-read-only nil)
2971 (erase-buffer)
2972 (insert-buffer-substring buf)
2973 (let ((org-startup-truncated t)
2974 (org-startup-folded t)
2975 (org-startup-align-all-tables nil)
2976 (org-startup-with-deadline-check nil))
2977 (org-mode))
2978 (setq buffer-read-only t)
2979 (if (boundp 'org-goto-start-pos)
2980 (goto-char org-goto-start-pos)
2981 (goto-char (point-min)))
2982 (org-beginning-of-line)
2983 (message "Select location and press RET")
2984 ;; now we make sure that during selection, ony very few keys work
2985 ;; and that it is impossible to switch to another window.
2986 (let ((gm (current-global-map))
2987 (overriding-local-map org-goto-map))
2988 (unwind-protect
2989 (progn
2990 (use-global-map org-goto-map)
2991 (recursive-edit))
2992 (use-global-map gm)))))
2993 (kill-buffer "*org-goto*")
2994 org-selected-point))
2996 ;; FIXME: It may not be a good idea to temper with the prefix argument...
2997 (defun org-goto-ret (&optional arg)
2998 "Finish `org-goto' by going to the new location."
2999 (interactive "P")
3000 (setq org-selected-point (point)
3001 current-prefix-arg arg)
3002 (throw 'exit nil))
3004 (defun org-goto-left ()
3005 "Finish `org-goto' by going to the new location."
3006 (interactive)
3007 (if (org-on-heading-p)
3008 (progn
3009 (beginning-of-line 1)
3010 (setq org-selected-point (point)
3011 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3012 (throw 'exit nil))
3013 (error "Not on a heading")))
3015 (defun org-goto-right ()
3016 "Finish `org-goto' by going to the new location."
3017 (interactive)
3018 (if (org-on-heading-p)
3019 (progn
3020 (outline-end-of-subtree)
3021 (or (eobp) (forward-char 1))
3022 (setq org-selected-point (point)
3023 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3024 (throw 'exit nil))
3025 (error "Not on a heading")))
3027 (defun org-goto-quit ()
3028 "Finish `org-goto' without cursor motion."
3029 (interactive)
3030 (setq org-selected-point nil)
3031 (throw 'exit nil))
3033 ;;; Promotion, Demotion, Inserting new headlines
3035 (defvar org-ignore-region nil
3036 "To temporarily disable the active region.")
3038 (defun org-insert-heading (&optional force-heading)
3039 "Insert a new heading or item with same depth at point."
3040 (interactive "P")
3041 (when (or force-heading (not (org-insert-item)))
3042 (let* ((head (save-excursion
3043 (condition-case nil
3044 (org-back-to-heading)
3045 (error (outline-next-heading)))
3046 (prog1 (match-string 0)
3047 (funcall outline-level)))))
3048 (unless (bolp) (newline))
3049 (insert head)
3050 (if (looking-at "[ \t]*")
3051 (replace-match " "))
3052 (run-hooks 'org-insert-heading-hook))))
3054 (defun org-insert-item ()
3055 "Insert a new item at the current level.
3056 Return t when things worked, nil when we are not in an item."
3057 (when (save-excursion
3058 (condition-case nil
3059 (progn
3060 (org-beginning-of-item)
3061 (org-at-item-p)
3063 (error nil)))
3064 (unless (bolp) (newline))
3065 (insert (match-string 0))
3066 (org-maybe-renumber-ordered-list)
3069 (defun org-insert-todo-heading (arg)
3070 "Insert a new heading with the same level and TODO state as current heading.
3071 If the heading has no TODO state, or if the state is DONE, use the first
3072 state (TODO by default). Also with prefix arg, force first state."
3073 (interactive "P")
3074 (org-insert-heading)
3075 (save-excursion
3076 (org-back-to-heading)
3077 (outline-previous-heading)
3078 (looking-at org-todo-line-regexp))
3079 (if (or arg
3080 (not (match-beginning 2))
3081 (equal (match-string 2) org-done-string))
3082 (insert (car org-todo-keywords) " ")
3083 (insert (match-string 2) " ")))
3085 (defun org-promote-subtree ()
3086 "Promote the entire subtree.
3087 See also `org-promote'."
3088 (interactive)
3089 (save-excursion
3090 (org-map-tree 'org-promote)))
3092 (defun org-demote-subtree ()
3093 "Demote the entire subtree. See `org-demote'.
3094 See also `org-promote'."
3095 (interactive)
3096 (save-excursion
3097 (org-map-tree 'org-demote)))
3099 (defun org-do-promote ()
3100 "Promote the current heading higher up the tree.
3101 If the region is active in `transient-mark-mode', promote all headings
3102 in the region."
3103 (interactive)
3104 (save-excursion
3105 (if (org-region-active-p)
3106 (org-map-region 'org-promote (region-beginning) (region-end))
3107 (org-promote)))
3108 (org-fix-position-after-promote))
3110 (defun org-do-demote ()
3111 "Demote the current heading lower down the tree.
3112 If the region is active in `transient-mark-mode', demote all headings
3113 in the region."
3114 (interactive)
3115 (save-excursion
3116 (if (org-region-active-p)
3117 (org-map-region 'org-demote (region-beginning) (region-end))
3118 (org-demote)))
3119 (org-fix-position-after-promote))
3121 (defun org-fix-position-after-promote ()
3122 "Make sure that after pro/demotion cursor position is right."
3123 (and (equal (char-after) ?\ )
3124 (equal (char-before) ?*)
3125 (forward-char 1)))
3127 (defun org-get-legal-level (level change)
3128 "Rectify a level change under the influence of `org-odd-levels-only'
3129 LEVEL is a current level, CHANGE is by how much the level should be
3130 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3131 even level numbers will become the next higher odd number."
3132 (if org-odd-levels-only
3133 (cond ((not change) (1+ (* 2 (/ level 2))))
3134 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3135 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3136 (max 1 (+ level change))))
3138 (defun org-promote ()
3139 "Promote the current heading higher up the tree.
3140 If the region is active in `transient-mark-mode', promote all headings
3141 in the region."
3142 (org-back-to-heading t)
3143 (let* ((level (save-match-data (funcall outline-level)))
3144 (up-head (make-string (org-get-legal-level level -1) ?*))
3145 (diff (abs (- level (length up-head)))))
3146 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3147 (replace-match up-head nil t)
3148 ;; Fixup tag positioning
3149 (and org-auto-align-tags (org-set-tags nil t))
3150 (if org-adapt-indentation
3151 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
3152 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
3154 (defun org-demote ()
3155 "Demote the current heading lower down the tree.
3156 If the region is active in `transient-mark-mode', demote all headings
3157 in the region."
3158 (org-back-to-heading t)
3159 (let* ((level (save-match-data (funcall outline-level)))
3160 (down-head (make-string (org-get-legal-level level 1) ?*))
3161 (diff (abs (- level (length down-head)))))
3162 (replace-match down-head nil t)
3163 ;; Fixup tag positioning
3164 (and org-auto-align-tags (org-set-tags nil t))
3165 (if org-adapt-indentation
3166 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
3168 (defun org-map-tree (fun)
3169 "Call FUN for every heading underneath the current one."
3170 (org-back-to-heading)
3171 (let ((level (funcall outline-level)))
3172 (save-excursion
3173 (funcall fun)
3174 (while (and (progn
3175 (outline-next-heading)
3176 (> (funcall outline-level) level))
3177 (not (eobp)))
3178 (funcall fun)))))
3180 (defun org-map-region (fun beg end)
3181 "Call FUN for every heading between BEG and END."
3182 (let ((org-ignore-region t))
3183 (save-excursion
3184 (setq end (copy-marker end))
3185 (goto-char beg)
3186 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3187 (< (point) end))
3188 (funcall fun))
3189 (while (and (progn
3190 (outline-next-heading)
3191 (< (point) end))
3192 (not (eobp)))
3193 (funcall fun)))))
3195 (defun org-fixup-indentation (from to prohibit)
3196 "Change the indentation in the current entry by re-replacing FROM with TO.
3197 However, if the regexp PROHIBIT matches at all, don't do anything.
3198 This is being used to change indentation along with the length of the
3199 heading marker. But if there are any lines which are not indented, nothing
3200 is changed at all."
3201 (save-excursion
3202 (let ((end (save-excursion (outline-next-heading)
3203 (point-marker))))
3204 (unless (save-excursion (re-search-forward prohibit end t))
3205 (while (re-search-forward from end t)
3206 (replace-match to)
3207 (beginning-of-line 2)))
3208 (move-marker end nil))))
3210 ;;; Vertical tree motion, cutting and pasting of subtrees
3212 (defun org-move-subtree-up (&optional arg)
3213 "Move the current subtree up past ARG headlines of the same level."
3214 (interactive "p")
3215 (org-move-subtree-down (- (prefix-numeric-value arg))))
3217 (defun org-move-subtree-down (&optional arg)
3218 "Move the current subtree down past ARG headlines of the same level."
3219 (interactive "p")
3220 (setq arg (prefix-numeric-value arg))
3221 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3222 'outline-get-last-sibling))
3223 (ins-point (make-marker))
3224 (cnt (abs arg))
3225 beg end txt folded)
3226 ;; Select the tree
3227 (org-back-to-heading)
3228 (setq beg (point))
3229 (save-match-data
3230 (save-excursion (outline-end-of-heading)
3231 (setq folded (org-invisible-p)))
3232 (outline-end-of-subtree))
3233 (outline-next-heading)
3234 (setq end (point))
3235 ;; Find insertion point, with error handling
3236 (goto-char beg)
3237 (while (> cnt 0)
3238 (or (and (funcall movfunc) (looking-at outline-regexp))
3239 (progn (goto-char beg)
3240 (error "Cannot move past superior level or buffer limit")))
3241 (setq cnt (1- cnt)))
3242 (if (> arg 0)
3243 ;; Moving forward - still need to move over subtree
3244 (progn (outline-end-of-subtree)
3245 (outline-next-heading)
3246 (if (not (or (looking-at (concat "^" outline-regexp))
3247 (bolp)))
3248 (newline))))
3249 (move-marker ins-point (point))
3250 (setq txt (buffer-substring beg end))
3251 (delete-region beg end)
3252 (insert txt)
3253 (goto-char ins-point)
3254 (if folded (hide-subtree))
3255 (move-marker ins-point nil)))
3257 (defvar org-subtree-clip ""
3258 "Clipboard for cut and paste of subtrees.
3259 This is actually only a copy of the kill, because we use the normal kill
3260 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3262 (defvar org-subtree-clip-folded nil
3263 "Was the last copied subtree folded?
3264 This is used to fold the tree back after pasting.")
3266 (defun org-cut-subtree ()
3267 "Cut the current subtree into the clipboard.
3268 This is a short-hand for marking the subtree and then cutting it."
3269 (interactive)
3270 (org-copy-subtree 'cut))
3272 (defun org-copy-subtree (&optional cut)
3273 "Cut the current subtree into the clipboard.
3274 This is a short-hand for marking the subtree and then copying it.
3275 If CUT is non nil, actually cut the subtree."
3276 (interactive)
3277 (let (beg end folded)
3278 (org-back-to-heading)
3279 (setq beg (point))
3280 (save-match-data
3281 (save-excursion (outline-end-of-heading)
3282 (setq folded (org-invisible-p)))
3283 (outline-end-of-subtree))
3284 (if (equal (char-after) ?\n) (forward-char 1))
3285 (setq end (point))
3286 (goto-char beg)
3287 (when (> end beg)
3288 (setq org-subtree-clip-folded folded)
3289 (if cut (kill-region beg end) (copy-region-as-kill beg end))
3290 (setq org-subtree-clip (current-kill 0))
3291 (message "%s: Subtree with %d characters"
3292 (if cut "Cut" "Copied")
3293 (length org-subtree-clip)))))
3295 (defun org-paste-subtree (&optional level tree)
3296 "Paste the clipboard as a subtree, with modification of headline level.
3297 The entire subtree is promoted or demoted in order to match a new headline
3298 level. By default, the new level is derived from the visible headings
3299 before and after the insertion point, and taken to be the inferior headline
3300 level of the two. So if the previous visible heading is level 3 and the
3301 next is level 4 (or vice versa), level 4 will be used for insertion.
3302 This makes sure that the subtree remains an independent subtree and does
3303 not swallow low level entries.
3305 You can also force a different level, either by using a numeric prefix
3306 argument, or by inserting the heading marker by hand. For example, if the
3307 cursor is after \"*****\", then the tree will be shifted to level 5.
3309 If you want to insert the tree as is, just use \\[yank].
3311 If optional TREE is given, use this text instead of the kill ring."
3312 (interactive "P")
3313 (unless (org-kill-is-subtree-p tree)
3314 (error
3315 (substitute-command-keys
3316 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
3317 (let* ((txt (or tree (current-kill 0)))
3318 (^re (concat "^\\(" outline-regexp "\\)"))
3319 (re (concat "\\(" outline-regexp "\\)"))
3320 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3322 (old-level (if (string-match ^re txt)
3323 (- (match-end 0) (match-beginning 0))
3324 -1))
3325 (force-level (cond (level (prefix-numeric-value level))
3326 ((string-match
3327 ^re_ (buffer-substring (point-at-bol) (point)))
3328 (- (match-end 0) (match-beginning 0)))
3329 (t nil)))
3330 (previous-level (save-excursion
3331 (condition-case nil
3332 (progn
3333 (outline-previous-visible-heading 1)
3334 (if (looking-at re)
3335 (- (match-end 0) (match-beginning 0))
3337 (error 1))))
3338 (next-level (save-excursion
3339 (condition-case nil
3340 (progn
3341 (outline-next-visible-heading 1)
3342 (if (looking-at re)
3343 (- (match-end 0) (match-beginning 0))
3345 (error 1))))
3346 (new-level (or force-level (max previous-level next-level)))
3347 (shift (if (or (= old-level -1)
3348 (= new-level -1)
3349 (= old-level new-level))
3351 (- new-level old-level)))
3352 (shift1 shift)
3353 (delta (if (> shift 0) -1 1))
3354 (func (if (> shift 0) 'org-demote 'org-promote))
3355 (org-odd-levels-only nil)
3356 beg end)
3357 ;; Remove the forces level indicator
3358 (if force-level
3359 (delete-region (point-at-bol) (point)))
3360 ;; Make sure we start at the beginning of an empty line
3361 (if (not (bolp)) (insert "\n"))
3362 (if (not (looking-at "[ \t]*$"))
3363 (progn (insert "\n") (backward-char 1)))
3364 ;; Paste
3365 (setq beg (point))
3366 (insert txt)
3367 (setq end (point))
3368 (goto-char beg)
3369 ;; Shift if necessary
3370 (if (= shift 0)
3371 (message "Pasted at level %d, without shift" new-level)
3372 (save-restriction
3373 (narrow-to-region beg end)
3374 (while (not (= shift 0))
3375 (org-map-region func (point-min) (point-max))
3376 (setq shift (+ delta shift)))
3377 (goto-char (point-min))
3378 (message "Pasted at level %d, with shift by %d levels"
3379 new-level shift1)))
3380 (if (and (eq org-subtree-clip (current-kill 0))
3381 org-subtree-clip-folded)
3382 ;; The tree was folded before it was killed/copied
3383 (hide-subtree))))
3385 (defun org-kill-is-subtree-p (&optional txt)
3386 "Check if the current kill is an outline subtree, or a set of trees.
3387 Returns nil if kill does not start with a headline, or if the first
3388 headline level is not the largest headline level in the tree.
3389 So this will actually accept several entries of equal levels as well,
3390 which is OK for `org-paste-subtree'.
3391 If optional TXT is given, check this string instead of the current kill."
3392 (let* ((kill (or txt (current-kill 0) ""))
3393 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3394 (- (match-end 0) (match-beginning 0))))
3395 (re (concat "^" outline-regexp))
3396 (start 1))
3397 (if (not start-level)
3398 nil ;; does not even start with a heading
3399 (catch 'exit
3400 (while (setq start (string-match re kill (1+ start)))
3401 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3402 (throw 'exit nil)))
3403 t))))
3405 ;;; Plain list items
3407 (defun org-at-item-p ()
3408 "Is point in a line starting a hand-formatted item?"
3409 (let ((llt org-plain-list-ordered-item-terminator))
3410 (save-excursion
3411 (goto-char (point-at-bol))
3412 (looking-at
3413 (cond
3414 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3415 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3416 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3417 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3419 (defun org-get-indentation ()
3420 "Get the indentation of the current line, interpreting tabs."
3421 (save-excursion
3422 (beginning-of-line 1)
3423 (skip-chars-forward " \t")
3424 (current-column)))
3426 (defun org-beginning-of-item ()
3427 "Go to the beginning of the current hand-formatted item.
3428 If the cursor is not in an item, throw an error."
3429 (let ((pos (point))
3430 (limit (save-excursion (org-back-to-heading)
3431 (beginning-of-line 2) (point)))
3432 ind ind1)
3433 (if (org-at-item-p)
3434 (beginning-of-line 1)
3435 (beginning-of-line 1)
3436 (skip-chars-forward " \t")
3437 (setq ind (current-column))
3438 (if (catch 'exit
3439 (while t
3440 (beginning-of-line 0)
3441 (if (< (point) limit) (throw 'exit nil))
3442 (unless (looking-at " \t]*$")
3443 (skip-chars-forward " \t")
3444 (setq ind1 (current-column))
3445 (if (< ind1 ind)
3446 (throw 'exit (org-at-item-p))))))
3448 (goto-char pos)
3449 (error "Not in an item")))))
3451 (defun org-end-of-item ()
3452 "Go to the end of the current hand-formatted item.
3453 If the cursor is not in an item, throw an error."
3454 (let ((pos (point))
3455 (limit (save-excursion (outline-next-heading) (point)))
3456 (ind (save-excursion
3457 (org-beginning-of-item)
3458 (skip-chars-forward " \t")
3459 (current-column)))
3460 ind1)
3461 (if (catch 'exit
3462 (while t
3463 (beginning-of-line 2)
3464 (if (>= (point) limit) (throw 'exit t))
3465 (unless (looking-at "[ \t]*$")
3466 (skip-chars-forward " \t")
3467 (setq ind1 (current-column))
3468 (if (<= ind1 ind) (throw 'exit t)))))
3469 (beginning-of-line 1)
3470 (goto-char pos)
3471 (error "Not in an item"))))
3473 (defun org-move-item-down (arg)
3474 "Move the plain list item at point down, i.e. swap with following item.
3475 Subitems (items with larger indentation) are considered part of the item,
3476 so this really moves item trees."
3477 (interactive "p")
3478 (let (beg end ind ind1 (pos (point)) txt)
3479 (org-beginning-of-item)
3480 (setq beg (point))
3481 (setq ind (org-get-indentation))
3482 (org-end-of-item)
3483 (setq end (point))
3484 (setq ind1 (org-get-indentation))
3485 (if (and (org-at-item-p) (= ind ind1))
3486 (progn
3487 (org-end-of-item)
3488 (setq txt (buffer-substring beg end))
3489 (save-excursion
3490 (delete-region beg end))
3491 (setq pos (point))
3492 (insert txt)
3493 (goto-char pos)
3494 (org-maybe-renumber-ordered-list))
3495 (goto-char pos)
3496 (error "Cannot move this item further down"))))
3498 (defun org-move-item-up (arg)
3499 "Move the plain list item at point up, i.e. swap with previous item.
3500 Subitems (items with larger indentation) are considered part of the item,
3501 so this really moves item trees."
3502 (interactive "p")
3503 (let (beg end ind ind1 (pos (point)) txt)
3504 (org-beginning-of-item)
3505 (setq beg (point))
3506 (setq ind (org-get-indentation))
3507 (org-end-of-item)
3508 (setq end (point))
3509 (goto-char beg)
3510 (catch 'exit
3511 (while t
3512 (beginning-of-line 0)
3513 (if (looking-at "[ \t]*$")
3515 (if (<= (setq ind1 (org-get-indentation)) ind)
3516 (throw 'exit t)))))
3517 (condition-case nil
3518 (org-beginning-of-item)
3519 (error (goto-char beg)
3520 (error "Cannot move this item further up")))
3521 (setq ind1 (org-get-indentation))
3522 (if (and (org-at-item-p) (= ind ind1))
3523 (progn
3524 (setq txt (buffer-substring beg end))
3525 (save-excursion
3526 (delete-region beg end))
3527 (setq pos (point))
3528 (insert txt)
3529 (goto-char pos)
3530 (org-maybe-renumber-ordered-list))
3531 (goto-char pos)
3532 (error "Cannot move this item further up"))))
3534 (defun org-maybe-renumber-ordered-list ()
3535 "Renumber the ordered list at point if setup allows it.
3536 This tests the user option `org-auto-renumber-ordered-lists' before
3537 doing the renumbering."
3538 (and org-auto-renumber-ordered-lists
3539 (org-at-item-p)
3540 (match-beginning 3)
3541 (org-renumber-ordered-list 1)))
3543 (defun org-get-string-indentation (s)
3544 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3545 (let ((n -1) (i 0) (w tab-width) c)
3546 (catch 'exit
3547 (while (< (setq n (1+ n)) (length s))
3548 (setq c (aref s n))
3549 (cond ((= c ?\ ) (setq i (1+ i)))
3550 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3551 (t (throw 'exit t)))))
3554 (defun org-renumber-ordered-list (arg)
3555 "Renumber an ordered plain list.
3556 Cursor next to be in the first line of an item, the line that starts
3557 with something like \"1.\" or \"2)\"."
3558 (interactive "p")
3559 (unless (and (org-at-item-p)
3560 (match-beginning 3))
3561 (error "This is not an ordered list"))
3562 (let ((line (org-current-line))
3563 (col (current-column))
3564 (ind (org-get-string-indentation
3565 (buffer-substring (point-at-bol) (match-beginning 3))))
3566 ;; (term (substring (match-string 3) -1))
3567 ind1 (n (1- arg)))
3568 ;; find where this list begins
3569 (catch 'exit
3570 (while t
3571 (catch 'next
3572 (beginning-of-line 0)
3573 (if (looking-at "[ \t]*$") (throw 'next t))
3574 (skip-chars-forward " \t") (setq ind1 (current-column))
3575 (if (or (< ind1 ind)
3576 (and (= ind1 ind)
3577 (not (org-at-item-p))))
3578 (throw 'exit t)))))
3579 ;; Walk forward and replace these numbers
3580 (catch 'exit
3581 (while t
3582 (catch 'next
3583 (beginning-of-line 2)
3584 (if (eobp) (throw 'exit nil))
3585 (if (looking-at "[ \t]*$") (throw 'next nil))
3586 (skip-chars-forward " \t") (setq ind1 (current-column))
3587 (if (> ind1 ind) (throw 'next t))
3588 (if (< ind1 ind) (throw 'exit t))
3589 (if (not (org-at-item-p)) (throw 'exit nil))
3590 (if (not (match-beginning 3))
3591 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3592 (delete-region (match-beginning 3) (1- (match-end 3)))
3593 (goto-char (match-beginning 3))
3594 (insert (format "%d" (setq n (1+ n)))))))
3595 (goto-line line)
3596 (move-to-column col)))
3598 (defvar org-last-indent-begin-marker (make-marker))
3599 (defvar org-last-indent-end-marker (make-marker))
3601 (defun org-outdent-item (arg)
3602 "Outdent a local list item."
3603 (interactive "p")
3604 (org-indent-item (- arg)))
3606 (defun org-indent-item (arg)
3607 "Indent a local list item."
3608 (interactive "p")
3609 (unless (org-at-item-p)
3610 (error "Not on an item"))
3611 (let (beg end ind ind1)
3612 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3613 (setq beg org-last-indent-begin-marker
3614 end org-last-indent-end-marker)
3615 (org-beginning-of-item)
3616 (setq beg (move-marker org-last-indent-begin-marker (point)))
3617 (org-end-of-item)
3618 (setq end (move-marker org-last-indent-end-marker (point))))
3619 (goto-char beg)
3620 (skip-chars-forward " \t") (setq ind (current-column))
3621 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3622 (while (< (point) end)
3623 (beginning-of-line 1)
3624 (skip-chars-forward " \t") (setq ind1 (current-column))
3625 (delete-region (point-at-bol) (point))
3626 (indent-to-column (+ ind1 arg))
3627 (beginning-of-line 2))
3628 (goto-char beg)))
3630 ;;; Archiving
3632 (defun org-archive-subtree ()
3633 "Move the current subtree to the archive.
3634 The archive can be a certain top-level heading in the current file, or in
3635 a different file. The tree will be moved to that location, the subtree
3636 heading be marked DONE, and the current time will be added."
3637 (interactive)
3638 ;; Save all relevant TODO keyword-relatex variables
3639 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3640 (tr-org-todo-keywords org-todo-keywords)
3641 (tr-org-todo-interpretation org-todo-interpretation)
3642 (tr-org-done-string org-done-string)
3643 (tr-org-todo-regexp org-todo-regexp)
3644 (tr-org-todo-line-regexp org-todo-line-regexp)
3645 (this-buffer (current-buffer))
3646 file heading buffer level newfile-p)
3647 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3648 (progn
3649 (setq file (format (match-string 1 org-archive-location)
3650 (file-name-nondirectory buffer-file-name))
3651 heading (match-string 2 org-archive-location)))
3652 (error "Invalid `org-archive-location'"))
3653 (if (> (length file) 0)
3654 (setq newfile-p (not (file-exists-p file))
3655 buffer (find-file-noselect file))
3656 (setq buffer (current-buffer)))
3657 (unless buffer
3658 (error "Cannot access file \"%s\"" file))
3659 (if (and (> (length heading) 0)
3660 (string-match "^\\*+" heading))
3661 (setq level (match-end 0))
3662 (setq heading nil level 0))
3663 (save-excursion
3664 ;; We first only copy, in case something goes wrong
3665 ;; we need to protect this-command, to avoid kill-region sets it,
3666 ;; which would lead to duplication of subtrees
3667 (let (this-command) (org-copy-subtree))
3668 (set-buffer buffer)
3669 ;; Enforce org-mode for the archive buffer
3670 (if (not (eq major-mode 'org-mode))
3671 ;; Force the mode for future visits.
3672 (let ((org-insert-mode-line-in-empty-file t))
3673 (call-interactively 'org-mode)))
3674 (when newfile-p
3675 (goto-char (point-max))
3676 (insert (format "\nArchived entries from file %s\n\n"
3677 (buffer-file-name this-buffer))))
3678 ;; Force the TODO keywords of the original buffer
3679 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3680 (org-todo-keywords tr-org-todo-keywords)
3681 (org-todo-interpretation tr-org-todo-interpretation)
3682 (org-done-string tr-org-done-string)
3683 (org-todo-regexp tr-org-todo-regexp)
3684 (org-todo-line-regexp tr-org-todo-line-regexp))
3685 (goto-char (point-min))
3686 (if heading
3687 (progn
3688 (if (re-search-forward
3689 (concat "\\(^\\|\r\\)"
3690 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3691 nil t)
3692 (goto-char (match-end 0))
3693 ;; Heading not found, just insert it at the end
3694 (goto-char (point-max))
3695 (or (bolp) (insert "\n"))
3696 (insert "\n" heading "\n")
3697 (end-of-line 0))
3698 ;; Make the heading visible, and the following as well
3699 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3700 (if (re-search-forward
3701 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3702 nil t)
3703 (progn (goto-char (match-beginning 0)) (insert "\n")
3704 (beginning-of-line 0))
3705 (goto-char (point-max)) (insert "\n")))
3706 (goto-char (point-max)) (insert "\n"))
3707 ;; Paste
3708 (org-paste-subtree (1+ level))
3709 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3710 (if org-archive-mark-done
3711 (org-todo (length org-todo-keywords)))
3712 ;; Move cursor to right after the TODO keyword
3713 (when org-archive-stamp-time
3714 (beginning-of-line 1)
3715 (looking-at org-todo-line-regexp)
3716 (goto-char (or (match-end 2) (match-beginning 3)))
3717 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3718 (org-current-time))
3719 ")"))
3720 ;; Save the buffer, if it is not the same buffer.
3721 (if (not (eq this-buffer buffer)) (save-buffer))))
3722 ;; Here we are back in the original buffer. Everything seems to have
3723 ;; worked. So now cut the tree and finish up.
3724 (let (this-command) (org-cut-subtree))
3725 (if (looking-at "[ \t]*$") (kill-line))
3726 (message "Subtree archived %s"
3727 (if (eq this-buffer buffer)
3728 (concat "under heading: " heading)
3729 (concat "in file: " (abbreviate-file-name file))))))
3731 ;;; Completion
3733 (defun org-complete (&optional arg)
3734 "Perform completion on word at point.
3735 At the beginning of a headline, this completes TODO keywords as given in
3736 `org-todo-keywords'.
3737 If the current word is preceded by a backslash, completes the TeX symbols
3738 that are supported for HTML support.
3739 If the current word is preceded by \"#+\", completes special words for
3740 setting file options.
3741 At all other locations, this simply calls `ispell-complete-word'."
3742 (interactive "P")
3743 (catch 'exit
3744 (let* ((end (point))
3745 (beg1 (save-excursion
3746 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3747 (skip-chars-backward "a-zA-Z_@0-9")
3748 (point)))
3749 (beg (save-excursion
3750 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3751 (skip-chars-backward "a-zA-Z0-9_:$")
3752 (point)))
3753 (camel (equal (char-before beg) ?*))
3754 (tag (equal (char-before beg1) ?:))
3755 (texp (equal (char-before beg) ?\\))
3756 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3757 beg)
3758 "#+"))
3759 (completion-ignore-case opt)
3760 (type nil)
3761 (tbl nil)
3762 (table (cond
3763 (opt
3764 (setq type :opt)
3765 (mapcar (lambda (x)
3766 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3767 (cons (match-string 2 x) (match-string 1 x)))
3768 (org-split-string (org-get-current-options) "\n")))
3769 (texp
3770 (setq type :tex)
3771 org-html-entities)
3772 ((string-match "\\`\\*+[ \t]*\\'"
3773 (buffer-substring (point-at-bol) beg))
3774 (setq type :todo)
3775 (mapcar 'list org-todo-keywords))
3776 (camel
3777 (setq type :camel)
3778 (save-excursion
3779 (goto-char (point-min))
3780 (while (re-search-forward org-todo-line-regexp nil t)
3781 (push (list
3782 (if org-file-link-context-use-camel-case
3783 (org-make-org-heading-camel (match-string 3) t)
3784 (org-make-org-heading-search-string
3785 (match-string 3) t)))
3786 tbl)))
3787 tbl)
3788 (tag (setq type :tag beg beg1)
3789 (org-get-buffer-tags))
3790 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3791 (pattern (buffer-substring-no-properties beg end))
3792 (completion (try-completion pattern table)))
3793 (cond ((eq completion t)
3794 (if (equal type :opt)
3795 (insert (substring (cdr (assoc (upcase pattern) table))
3796 (length pattern)))))
3797 ((null completion)
3798 (message "Can't find completion for \"%s\"" pattern)
3799 (ding))
3800 ((not (string= pattern completion))
3801 (delete-region beg end)
3802 (if (string-match " +$" completion)
3803 (setq completion (replace-match "" t t completion)))
3804 (insert completion)
3805 (if (get-buffer-window "*Completions*")
3806 (delete-window (get-buffer-window "*Completions*")))
3807 (if (assoc completion table)
3808 (if (eq type :todo) (insert " ")
3809 (if (eq type :tag) (insert ":"))))
3810 (if (and (equal type :opt) (assoc completion table))
3811 (message "%s" (substitute-command-keys
3812 "Press \\[org-complete] again to insert example settings"))))
3814 (message "Making completion list...")
3815 (let ((list (sort (all-completions pattern table) 'string<)))
3816 (with-output-to-temp-buffer "*Completions*"
3817 (condition-case nil
3818 ;; Protection needed for XEmacs and emacs 21
3819 (display-completion-list list pattern)
3820 (error (display-completion-list list)))))
3821 (message "Making completion list...%s" "done"))))))
3823 ;;; Comments, TODO and DEADLINE
3825 (defun org-toggle-comment ()
3826 "Change the COMMENT state of an entry."
3827 (interactive)
3828 (save-excursion
3829 (org-back-to-heading)
3830 (if (looking-at (concat outline-regexp
3831 "\\( +\\<" org-comment-string "\\>\\)"))
3832 (replace-match "" t t nil 1)
3833 (if (looking-at outline-regexp)
3834 (progn
3835 (goto-char (match-end 0))
3836 (insert " " org-comment-string))))))
3838 (defvar org-last-todo-state-is-todo nil
3839 "This is non-nil when the last TODO state change led to a TODO state.
3840 If the last change removed the TODO tag or switched to DONE, then
3841 this is nil.")
3843 (defun org-todo (&optional arg)
3844 "Change the TODO state of an item.
3845 The state of an item is given by a keyword at the start of the heading,
3846 like
3847 *** TODO Write paper
3848 *** DONE Call mom
3850 The different keywords are specified in the variable `org-todo-keywords'.
3851 By default the available states are \"TODO\" and \"DONE\".
3852 So for this example: when the item starts with TODO, it is changed to DONE.
3853 When it starts with DONE, the DONE is removed. And when neither TODO nor
3854 DONE are present, add TODO at the beginning of the heading.
3856 With prefix arg, use completion to determine the new state. With numeric
3857 prefix arg, switch to that state."
3858 (interactive "P")
3859 (save-excursion
3860 (org-back-to-heading)
3861 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3862 (or (looking-at (concat " +" org-todo-regexp " *"))
3863 (looking-at " *"))
3864 (let* ((this (match-string 1))
3865 (completion-ignore-case t)
3866 (member (member this org-todo-keywords))
3867 (tail (cdr member))
3868 (state (cond
3869 ((equal arg '(4))
3870 ;; Read a state with completion
3871 (completing-read "State: " (mapcar (lambda(x) (list x))
3872 org-todo-keywords)
3873 nil t))
3874 ((eq arg 'right)
3875 (if this
3876 (if tail (car tail) nil)
3877 (car org-todo-keywords)))
3878 ((eq arg 'left)
3879 (if (equal member org-todo-keywords)
3881 (if this
3882 (nth (- (length org-todo-keywords) (length tail) 2)
3883 org-todo-keywords)
3884 org-done-string)))
3885 (arg
3886 ;; user requests a specific state
3887 (nth (1- (prefix-numeric-value arg))
3888 org-todo-keywords))
3889 ((null member) (car org-todo-keywords))
3890 ((null tail) nil) ;; -> first entry
3891 ((eq org-todo-interpretation 'sequence)
3892 (car tail))
3893 ((memq org-todo-interpretation '(type priority))
3894 (if (eq this-command last-command)
3895 (car tail)
3896 (if (> (length tail) 0) org-done-string nil)))
3897 (t nil)))
3898 (next (if state (concat " " state " ") " ")))
3899 (replace-match next t t)
3900 (setq org-last-todo-state-is-todo
3901 (not (equal state org-done-string)))
3902 (when org-log-done
3903 (if (equal state org-done-string)
3904 (org-log-done)
3905 (if (not this)
3906 (org-log-done t))))
3907 ;; Fixup tag positioning
3908 (and org-auto-align-tags (org-set-tags nil t))
3909 (run-hooks 'org-after-todo-state-change-hook)))
3910 ;; Fixup cursor location if close to the keyword
3911 (if (and (outline-on-heading-p)
3912 (not (bolp))
3913 (save-excursion (beginning-of-line 1)
3914 (looking-at org-todo-line-regexp))
3915 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3916 (progn
3917 (goto-char (or (match-end 2) (match-end 1)))
3918 (just-one-space))))
3920 (defun org-log-done (&optional undone)
3921 "Add a time stamp logging that a TODO entry has been closed.
3922 When UNDONE is non-nil, remove such a time stamp again."
3923 (interactive)
3924 (let (beg end col)
3925 (save-excursion
3926 (org-back-to-heading t)
3927 (setq beg (point))
3928 (looking-at (concat outline-regexp " *"))
3929 (goto-char (match-end 0))
3930 (setq col (current-column))
3931 (outline-next-heading)
3932 (setq end (point))
3933 (goto-char beg)
3934 (when (re-search-forward (concat
3935 "[\r\n]\\([ \t]*"
3936 (regexp-quote org-closed-string)
3937 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3938 (delete-region (match-beginning 1) (match-end 1)))
3939 (unless undone
3940 (org-back-to-heading t)
3941 (skip-chars-forward "^\n\r")
3942 (goto-char (min (1+ (point)) (point-max)))
3943 (when (not (member (char-before) '(?\r ?\n)))
3944 (insert "\n"))
3945 (indent-to col)
3946 (insert org-closed-string " "
3947 (format-time-string
3948 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3949 (org-current-time))
3950 "\n")))))
3952 (defun org-show-todo-tree (arg)
3953 "Make a compact tree which shows all headlines marked with TODO.
3954 The tree will show the lines where the regexp matches, and all higher
3955 headlines above the match.
3956 With \\[universal-argument] prefix, also show the DONE entries.
3957 With a numeric prefix N, construct a sparse tree for the Nth element
3958 of `org-todo-keywords'."
3959 (interactive "P")
3960 (let ((case-fold-search nil)
3961 (kwd-re
3962 (cond ((null arg) org-not-done-regexp)
3963 ((equal arg '(4)) org-todo-regexp)
3964 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3965 (regexp-quote (nth (1- (prefix-numeric-value arg))
3966 org-todo-keywords)))
3967 (t (error "Invalid prefix argument: %s" arg)))))
3968 (message "%d TODO entries found"
3969 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3971 (defun org-deadline ()
3972 "Insert the DEADLINE: string to make a deadline.
3973 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3974 to modify it to the correct date."
3975 (interactive)
3976 (insert
3977 org-deadline-string " "
3978 (format-time-string (car org-time-stamp-formats)
3979 (org-read-date nil 'to-time)))
3980 (message "%s" (substitute-command-keys
3981 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3983 (defun org-schedule ()
3984 "Insert the SCHEDULED: string to schedule a TODO item.
3985 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3986 to modify it to the correct date."
3987 (interactive)
3988 (insert
3989 org-scheduled-string " "
3990 (format-time-string (car org-time-stamp-formats)
3991 (org-read-date nil 'to-time)))
3992 (message "%s" (substitute-command-keys
3993 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3996 (defun org-occur (regexp &optional callback)
3997 "Make a compact tree which shows all matches of REGEXP.
3998 The tree will show the lines where the regexp matches, and all higher
3999 headlines above the match. It will also show the heading after the match,
4000 to make sure editing the matching entry is easy.
4001 If CALLBACK is non-nil, it is a function which is called to confirm
4002 that the match should indeed be shown."
4003 (interactive "sRegexp: ")
4004 (org-remove-occur-highlights nil nil t)
4005 (setq regexp (org-check-occur-regexp regexp))
4006 (let ((cnt 0))
4007 (save-excursion
4008 (goto-char (point-min))
4009 (hide-sublevels 1)
4010 (while (re-search-forward regexp nil t)
4011 (when (or (not callback)
4012 (save-match-data (funcall callback)))
4013 (setq cnt (1+ cnt))
4014 (org-highlight-new-match (match-beginning 0) (match-end 0))
4015 (org-show-hierarchy-above))))
4016 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
4017 nil 'local)
4018 (run-hooks 'org-occur-hook)
4019 (if (interactive-p)
4020 (message "%d match(es) for regexp %s" cnt regexp))
4021 cnt))
4023 (defun org-show-hierarchy-above ()
4024 "Make sure point and the headings hierarchy above is visible."
4025 (catch 'exit
4026 (if (org-on-heading-p t)
4027 (org-flag-heading nil) ; only show the heading
4028 (and (or (org-invisible-p) (org-invisible-p2))
4029 (org-show-hidden-entry))) ; show entire entry
4030 (save-excursion
4031 (and org-show-following-heading
4032 (outline-next-heading)
4033 (org-flag-heading nil))) ; show the next heading
4034 (when org-show-hierarchy-above
4035 (save-excursion ; show all higher headings
4036 (while (and (condition-case nil
4037 (progn (org-up-heading-all 1) t)
4038 (error nil))
4039 (not (bobp)))
4040 (org-flag-heading nil))))))
4042 ;; Overlay compatibility functions
4043 (defun org-make-overlay (beg end &optional buffer)
4044 (if (featurep 'xemacs)
4045 (make-extent beg end buffer)
4046 (make-overlay beg end buffer)))
4047 (defun org-delete-overlay (ovl)
4048 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4049 (defun org-detatch-overlay (ovl)
4050 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4051 (defun org-move-overlay (ovl beg end &optional buffer)
4052 (if (featurep 'xemacs)
4053 (set-extent-endpoints ovl beg end buffer)
4054 (move-overlay ovl beg end buffer)))
4055 (defun org-overlay-put (ovl prop value)
4056 (if (featurep 'xemacs)
4057 (set-extent-property ovl prop value)
4058 (overlay-put ovl prop value)))
4060 (defvar org-occur-highlights nil)
4061 (defun org-highlight-new-match (beg end)
4062 "Highlight from BEG to END and mark the highlight is an occur headline."
4063 (let ((ov (org-make-overlay beg end)))
4064 (org-overlay-put ov 'face 'secondary-selection)
4065 (push ov org-occur-highlights)))
4067 (defun org-remove-occur-highlights (&optional beg end noremove)
4068 "Remove the occur highlights from the buffer.
4069 BEG and END are ignored. If NOREMOVE is nil, remove this function
4070 from the `before-change-functions' in the current buffer."
4071 (interactive)
4072 (mapc 'org-delete-overlay org-occur-highlights)
4073 (setq org-occur-highlights nil)
4074 (unless noremove
4075 (remove-hook 'before-change-functions
4076 'org-remove-occur-highlights 'local)))
4078 ;;; Priorities
4080 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
4081 "Regular expression matching the priority indicator.")
4083 (defvar org-remove-priority-next-time nil)
4085 (defun org-priority-up ()
4086 "Increase the priority of the current item."
4087 (interactive)
4088 (org-priority 'up))
4090 (defun org-priority-down ()
4091 "Decrease the priority of the current item."
4092 (interactive)
4093 (org-priority 'down))
4095 (defun org-priority (&optional action)
4096 "Change the priority of an item by ARG.
4097 ACTION can be set, up, or down."
4098 (interactive)
4099 (setq action (or action 'set))
4100 (let (current new news have remove)
4101 (save-excursion
4102 (org-back-to-heading)
4103 (if (looking-at org-priority-regexp)
4104 (setq current (string-to-char (match-string 2))
4105 have t)
4106 (setq current org-default-priority))
4107 (cond
4108 ((eq action 'set)
4109 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
4110 (setq new (read-char-exclusive))
4111 (cond ((equal new ?\ ) (setq remove t))
4112 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
4113 (error "Priority must be between `%c' and `%c'"
4114 ?A org-lowest-priority))))
4115 ((eq action 'up)
4116 (setq new (1- current)))
4117 ((eq action 'down)
4118 (setq new (1+ current)))
4119 (t (error "Invalid action")))
4120 (setq new (min (max ?A (upcase new)) org-lowest-priority))
4121 (setq news (format "%c" new))
4122 (if have
4123 (if remove
4124 (replace-match "" t t nil 1)
4125 (replace-match news t t nil 2))
4126 (if remove
4127 (error "No priority cookie found in line")
4128 (looking-at org-todo-line-regexp)
4129 (if (match-end 2)
4130 (progn
4131 (goto-char (match-end 2))
4132 (insert " [#" news "]"))
4133 (goto-char (match-beginning 3))
4134 (insert "[#" news "] ")))))
4135 (if remove
4136 (message "Priority removed")
4137 (message "Priority of current item set to %s" news))))
4140 (defun org-get-priority (s)
4141 "Find priority cookie and return priority."
4142 (save-match-data
4143 (if (not (string-match org-priority-regexp s))
4144 (* 1000 (- org-lowest-priority org-default-priority))
4145 (* 1000 (- org-lowest-priority
4146 (string-to-char (match-string 2 s)))))))
4148 ;;; Timestamps
4150 (defvar org-last-changed-timestamp nil)
4152 (defun org-time-stamp (arg)
4153 "Prompt for a date/time and insert a time stamp.
4154 If the user specifies a time like HH:MM, or if this command is called
4155 with a prefix argument, the time stamp will contain date and time.
4156 Otherwise, only the date will be included. All parts of a date not
4157 specified by the user will be filled in from the current date/time.
4158 So if you press just return without typing anything, the time stamp
4159 will represent the current date/time. If there is already a timestamp
4160 at the cursor, it will be modified."
4161 (interactive "P")
4162 (let ((fmt (if arg (cdr org-time-stamp-formats)
4163 (car org-time-stamp-formats)))
4164 (org-time-was-given nil)
4165 time)
4166 (cond
4167 ((and (org-at-timestamp-p)
4168 (eq last-command 'org-time-stamp)
4169 (eq this-command 'org-time-stamp))
4170 (insert "--")
4171 (setq time (let ((this-command this-command))
4172 (org-read-date arg 'totime)))
4173 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4174 (insert (format-time-string fmt time)))
4175 ((org-at-timestamp-p)
4176 (setq time (let ((this-command this-command))
4177 (org-read-date arg 'totime)))
4178 (and (org-at-timestamp-p) (replace-match
4179 (setq org-last-changed-timestamp
4180 (format-time-string fmt time))
4181 t t))
4182 (message "Timestamp updated"))
4184 (setq time (let ((this-command this-command))
4185 (org-read-date arg 'totime)))
4186 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4187 (insert (format-time-string fmt time))))))
4189 (defun org-time-stamp-inactive (&optional arg)
4190 "Insert an inactive time stamp.
4191 An inactive time stamp is enclosed in square brackets instead of angle
4192 brackets. It is inactive in the sense that it does not trigger agenda entries,
4193 does not link to the calendar and cannot be changed with the S-cursor keys.
4194 So these are more for recording a certain time/date."
4195 (interactive "P")
4196 (let ((fmt (if arg (cdr org-time-stamp-formats)
4197 (car org-time-stamp-formats)))
4198 (org-time-was-given nil)
4199 time)
4200 (setq time (org-read-date arg 'totime))
4201 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4202 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
4203 (insert (format-time-string fmt time))))
4205 (defvar org-date-ovl (org-make-overlay 1 1))
4206 (org-overlay-put org-date-ovl 'face 'org-warning)
4207 (org-detatch-overlay org-date-ovl)
4209 (defun org-read-date (&optional with-time to-time)
4210 "Read a date and make things smooth for the user.
4211 The prompt will suggest to enter an ISO date, but you can also enter anything
4212 which will at least partially be understood by `parse-time-string'.
4213 Unrecognized parts of the date will default to the current day, month, year,
4214 hour and minute. For example,
4215 3-2-5 --> 2003-02-05
4216 feb 15 --> currentyear-02-15
4217 sep 12 9 --> 2009-09-12
4218 12:45 --> today 12:45
4219 22 sept 0:34 --> currentyear-09-22 0:34
4220 12 --> currentyear-currentmonth-12
4221 Fri --> nearest Friday (today or later)
4222 etc.
4223 The function understands only English month and weekday abbreviations,
4224 but this can be configured with the variables `parse-time-months' and
4225 `parse-time-weekdays'.
4227 While prompting, a calendar is popped up - you can also select the
4228 date with the mouse (button 1). The calendar shows a period of three
4229 months. To scroll it to other months, use the keys `>' and `<'.
4230 If you don't like the calendar, turn it off with
4231 \(setq org-popup-calendar-for-date-prompt nil)
4233 With optional argument TO-TIME, the date will immediately be converted
4234 to an internal time.
4235 With an optional argument WITH-TIME, the prompt will suggest to also
4236 insert a time. Note that when WITH-TIME is not set, you can still
4237 enter a time, and this function will inform the calling routine about
4238 this change. The calling routine may then choose to change the format
4239 used to insert the time stamp into the buffer to include the time."
4240 (require 'parse-time)
4241 (let* ((org-time-stamp-rounding-minutes
4242 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
4243 (ct (org-current-time))
4244 (default-time
4245 ;; Default time is either today, or, when entering a range,
4246 ;; the range start.
4247 (if (save-excursion
4248 (re-search-backward
4249 (concat org-ts-regexp "--\\=")
4250 (- (point) 20) t))
4251 (apply
4252 'encode-time
4253 (mapcar (lambda(x) (or x 0))
4254 (parse-time-string (match-string 1))))
4255 ct))
4256 (calendar-move-hook nil)
4257 (view-diary-entries-initially nil)
4258 (timestr (format-time-string
4259 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
4260 (prompt (format "YYYY-MM-DD [%s]: " timestr))
4261 ans ans1 ans2
4262 second minute hour day month year tl wday wday1)
4264 (if org-popup-calendar-for-date-prompt
4265 (save-excursion
4266 (save-window-excursion
4267 (calendar)
4268 (calendar-forward-day (- (time-to-days default-time)
4269 (calendar-absolute-from-gregorian
4270 (calendar-current-date))))
4271 (org-eval-in-calendar nil)
4272 (let* ((old-map (current-local-map))
4273 (map (copy-keymap calendar-mode-map))
4274 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
4275 (define-key map (kbd "RET") 'org-calendar-select)
4276 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
4277 'org-calendar-select-mouse)
4278 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
4279 'org-calendar-select-mouse)
4280 (define-key minibuffer-local-map [(meta shift left)]
4281 (lambda () (interactive)
4282 (org-eval-in-calendar '(calendar-backward-month 1))))
4283 (define-key minibuffer-local-map [(meta shift right)]
4284 (lambda () (interactive)
4285 (org-eval-in-calendar '(calendar-forward-month 1))))
4286 (define-key minibuffer-local-map [(shift up)]
4287 (lambda () (interactive)
4288 (org-eval-in-calendar '(calendar-backward-week 1))))
4289 (define-key minibuffer-local-map [(shift down)]
4290 (lambda () (interactive)
4291 (org-eval-in-calendar '(calendar-forward-week 1))))
4292 (define-key minibuffer-local-map [(shift left)]
4293 (lambda () (interactive)
4294 (org-eval-in-calendar '(calendar-backward-day 1))))
4295 (define-key minibuffer-local-map [(shift right)]
4296 (lambda () (interactive)
4297 (org-eval-in-calendar '(calendar-forward-day 1))))
4298 (define-key minibuffer-local-map ">"
4299 (lambda () (interactive)
4300 (org-eval-in-calendar '(scroll-calendar-left 1))))
4301 (define-key minibuffer-local-map "<"
4302 (lambda () (interactive)
4303 (org-eval-in-calendar '(scroll-calendar-right 1))))
4304 (unwind-protect
4305 (progn
4306 (use-local-map map)
4307 (setq ans (read-string prompt "" nil nil))
4308 (if (not (string-match "\\S-" ans)) (setq ans nil))
4309 (setq ans (or ans1 ans ans2)))
4310 (use-local-map old-map)))))
4311 ;; Naked prompt only
4312 (setq ans (read-string prompt "" nil timestr)))
4313 (org-detatch-overlay org-date-ovl)
4315 (if (string-match
4316 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
4317 (progn
4318 (setq year (if (match-end 2)
4319 (string-to-number (match-string 2 ans))
4320 (string-to-number (format-time-string "%Y")))
4321 month (string-to-number (match-string 3 ans))
4322 day (string-to-number (match-string 4 ans)))
4323 (if (< year 100) (setq year (+ 2000 year)))
4324 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
4325 t nil ans))))
4326 (setq tl (parse-time-string ans)
4327 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
4328 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
4329 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
4330 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
4331 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
4332 second (or (nth 0 tl) 0)
4333 wday (nth 6 tl))
4334 (when (and wday (not (nth 3 tl)))
4335 ;; Weekday was given, but no day, so pick that day in the week
4336 ;; on or after the derived date.
4337 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
4338 (unless (equal wday wday1)
4339 (setq day (+ day (% (- wday wday1 -7) 7)))))
4340 (if (and (boundp 'org-time-was-given)
4341 (nth 2 tl))
4342 (setq org-time-was-given t))
4343 (if (< year 100) (setq year (+ 2000 year)))
4344 (if to-time
4345 (encode-time second minute hour day month year)
4346 (if (or (nth 1 tl) (nth 2 tl))
4347 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
4348 (format "%04d-%02d-%02d" year month day)))))
4350 (defun org-eval-in-calendar (form)
4351 "Eval FORM in the calendar window and return to current window.
4352 Also, store the cursor date in variable ans2."
4353 (let ((sw (selected-window)))
4354 (select-window (get-buffer-window "*Calendar*"))
4355 (eval form)
4356 (when (calendar-cursor-to-date)
4357 (let* ((date (calendar-cursor-to-date))
4358 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4359 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4360 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4361 (select-window sw)))
4363 (defun org-calendar-select ()
4364 "Return to `org-read-date' with the date currently selected.
4365 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4366 (interactive)
4367 (when (calendar-cursor-to-date)
4368 (let* ((date (calendar-cursor-to-date))
4369 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4370 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4371 (if (active-minibuffer-window) (exit-minibuffer))))
4373 (defun org-calendar-select-mouse (ev)
4374 "Return to `org-read-date' with the date currently selected.
4375 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4376 (interactive "e")
4377 (mouse-set-point ev)
4378 (when (calendar-cursor-to-date)
4379 (let* ((date (calendar-cursor-to-date))
4380 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4381 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4382 (if (active-minibuffer-window) (exit-minibuffer))))
4384 (defun org-check-deadlines (ndays)
4385 "Check if there are any deadlines due or past due.
4386 A deadline is considered due if it happens within `org-deadline-warning-days'
4387 days from today's date. If the deadline appears in an entry marked DONE,
4388 it is not shown. The prefix arg NDAYS can be used to test that many
4389 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4390 (interactive "P")
4391 (let* ((org-warn-days
4392 (cond
4393 ((equal ndays '(4)) 100000)
4394 (ndays (prefix-numeric-value ndays))
4395 (t org-deadline-warning-days)))
4396 (case-fold-search nil)
4397 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4398 (callback
4399 (lambda ()
4400 (and (let ((d1 (time-to-days (current-time)))
4401 (d2 (time-to-days
4402 (org-time-string-to-time (match-string 1)))))
4403 (< (- d2 d1) org-warn-days))
4404 (not (org-entry-is-done-p))))))
4405 (message "%d deadlines past-due or due within %d days"
4406 (org-occur regexp callback)
4407 org-warn-days)))
4409 (defun org-evaluate-time-range (&optional to-buffer)
4410 "Evaluate a time range by computing the difference between start and end.
4411 Normally the result is just printed in the echo area, but with prefix arg
4412 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4413 If the time range is actually in a table, the result is inserted into the
4414 next column.
4415 For time difference computation, a year is assumed to be exactly 365
4416 days in order to avoid rounding problems."
4417 (interactive "P")
4418 (save-excursion
4419 (unless (org-at-date-range-p)
4420 (goto-char (point-at-bol))
4421 (re-search-forward org-tr-regexp (point-at-eol) t))
4422 (if (not (org-at-date-range-p))
4423 (error "Not at a time-stamp range, and none found in current line")))
4424 (let* ((ts1 (match-string 1))
4425 (ts2 (match-string 2))
4426 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4427 (match-end (match-end 0))
4428 (time1 (org-time-string-to-time ts1))
4429 (time2 (org-time-string-to-time ts2))
4430 (t1 (time-to-seconds time1))
4431 (t2 (time-to-seconds time2))
4432 (diff (abs (- t2 t1)))
4433 (negative (< (- t2 t1) 0))
4434 ;; (ys (floor (* 365 24 60 60)))
4435 (ds (* 24 60 60))
4436 (hs (* 60 60))
4437 (fy "%dy %dd %02d:%02d")
4438 (fy1 "%dy %dd")
4439 (fd "%dd %02d:%02d")
4440 (fd1 "%dd")
4441 (fh "%02d:%02d")
4442 y d h m align)
4443 (if havetime
4444 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4446 d (floor (/ diff ds)) diff (mod diff ds)
4447 h (floor (/ diff hs)) diff (mod diff hs)
4448 m (floor (/ diff 60)))
4449 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4451 d (floor (+ (/ diff ds) 0.5))
4452 h 0 m 0))
4453 (if (not to-buffer)
4454 (message (org-make-tdiff-string y d h m))
4455 (when (org-at-table-p)
4456 (goto-char match-end)
4457 (setq align t)
4458 (and (looking-at " *|") (goto-char (match-end 0))))
4459 (if (looking-at
4460 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4461 (replace-match ""))
4462 (if negative (insert " -"))
4463 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4464 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4465 (insert " " (format fh h m))))
4466 (if align (org-table-align))
4467 (message "Time difference inserted"))))
4469 (defun org-make-tdiff-string (y d h m)
4470 (let ((fmt "")
4471 (l nil))
4472 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4473 l (push y l)))
4474 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4475 l (push d l)))
4476 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4477 l (push h l)))
4478 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4479 l (push m l)))
4480 (apply 'format fmt (nreverse l))))
4482 (defun org-time-string-to-time (s)
4483 (apply 'encode-time (org-parse-time-string s)))
4485 (defun org-parse-time-string (s &optional nodefault)
4486 "Parse the standard Org-mode time string.
4487 This should be a lot faster than the normal `parse-time-string'.
4488 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4489 hour and minute fields will be nil if not given."
4490 (if (string-match org-ts-regexp1 s)
4491 (list 0
4492 (if (or (match-beginning 8) (not nodefault))
4493 (string-to-number (or (match-string 8 s) "0")))
4494 (if (or (match-beginning 7) (not nodefault))
4495 (string-to-number (or (match-string 7 s) "0")))
4496 (string-to-number (match-string 4 s))
4497 (string-to-number (match-string 3 s))
4498 (string-to-number (match-string 2 s))
4499 nil nil nil)
4500 (make-list 9 0)))
4502 (defun org-timestamp-up (&optional arg)
4503 "Increase the date item at the cursor by one.
4504 If the cursor is on the year, change the year. If it is on the month or
4505 the day, change that.
4506 With prefix ARG, change by that many units."
4507 (interactive "p")
4508 (org-timestamp-change (prefix-numeric-value arg)))
4510 (defun org-timestamp-down (&optional arg)
4511 "Decrease the date item at the cursor by one.
4512 If the cursor is on the year, change the year. If it is on the month or
4513 the day, change that.
4514 With prefix ARG, change by that many units."
4515 (interactive "p")
4516 (org-timestamp-change (- (prefix-numeric-value arg))))
4518 (defun org-timestamp-up-day (&optional arg)
4519 "Increase the date in the time stamp by one day.
4520 With prefix ARG, change that many days."
4521 (interactive "p")
4522 (if (and (not (org-at-timestamp-p))
4523 (org-on-heading-p))
4524 (org-todo 'up)
4525 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4527 (defun org-timestamp-down-day (&optional arg)
4528 "Decrease the date in the time stamp by one day.
4529 With prefix ARG, change that many days."
4530 (interactive "p")
4531 (if (and (not (org-at-timestamp-p))
4532 (org-on-heading-p))
4533 (org-todo 'down)
4534 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4536 (defsubst org-pos-in-match-range (pos n)
4537 (and (match-beginning n)
4538 (<= (match-beginning n) pos)
4539 (>= (match-end n) pos)))
4541 (defun org-at-timestamp-p ()
4542 "Determine if the cursor is in or at a timestamp."
4543 (interactive)
4544 (let* ((tsr org-ts-regexp2)
4545 (pos (point))
4546 (ans (or (looking-at tsr)
4547 (save-excursion
4548 (skip-chars-backward "^<\n\r\t")
4549 (if (> (point) 1) (backward-char 1))
4550 (and (looking-at tsr)
4551 (> (- (match-end 0) pos) -1))))))
4552 (and (boundp 'org-ts-what)
4553 (setq org-ts-what
4554 (cond
4555 ((org-pos-in-match-range pos 2) 'year)
4556 ((org-pos-in-match-range pos 3) 'month)
4557 ((org-pos-in-match-range pos 7) 'hour)
4558 ((org-pos-in-match-range pos 8) 'minute)
4559 ((or (org-pos-in-match-range pos 4)
4560 (org-pos-in-match-range pos 5)) 'day)
4561 (t 'day))))
4562 ans))
4564 (defun org-timestamp-change (n &optional what)
4565 "Change the date in the time stamp at point.
4566 The date will be changed by N times WHAT. WHAT can be `day', `month',
4567 `year', `minute', `second'. If WHAT is not given, the cursor position
4568 in the timestamp determines what will be changed."
4569 (let ((fmt (car org-time-stamp-formats))
4570 org-ts-what
4571 (pos (point))
4572 ts time time0)
4573 (if (not (org-at-timestamp-p))
4574 (error "Not at a timestamp"))
4575 (setq org-ts-what (or what org-ts-what))
4576 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4577 (- (match-end 0) (match-beginning 0))))
4579 (cdr org-time-stamp-formats)
4580 (car org-time-stamp-formats)))
4581 (setq ts (match-string 0))
4582 (replace-match "")
4583 (setq time0 (org-parse-time-string ts))
4584 (setq time
4585 (apply 'encode-time
4586 (append
4587 (list (or (car time0) 0))
4588 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4589 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4590 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4591 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4592 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4593 (nthcdr 6 time0))))
4594 (if (eq what 'calendar)
4595 (let ((cal-date
4596 (save-excursion
4597 (save-match-data
4598 (set-buffer "*Calendar*")
4599 (calendar-cursor-to-date)))))
4600 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4601 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4602 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4603 (setcar time0 (or (car time0) 0))
4604 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4605 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4606 (setq time (apply 'encode-time time0))))
4607 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4608 (goto-char pos)
4609 ;; Try to recenter the calendar window, if any
4610 (if (and org-calendar-follow-timestamp-change
4611 (get-buffer-window "*Calendar*" t)
4612 (memq org-ts-what '(day month year)))
4613 (org-recenter-calendar (time-to-days time)))))
4615 (defun org-recenter-calendar (date)
4616 "If the calendar is visible, recenter it to DATE."
4617 (let* ((win (selected-window))
4618 (cwin (get-buffer-window "*Calendar*" t))
4619 (calendar-move-hook nil))
4620 (when cwin
4621 (select-window cwin)
4622 (calendar-goto-date (if (listp date) date
4623 (calendar-gregorian-from-absolute date)))
4624 (select-window win))))
4626 (defun org-goto-calendar (&optional arg)
4627 "Go to the Emacs calendar at the current date.
4628 If there is a time stamp in the current line, go to that date.
4629 A prefix ARG can be used to force the current date."
4630 (interactive "P")
4631 (let ((tsr org-ts-regexp) diff
4632 (calendar-move-hook nil)
4633 (view-diary-entries-initially nil))
4634 (if (or (org-at-timestamp-p)
4635 (save-excursion
4636 (beginning-of-line 1)
4637 (looking-at (concat ".*" tsr))))
4638 (let ((d1 (time-to-days (current-time)))
4639 (d2 (time-to-days
4640 (org-time-string-to-time (match-string 1)))))
4641 (setq diff (- d2 d1))))
4642 (calendar)
4643 (calendar-goto-today)
4644 (if (and diff (not arg)) (calendar-forward-day diff))))
4646 (defun org-date-from-calendar ()
4647 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4648 If there is already a time stamp at the cursor position, update it."
4649 (interactive)
4650 (org-timestamp-change 0 'calendar))
4652 ;;; Agenda, and Diary Integration
4654 ;;; Define the mode
4656 (defvar org-agenda-mode-map (make-sparse-keymap)
4657 "Keymap for `org-agenda-mode'.")
4659 (defvar org-agenda-menu) ; defined later in this file.
4660 (defvar org-agenda-follow-mode nil)
4661 (defvar org-agenda-show-log nil)
4662 (defvar org-agenda-buffer-name "*Org Agenda*")
4663 (defvar org-agenda-redo-command nil)
4664 (defvar org-agenda-mode-hook nil)
4665 (defvar org-agenda-type nil)
4666 (defvar org-agenda-force-single-file nil)
4668 ;;;###autoload
4669 (defun org-agenda-mode ()
4670 "Mode for time-sorted view on action items in Org-mode files.
4672 The following commands are available:
4674 \\{org-agenda-mode-map}"
4675 (interactive)
4676 (kill-all-local-variables)
4677 (setq major-mode 'org-agenda-mode)
4678 (setq mode-name "Org-Agenda")
4679 (use-local-map org-agenda-mode-map)
4680 (easy-menu-add org-agenda-menu)
4681 (if org-startup-truncated (setq truncate-lines t))
4682 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4683 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4684 (unless org-agenda-keep-modes
4685 (setq org-agenda-follow-mode nil
4686 org-agenda-show-log nil))
4687 (easy-menu-change
4688 '("Agenda") "Agenda Files"
4689 (append
4690 (list
4691 (vector
4692 (if (get 'org-agenda-files 'org-restrict)
4693 "Restricted to single file"
4694 "Edit File List")
4695 '(org-edit-agenda-file-list)
4696 (not (get 'org-agenda-files 'org-restrict)))
4697 "--")
4698 (mapcar 'org-file-menu-entry (org-agenda-files))))
4699 (org-agenda-set-mode-name)
4700 (apply
4701 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4702 (list 'org-agenda-mode-hook)))
4704 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4705 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
4706 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4707 (define-key org-agenda-mode-map " " 'org-agenda-show)
4708 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4709 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4710 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4711 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4712 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4713 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4714 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4715 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4716 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4717 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4718 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4719 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4721 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4722 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4723 (while l (define-key org-agenda-mode-map
4724 (int-to-string (pop l)) 'digit-argument)))
4726 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4727 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4728 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4729 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4730 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4731 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4732 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4733 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4734 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4735 (define-key org-agenda-mode-map "n" 'next-line)
4736 (define-key org-agenda-mode-map "p" 'previous-line)
4737 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4738 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4739 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4740 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4741 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4742 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4743 (eval-after-load "calendar"
4744 '(define-key calendar-mode-map org-calendar-to-agenda-key
4745 'org-calendar-goto-agenda))
4746 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4747 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4748 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4749 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4750 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4751 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4752 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4753 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4754 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4755 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4756 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4757 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4758 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4759 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4760 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4761 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4762 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4763 "Local keymap for agenda entries from Org-mode.")
4765 (define-key org-agenda-keymap
4766 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4767 (define-key org-agenda-keymap
4768 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4769 (define-key org-agenda-keymap [follow-link] 'mouse-face)
4770 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4771 '("Agenda"
4772 ("Agenda Files")
4773 "--"
4774 ["Show" org-agenda-show t]
4775 ["Go To (other window)" org-agenda-goto t]
4776 ["Go To (one window)" org-agenda-switch-to t]
4777 ["Follow Mode" org-agenda-follow-mode
4778 :style toggle :selected org-agenda-follow-mode :active t]
4779 "--"
4780 ["Cycle TODO" org-agenda-todo t]
4781 ("Tags"
4782 ["Show all Tags" org-agenda-show-tags t]
4783 ["Set Tags" org-agenda-set-tags t])
4784 ("Reschedule"
4785 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4786 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4787 "--"
4788 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4789 ("Priority"
4790 ["Set Priority" org-agenda-priority t]
4791 ["Increase Priority" org-agenda-priority-up t]
4792 ["Decrease Priority" org-agenda-priority-down t]
4793 ["Show Priority" org-agenda-show-priority t])
4794 "--"
4795 ;; ["New agenda command" org-agenda t]
4796 ["Rebuild buffer" org-agenda-redo t]
4797 "--"
4798 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4799 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4800 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4801 "--"
4802 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4803 :style radio :selected (equal org-agenda-ndays 1)]
4804 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4805 :style radio :selected (equal org-agenda-ndays 7)]
4806 "--"
4807 ["Show Logbook entries" org-agenda-log-mode
4808 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4809 ["Include Diary" org-agenda-toggle-diary
4810 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4811 ["Use Time Grid" org-agenda-toggle-time-grid
4812 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4813 "--"
4814 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4815 ("Calendar Commands"
4816 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4817 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4818 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4819 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4820 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4821 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4822 "--"
4823 ["Quit" org-agenda-quit t]
4824 ["Exit and Release Buffers" org-agenda-exit t]
4827 ;;;###autoload
4828 (defun org-agenda (arg)
4829 "Dispatch agenda commands to collect entries to the agenda buffer.
4830 Prompts for a character to select a command. Any prefix arg will be passed
4831 on to the selected command. The default selections are:
4833 a Call `org-agenda' to display the agenda for the current day or week.
4834 t Call `org-todo-list' to display the global todo list.
4835 T Call `org-todo-list' to display the global todo list, select only
4836 entries with a specific TODO keyword (the user gets a prompt).
4837 m Call `org-tags-view' to display headlines with tags matching
4838 a condition (the user is prompted for the condition).
4839 M Like `m', but select only TODO entries, no ordinary headlines.
4841 More commands can be added by configuring the variable
4842 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4843 searches can be pre-defined in this way.
4845 If the current buffer is in Org-mode and visiting a file, you can also
4846 first press `1' to indicate that the agenda should be temporarily (until the
4847 next use of \\[org-agenda]) restricted to the current file."
4848 (interactive "P")
4849 (catch 'exit
4850 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
4851 (custom org-agenda-custom-commands)
4852 c entry key type string)
4853 (put 'org-agenda-files 'org-restrict nil)
4854 (save-window-excursion
4855 (delete-other-windows)
4856 (switch-to-buffer-other-window " *Agenda Commands*")
4857 (erase-buffer)
4858 (insert
4859 "Press key for an agenda command:
4860 --------------------------------
4861 a Agenda for current week or day
4862 t List of all TODO entries T Entries with special TODO kwd
4863 m Match a TAGS query M Like m, but only TODO entries
4864 C Configure your own agenda commands")
4865 (while (setq entry (pop custom))
4866 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4867 (insert (format "\n%-4s%-14s: %s"
4869 (cond
4870 ((eq type 'tags) "Tags query")
4871 ((eq type 'todo) "TODO keyword")
4872 ((eq type 'tags-tree) "Tags tree")
4873 ((eq type 'todo-tree) "TODO kwd tree")
4874 ((eq type 'occur-tree) "Occur tree")
4875 (t "???"))
4876 (org-add-props string nil 'face 'org-warning))))
4877 (goto-char (point-min))
4878 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4879 (message "Press key for agenda command%s"
4880 (if restrict-ok ", or [1] to restrict to current file" ""))
4881 (setq c (read-char-exclusive))
4882 (message "")
4883 (when (equal c ?1)
4884 (if restrict-ok
4885 (put 'org-agenda-files 'org-restrict (list buffer-file-name))
4886 (error "Cannot restrict agenda to current buffer"))
4887 (message "Press key for agenda command%s"
4888 (if restrict-ok " (restricted to current file)" ""))
4889 (setq c (read-char-exclusive))
4890 (message "")))
4891 (require 'calendar) ; FIXME: can we avoid this for some commands?
4892 ;; For example the todo list should not need it (but does...)
4893 (cond
4894 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4895 ((equal c ?a) (call-interactively 'org-agenda-list))
4896 ((equal c ?t) (call-interactively 'org-todo-list))
4897 ((equal c ?T)
4898 (setq current-prefix-arg (or arg '(4)))
4899 (call-interactively 'org-todo-list))
4900 ((equal c ?m) (call-interactively 'org-tags-view))
4901 ((equal c ?M)
4902 (setq current-prefix-arg (or arg '(4)))
4903 (call-interactively 'org-tags-view))
4904 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4905 (setq type (nth 1 entry) string (nth 2 entry))
4906 (cond
4907 ((eq type 'tags)
4908 (org-tags-view current-prefix-arg string))
4909 ((eq type 'todo)
4910 (org-todo-list string))
4911 ((eq type 'tags-tree)
4912 (org-check-for-org-mode)
4913 (org-tags-sparse-tree current-prefix-arg string))
4914 ((eq type 'todo-tree)
4915 (org-check-for-org-mode)
4916 (org-occur (concat "^" outline-regexp "[ \t]*"
4917 (regexp-quote string) "\\>")))
4918 ((eq type 'occur-tree)
4919 (org-check-for-org-mode)
4920 (org-occur string))
4921 (t (error "Invalid custom agenda command type %s" type))))
4922 (t (error "Invalid key"))))))
4924 (defun org-check-for-org-mode ()
4925 "Make sure current buffer is in org-mode. Error if not."
4926 (or (eq major-mode 'org-mode)
4927 (error "Cannot execute org-mode agenda command on buffer in %s."
4928 major-mode)))
4930 (defun org-fit-agenda-window ()
4931 "Fit the window to the buffer size."
4932 (and org-fit-agenda-window
4933 (fboundp 'fit-window-to-buffer)
4934 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4935 (/ (frame-height) 2))))
4937 (defun org-agenda-files (&optional unrestricted)
4938 "Get the list of agenda files.
4939 Optional UNRESTRICTED means return the full list even if a restriction
4940 is currently in place."
4941 (cond
4942 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
4943 ((stringp org-agenda-files) (org-read-agenda-file-list))
4944 ((listp org-agenda-files) org-agenda-files)
4945 (t (error "Invalid value of `org-agenda-files'"))))
4947 (defvar org-window-configuration)
4949 (defun org-edit-agenda-file-list ()
4950 "Edit the list of agenda files.
4951 Depending on setup, this either uses customize to edit the variable
4952 `org-agenda-files', or it visits the file that is holding the list. In the
4953 latter case, the buffer is set up in a way that saving it automatically kills
4954 the buffer and restores the previous window configuration."
4955 (interactive)
4956 (if (stringp org-agenda-files)
4957 (let ((cw (current-window-configuration)))
4958 (find-file org-agenda-files)
4959 (set (make-local-variable 'org-window-configuration) cw)
4960 (org-add-hook 'after-save-hook
4961 (lambda ()
4962 (set-window-configuration
4963 (prog1 org-window-configuration
4964 (kill-buffer (current-buffer))))
4965 (org-install-agenda-files-menu)
4966 (message "New agenda file list installed"))
4967 nil 'local)
4968 (message (substitute-command-keys
4969 "Edit list and finish with \\[save-buffer]")))
4970 (customize-variable 'org-agenda-files)))
4972 (defun org-store-new-agenda-file-list (list)
4973 "Set new value for the agenda file list and save it correcly."
4974 (if (stringp org-agenda-files)
4975 (let ((f org-agenda-files) b)
4976 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
4977 (with-temp-file f
4978 (insert (mapconcat 'identity list "\n") "\n")))
4979 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
4980 (setq org-agenda-files list)
4981 (customize-save-variable 'org-agenda-files org-agenda-files))))
4983 (defun org-read-agenda-file-list ()
4984 "Read the list of agenda files from a file."
4985 (when (stringp org-agenda-files)
4986 (with-temp-buffer
4987 (insert-file-contents org-agenda-files)
4988 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
4990 (defvar org-agenda-markers nil
4991 "List of all currently active markers created by `org-agenda'.")
4992 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4993 "Creation time of the last agenda marker.")
4995 (defun org-agenda-new-marker (&optional pos)
4996 "Return a new agenda marker.
4997 Org-mode keeps a list of these markers and resets them when they are
4998 no longer in use."
4999 (let ((m (copy-marker (or pos (point)))))
5000 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
5001 (push m org-agenda-markers)
5004 (defun org-agenda-maybe-reset-markers (&optional force)
5005 "Reset markers created by `org-agenda'. But only if they are old enough."
5006 (if (or force
5007 (> (- (time-to-seconds (current-time))
5008 org-agenda-last-marker-time)
5010 (while org-agenda-markers
5011 (move-marker (pop org-agenda-markers) nil))))
5013 (defvar org-agenda-new-buffers nil
5014 "Buffers created to visit agenda files.")
5016 (defun org-get-agenda-file-buffer (file)
5017 "Get a buffer visiting FILE. If the buffer needs to be created, add
5018 it to the list of buffers which might be released later."
5019 (let ((buf (find-buffer-visiting file)))
5020 (if buf
5021 buf ; just return it
5022 ;; Make a new buffer and remember it
5023 (setq buf (find-file-noselect file))
5024 (if buf (push buf org-agenda-new-buffers))
5025 buf)))
5027 (defun org-release-buffers (blist)
5028 "Release all buffers in list, asking the user for confirmation when needed.
5029 When a buffer is unmodified, it is just killed. When modified, it is saved
5030 \(if the user agrees) and then killed."
5031 (let (buf file)
5032 (while (setq buf (pop blist))
5033 (setq file (buffer-file-name buf))
5034 (when (and (buffer-modified-p buf)
5035 file
5036 (y-or-n-p (format "Save file %s? " file)))
5037 (with-current-buffer buf (save-buffer)))
5038 (kill-buffer buf))))
5040 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
5042 (defun org-timeline (&optional include-all keep-modes)
5043 "Show a time-sorted view of the entries in the current org file.
5044 Only entries with a time stamp of today or later will be listed. With
5045 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
5046 under the current date.
5047 If the buffer contains an active region, only check the region for
5048 dates."
5049 (interactive "P")
5050 (require 'calendar)
5051 (org-agenda-maybe-reset-markers 'force)
5052 (org-compile-prefix-format org-timeline-prefix-format)
5053 (let* ((dopast t)
5054 (dotodo include-all)
5055 (doclosed org-agenda-show-log)
5056 (org-agenda-keep-modes keep-modes)
5057 (entry buffer-file-name)
5058 (org-agenda-files (list buffer-file-name))
5059 (date (calendar-current-date))
5060 (win (selected-window))
5061 (pos1 (point))
5062 (beg (if (org-region-active-p) (region-beginning) (point-min)))
5063 (end (if (org-region-active-p) (region-end) (point-max)))
5064 (day-numbers (org-get-all-dates beg end 'no-ranges
5065 t doclosed)) ; always include today
5066 (today (time-to-days (current-time)))
5067 (org-respect-restriction t)
5068 (past t)
5069 args
5070 s e rtn d)
5071 (setq org-agenda-redo-command
5072 (list 'progn
5073 (list 'switch-to-buffer-other-window (current-buffer))
5074 (list 'org-timeline (list 'quote include-all) t)))
5075 (if (not dopast)
5076 ;; Remove past dates from the list of dates.
5077 (setq day-numbers (delq nil (mapcar (lambda(x)
5078 (if (>= x today) x nil))
5079 day-numbers))))
5080 (switch-to-buffer-other-window
5081 (get-buffer-create org-agenda-buffer-name))
5082 (setq buffer-read-only nil)
5083 (erase-buffer)
5084 (org-agenda-mode) (setq buffer-read-only nil)
5085 (set (make-local-variable 'org-agenda-type) 'timeline)
5086 (if doclosed (push :closed args))
5087 (push :timestamp args)
5088 (if dotodo (push :todo args))
5089 (while (setq d (pop day-numbers))
5090 (if (and (>= d today)
5091 dopast
5092 past)
5093 (progn
5094 (setq past nil)
5095 (insert (make-string 79 ?-) "\n")))
5096 (setq date (calendar-gregorian-from-absolute d))
5097 (setq s (point))
5098 (setq rtn (apply 'org-agenda-get-day-entries
5099 entry date args))
5100 (if (or rtn (equal d today))
5101 (progn
5102 (insert (calendar-day-name date) " "
5103 (number-to-string (extract-calendar-day date)) " "
5104 (calendar-month-name (extract-calendar-month date)) " "
5105 (number-to-string (extract-calendar-year date)) "\n")
5106 (put-text-property s (1- (point)) 'face
5107 'org-level-3)
5108 (if (equal d today)
5109 (put-text-property s (1- (point)) 'org-today t))
5110 (insert (org-finalize-agenda-entries rtn) "\n")
5111 (put-text-property s (1- (point)) 'day d))))
5112 (goto-char (point-min))
5113 (setq buffer-read-only t)
5114 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5115 (point-min)))
5116 (when (not org-select-timeline-window)
5117 (select-window win)
5118 (goto-char pos1))))
5120 ;;;###autoload
5121 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
5122 "Produce a weekly view from all files in variable `org-agenda-files'.
5123 The view will be for the current week, but from the overview buffer you
5124 will be able to go to other weeks.
5125 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
5126 also be shown, under the current date.
5127 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
5128 on the days are also shown. See the variable `org-log-done' for how
5129 to turn on logging.
5130 START-DAY defaults to TODAY, or to the most recent match for the weekday
5131 given in `org-agenda-start-on-weekday'.
5132 NDAYS defaults to `org-agenda-ndays'."
5133 (interactive "P")
5134 (org-agenda-maybe-reset-markers 'force)
5135 (org-compile-prefix-format org-agenda-prefix-format)
5136 (require 'calendar)
5137 (let* ((org-agenda-start-on-weekday
5138 (if (or (equal ndays 1)
5139 (and (null ndays) (equal 1 org-agenda-ndays)))
5140 nil org-agenda-start-on-weekday))
5141 (org-agenda-keep-modes keep-modes)
5142 (thefiles (org-agenda-files))
5143 (files thefiles)
5144 (win (selected-window))
5145 (today (time-to-days (current-time)))
5146 (sd (or start-day today))
5147 (start (if (or (null org-agenda-start-on-weekday)
5148 (< org-agenda-ndays 7))
5150 (let* ((nt (calendar-day-of-week
5151 (calendar-gregorian-from-absolute sd)))
5152 (n1 org-agenda-start-on-weekday)
5153 (d (- nt n1)))
5154 (- sd (+ (if (< d 0) 7 0) d)))))
5155 (day-numbers (list start))
5156 (inhibit-redisplay t)
5157 s e rtn rtnall file date d start-pos end-pos todayp nd)
5158 (setq org-agenda-redo-command
5159 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
5160 ;; Make the list of days
5161 (setq ndays (or ndays org-agenda-ndays)
5162 nd ndays)
5163 (while (> ndays 1)
5164 (push (1+ (car day-numbers)) day-numbers)
5165 (setq ndays (1- ndays)))
5166 (setq day-numbers (nreverse day-numbers))
5167 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5168 (progn
5169 (delete-other-windows)
5170 (switch-to-buffer-other-window
5171 (get-buffer-create org-agenda-buffer-name))))
5172 (setq buffer-read-only nil)
5173 (erase-buffer)
5174 (org-agenda-mode) (setq buffer-read-only nil)
5175 (set (make-local-variable 'org-agenda-type) 'agenda)
5176 (set (make-local-variable 'starting-day) (car day-numbers))
5177 (set (make-local-variable 'include-all-loc) include-all)
5178 (when (and (or include-all org-agenda-include-all-todo)
5179 (member today day-numbers))
5180 (setq files thefiles
5181 rtnall nil)
5182 (while (setq file (pop files))
5183 (catch 'nextfile
5184 (org-check-agenda-file file)
5185 (setq date (calendar-gregorian-from-absolute today)
5186 rtn (org-agenda-get-day-entries
5187 file date :todo))
5188 (setq rtnall (append rtnall rtn))))
5189 (when rtnall
5190 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
5191 (add-text-properties (point-min) (1- (point))
5192 (list 'face 'org-level-3))
5193 (insert (org-finalize-agenda-entries rtnall) "\n")))
5194 (while (setq d (pop day-numbers))
5195 (setq date (calendar-gregorian-from-absolute d)
5196 s (point))
5197 (if (or (setq todayp (= d today))
5198 (and (not start-pos) (= d sd)))
5199 (setq start-pos (point))
5200 (if (and start-pos (not end-pos))
5201 (setq end-pos (point))))
5202 (setq files thefiles
5203 rtnall nil)
5204 (while (setq file (pop files))
5205 (catch 'nextfile
5206 (org-check-agenda-file file)
5207 (if org-agenda-show-log
5208 (setq rtn (org-agenda-get-day-entries
5209 file date
5210 :deadline :scheduled :timestamp :closed))
5211 (setq rtn (org-agenda-get-day-entries
5212 file date
5213 :deadline :scheduled :timestamp)))
5214 (setq rtnall (append rtnall rtn))))
5215 (if org-agenda-include-diary
5216 (progn
5217 (require 'diary-lib)
5218 (setq rtn (org-get-entries-from-diary date))
5219 (setq rtnall (append rtnall rtn))))
5220 (if (or rtnall org-agenda-show-all-dates)
5221 (progn
5222 (insert (format "%-9s %2d %s %4d\n"
5223 (calendar-day-name date)
5224 (extract-calendar-day date)
5225 (calendar-month-name (extract-calendar-month date))
5226 (extract-calendar-year date)))
5227 (put-text-property s (1- (point)) 'face
5228 'org-level-3)
5229 (if rtnall (insert
5230 (org-finalize-agenda-entries
5231 (org-agenda-add-time-grid-maybe
5232 rtnall nd todayp))
5233 "\n"))
5234 (put-text-property s (1- (point)) 'day d))))
5235 (goto-char (point-min))
5236 (setq buffer-read-only t)
5237 (org-fit-agenda-window)
5238 (unless (and (pos-visible-in-window-p (point-min))
5239 (pos-visible-in-window-p (point-max)))
5240 (goto-char (1- (point-max)))
5241 (recenter -1)
5242 (if (not (pos-visible-in-window-p (or start-pos 1)))
5243 (progn
5244 (goto-char (or start-pos 1))
5245 (recenter 1))))
5246 (goto-char (or start-pos 1))
5247 (if (not org-select-agenda-window) (select-window win))
5248 (message "")))
5250 (defvar org-select-this-todo-keyword nil)
5252 ;;;###autoload
5253 (defun org-todo-list (arg &optional keep-modes)
5254 "Show all TODO entries from all agenda file in a single list.
5255 The prefix arg can be used to select a specific TODO keyword and limit
5256 the list to these. When using \\[universal-argument], you will be prompted
5257 for a keyword. A numeric prefix directly selects the Nth keyword in
5258 `org-todo-keywords'."
5259 (interactive "P")
5260 (org-agenda-maybe-reset-markers 'force)
5261 (org-compile-prefix-format org-agenda-prefix-format)
5262 (let* ((org-agenda-keep-modes keep-modes)
5263 (today (time-to-days (current-time)))
5264 (date (calendar-gregorian-from-absolute today))
5265 (win (selected-window))
5266 (kwds org-todo-keywords)
5267 (completion-ignore-case t)
5268 (org-select-this-todo-keyword
5269 (if (stringp arg) arg
5270 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
5271 rtn rtnall files file pos)
5272 (when (equal arg '(4))
5273 (setq org-select-this-todo-keyword
5274 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
5275 nil t)))
5276 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
5277 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5278 (progn
5279 (delete-other-windows)
5280 (switch-to-buffer-other-window
5281 (get-buffer-create org-agenda-buffer-name))))
5282 (setq buffer-read-only nil)
5283 (erase-buffer)
5284 (org-agenda-mode) (setq buffer-read-only nil)
5285 (set (make-local-variable 'org-agenda-type) 'todo)
5286 (set (make-local-variable 'last-arg) arg)
5287 (set (make-local-variable 'org-todo-keywords) kwds)
5288 (set (make-local-variable 'org-agenda-redo-command)
5289 '(org-todo-list (or current-prefix-arg last-arg) t))
5290 (setq files (org-agenda-files)
5291 rtnall nil)
5292 (while (setq file (pop files))
5293 (catch 'nextfile
5294 (org-check-agenda-file file)
5295 (setq rtn (org-agenda-get-day-entries file date :todo))
5296 (setq rtnall (append rtnall rtn))))
5297 (insert "Global list of TODO items of type: ")
5298 (add-text-properties (point-min) (1- (point))
5299 (list 'face 'org-level-3))
5300 (setq pos (point))
5301 (insert (or org-select-this-todo-keyword "ALL") "\n")
5302 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
5303 (setq pos (point))
5304 (insert
5305 "Available with `N r': (0)ALL "
5306 (let ((n 0))
5307 (mapconcat (lambda (x)
5308 (format "(%d)%s" (setq n (1+ n)) x))
5309 org-todo-keywords " "))
5310 "\n")
5311 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
5312 (when rtnall
5313 (insert (org-finalize-agenda-entries rtnall) "\n"))
5314 (goto-char (point-min))
5315 (setq buffer-read-only t)
5316 (org-fit-agenda-window)
5317 (if (not org-select-agenda-window) (select-window win))))
5319 (defun org-check-agenda-file (file)
5320 "Make sure FILE exists. If not, ask user what to do."
5321 (when (not (file-exists-p file))
5322 (message "non-existent file %s. [R]emove from list or [A]bort?"
5323 (abbreviate-file-name file))
5324 (let ((r (downcase (read-char-exclusive))))
5325 (cond
5326 ((equal r ?r)
5327 (org-remove-file file)
5328 (throw 'nextfile t))
5329 (t (error "Abort"))))))
5331 (defun org-agenda-check-type (error &rest types)
5332 "Check if agenda buffer is of allowed type.
5333 If ERROR is non-nil, throw an error, otherwise just return nil."
5334 (if (memq org-agenda-type types)
5336 (if error
5337 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
5338 nil)))
5340 (defun org-agenda-quit ()
5341 "Exit agenda by removing the window or the buffer."
5342 (interactive)
5343 (let ((buf (current-buffer)))
5344 (if (not (one-window-p)) (delete-window))
5345 (kill-buffer buf)
5346 (org-agenda-maybe-reset-markers 'force)))
5348 (defun org-agenda-exit ()
5349 "Exit agenda by removing the window or the buffer.
5350 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
5351 Org-mode buffers visited directly by the user will not be touched."
5352 (interactive)
5353 (org-release-buffers org-agenda-new-buffers)
5354 (setq org-agenda-new-buffers nil)
5355 (org-agenda-quit))
5357 (defun org-agenda-redo ()
5358 "Rebuild Agenda.
5359 When this is the global TODO list, a prefix argument will be interpreted."
5360 (interactive)
5361 (message "Rebuilding agenda buffer...")
5362 (eval org-agenda-redo-command)
5363 (message "Rebuilding agenda buffer...done"))
5365 (defun org-agenda-goto-today ()
5366 "Go to today."
5367 (interactive)
5368 (org-agenda-check-type t 'timeline 'agenda)
5369 (if (boundp 'starting-day)
5370 (let ((cmd (car org-agenda-redo-command))
5371 (iall (nth 1 org-agenda-redo-command))
5372 (nday (nth 3 org-agenda-redo-command))
5373 (keep (nth 4 org-agenda-redo-command)))
5374 (eval (list cmd iall nil nday keep)))
5375 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5376 (point-min)))))
5378 (defun org-agenda-later (arg)
5379 "Go forward in time by `org-agenda-ndays' days.
5380 With prefix ARG, go forward that many times `org-agenda-ndays'."
5381 (interactive "p")
5382 (org-agenda-check-type t 'agenda)
5383 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5384 (+ starting-day (* arg org-agenda-ndays)) nil t))
5386 (defun org-agenda-earlier (arg)
5387 "Go back in time by `org-agenda-ndays' days.
5388 With prefix ARG, go back that many times `org-agenda-ndays'."
5389 (interactive "p")
5390 (org-agenda-check-type t 'agenda)
5391 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5392 (- starting-day (* arg org-agenda-ndays)) nil t))
5394 (defun org-agenda-week-view ()
5395 "Switch to weekly view for agenda."
5396 (interactive)
5397 (org-agenda-check-type t 'agenda)
5398 (setq org-agenda-ndays 7)
5399 (org-agenda-list include-all-loc
5400 (or (get-text-property (point) 'day)
5401 starting-day)
5402 nil t)
5403 (org-agenda-set-mode-name)
5404 (message "Switched to week view"))
5406 (defun org-agenda-day-view ()
5407 "Switch to daily view for agenda."
5408 (interactive)
5409 (org-agenda-check-type t 'agenda)
5410 (setq org-agenda-ndays 1)
5411 (org-agenda-list include-all-loc
5412 (or (get-text-property (point) 'day)
5413 starting-day)
5414 nil t)
5415 (org-agenda-set-mode-name)
5416 (message "Switched to day view"))
5418 (defun org-agenda-next-date-line (&optional arg)
5419 "Jump to the next line indicating a date in agenda buffer."
5420 (interactive "p")
5421 (org-agenda-check-type t 'agenda 'timeline)
5422 (beginning-of-line 1)
5423 (if (looking-at "^\\S-") (forward-char 1))
5424 (if (not (re-search-forward "^\\S-" nil t arg))
5425 (progn
5426 (backward-char 1)
5427 (error "No next date after this line in this buffer")))
5428 (goto-char (match-beginning 0)))
5430 (defun org-agenda-previous-date-line (&optional arg)
5431 "Jump to the previous line indicating a date in agenda buffer."
5432 (interactive "p")
5433 (org-agenda-check-type t 'agenda 'timeline)
5434 (beginning-of-line 1)
5435 (if (not (re-search-backward "^\\S-" nil t arg))
5436 (error "No previous date before this line in this buffer")))
5438 ;; Initialize the highlight
5439 (defvar org-hl (org-make-overlay 1 1))
5440 (org-overlay-put org-hl 'face 'highlight)
5442 (defun org-highlight (begin end &optional buffer)
5443 "Highlight a region with overlay."
5444 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
5445 org-hl begin end (or buffer (current-buffer))))
5447 (defun org-unhighlight ()
5448 "Detach overlay INDEX."
5449 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
5452 (defun org-agenda-follow-mode ()
5453 "Toggle follow mode in an agenda buffer."
5454 (interactive)
5455 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5456 (org-agenda-set-mode-name)
5457 (message "Follow mode is %s"
5458 (if org-agenda-follow-mode "on" "off")))
5460 (defun org-agenda-log-mode ()
5461 "Toggle log mode in an agenda buffer."
5462 (interactive)
5463 (org-agenda-check-type t 'agenda 'timeline)
5464 (setq org-agenda-show-log (not org-agenda-show-log))
5465 (org-agenda-set-mode-name)
5466 (org-agenda-redo)
5467 (message "Log mode is %s"
5468 (if org-agenda-show-log "on" "off")))
5470 (defun org-agenda-toggle-diary ()
5471 "Toggle diary inclusion in an agenda buffer."
5472 (interactive)
5473 (org-agenda-check-type t 'agenda)
5474 (setq org-agenda-include-diary (not org-agenda-include-diary))
5475 (org-agenda-redo)
5476 (org-agenda-set-mode-name)
5477 (message "Diary inclusion turned %s"
5478 (if org-agenda-include-diary "on" "off")))
5480 (defun org-agenda-toggle-time-grid ()
5481 "Toggle time grid in an agenda buffer."
5482 (interactive)
5483 (org-agenda-check-type t 'agenda)
5484 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5485 (org-agenda-redo)
5486 (org-agenda-set-mode-name)
5487 (message "Time-grid turned %s"
5488 (if org-agenda-use-time-grid "on" "off")))
5490 (defun org-agenda-set-mode-name ()
5491 "Set the mode name to indicate all the small mode settings."
5492 (setq mode-name
5493 (concat "Org-Agenda"
5494 (if (equal org-agenda-ndays 1) " Day" "")
5495 (if (equal org-agenda-ndays 7) " Week" "")
5496 (if org-agenda-follow-mode " Follow" "")
5497 (if org-agenda-include-diary " Diary" "")
5498 (if org-agenda-use-time-grid " Grid" "")
5499 (if org-agenda-show-log " Log" "")))
5500 (force-mode-line-update))
5502 (defun org-agenda-post-command-hook ()
5503 (and (eolp) (not (bolp)) (backward-char 1))
5504 (if (and org-agenda-follow-mode
5505 (get-text-property (point) 'org-marker))
5506 (org-agenda-show)))
5508 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5510 (defun org-get-entries-from-diary (date)
5511 "Get the (Emacs Calendar) diary entries for DATE."
5512 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5513 (diary-display-hook '(fancy-diary-display))
5514 (list-diary-entries-hook
5515 (cons 'org-diary-default-entry list-diary-entries-hook))
5516 (diary-file-name-prefix-function nil) ; turn this feature off
5517 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5518 entries
5519 (org-disable-agenda-to-diary t))
5520 (save-excursion
5521 (save-window-excursion
5522 (list-diary-entries date 1)))
5523 (if (not (get-buffer fancy-diary-buffer))
5524 (setq entries nil)
5525 (with-current-buffer fancy-diary-buffer
5526 (setq buffer-read-only nil)
5527 (if (= (point-max) 1)
5528 ;; No entries
5529 (setq entries nil)
5530 ;; Omit the date and other unnecessary stuff
5531 (org-agenda-cleanup-fancy-diary)
5532 ;; Add prefix to each line and extend the text properties
5533 (if (= (point-max) 1)
5534 (setq entries nil)
5535 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5536 (set-buffer-modified-p nil)
5537 (kill-buffer fancy-diary-buffer)))
5538 (when entries
5539 (setq entries (org-split-string entries "\n"))
5540 (setq entries
5541 (mapcar
5542 (lambda (x)
5543 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5544 ;; Extend the text properties to the beginning of the line
5545 (org-add-props x (text-properties-at (1- (length x)) x)))
5546 entries)))))
5548 (defun org-agenda-cleanup-fancy-diary ()
5549 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5550 This gets rid of the date, the underline under the date, and
5551 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5552 date. It also removes lines that contain only whitespace."
5553 (goto-char (point-min))
5554 (if (looking-at ".*?:[ \t]*")
5555 (progn
5556 (replace-match "")
5557 (re-search-forward "\n=+$" nil t)
5558 (replace-match "")
5559 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5560 (re-search-forward "\n=+$" nil t)
5561 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5562 (goto-char (point-min))
5563 (while (re-search-forward "^ +\n" nil t)
5564 (replace-match ""))
5565 (goto-char (point-min))
5566 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5567 (replace-match "")))
5569 ;; Make sure entries from the diary have the right text properties.
5570 (eval-after-load "diary-lib"
5571 '(if (boundp 'diary-modify-entry-list-string-function)
5572 ;; We can rely on the hook, nothing to do
5574 ;; Hook not avaiable, must use advice to make this work
5575 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5576 "Make the position visible."
5577 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5578 (stringp string)
5579 buffer-file-name)
5580 (setq string (org-modify-diary-entry-string string))))))
5582 (defun org-modify-diary-entry-string (string)
5583 "Add text properties to string, allowing org-mode to act on it."
5584 (org-add-props string nil
5585 'mouse-face 'highlight
5586 'keymap org-agenda-keymap
5587 'help-echo (format "mouse-2 or RET jump to diary file %s"
5588 (abbreviate-file-name buffer-file-name))
5589 'org-agenda-diary-link t
5590 'org-marker (org-agenda-new-marker (point-at-bol))))
5592 (defun org-diary-default-entry ()
5593 "Add a dummy entry to the diary.
5594 Needed to avoid empty dates which mess up holiday display."
5595 ;; Catch the error if dealing with the new add-to-diary-alist
5596 (when org-disable-agenda-to-diary
5597 (condition-case nil
5598 (add-to-diary-list original-date "Org-mode dummy" "")
5599 (error
5600 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5602 (defun org-cycle-agenda-files ()
5603 "Cycle through the files in `org-agenda-files'.
5604 If the current buffer visits an agenda file, find the next one in the list.
5605 If the current buffer does not, find the first agenda file."
5606 (interactive)
5607 (let* ((fs (org-agenda-files t))
5608 (files (append fs (list (car fs))))
5609 (tcf (if buffer-file-name (file-truename buffer-file-name)))
5610 file)
5611 (unless files (error "No agenda files"))
5612 (catch 'exit
5613 (while (setq file (pop files))
5614 (if (equal (file-truename file) tcf)
5615 (when (car files)
5616 (find-file (car files))
5617 (throw 'exit t))))
5618 (find-file (car fs)))))
5620 (defun org-agenda-file-to-end ()
5621 "Move/add the current file to the end of the agenda file list.
5622 If the file is not present in the list, it is appended to the list. If it is
5623 present, it is moved there."
5624 (interactive)
5625 (org-agenda-file-to-front 'to-end))
5627 (defun org-agenda-file-to-front (&optional to-end)
5628 "Move/add the current file to the top of the agenda file list.
5629 If the file is not present in the list, it is added to the front. If it is
5630 present, it is moved there. With optional argument TO-END, add/move to the
5631 end of the list."
5632 (interactive "P")
5633 (let ((file-alist (mapcar (lambda (x)
5634 (cons (file-truename x) x))
5635 (org-agenda-files t)))
5636 (ctf (file-truename buffer-file-name))
5637 x had)
5638 (setq x (assoc ctf file-alist) had x)
5640 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
5641 (if to-end
5642 (setq file-alist (append (delq x file-alist) (list x)))
5643 (setq file-alist (cons x (delq x file-alist))))
5644 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
5645 (org-install-agenda-files-menu)
5646 (message "File %s to %s of agenda file list"
5647 (if had "moved" "added") (if to-end "end" "front"))))
5649 (defun org-remove-file (&optional file)
5650 "Remove current file from the list of files in variable `org-agenda-files'.
5651 These are the files which are being checked for agenda entries.
5652 Optional argument FILE means, use this file instead of the current."
5653 (interactive)
5654 (let* ((file (or file buffer-file-name))
5655 (true-file (file-truename file))
5656 (afile (abbreviate-file-name file))
5657 (files (delq nil (mapcar
5658 (lambda (x)
5659 (if (equal true-file
5660 (file-truename x))
5661 nil x))
5662 (org-agenda-files t)))))
5663 (if (not (= (length files) (length (org-agenda-files t))))
5664 (progn
5665 (org-store-new-agenda-file-list files)
5666 (org-install-agenda-files-menu)
5667 (message "Removed file: %s" afile))
5668 (message "File was not in list: %s" afile))))
5670 (defun org-file-menu-entry (file)
5671 (vector file (list 'find-file file) t))
5673 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5674 "Return a list of all relevant day numbers from BEG to END buffer positions.
5675 If NO-RANGES is non-nil, include only the start and end dates of a range,
5676 not every single day in the range. If FORCE-TODAY is non-nil, make
5677 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5678 inactive time stamps (those in square brackets) are included."
5679 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5680 dates date day day1 day2 ts1 ts2)
5681 (if force-today
5682 (setq dates (list (time-to-days (current-time)))))
5683 (save-excursion
5684 (goto-char beg)
5685 (while (re-search-forward re end t)
5686 (setq day (time-to-days (org-time-string-to-time
5687 (substring (match-string 1) 0 10))))
5688 (or (memq day dates) (push day dates)))
5689 (unless no-ranges
5690 (goto-char beg)
5691 (while (re-search-forward org-tr-regexp end t)
5692 (setq ts1 (substring (match-string 1) 0 10)
5693 ts2 (substring (match-string 2) 0 10)
5694 day1 (time-to-days (org-time-string-to-time ts1))
5695 day2 (time-to-days (org-time-string-to-time ts2)))
5696 (while (< (setq day1 (1+ day1)) day2)
5697 (or (memq day1 dates) (push day1 dates)))))
5698 (sort dates '<))))
5700 ;;;###autoload
5701 (defun org-diary (&rest args)
5702 "Return diary information from org-files.
5703 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5704 It accesses org files and extracts information from those files to be
5705 listed in the diary. The function accepts arguments specifying what
5706 items should be listed. The following arguments are allowed:
5708 :timestamp List the headlines of items containing a date stamp or
5709 date range matching the selected date. Deadlines will
5710 also be listed, on the expiration day.
5712 :deadline List any deadlines past due, or due within
5713 `org-deadline-warning-days'. The listing occurs only
5714 in the diary for *today*, not at any other date. If
5715 an entry is marked DONE, it is no longer listed.
5717 :scheduled List all items which are scheduled for the given date.
5718 The diary for *today* also contains items which were
5719 scheduled earlier and are not yet marked DONE.
5721 :todo List all TODO items from the org-file. This may be a
5722 long list - so this is not turned on by default.
5723 Like deadlines, these entries only show up in the
5724 diary for *today*, not at any other date.
5726 The call in the diary file should look like this:
5728 &%%(org-diary) ~/path/to/some/orgfile.org
5730 Use a separate line for each org file to check. Or, if you omit the file name,
5731 all files listed in `org-agenda-files' will be checked automatically:
5733 &%%(org-diary)
5735 If you don't give any arguments (as in the example above), the default
5736 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5737 also be written as
5739 &%%(org-diary :deadline :timestamp :scheduled)
5741 The function expects the lisp variables `entry' and `date' to be provided
5742 by the caller, because this is how the calendar works. Don't use this
5743 function from a program - use `org-agenda-get-day-entries' instead."
5744 (org-agenda-maybe-reset-markers)
5745 (org-compile-prefix-format org-agenda-prefix-format)
5746 (setq args (or args '(:deadline :scheduled :timestamp)))
5747 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5748 (list entry)
5749 (org-agenda-files t)))
5750 file rtn results)
5751 ;; If this is called during org-agenda, don't return any entries to
5752 ;; the calendar. Org Agenda will list these entries itself.
5753 (if org-disable-agenda-to-diary (setq files nil))
5754 (while (setq file (pop files))
5755 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5756 (setq results (append results rtn)))
5757 (if results
5758 (concat (org-finalize-agenda-entries results) "\n"))))
5759 (defvar org-category-table nil)
5760 (defun org-get-category-table ()
5761 "Get the table of categories and positions in current buffer."
5762 (let (tbl)
5763 (save-excursion
5764 (goto-char (point-min))
5765 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5766 (push (cons (point) (org-trim (match-string 2))) tbl)))
5767 tbl))
5768 (defun org-get-category (&optional pos)
5769 "Get the category applying to position POS."
5770 (if (not org-category-table)
5771 (cond
5772 ((null org-category)
5773 (setq org-category
5774 (if buffer-file-name
5775 (file-name-sans-extension
5776 (file-name-nondirectory buffer-file-name))
5777 "???")))
5778 ((symbolp org-category) (symbol-name org-category))
5779 (t org-category))
5780 (let ((tbl org-category-table)
5781 (pos (or pos (point))))
5782 (while (and tbl (> (caar tbl) pos))
5783 (pop tbl))
5784 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5785 org-category-table))))))
5787 (defun org-agenda-get-day-entries (file date &rest args)
5788 "Does the work for `org-diary' and `org-agenda'.
5789 FILE is the path to a file to be checked for entries. DATE is date like
5790 the one returned by `calendar-current-date'. ARGS are symbols indicating
5791 which kind of entries should be extracted. For details about these, see
5792 the documentation of `org-diary'."
5793 (setq args (or args '(:deadline :scheduled :timestamp)))
5794 (let* ((org-startup-with-deadline-check nil)
5795 (org-startup-folded nil)
5796 (org-startup-align-all-tables nil)
5797 (buffer (if (file-exists-p file)
5798 (org-get-agenda-file-buffer file)
5799 (error "No such file %s" file)))
5800 arg results rtn)
5801 (if (not buffer)
5802 ;; If file does not exist, make sure an error message ends up in diary
5803 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5804 (with-current-buffer buffer
5805 (unless (eq major-mode 'org-mode)
5806 (error "Agenda file %s is not in `org-mode'" file))
5807 (setq org-category-table (org-get-category-table))
5808 (let ((case-fold-search nil))
5809 (save-excursion
5810 (save-restriction
5811 (if org-respect-restriction
5812 (if (org-region-active-p)
5813 ;; Respect a region to restrict search
5814 (narrow-to-region (region-beginning) (region-end)))
5815 ;; If we work for the calendar or many files,
5816 ;; get rid of any restriction
5817 (widen))
5818 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5819 (while (setq arg (pop args))
5820 (cond
5821 ((and (eq arg :todo)
5822 (equal date (calendar-current-date)))
5823 (setq rtn (org-agenda-get-todos))
5824 (setq results (append results rtn)))
5825 ((eq arg :timestamp)
5826 (setq rtn (org-agenda-get-blocks))
5827 (setq results (append results rtn))
5828 (setq rtn (org-agenda-get-timestamps))
5829 (setq results (append results rtn)))
5830 ((eq arg :scheduled)
5831 (setq rtn (org-agenda-get-scheduled))
5832 (setq results (append results rtn)))
5833 ((eq arg :closed)
5834 (setq rtn (org-agenda-get-closed))
5835 (setq results (append results rtn)))
5836 ((and (eq arg :deadline)
5837 (equal date (calendar-current-date)))
5838 (setq rtn (org-agenda-get-deadlines))
5839 (setq results (append results rtn))))))))
5840 results))))
5842 (defun org-entry-is-done-p ()
5843 "Is the current entry marked DONE?"
5844 (save-excursion
5845 (and (re-search-backward "[\r\n]\\*" nil t)
5846 (looking-at org-nl-done-regexp))))
5848 (defun org-at-date-range-p ()
5849 "Is the cursor inside a date range?"
5850 (interactive)
5851 (save-excursion
5852 (catch 'exit
5853 (let ((pos (point)))
5854 (skip-chars-backward "^<\r\n")
5855 (skip-chars-backward "<")
5856 (and (looking-at org-tr-regexp)
5857 (>= (match-end 0) pos)
5858 (throw 'exit t))
5859 (skip-chars-backward "^<\r\n")
5860 (skip-chars-backward "<")
5861 (and (looking-at org-tr-regexp)
5862 (>= (match-end 0) pos)
5863 (throw 'exit t)))
5864 nil)))
5866 (defun org-agenda-get-todos ()
5867 "Return the TODO information for agenda display."
5868 (let* ((props (list 'face nil
5869 'done-face 'org-done
5870 'mouse-face 'highlight
5871 'keymap org-agenda-keymap
5872 'help-echo
5873 (format "mouse-2 or RET jump to org file %s"
5874 (abbreviate-file-name buffer-file-name))))
5875 (regexp (concat "[\n\r]\\*+ *\\("
5876 (if org-select-this-todo-keyword
5877 (concat "\\<\\(" org-select-this-todo-keyword
5878 "\\)\\>")
5879 org-not-done-regexp)
5880 "[^\n\r]*\\)"))
5881 marker priority category tags
5882 ee txt)
5883 (goto-char (point-min))
5884 (while (re-search-forward regexp nil t)
5885 (goto-char (match-beginning 1))
5886 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5887 category (org-get-category)
5888 tags (org-get-tags-at (point))
5889 txt (org-format-agenda-item "" (match-string 1) category tags)
5890 priority
5891 (+ (org-get-priority txt)
5892 (if org-todo-kwd-priority-p
5893 (- org-todo-kwd-max-priority -2
5894 (length
5895 (member (match-string 2) org-todo-keywords)))
5896 1)))
5897 (org-add-props txt props
5898 'org-marker marker 'org-hd-marker marker
5899 'priority priority 'category category)
5900 (push txt ee)
5901 (goto-char (match-end 1)))
5902 (nreverse ee)))
5904 (defconst org-agenda-no-heading-message
5905 "No heading for this item in buffer or region.")
5907 (defun org-agenda-get-timestamps ()
5908 "Return the date stamp information for agenda display."
5909 (let* ((props (list 'face nil
5910 'mouse-face 'highlight
5911 'keymap org-agenda-keymap
5912 'help-echo
5913 (format "mouse-2 or RET jump to org file %s"
5914 (abbreviate-file-name buffer-file-name))))
5915 (regexp (regexp-quote
5916 (substring
5917 (format-time-string
5918 (car org-time-stamp-formats)
5919 (apply 'encode-time ; DATE bound by calendar
5920 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5921 0 11)))
5922 marker hdmarker deadlinep scheduledp donep tmp priority category
5923 ee txt timestr tags)
5924 (goto-char (point-min))
5925 (while (re-search-forward regexp nil t)
5926 (if (not (save-match-data (org-at-date-range-p)))
5927 (progn
5928 (setq marker (org-agenda-new-marker (match-beginning 0))
5929 category (org-get-category (match-beginning 0))
5930 tmp (buffer-substring (max (point-min)
5931 (- (match-beginning 0)
5932 org-ds-keyword-length))
5933 (match-beginning 0))
5934 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5935 deadlinep (string-match org-deadline-regexp tmp)
5936 scheduledp (string-match org-scheduled-regexp tmp)
5937 donep (org-entry-is-done-p))
5938 (if (string-match ">" timestr)
5939 ;; substring should only run to end of time stamp
5940 (setq timestr (substring timestr 0 (match-end 0))))
5941 (save-excursion
5942 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5943 (progn
5944 (goto-char (match-end 1))
5945 (setq hdmarker (org-agenda-new-marker)
5946 tags (org-get-tags-at))
5947 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5948 (setq txt (org-format-agenda-item
5949 (format "%s%s"
5950 (if deadlinep "Deadline: " "")
5951 (if scheduledp "Scheduled: " ""))
5952 (match-string 1) category tags timestr)))
5953 (setq txt org-agenda-no-heading-message))
5954 (setq priority (org-get-priority txt))
5955 (org-add-props txt props
5956 'org-marker marker 'org-hd-marker hdmarker)
5957 (if deadlinep
5958 (org-add-props txt nil
5959 'face (if donep 'org-done 'org-warning)
5960 'undone-face 'org-warning 'done-face 'org-done
5961 'category category 'priority (+ 100 priority))
5962 (if scheduledp
5963 (org-add-props txt nil
5964 'face 'org-scheduled-today
5965 'undone-face 'org-scheduled-today 'done-face 'org-done
5966 'category category priority (+ 99 priority))
5967 (org-add-props txt nil 'priority priority 'category category)))
5968 (push txt ee))
5969 (outline-next-heading))))
5970 (nreverse ee)))
5972 (defun org-agenda-get-closed ()
5973 "Return the logged TODO entries for agenda display."
5974 (let* ((props (list 'mouse-face 'highlight
5975 'keymap org-agenda-keymap
5976 'help-echo
5977 (format "mouse-2 or RET jump to org file %s"
5978 (abbreviate-file-name buffer-file-name))))
5979 (regexp (concat
5980 "\\<" org-closed-string " *\\["
5981 (regexp-quote
5982 (substring
5983 (format-time-string
5984 (car org-time-stamp-formats)
5985 (apply 'encode-time ; DATE bound by calendar
5986 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5987 1 11))))
5988 marker hdmarker priority category tags
5989 ee txt timestr)
5990 (goto-char (point-min))
5991 (while (re-search-forward regexp nil t)
5992 (if (not (save-match-data (org-at-date-range-p)))
5993 (progn
5994 (setq marker (org-agenda-new-marker (match-beginning 0))
5995 category (org-get-category (match-beginning 0))
5996 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5997 ;; donep (org-entry-is-done-p)
5999 (if (string-match "\\]" timestr)
6000 ;; substring should only run to end of time stamp
6001 (setq timestr (substring timestr 0 (match-end 0))))
6002 (save-excursion
6003 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6004 (progn
6005 (goto-char (match-end 1))
6006 (setq hdmarker (org-agenda-new-marker)
6007 tags (org-get-tags-at))
6008 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6009 (setq txt (org-format-agenda-item
6010 "Closed: "
6011 (match-string 1) category tags timestr)))
6012 (setq txt org-agenda-no-heading-message))
6013 (setq priority 100000)
6014 (org-add-props txt props
6015 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
6016 'priority priority 'category category
6017 'undone-face 'org-warning 'done-face 'org-done)
6018 (push txt ee))
6019 (outline-next-heading))))
6020 (nreverse ee)))
6022 (defun org-agenda-get-deadlines ()
6023 "Return the deadline information for agenda display."
6024 (let* ((wdays org-deadline-warning-days)
6025 (props (list 'mouse-face 'highlight
6026 'keymap org-agenda-keymap
6027 'help-echo
6028 (format "mouse-2 or RET jump to org file %s"
6029 (abbreviate-file-name buffer-file-name))))
6030 (regexp org-deadline-time-regexp)
6031 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6032 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6033 d2 diff pos pos1 category tags
6034 ee txt head)
6035 (goto-char (point-min))
6036 (while (re-search-forward regexp nil t)
6037 (setq pos (1- (match-beginning 1))
6038 d2 (time-to-days
6039 (org-time-string-to-time (match-string 1)))
6040 diff (- d2 d1))
6041 ;; When to show a deadline in the calendar:
6042 ;; If the expiration is within wdays warning time.
6043 ;; Past-due deadlines are only shown on the current date
6044 (if (and (< diff wdays) todayp (not (= diff 0)))
6045 (save-excursion
6046 (setq category (org-get-category))
6047 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6048 (progn
6049 (goto-char (match-end 0))
6050 (setq pos1 (match-end 1))
6051 (setq tags (org-get-tags-at pos1))
6052 (setq head (buffer-substring-no-properties
6053 (point)
6054 (progn (skip-chars-forward "^\r\n")
6055 (point))))
6056 (if (string-match org-looking-at-done-regexp head)
6057 (setq txt nil)
6058 (setq txt (org-format-agenda-item
6059 (format "In %3d d.: " diff) head category tags))))
6060 (setq txt org-agenda-no-heading-message))
6061 (when txt
6062 (org-add-props txt props
6063 'org-marker (org-agenda-new-marker pos)
6064 'org-hd-marker (org-agenda-new-marker pos1)
6065 'priority (+ (- 10 diff) (org-get-priority txt))
6066 'category category
6067 'face (cond ((<= diff 0) 'org-warning)
6068 ((<= diff 5) 'org-scheduled-previously)
6069 (t nil))
6070 'undone-face (cond
6071 ((<= diff 0) 'org-warning)
6072 ((<= diff 5) 'org-scheduled-previously)
6073 (t nil))
6074 'done-face 'org-done)
6075 (push txt ee)))))
6076 ee))
6078 (defun org-agenda-get-scheduled ()
6079 "Return the scheduled information for agenda display."
6080 (let* ((props (list 'face 'org-scheduled-previously
6081 'undone-face 'org-scheduled-previously
6082 'done-face 'org-done
6083 'mouse-face 'highlight
6084 'keymap org-agenda-keymap
6085 'help-echo
6086 (format "mouse-2 or RET jump to org file %s"
6087 (abbreviate-file-name buffer-file-name))))
6088 (regexp org-scheduled-time-regexp)
6089 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6090 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6091 d2 diff pos pos1 category tags
6092 ee txt head)
6093 (goto-char (point-min))
6094 (while (re-search-forward regexp nil t)
6095 (setq pos (1- (match-beginning 1))
6096 d2 (time-to-days
6097 (org-time-string-to-time (match-string 1)))
6098 diff (- d2 d1))
6099 ;; When to show a scheduled item in the calendar:
6100 ;; If it is on or past the date.
6101 (if (and (< diff 0) todayp)
6102 (save-excursion
6103 (setq category (org-get-category))
6104 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6105 (progn
6106 (goto-char (match-end 0))
6107 (setq pos1 (match-end 1))
6108 (setq tags (org-get-tags-at))
6109 (setq head (buffer-substring-no-properties
6110 (point)
6111 (progn (skip-chars-forward "^\r\n") (point))))
6112 (if (string-match org-looking-at-done-regexp head)
6113 (setq txt nil)
6114 (setq txt (org-format-agenda-item
6115 (format "Sched.%2dx: " (- 1 diff)) head
6116 category tags))))
6117 (setq txt org-agenda-no-heading-message))
6118 (when txt
6119 (org-add-props txt props
6120 'org-marker (org-agenda-new-marker pos)
6121 'org-hd-marker (org-agenda-new-marker pos1)
6122 'priority (+ (- 5 diff) (org-get-priority txt))
6123 'category category)
6124 (push txt ee)))))
6125 ee))
6127 (defun org-agenda-get-blocks ()
6128 "Return the date-range information for agenda display."
6129 (let* ((props (list 'face nil
6130 'mouse-face 'highlight
6131 'keymap org-agenda-keymap
6132 'help-echo
6133 (format "mouse-2 or RET jump to org file %s"
6134 (abbreviate-file-name buffer-file-name))))
6135 (regexp org-tr-regexp)
6136 (d0 (calendar-absolute-from-gregorian date))
6137 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
6138 (goto-char (point-min))
6139 (while (re-search-forward regexp nil t)
6140 (setq timestr (match-string 0)
6141 s1 (match-string 1)
6142 s2 (match-string 2)
6143 d1 (time-to-days (org-time-string-to-time s1))
6144 d2 (time-to-days (org-time-string-to-time s2)))
6145 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
6146 ;; Only allow days between the limits, because the normal
6147 ;; date stamps will catch the limits.
6148 (save-excursion
6149 (setq marker (org-agenda-new-marker (point)))
6150 (setq category (org-get-category))
6151 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6152 (progn
6153 (setq hdmarker (org-agenda-new-marker (match-end 1)))
6154 (goto-char (match-end 1))
6155 (setq tags (org-get-tags-at))
6156 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6157 (setq txt (org-format-agenda-item
6158 (format (if (= d1 d2) "" "(%d/%d): ")
6159 (1+ (- d0 d1)) (1+ (- d2 d1)))
6160 (match-string 1) category tags
6161 (if (= d0 d1) timestr))))
6162 (setq txt org-agenda-no-heading-message))
6163 (org-add-props txt props
6164 'org-marker marker 'org-hd-marker hdmarker
6165 'priority (org-get-priority txt) 'category category)
6166 (push txt ee)))
6167 (outline-next-heading))
6168 ;; Sort the entries by expiration date.
6169 (nreverse ee)))
6171 (defconst org-plain-time-of-day-regexp
6172 (concat
6173 "\\(\\<[012]?[0-9]"
6174 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6175 "\\(--?"
6176 "\\(\\<[012]?[0-9]"
6177 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6178 "\\)?")
6179 "Regular expression to match a plain time or time range.
6180 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
6181 groups carry important information:
6182 0 the full match
6183 1 the first time, range or not
6184 8 the second time, if it is a range.")
6186 (defconst org-stamp-time-of-day-regexp
6187 (concat
6188 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
6189 "\\([012][0-9]:[0-5][0-9]\\)>"
6190 "\\(--?"
6191 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
6192 "Regular expression to match a timestamp time or time range.
6193 After a match, the following groups carry important information:
6194 0 the full match
6195 1 date plus weekday, for backreferencing to make sure both times on same day
6196 2 the first time, range or not
6197 4 the second time, if it is a range.")
6199 (defvar org-prefix-has-time nil
6200 "A flag, set by `org-compile-prefix-format'.
6201 The flag is set if the currently compiled format contains a `%t'.")
6202 (defvar org-prefix-has-tag nil
6203 "A flag, set by `org-compile-prefix-format'.
6204 The flag is set if the currently compiled format contains a `%T'.")
6206 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
6207 "Format TXT to be inserted into the agenda buffer.
6208 In particular, it adds the prefix and corresponding text properties. EXTRA
6209 must be a string and replaces the `%s' specifier in the prefix format.
6210 CATEGORY (string, symbol or nil) may be used to overrule the default
6211 category taken from local variable or file name. It will replace the `%c'
6212 specifier in the format. DOTIME, when non-nil, indicates that a
6213 time-of-day should be extracted from TXT for sorting of this entry, and for
6214 the `%t' specifier in the format. When DOTIME is a string, this string is
6215 searched for a time before TXT is. NOPREFIX is a flag and indicates that
6216 only the correctly processes TXT should be returned - this is used by
6217 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
6218 (save-match-data
6219 ;; Diary entries sometimes have extra whitespace at the beginning
6220 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
6221 (let* ((category (or category
6222 org-category
6223 (if buffer-file-name
6224 (file-name-sans-extension
6225 (file-name-nondirectory buffer-file-name))
6226 "")))
6227 (tag (or (nth (1- (or (length tags) 0)) tags) ""))
6228 time ;; needed for the eval of the prefix format
6229 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
6230 (time-of-day (and dotime (org-get-time-of-day ts)))
6231 stamp plain s0 s1 s2 rtn)
6232 (when (and dotime time-of-day org-prefix-has-time)
6233 ;; Extract starting and ending time and move them to prefix
6234 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
6235 (setq plain (string-match org-plain-time-of-day-regexp ts)))
6236 (setq s0 (match-string 0 ts)
6237 s1 (match-string (if plain 1 2) ts)
6238 s2 (match-string (if plain 8 4) ts))
6240 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
6241 ;; them, we might want to remove them there to avoid duplication.
6242 ;; The user can turn this off with a variable.
6243 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
6244 (string-match (concat (regexp-quote s0) " *") txt)
6245 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
6246 (= (match-beginning 0) 0)
6248 (setq txt (replace-match "" nil nil txt))))
6249 ;; Normalize the time(s) to 24 hour
6250 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
6251 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
6253 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
6254 (and org-agenda-remove-tags-when-in-prefix
6255 org-prefix-has-tag))
6256 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
6257 (setq txt (replace-match "" t t txt)))
6259 ;; Create the final string
6260 (if noprefix
6261 (setq rtn txt)
6262 ;; Prepare the variables needed in the eval of the compiled format
6263 (setq time (cond (s2 (concat s1 "-" s2))
6264 (s1 (concat s1 "......"))
6265 (t ""))
6266 extra (or extra "")
6267 category (if (symbolp category) (symbol-name category) category))
6268 ;; Evaluate the compiled format
6269 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
6271 ;; And finally add the text properties
6272 (org-add-props rtn nil
6273 'category (downcase category) 'tags tags
6274 'prefix-length (- (length rtn) (length txt))
6275 'time-of-day time-of-day
6276 'dotime dotime))))
6278 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
6279 (catch 'exit
6280 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
6281 ((and todayp (member 'today (car org-agenda-time-grid))))
6282 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
6283 ((member 'weekly (car org-agenda-time-grid)))
6284 (t (throw 'exit list)))
6285 (let* ((have (delq nil (mapcar
6286 (lambda (x) (get-text-property 1 'time-of-day x))
6287 list)))
6288 (string (nth 1 org-agenda-time-grid))
6289 (gridtimes (nth 2 org-agenda-time-grid))
6290 (req (car org-agenda-time-grid))
6291 (remove (member 'remove-match req))
6292 new time)
6293 (if (and (member 'require-timed req) (not have))
6294 ;; don't show empty grid
6295 (throw 'exit list))
6296 (while (setq time (pop gridtimes))
6297 (unless (and remove (member time have))
6298 (setq time (int-to-string time))
6299 (push (org-format-agenda-item
6300 nil string "" nil
6301 (concat (substring time 0 -2) ":" (substring time -2)))
6302 new)
6303 (put-text-property
6304 1 (length (car new)) 'face 'org-time-grid (car new))))
6305 (if (member 'time-up org-agenda-sorting-strategy)
6306 (append new list)
6307 (append list new)))))
6309 (defun org-compile-prefix-format (format)
6310 "Compile the prefix format into a Lisp form that can be evaluated.
6311 The resulting form is returned and stored in the variable
6312 `org-prefix-format-compiled'."
6313 (setq org-prefix-has-time nil org-prefix-has-tag nil)
6314 (let ((start 0) varform vars var (s format)e c f opt)
6315 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
6316 s start)
6317 (setq var (cdr (assoc (match-string 4 s)
6318 '(("c" . category) ("t" . time) ("s" . extra)
6319 ("T" . tag))))
6320 c (or (match-string 3 s) "")
6321 opt (match-beginning 1)
6322 start (1+ (match-beginning 0)))
6323 (if (equal var 'time) (setq org-prefix-has-time t))
6324 (if (equal var 'tag) (setq org-prefix-has-tag t))
6325 (setq f (concat "%" (match-string 2 s) "s"))
6326 (if opt
6327 (setq varform
6328 `(if (equal "" ,var)
6330 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
6331 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
6332 (setq s (replace-match "%s" t nil s))
6333 (push varform vars))
6334 (setq vars (nreverse vars))
6335 (setq org-prefix-format-compiled `(format ,s ,@vars))))
6337 (defun org-get-time-of-day (s &optional string)
6338 "Check string S for a time of day.
6339 If found, return it as a military time number between 0 and 2400.
6340 If not found, return nil.
6341 The optional STRING argument forces conversion into a 5 character wide string
6342 HH:MM."
6343 (save-match-data
6344 (when
6346 (string-match
6347 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
6348 (string-match
6349 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
6350 (let* ((t0 (+ (* 100
6351 (+ (string-to-number (match-string 1 s))
6352 (if (and (match-beginning 4)
6353 (equal (downcase (match-string 4 s)) "pm"))
6354 12 0)))
6355 (if (match-beginning 3)
6356 (string-to-number (match-string 3 s))
6357 0)))
6358 (t1 (concat " "
6359 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6360 (int-to-string t0))))
6361 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6363 (defun org-finalize-agenda-entries (list)
6364 "Sort and concatenate the agenda items."
6365 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6367 (defsubst org-cmp-priority (a b)
6368 "Compare the priorities of string A and B."
6369 (let ((pa (or (get-text-property 1 'priority a) 0))
6370 (pb (or (get-text-property 1 'priority b) 0)))
6371 (cond ((> pa pb) +1)
6372 ((< pa pb) -1)
6373 (t nil))))
6375 (defsubst org-cmp-category (a b)
6376 "Compare the string values of categories of strings A and B."
6377 (let ((ca (or (get-text-property 1 'category a) ""))
6378 (cb (or (get-text-property 1 'category b) "")))
6379 (cond ((string-lessp ca cb) -1)
6380 ((string-lessp cb ca) +1)
6381 (t nil))))
6383 (defsubst org-cmp-time (a b)
6384 "Compare the time-of-day values of strings A and B."
6385 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6386 (ta (or (get-text-property 1 'time-of-day a) def))
6387 (tb (or (get-text-property 1 'time-of-day b) def)))
6388 (cond ((< ta tb) -1)
6389 ((< tb ta) +1)
6390 (t nil))))
6392 (defun org-entries-lessp (a b)
6393 "Predicate for sorting agenda entries."
6394 ;; The following variables will be used when the form is evaluated.
6395 (let* ((time-up (org-cmp-time a b))
6396 (time-down (if time-up (- time-up) nil))
6397 (priority-up (org-cmp-priority a b))
6398 (priority-down (if priority-up (- priority-up) nil))
6399 (category-up (org-cmp-category a b))
6400 (category-down (if category-up (- category-up) nil))
6401 (category-keep (if category-up +1 nil)))
6402 (cdr (assoc
6403 (eval (cons 'or org-agenda-sorting-strategy))
6404 '((-1 . t) (1 . nil) (nil . nil))))))
6406 (defun org-agenda-show-priority ()
6407 "Show the priority of the current item.
6408 This priority is composed of the main priority given with the [#A] cookies,
6409 and by additional input from the age of a schedules or deadline entry."
6410 (interactive)
6411 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6412 (message "Priority is %d" (if pri pri -1000))))
6414 (defun org-agenda-show-tags ()
6415 "Show the tags applicable to the current item."
6416 (interactive)
6417 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6418 (if tags
6419 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6420 (message "No tags associated with this line"))))
6422 (defun org-agenda-goto (&optional highlight)
6423 "Go to the Org-mode file which contains the item at point."
6424 (interactive)
6425 (let* ((marker (or (get-text-property (point) 'org-marker)
6426 (org-agenda-error)))
6427 (buffer (marker-buffer marker))
6428 (pos (marker-position marker)))
6429 (switch-to-buffer-other-window buffer)
6430 (widen)
6431 (goto-char pos)
6432 (when (eq major-mode 'org-mode)
6433 (org-show-hidden-entry)
6434 (save-excursion
6435 (and (outline-next-heading)
6436 (org-flag-heading nil)))) ; show the next heading
6437 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6439 (defun org-agenda-switch-to ()
6440 "Go to the Org-mode file which contains the item at point."
6441 (interactive)
6442 (let* ((marker (or (get-text-property (point) 'org-marker)
6443 (org-agenda-error)))
6444 (buffer (marker-buffer marker))
6445 (pos (marker-position marker)))
6446 (switch-to-buffer buffer)
6447 (delete-other-windows)
6448 (widen)
6449 (goto-char pos)
6450 (when (eq major-mode 'org-mode)
6451 (org-show-hidden-entry)
6452 (save-excursion
6453 (and (outline-next-heading)
6454 (org-flag-heading nil)))))) ; show the next heading
6456 (defun org-agenda-goto-mouse (ev)
6457 "Go to the Org-mode file which contains the item at the mouse click."
6458 (interactive "e")
6459 (mouse-set-point ev)
6460 (org-agenda-goto))
6462 (defun org-agenda-show ()
6463 "Display the Org-mode file which contains the item at point."
6464 (interactive)
6465 (let ((win (selected-window)))
6466 (org-agenda-goto t)
6467 (select-window win)))
6469 (defun org-agenda-recenter (arg)
6470 "Display the Org-mode file which contains the item at point and recenter."
6471 (interactive "P")
6472 (let ((win (selected-window)))
6473 (org-agenda-goto t)
6474 (recenter arg)
6475 (select-window win)))
6477 (defun org-agenda-show-mouse (ev)
6478 "Display the Org-mode file which contains the item at the mouse click."
6479 (interactive "e")
6480 (mouse-set-point ev)
6481 (org-agenda-show))
6483 (defun org-agenda-check-no-diary ()
6484 "Check if the entry is a diary link and abort if yes."
6485 (if (get-text-property (point) 'org-agenda-diary-link)
6486 (org-agenda-error)))
6488 (defun org-agenda-error ()
6489 (error "Command not allowed in this line"))
6491 (defvar org-last-heading-marker (make-marker)
6492 "Marker pointing to the headline that last changed its TODO state
6493 by a remote command from the agenda.")
6495 (defun org-agenda-todo (&optional arg)
6496 "Cycle TODO state of line at point, also in Org-mode file.
6497 This changes the line at point, all other lines in the agenda referring to
6498 the same tree node, and the headline of the tree node in the Org-mode file."
6499 (interactive "P")
6500 (org-agenda-check-no-diary)
6501 (let* ((col (current-column))
6502 (marker (or (get-text-property (point) 'org-marker)
6503 (org-agenda-error)))
6504 (buffer (marker-buffer marker))
6505 (pos (marker-position marker))
6506 (hdmarker (get-text-property (point) 'org-hd-marker))
6507 (buffer-read-only nil)
6508 newhead)
6509 (with-current-buffer buffer
6510 (widen)
6511 (goto-char pos)
6512 (org-show-hidden-entry)
6513 (save-excursion
6514 (and (outline-next-heading)
6515 (org-flag-heading nil))) ; show the next heading
6516 (org-todo arg)
6517 (forward-char 1)
6518 (setq newhead (org-get-heading))
6519 (save-excursion
6520 (org-back-to-heading)
6521 (move-marker org-last-heading-marker (point))))
6522 (beginning-of-line 1)
6523 (save-excursion
6524 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6525 (move-to-column col)))
6527 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6528 "Change all lines in the agenda buffer which match HDMARKER.
6529 The new content of the line will be NEWHEAD (as modified by
6530 `org-format-agenda-item'). HDMARKER is checked with
6531 `equal' against all `org-hd-marker' text properties in the file.
6532 If FIXFACE is non-nil, the face of each item is modified acording to
6533 the new TODO state."
6534 (let* (props m pl undone-face done-face finish new dotime cat tags)
6535 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6536 (save-excursion
6537 (goto-char (point-max))
6538 (beginning-of-line 1)
6539 (while (not finish)
6540 (setq finish (bobp))
6541 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6542 (equal m hdmarker))
6543 (setq props (text-properties-at (point))
6544 dotime (get-text-property (point) 'dotime)
6545 cat (get-text-property (point) 'category)
6546 tags (get-text-property (point) 'tags)
6547 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6548 pl (get-text-property (point) 'prefix-length)
6549 undone-face (get-text-property (point) 'undone-face)
6550 done-face (get-text-property (point) 'done-face))
6551 (move-to-column pl)
6552 (if (looking-at ".*")
6553 (progn
6554 (replace-match new t t)
6555 (beginning-of-line 1)
6556 (add-text-properties (point-at-bol) (point-at-eol) props)
6557 (if fixface
6558 (add-text-properties
6559 (point-at-bol) (point-at-eol)
6560 (list 'face
6561 (if org-last-todo-state-is-todo
6562 undone-face done-face))))
6563 (beginning-of-line 1))
6564 (error "Line update did not work")))
6565 (beginning-of-line 0)))))
6567 (defun org-agenda-priority-up ()
6568 "Increase the priority of line at point, also in Org-mode file."
6569 (interactive)
6570 (org-agenda-priority 'up))
6572 (defun org-agenda-priority-down ()
6573 "Decrease the priority of line at point, also in Org-mode file."
6574 (interactive)
6575 (org-agenda-priority 'down))
6577 (defun org-agenda-priority (&optional force-direction)
6578 "Set the priority of line at point, also in Org-mode file.
6579 This changes the line at point, all other lines in the agenda referring to
6580 the same tree node, and the headline of the tree node in the Org-mode file."
6581 (interactive)
6582 (org-agenda-check-no-diary)
6583 (let* ((marker (or (get-text-property (point) 'org-marker)
6584 (org-agenda-error)))
6585 (buffer (marker-buffer marker))
6586 (pos (marker-position marker))
6587 (hdmarker (get-text-property (point) 'org-hd-marker))
6588 (buffer-read-only nil)
6589 newhead)
6590 (with-current-buffer buffer
6591 (widen)
6592 (goto-char pos)
6593 (org-show-hidden-entry)
6594 (save-excursion
6595 (and (outline-next-heading)
6596 (org-flag-heading nil))) ; show the next heading
6597 (funcall 'org-priority force-direction)
6598 (end-of-line 1)
6599 (setq newhead (org-get-heading)))
6600 (org-agenda-change-all-lines newhead hdmarker)
6601 (beginning-of-line 1)))
6603 (defun org-get-tags-at (&optional pos)
6604 "Get a list of all headline targs applicable at POS.
6605 POS defaults to point. If tags are inherited, the list contains
6606 the targets in the same sequence as the headlines appear, i.e.
6607 the tags of the current headline come last."
6608 (interactive)
6609 (let (tags)
6610 (save-excursion
6611 (goto-char (or pos (point)))
6612 (save-match-data
6613 (org-back-to-heading t)
6614 (condition-case nil
6615 (while t
6616 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6617 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6618 (or org-use-tag-inheritance (error ""))
6619 (org-up-heading-all 1))
6620 (error nil))))
6621 (message "%s" tags)
6622 tags))
6624 (defun org-agenda-set-tags ()
6625 "Set tags for the current headline."
6626 (interactive)
6627 (org-agenda-check-no-diary)
6628 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6629 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6630 (org-agenda-error)))
6631 (buffer (marker-buffer hdmarker))
6632 (pos (marker-position hdmarker))
6633 (buffer-read-only nil)
6634 newhead)
6635 (with-current-buffer buffer
6636 (widen)
6637 (goto-char pos)
6638 (org-show-hidden-entry)
6639 (save-excursion
6640 (and (outline-next-heading)
6641 (org-flag-heading nil))) ; show the next heading
6642 (call-interactively 'org-set-tags)
6643 (end-of-line 1)
6644 (setq newhead (org-get-heading)))
6645 (org-agenda-change-all-lines newhead hdmarker)
6646 (beginning-of-line 1)))
6648 (defun org-agenda-date-later (arg &optional what)
6649 "Change the date of this item to one day later."
6650 (interactive "p")
6651 (org-agenda-check-type t 'agenda 'timeline)
6652 (org-agenda-check-no-diary)
6653 (let* ((marker (or (get-text-property (point) 'org-marker)
6654 (org-agenda-error)))
6655 (buffer (marker-buffer marker))
6656 (pos (marker-position marker)))
6657 (with-current-buffer buffer
6658 (widen)
6659 (goto-char pos)
6660 (if (not (org-at-timestamp-p))
6661 (error "Cannot find time stamp"))
6662 (org-timestamp-change arg (or what 'day))
6663 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6665 (defun org-agenda-date-earlier (arg &optional what)
6666 "Change the date of this item to one day earlier."
6667 (interactive "p")
6668 (org-agenda-date-later (- arg) what))
6670 (defun org-agenda-date-prompt (arg)
6671 "Change the date of this item. Date is prompted for, with default today.
6672 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6673 be used to request time specification in the time stamp."
6674 (interactive "P")
6675 (org-agenda-check-type t 'agenda 'timeline)
6676 (org-agenda-check-no-diary)
6677 (let* ((marker (or (get-text-property (point) 'org-marker)
6678 (org-agenda-error)))
6679 (buffer (marker-buffer marker))
6680 (pos (marker-position marker)))
6681 (with-current-buffer buffer
6682 (widen)
6683 (goto-char pos)
6684 (if (not (org-at-timestamp-p))
6685 (error "Cannot find time stamp"))
6686 (org-time-stamp arg)
6687 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6689 (defun org-get-heading ()
6690 "Return the heading of the current entry, without the stars."
6691 (save-excursion
6692 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6693 (if (and (re-search-backward "[\r\n]\\*" nil t)
6694 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6695 (match-string 1)
6696 "")))
6698 (defun org-agenda-diary-entry ()
6699 "Make a diary entry, like the `i' command from the calendar.
6700 All the standard commands work: block, weekly etc."
6701 (interactive)
6702 (org-agenda-check-type t 'agenda 'timeline)
6703 (require 'diary-lib)
6704 (let* ((char (progn
6705 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6706 (read-char-exclusive)))
6707 (cmd (cdr (assoc char
6708 '((?d . insert-diary-entry)
6709 (?w . insert-weekly-diary-entry)
6710 (?m . insert-monthly-diary-entry)
6711 (?y . insert-yearly-diary-entry)
6712 (?a . insert-anniversary-diary-entry)
6713 (?b . insert-block-diary-entry)
6714 (?c . insert-cyclic-diary-entry)))))
6715 (oldf (symbol-function 'calendar-cursor-to-date))
6716 (point (point))
6717 (mark (or (mark t) (point))))
6718 (unless cmd
6719 (error "No command associated with <%c>" char))
6720 (unless (and (get-text-property point 'day)
6721 (or (not (equal ?b char))
6722 (get-text-property mark 'day)))
6723 (error "Don't know which date to use for diary entry"))
6724 ;; We implement this by hacking the `calendar-cursor-to-date' function
6725 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6726 (let ((calendar-mark-ring
6727 (list (calendar-gregorian-from-absolute
6728 (or (get-text-property mark 'day)
6729 (get-text-property point 'day))))))
6730 (unwind-protect
6731 (progn
6732 (fset 'calendar-cursor-to-date
6733 (lambda (&optional error)
6734 (calendar-gregorian-from-absolute
6735 (get-text-property point 'day))))
6736 (call-interactively cmd))
6737 (fset 'calendar-cursor-to-date oldf)))))
6740 (defun org-agenda-execute-calendar-command (cmd)
6741 "Execute a calendar command from the agenda, with the date associated to
6742 the cursor position."
6743 (org-agenda-check-type t 'agenda 'timeline)
6744 (require 'diary-lib)
6745 (unless (get-text-property (point) 'day)
6746 (error "Don't know which date to use for calendar command"))
6747 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6748 (point (point))
6749 (date (calendar-gregorian-from-absolute
6750 (get-text-property point 'day)))
6751 (displayed-day (extract-calendar-day date))
6752 (displayed-month (extract-calendar-month date))
6753 (displayed-year (extract-calendar-year date)))
6754 (unwind-protect
6755 (progn
6756 (fset 'calendar-cursor-to-date
6757 (lambda (&optional error)
6758 (calendar-gregorian-from-absolute
6759 (get-text-property point 'day))))
6760 (call-interactively cmd))
6761 (fset 'calendar-cursor-to-date oldf))))
6763 (defun org-agenda-phases-of-moon ()
6764 "Display the phases of the moon for the 3 months around the cursor date."
6765 (interactive)
6766 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6768 (defun org-agenda-holidays ()
6769 "Display the holidays for the 3 months around the cursor date."
6770 (interactive)
6771 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6773 (defun org-agenda-sunrise-sunset (arg)
6774 "Display sunrise and sunset for the cursor date.
6775 Latitude and longitude can be specified with the variables
6776 `calendar-latitude' and `calendar-longitude'. When called with prefix
6777 argument, latitude and longitude will be prompted for."
6778 (interactive "P")
6779 (let ((calendar-longitude (if arg nil calendar-longitude))
6780 (calendar-latitude (if arg nil calendar-latitude))
6781 (calendar-location-name
6782 (if arg "the given coordinates" calendar-location-name)))
6783 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6785 (defun org-agenda-goto-calendar ()
6786 "Open the Emacs calendar with the date at the cursor."
6787 (interactive)
6788 (org-agenda-check-type t 'agenda 'timeline)
6789 (let* ((day (or (get-text-property (point) 'day)
6790 (error "Don't know which date to open in calendar")))
6791 (date (calendar-gregorian-from-absolute day))
6792 (calendar-move-hook nil)
6793 (view-diary-entries-initially nil))
6794 (calendar)
6795 (calendar-goto-date date)))
6797 (defun org-calendar-goto-agenda ()
6798 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6799 This is a command that has to be installed in `calendar-mode-map'."
6800 (interactive)
6801 (org-agenda-list nil (calendar-absolute-from-gregorian
6802 (calendar-cursor-to-date))
6803 nil t))
6805 (defun org-agenda-convert-date ()
6806 (interactive)
6807 (org-agenda-check-type t 'agenda 'timeline)
6808 (let ((day (get-text-property (point) 'day))
6809 date s)
6810 (unless day
6811 (error "Don't know which date to convert"))
6812 (setq date (calendar-gregorian-from-absolute day))
6813 (setq s (concat
6814 "Gregorian: " (calendar-date-string date) "\n"
6815 "ISO: " (calendar-iso-date-string date) "\n"
6816 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6817 "Julian: " (calendar-julian-date-string date) "\n"
6818 "Astron. JD: " (calendar-astro-date-string date)
6819 " (Julian date number at noon UTC)\n"
6820 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6821 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6822 "French: " (calendar-french-date-string date) "\n"
6823 "Mayan: " (calendar-mayan-date-string date) "\n"
6824 "Coptic: " (calendar-coptic-date-string date) "\n"
6825 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6826 "Persian: " (calendar-persian-date-string date) "\n"
6827 "Chinese: " (calendar-chinese-date-string date) "\n"))
6828 (with-output-to-temp-buffer "*Dates*"
6829 (princ s))
6830 (if (fboundp 'fit-window-to-buffer)
6831 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6833 ;;; Tags
6835 (defun org-scan-tags (action matcher &optional todo-only)
6836 "Scan headline tags with inheritance and produce output ACTION.
6837 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6838 evaluated, testing if a given set of tags qualifies a headline for
6839 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
6840 are included in the output."
6841 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6842 (mapconcat 'regexp-quote
6843 (nreverse (cdr (reverse org-todo-keywords)))
6844 "\\|")
6845 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
6846 (props (list 'face nil
6847 'done-face 'org-done
6848 'undone-face nil
6849 'mouse-face 'highlight
6850 'keymap org-agenda-keymap
6851 'help-echo
6852 (format "mouse-2 or RET jump to org file %s"
6853 (abbreviate-file-name buffer-file-name))))
6854 lspos
6855 tags tags-list tags-alist (llast 0) rtn level category i txt
6856 todo marker)
6858 (save-excursion
6859 (goto-char (point-min))
6860 (when (eq action 'sparse-tree) (hide-sublevels 1))
6861 (while (re-search-forward re nil t)
6862 (setq todo (if (match-end 1) (match-string 2))
6863 tags (if (match-end 4) (match-string 4)))
6864 (goto-char (setq lspos (1+ (match-beginning 0))))
6865 (setq level (funcall outline-level)
6866 category (org-get-category))
6867 (setq i llast llast level)
6868 ;; remove tag lists from same and sublevels
6869 (while (>= i level)
6870 (when (setq entry (assoc i tags-alist))
6871 (setq tags-alist (delete entry tags-alist)))
6872 (setq i (1- i)))
6873 ;; add the nex tags
6874 (when tags
6875 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6876 tags-alist
6877 (cons (cons level tags) tags-alist)))
6878 ;; compile tags for current headline
6879 (setq tags-list
6880 (if org-use-tag-inheritance
6881 (apply 'append (mapcar 'cdr tags-alist))
6882 tags))
6883 (when (and (or (not todo-only) todo)
6884 (eval matcher))
6885 ;; list this headline
6886 (if (eq action 'sparse-tree)
6887 (progn
6888 (org-show-hierarchy-above))
6889 (setq txt (org-format-agenda-item
6891 (concat
6892 (if org-tags-match-list-sublevels
6893 (make-string (1- level) ?.) "")
6894 (org-get-heading))
6895 category tags-list))
6896 (goto-char lspos)
6897 (setq marker (org-agenda-new-marker))
6898 (org-add-props txt props
6899 'org-marker marker 'org-hd-marker marker 'category category)
6900 (push txt rtn))
6901 ;; if we are to skip sublevels, jump to end of subtree
6902 (point)
6903 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6904 (nreverse rtn)))
6906 (defun org-tags-sparse-tree (&optional arg match)
6907 "Create a sparse tree according to tags search string MATCH.
6908 MATCH can contain positive and negative selection of tags, like
6909 \"+WORK+URGENT-WITHBOSS\"."
6910 (interactive "P")
6911 (let ((org-show-following-heading nil)
6912 (org-show-hierarchy-above nil))
6913 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6915 (defun org-make-tags-matcher (match)
6916 "Create the TAGS matcher form for the tags-selecting string MATCH."
6917 (unless match
6918 ;; Get a new match request, with completion
6919 (setq org-last-tags-completion-table
6920 (or (org-get-buffer-tags)
6921 org-last-tags-completion-table))
6922 (setq match (completing-read
6923 "Tags: " 'org-tags-completion-function nil nil nil
6924 'org-tags-history)))
6925 ;; parse the string and create a lisp form
6926 (let ((match0 match) minus tag mm matcher orterms term orlist)
6927 (setq orterms (org-split-string match "|"))
6928 (while (setq term (pop orterms))
6929 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
6930 (setq minus (and (match-end 1)
6931 (equal (match-string 1 term) "-"))
6932 tag (match-string 2 term)
6933 term (substring term (match-end 0))
6934 mm (list 'member (downcase tag) 'tags-list)
6935 mm (if minus (list 'not mm) mm))
6936 (push mm matcher))
6937 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6938 orlist)
6939 (setq matcher nil))
6940 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6941 ;; Return the string and lisp forms of the matcher
6942 (cons match0 matcher)))
6944 ;;;###autoload
6945 (defun org-tags-view (&optional todo-only match keep-modes)
6946 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
6947 The prefix arg TODO-ONLY limits the search to TODO entries."
6948 (interactive "P")
6949 (org-agenda-maybe-reset-markers 'force)
6950 (org-compile-prefix-format org-agenda-prefix-format)
6951 (let* ((org-agenda-keep-modes keep-modes)
6952 (org-tags-match-list-sublevels
6953 (if todo-only t org-tags-match-list-sublevels))
6954 (win (selected-window))
6955 (completion-ignore-case t)
6956 rtn rtnall files file pos matcher
6957 buffer)
6958 (setq matcher (org-make-tags-matcher match)
6959 match (car matcher) matcher (cdr matcher))
6960 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6961 (progn
6962 (delete-other-windows)
6963 (switch-to-buffer-other-window
6964 (get-buffer-create org-agenda-buffer-name))))
6965 (setq buffer-read-only nil)
6966 (erase-buffer)
6967 (org-agenda-mode) (setq buffer-read-only nil)
6968 (set (make-local-variable 'org-agenda-type) 'tags)
6969 (set (make-local-variable 'org-agenda-redo-command)
6970 (list 'org-tags-view (list 'quote todo-only)
6971 (list 'if 'current-prefix-arg nil match) t))
6972 (setq files (org-agenda-files)
6973 rtnall nil)
6974 (while (setq file (pop files))
6975 (catch 'nextfile
6976 (org-check-agenda-file file)
6977 (setq buffer (if (file-exists-p file)
6978 (org-get-agenda-file-buffer file)
6979 (error "No such file %s" file)))
6980 (if (not buffer)
6981 ;; If file does not exist, merror message to agenda
6982 (setq rtn (list
6983 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6984 rtnall (append rtnall rtn))
6985 (with-current-buffer buffer
6986 (unless (eq major-mode 'org-mode)
6987 (error "Agenda file %s is not in `org-mode'" file))
6988 (save-excursion
6989 (save-restriction
6990 (if org-respect-restriction
6991 (if (org-region-active-p)
6992 ;; Respect a region to restrict search
6993 (narrow-to-region (region-beginning) (region-end)))
6994 ;; If we work for the calendar or many files,
6995 ;; get rid of any restriction
6996 (widen))
6997 (setq rtn (org-scan-tags 'agenda matcher todo-only))
6998 (setq rtnall (append rtnall rtn))))))))
6999 (insert "Headlines with TAGS match: ")
7000 (add-text-properties (point-min) (1- (point))
7001 (list 'face 'org-level-3))
7002 (setq pos (point))
7003 (insert match "\n")
7004 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7005 (setq pos (point))
7006 (insert "Press `C-u r' to search again with new search string\n")
7007 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7008 (when rtnall
7009 (insert (mapconcat 'identity rtnall "\n")))
7010 (goto-char (point-min))
7011 (setq buffer-read-only t)
7012 (org-fit-agenda-window)
7013 (if (not org-select-agenda-window) (select-window win))))
7015 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
7016 (defun org-set-tags (&optional arg just-align)
7017 "Set the tags for the current headline.
7018 With prefix ARG, realign all tags in headings in the current buffer."
7019 (interactive)
7020 (let* (;(inherit (org-get-inherited-tags))
7021 (re (concat "^" outline-regexp))
7022 (col (current-column))
7023 (current (org-get-tags))
7024 tags hd empty invis)
7025 (if arg
7026 (save-excursion
7027 (goto-char (point-min))
7028 (while (re-search-forward re nil t)
7029 (org-set-tags nil t))
7030 (message "All tags realigned to column %d" org-tags-column))
7031 (if just-align
7032 (setq tags current)
7033 (setq org-last-tags-completion-table
7034 (or (org-get-buffer-tags)
7035 org-last-tags-completion-table))
7036 (setq tags
7037 (let ((org-add-colon-after-tag-completion t))
7038 (completing-read "Tags: " 'org-tags-completion-function
7039 nil nil current 'org-tags-history)))
7040 (while (string-match "[-+&]+" tags)
7041 (setq tags (replace-match ":" t t tags))))
7042 ;; FIXME: still optimize this by not checking when JUST-ALIGN?
7043 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
7044 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
7045 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
7046 (if (equal current "")
7047 (progn
7048 (end-of-line 1)
7049 (or empty (insert-before-markers " ")))
7050 (beginning-of-line 1)
7051 (setq invis (org-invisible-p))
7052 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
7053 (setq hd (match-string 1))
7054 (delete-region (match-beginning 0) (match-end 0))
7055 (insert-before-markers (org-trim hd) (if empty "" " ")))
7056 (unless (equal tags "")
7057 (move-to-column (max (current-column)
7058 (if (> org-tags-column 0)
7059 org-tags-column
7060 (- (- org-tags-column) (length tags))))
7062 (insert-before-markers tags)
7063 (if (and (not invis) (org-invisible-p))
7064 (outline-flag-region (point-at-bol) (point) nil)))
7065 (move-to-column col))))
7067 (defun org-tags-completion-function (string predicate &optional flag)
7068 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
7069 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
7070 (setq s1 (match-string 1 string)
7071 s2 (match-string 2 string))
7072 (setq s1 "" s2 string))
7073 (cond
7074 ((eq flag nil)
7075 ;; try completion
7076 (setq rtn (try-completion s2 ctable))
7077 (if (stringp rtn)
7078 (concat s1 s2 (substring rtn (length s2))
7079 (if (and org-add-colon-after-tag-completion
7080 (assoc rtn ctable))
7081 ":" "")))
7083 ((eq flag t)
7084 ;; all-completions
7085 (all-completions s2 ctable)
7087 ((eq flag 'lambda)
7088 ;; exact match?
7089 (assoc s2 ctable)))
7092 (defun org-get-tags ()
7093 "Get the TAGS string in the current headline."
7094 (unless (org-on-heading-p)
7095 (error "Not on a heading"))
7096 (save-excursion
7097 (beginning-of-line 1)
7098 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
7099 (org-match-string-no-properties 1)
7100 "")))
7102 (defun org-get-buffer-tags ()
7103 "Get a table of all tags used in the buffer, for completion."
7104 (let (tags)
7105 (save-excursion
7106 (goto-char (point-min))
7107 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
7108 (mapc (lambda (x) (add-to-list 'tags x))
7109 (org-split-string (org-match-string-no-properties 1) ":"))))
7110 (mapcar 'list tags)))
7112 ;;; Link Stuff
7114 (defun org-find-file-at-mouse (ev)
7115 "Open file link or URL at mouse."
7116 (interactive "e")
7117 (mouse-set-point ev)
7118 (org-open-at-point 'in-emacs))
7120 (defun org-open-at-mouse (ev)
7121 "Open file link or URL at mouse."
7122 (interactive "e")
7123 (mouse-set-point ev)
7124 (org-open-at-point))
7126 (defun org-open-at-point (&optional in-emacs)
7127 "Open link at or after point.
7128 If there is no link at point, this function will search forward up to
7129 the end of the current subtree.
7130 Normally, files will be opened by an appropriate application. If the
7131 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7132 (interactive "P")
7133 (org-remove-occur-highlights nil nil t)
7134 (if (org-at-timestamp-p)
7135 (org-agenda-list nil (time-to-days (org-time-string-to-time
7136 (substring (match-string 1) 0 10)))
7138 (let (type path link line search (pos (point)))
7139 (catch 'match
7140 (save-excursion
7141 (skip-chars-forward "^]\n\r")
7142 (when (and (re-search-backward "\\[\\[" nil t)
7143 (looking-at org-bracket-link-regexp)
7144 (<= (match-beginning 0) pos)
7145 (>= (match-end 0) pos))
7146 (setq link (org-link-unescape (org-match-string-no-properties 1)))
7147 (while (string-match " *\n *" link)
7148 (setq link (replace-match " " t t link)))
7149 (if (string-match org-link-re-with-space2 link)
7150 (setq type (match-string 1 link)
7151 path (match-string 2 link))
7152 (setq type "thisfile"
7153 path link))
7154 (throw 'match t)))
7156 (when (get-text-property (point) 'org-linked-text)
7157 (setq type "thisfile"
7158 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7159 (1+ (point)) (point))
7160 path (buffer-substring
7161 (previous-single-property-change pos 'org-linked-text)
7162 (next-single-property-change pos 'org-linked-text)))
7163 (throw 'match t))
7165 (save-excursion
7166 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
7167 (if (equal (char-before) ?<) (backward-char 1))
7168 (when (or (looking-at org-angle-link-re)
7169 (looking-at org-plain-link-re)
7170 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
7171 (re-search-forward org-plain-link-re (point-at-eol) t))
7172 (<= (match-beginning 0) pos)
7173 (>= (match-end 0) pos)))
7174 (setq type (match-string 1)
7175 path (match-string 2))
7176 (throw 'match t)))
7177 (save-excursion
7178 (skip-chars-backward "^ \t\n\r")
7179 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
7180 (setq type "tags"
7181 path (match-string 1))
7182 (while (string-match ":" path)
7183 (setq path (replace-match "+" t t path)))
7184 (throw 'match t)))
7185 (save-excursion
7186 (skip-chars-backward "a-zA-Z_")
7187 (when (and (memq 'camel org-activate-links)
7188 (looking-at org-camel-regexp))
7189 (setq type "camel" path (match-string 0))
7190 (if (equal (char-before) ?*)
7191 (setq path (concat "*" path))))
7192 (throw 'match t)))
7193 (unless path
7194 (error "No link found"))
7195 ;; Remove any trailing spaces in path
7196 (if (string-match " +\\'" path)
7197 (setq path (replace-match "" t t path)))
7199 (cond
7201 ((member type '("http" "https" "ftp" "mailto" "news"))
7202 (browse-url (concat type ":" path)))
7204 ((string= type "tags")
7205 (org-tags-view in-emacs path))
7206 ((or (string= type "camel")
7207 (string= type "thisfile"))
7208 (org-mark-ring-push)
7209 (org-link-search
7210 path
7211 (cond ((equal in-emacs '(4)) 'occur)
7212 ((equal in-emacs '(16)) 'org-occur)
7213 (t nil))))
7215 ((string= type "file")
7216 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
7217 (setq line (string-to-number (match-string 1 path))
7218 path (substring path 0 (match-beginning 0)))
7219 (if (string-match "::\\(.+\\)\\'" path)
7220 (setq search (match-string 1 path)
7221 path (substring path 0 (match-beginning 0)))))
7222 (org-open-file path in-emacs line search))
7224 ((string= type "news")
7225 (org-follow-gnus-link path))
7227 ((string= type "bbdb")
7228 (org-follow-bbdb-link path))
7230 ((string= type "gnus")
7231 (let (group article)
7232 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7233 (error "Error in Gnus link"))
7234 (setq group (match-string 1 path)
7235 article (match-string 3 path))
7236 (org-follow-gnus-link group article)))
7238 ((string= type "vm")
7239 (let (folder article)
7240 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7241 (error "Error in VM link"))
7242 (setq folder (match-string 1 path)
7243 article (match-string 3 path))
7244 ;; in-emacs is the prefix arg, will be interpreted as read-only
7245 (org-follow-vm-link folder article in-emacs)))
7247 ((string= type "wl")
7248 (let (folder article)
7249 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7250 (error "Error in Wanderlust link"))
7251 (setq folder (match-string 1 path)
7252 article (match-string 3 path))
7253 (org-follow-wl-link folder article)))
7255 ((string= type "mhe")
7256 (let (folder article)
7257 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7258 (error "Error in MHE link"))
7259 (setq folder (match-string 1 path)
7260 article (match-string 3 path))
7261 (org-follow-mhe-link folder article)))
7263 ((string= type "rmail")
7264 (let (folder article)
7265 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7266 (error "Error in RMAIL link"))
7267 (setq folder (match-string 1 path)
7268 article (match-string 3 path))
7269 (org-follow-rmail-link folder article)))
7271 ((string= type "shell")
7272 (let ((cmd path))
7273 (while (string-match "@{" cmd)
7274 (setq cmd (replace-match "<" t t cmd)))
7275 (while (string-match "@}" cmd)
7276 (setq cmd (replace-match ">" t t cmd)))
7277 (if (or (not org-confirm-shell-links)
7278 (funcall org-confirm-shell-links
7279 (format "Execute \"%s\" in shell? "
7280 (org-add-props cmd nil
7281 'face 'org-warning))))
7282 (shell-command cmd)
7283 (error "Abort"))))
7286 (browse-url-at-point))))))
7288 (defun org-link-search (s &optional type)
7289 "Search for a link search option.
7290 When S is a CamelCaseWord, search for a target, or for a sentence containing
7291 the words. If S is surrounded by forward slashes, it is interpreted as a
7292 regular expression. In org-mode files, this will create an `org-occur'
7293 sparse tree. In ordinary files, `occur' will be used to list matches.
7294 If the current buffer is in `dired-mode', grep will be used to search
7295 in all files."
7296 (let ((case-fold-search t)
7297 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7298 (pos (point))
7299 (pre "") (post "")
7300 words re0 re1 re2 re3 re4 re5 re2a reall camel)
7301 (cond ((save-excursion
7302 (goto-char (point-min))
7303 (and
7304 (re-search-forward
7305 (concat "<<" (regexp-quote s0) ">>") nil t)
7306 (setq pos (match-beginning 0))))
7307 ;; There is an exact target for this
7308 (goto-char pos))
7309 ((string-match "^/\\(.*\\)/$" s)
7310 ;; A regular expression
7311 (cond
7312 ((eq major-mode 'org-mode)
7313 (org-occur (match-string 1 s)))
7314 ;;((eq major-mode 'dired-mode)
7315 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7316 (t (org-do-occur (match-string 1 s)))))
7317 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
7319 ;; A camel or a normal search string
7320 (when (equal (string-to-char s) ?*)
7321 ;; Anchor on headlines, post may include tags.
7322 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
7323 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
7324 s (substring s 1)))
7325 (remove-text-properties
7326 0 (length s)
7327 '(face nil mouse-face nil keymap nil fontified nil) s)
7328 ;; Make a series of regular expressions to find a match
7329 (setq words
7330 (if camel
7331 (org-camel-to-words s)
7332 (org-split-string s "[ \n\r\t]+"))
7333 re0 (concat "<<" (regexp-quote s0) ">>")
7334 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
7335 re2a (concat "\\<" (mapconcat 'downcase words "[ \t\r\n]+") "\\>")
7336 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
7337 re1 (concat pre re2 post)
7338 re3 (concat pre re4 post)
7339 re5 (concat pre ".*" re4)
7340 re2 (concat pre re2)
7341 re2a (concat pre re2a)
7342 re4 (concat pre re4)
7343 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7344 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7345 re5 "\\)"
7347 (cond
7348 ((eq type 'org-occur) (org-occur reall))
7349 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7350 (t (goto-char (point-min))
7351 (if (or (org-search-not-link re0 nil t)
7352 (org-search-not-link re1 nil t)
7353 (org-search-not-link re2 nil t)
7354 (org-search-not-link re2a nil t)
7355 (org-search-not-link re3 nil t)
7356 (org-search-not-link re4 nil t)
7357 (org-search-not-link re5 nil t)
7359 (goto-char (match-beginning 0))
7360 (goto-char pos)
7361 (error "No match")))))
7363 ;; Normal string-search
7364 (goto-char (point-min))
7365 (if (search-forward s nil t)
7366 (goto-char (match-beginning 0))
7367 (error "No match"))))
7368 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
7370 (defun org-search-not-link (&rest args)
7371 "Execute `re-search-forward', but only accept matches that are not a link."
7372 (catch 'exit
7373 (let ((pos (point)) p1)
7374 (while (apply 're-search-forward args)
7375 (setq p1 (point))
7376 (if (not (save-match-data
7377 (and (re-search-backward "\\[\\[" nil t)
7378 (looking-at org-bracket-link-regexp)
7379 (<= (match-beginning 0) p1)
7380 (>= (match-end 0) p1))))
7381 (progn (goto-char (match-end 0))
7382 (throw 'exit (point)))
7383 (goto-char (match-end 0)))))))
7385 (defun org-do-occur (regexp &optional cleanup)
7386 "Call the Emacs command `occur'.
7387 If CLEANUP is non-nil, remove the printout of the regular expression
7388 in the *Occur* buffer. This is useful if the regex is long and not useful
7389 to read."
7390 (occur regexp)
7391 (when cleanup
7392 (let ((cwin (selected-window)) win beg end)
7393 (when (setq win (get-buffer-window "*Occur*"))
7394 (select-window win))
7395 (goto-char (point-min))
7396 (when (re-search-forward "match[a-z]+" nil t)
7397 (setq beg (match-end 0))
7398 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7399 (setq end (1- (match-beginning 0)))))
7400 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
7401 (goto-char (point-min))
7402 (select-window cwin))))
7404 (defvar org-mark-ring nil
7405 "Mark ring for positions before jumps in Org-mode.")
7406 (defvar org-mark-ring-last-goto nil
7407 "Last position in the mark ring used to go back.")
7408 ;; Fill and close the ring
7409 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7410 (loop for i from 1 to org-mark-ring-length do
7411 (push (make-marker) org-mark-ring))
7412 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7413 org-mark-ring)
7415 (defun org-mark-ring-push (&optional pos buffer)
7416 "Put the current position or POS into the mark ring and rotate it."
7417 (interactive)
7418 (setq pos (or pos (point)))
7419 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7420 (move-marker (car org-mark-ring)
7421 (or pos (point))
7422 (or buffer (current-buffer)))
7423 (message
7424 (substitute-command-keys
7425 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7427 (defun org-mark-ring-goto (&optional n)
7428 "Jump to the previous position in the mark ring.
7429 With prefix arg N, jump back that many stored positions. When
7430 called several times in succession, walk through the entire ring.
7431 Org-mode commands jumping to a different position in the current file,
7432 or to another Org-mode file, automatically push the old position
7433 onto the ring."
7434 (interactive "p")
7435 (let (p m)
7436 (if (eq last-command this-command)
7437 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7438 (setq p org-mark-ring))
7439 (setq org-mark-ring-last-goto p)
7440 (setq m (car p))
7441 (switch-to-buffer (marker-buffer m))
7442 (goto-char m)
7443 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7445 (defun org-camel-to-words (s)
7446 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7447 (let ((case-fold-search nil)
7448 words)
7449 (while (string-match "[a-z][A-Z]" s)
7450 (push (substring s 0 (1+ (match-beginning 0))) words)
7451 (setq s (substring s (1+ (match-beginning 0)))))
7452 (nreverse (cons s words))))
7454 (defun org-remove-angle-brackets (s)
7455 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7456 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7458 (defun org-add-angle-brackets (s)
7459 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7460 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7463 (defun org-follow-bbdb-link (name)
7464 "Follow a BBDB link to NAME."
7465 (require 'bbdb)
7466 (let ((inhibit-redisplay t)
7467 (bbdb-electric-p nil))
7468 (catch 'exit
7469 ;; Exact match on name
7470 (bbdb-name (concat "\\`" name "\\'") nil)
7471 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7472 ;; Exact match on name
7473 (bbdb-company (concat "\\`" name "\\'") nil)
7474 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7475 ;; Partial match on name
7476 (bbdb-name name nil)
7477 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7478 ;; Partial match on company
7479 (bbdb-company name nil)
7480 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7481 ;; General match including network address and notes
7482 (bbdb name nil)
7483 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7484 (delete-window (get-buffer-window "*BBDB*"))
7485 (error "No matching BBDB record")))))
7487 (defun org-follow-gnus-link (&optional group article)
7488 "Follow a Gnus link to GROUP and ARTICLE."
7489 (require 'gnus)
7490 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7491 (if group (gnus-fetch-group group))
7492 (if article
7493 (or (gnus-summary-goto-article article nil 'force)
7494 (if (fboundp 'gnus-summary-insert-cached-articles)
7495 (progn
7496 (gnus-summary-insert-cached-articles)
7497 (gnus-summary-goto-article article nil 'force))
7498 (message "Message could not be found.")))))
7500 (defun org-follow-vm-link (&optional folder article readonly)
7501 "Follow a VM link to FOLDER and ARTICLE."
7502 (require 'vm)
7503 (setq article (org-add-angle-brackets article))
7504 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7505 ;; ange-ftp or efs or tramp access
7506 (let ((user (or (match-string 1 folder) (user-login-name)))
7507 (host (match-string 2 folder))
7508 (file (match-string 3 folder)))
7509 (cond
7510 ((featurep 'tramp)
7511 ;; use tramp to access the file
7512 (if (featurep 'xemacs)
7513 (setq folder (format "[%s@%s]%s" user host file))
7514 (setq folder (format "/%s@%s:%s" user host file))))
7516 ;; use ange-ftp or efs
7517 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
7518 (setq folder (format "/%s@%s:%s" user host file))))))
7519 (when folder
7520 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7521 (sit-for 0.1)
7522 (when article
7523 (vm-select-folder-buffer)
7524 (widen)
7525 (let ((case-fold-search t))
7526 (goto-char (point-min))
7527 (if (not (re-search-forward
7528 (concat "^" "message-id: *" (regexp-quote article))))
7529 (error "Could not find the specified message in this folder"))
7530 (vm-isearch-update)
7531 (vm-isearch-narrow)
7532 (vm-beginning-of-message)
7533 (vm-summarize)))))
7535 (defun org-follow-wl-link (folder article)
7536 "Follow a Wanderlust link to FOLDER and ARTICLE."
7537 (setq article (org-add-angle-brackets article))
7538 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7539 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7540 (wl-summary-redisplay))
7542 (defun org-follow-rmail-link (folder article)
7543 "Follow an RMAIL link to FOLDER and ARTICLE."
7544 (setq article (org-add-angle-brackets article))
7545 (let (message-number)
7546 (save-excursion
7547 (save-window-excursion
7548 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7549 (setq message-number
7550 (save-restriction
7551 (widen)
7552 (goto-char (point-max))
7553 (if (re-search-backward
7554 (concat "^Message-ID:\\s-+" (regexp-quote
7555 (or article "")))
7556 nil t)
7557 (rmail-what-message))))))
7558 (if message-number
7559 (progn
7560 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7561 (rmail-show-message message-number)
7562 message-number)
7563 (error "Message not found"))))
7565 ;; mh-e integration based on planner-mode
7566 (defun org-mhe-get-message-real-folder ()
7567 "Return the name of the current message real folder, so if you use
7568 sequences, it will now work."
7569 (save-excursion
7570 (let* ((folder
7571 (if (equal major-mode 'mh-folder-mode)
7572 mh-current-folder
7573 ;; Refer to the show buffer
7574 mh-show-folder-buffer))
7575 (end-index
7576 (if (boundp 'mh-index-folder)
7577 (min (length mh-index-folder) (length folder))))
7579 ;; a simple test on mh-index-data does not work, because
7580 ;; mh-index-data is always nil in a show buffer.
7581 (if (and (boundp 'mh-index-folder)
7582 (string= mh-index-folder (substring folder 0 end-index)))
7583 (if (equal major-mode 'mh-show-mode)
7584 (save-window-excursion
7585 (when (buffer-live-p (get-buffer folder))
7586 (progn
7587 (pop-to-buffer folder)
7588 (org-mhe-get-message-folder-from-index)
7591 (org-mhe-get-message-folder-from-index)
7593 folder
7597 (defun org-mhe-get-message-folder-from-index ()
7598 "Returns the name of the message folder in a index folder buffer."
7599 (save-excursion
7600 (mh-index-previous-folder)
7601 (re-search-forward "^\\(+.*\\)$" nil t)
7602 (message (match-string 1))))
7604 (defun org-mhe-get-message-folder ()
7605 "Return the name of the current message folder. Be careful if you
7606 use sequences."
7607 (save-excursion
7608 (if (equal major-mode 'mh-folder-mode)
7609 mh-current-folder
7610 ;; Refer to the show buffer
7611 mh-show-folder-buffer)))
7613 (defun org-mhe-get-message-num ()
7614 "Return the number of the current message. Be careful if you
7615 use sequences."
7616 (save-excursion
7617 (if (equal major-mode 'mh-folder-mode)
7618 (mh-get-msg-num nil)
7619 ;; Refer to the show buffer
7620 (mh-show-buffer-message-number))))
7622 (defun org-mhe-get-header (header)
7623 "Return a header of the message in folder mode. This will create a
7624 show buffer for the corresponding message. If you have a more clever
7625 idea..."
7626 (let* ((folder (org-mhe-get-message-folder))
7627 (num (org-mhe-get-message-num))
7628 (buffer (get-buffer-create (concat "show-" folder)))
7629 (header-field))
7630 (with-current-buffer buffer
7631 (mh-display-msg num folder)
7632 (if (equal major-mode 'mh-folder-mode)
7633 (mh-header-display)
7634 (mh-show-header-display))
7635 (set-buffer buffer)
7636 (setq header-field (mh-get-header-field header))
7637 (if (equal major-mode 'mh-folder-mode)
7638 (mh-show)
7639 (mh-show-show))
7640 header-field)))
7642 (defun org-follow-mhe-link (folder article)
7643 "Follow an MHE link to FOLDER and ARTICLE.
7644 If ARTICLE is nil FOLDER is shown. If the configuration variable
7645 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
7646 ARTICLE is searched in all folders. Indexed searches (swish++,
7647 namazu, and others supported by MH-E) will always search in all
7648 folders."
7649 (require 'mh-e)
7650 (require 'mh-search)
7651 (require 'mh-utils)
7652 (mh-find-path)
7653 (if (not article)
7654 (mh-visit-folder (mh-normalize-folder-name folder))
7655 (setq article (org-add-angle-brackets article))
7656 (mh-search-choose)
7657 (if (equal mh-searcher 'pick)
7658 (progn
7659 (mh-search folder (list "--message-id" article))
7660 (when (and org-mhe-search-all-folders
7661 (not (org-mhe-get-message-real-folder)))
7662 (kill-this-buffer)
7663 (mh-search "+" (list "--message-id" article))))
7664 (mh-search "+" article))
7665 (if (org-mhe-get-message-real-folder)
7666 (mh-show-msg 1)
7667 (kill-this-buffer)
7668 (error "Message not found"))))
7670 (defun org-open-file (path &optional in-emacs line search)
7671 "Open the file at PATH.
7672 First, this expands any special file name abbreviations. Then the
7673 configuration variable `org-file-apps' is checked if it contains an
7674 entry for this file type, and if yes, the corresponding command is launched.
7675 If no application is found, Emacs simply visits the file.
7676 With optional argument IN-EMACS, Emacs will visit the file.
7677 Optional LINE specifies a line to go to, optional SEARCH a string to
7678 search for. If LINE or SEARCH is given, the file will always be
7679 opened in Emacs.
7680 If the file does not exist, an error is thrown."
7681 (setq in-emacs (or in-emacs line search))
7682 (let* ((file (if (equal path "")
7683 buffer-file-name
7684 (convert-standard-filename (org-expand-file-name path))))
7685 (dirp (file-directory-p file))
7686 (dfile (downcase file))
7687 (old-buffer (current-buffer))
7688 (old-pos (point))
7689 (old-mode major-mode)
7690 ext cmd apps)
7691 (if (and (not (file-exists-p file))
7692 (not org-open-non-existing-files))
7693 (error "No such file: %s" file))
7694 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7695 (setq ext (match-string 1 dfile))
7696 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7697 (setq ext (match-string 1 dfile))))
7698 (setq apps (append org-file-apps (org-default-apps)))
7699 (if in-emacs
7700 (setq cmd 'emacs)
7701 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7702 (cdr (assoc ext apps))
7703 (cdr (assoc t apps)))))
7704 (when (eq cmd 'mailcap)
7705 (require 'mailcap)
7706 (mailcap-parse-mailcaps)
7707 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7708 (command (mailcap-mime-info mime-type)))
7709 (if (stringp command)
7710 (setq cmd command)
7711 (setq cmd 'emacs))))
7712 (cond
7713 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7714 (setq cmd (format cmd (concat "\"" file "\"")))
7715 (save-window-excursion
7716 (shell-command (concat cmd " &"))))
7717 ((or (stringp cmd)
7718 (eq cmd 'emacs))
7719 (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
7720 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7721 (if line (goto-line line)
7722 (if search (org-link-search search))))
7723 ((consp cmd)
7724 (eval cmd))
7725 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7726 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7727 (or (not (equal old-buffer (current-buffer)))
7728 (not (equal old-pos (point))))
7729 (org-mark-ring-push old-pos old-buffer))))
7731 (defun org-default-apps ()
7732 "Return the default applications for this operating system."
7733 (cond
7734 ((eq system-type 'darwin)
7735 org-file-apps-defaults-macosx)
7736 ((eq system-type 'windows-nt)
7737 org-file-apps-defaults-windowsnt)
7738 (t org-file-apps-defaults-gnu)))
7740 (defun org-expand-file-name (path)
7741 "Replace special path abbreviations and expand the file name."
7742 (expand-file-name path))
7745 (defvar org-insert-link-history nil
7746 "Minibuffer history for links inserted with `org-insert-link'.")
7748 (defvar org-stored-links nil
7749 "Contains the links stored with `org-store-link'.")
7751 ;;;###autoload
7752 (defun org-store-link (arg)
7753 "\\<org-mode-map>Store an org-link to the current location.
7754 This link can later be inserted into an org-buffer with
7755 \\[org-insert-link].
7756 For some link types, a prefix arg is interpreted:
7757 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7758 For file links, arg negates `org-context-in-file-links'."
7759 (interactive "P")
7760 (let (link cpltxt desc txt (pos (point)))
7761 (cond
7763 ((eq major-mode 'bbdb-mode)
7764 (setq cpltxt (concat
7765 "bbdb:"
7766 (or (bbdb-record-name (bbdb-current-record))
7767 (bbdb-record-company (bbdb-current-record))))
7768 link (org-make-link cpltxt)))
7770 ((eq major-mode 'calendar-mode)
7771 (let ((cd (calendar-cursor-to-date)))
7772 (setq link
7773 (format-time-string
7774 (car org-time-stamp-formats)
7775 (apply 'encode-time
7776 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7777 nil nil nil))))))
7779 ((or (eq major-mode 'vm-summary-mode)
7780 (eq major-mode 'vm-presentation-mode))
7781 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7782 (vm-follow-summary-cursor)
7783 (save-excursion
7784 (vm-select-folder-buffer)
7785 (let* ((message (car vm-message-pointer))
7786 (folder buffer-file-name)
7787 (subject (vm-su-subject message))
7788 (author (vm-su-full-name message))
7789 (message-id (vm-su-message-id message)))
7790 (setq message-id (org-remove-angle-brackets message-id))
7791 (setq folder (abbreviate-file-name folder))
7792 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7793 folder)
7794 (setq folder (replace-match "" t t folder)))
7795 (setq cpltxt (concat author " on: " subject))
7796 (setq link (org-make-link "vm:" folder "#" message-id)))))
7798 ((eq major-mode 'wl-summary-mode)
7799 (let* ((msgnum (wl-summary-message-number))
7800 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7801 msgnum 'message-id))
7802 (wl-message-entity (elmo-msgdb-overview-get-entity
7803 msgnum (wl-summary-buffer-msgdb)))
7804 (author (wl-summary-line-from)) ; FIXME: correct?
7805 (subject "???")) ; FIXME:
7806 (setq message-id (org-remove-angle-brackets message-id))
7807 (setq cpltxt (concat author " on: " subject))
7808 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
7809 "#" message-id))))
7811 ((or (equal major-mode 'mh-folder-mode)
7812 (equal major-mode 'mh-show-mode))
7813 (let ((from-header (org-mhe-get-header "From:"))
7814 (to-header (org-mhe-get-header "To:"))
7815 (subject (org-mhe-get-header "Subject:")))
7816 (setq cpltxt (concat from-header " on: " subject))
7817 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
7818 (org-remove-angle-brackets
7819 (org-mhe-get-header "Message-Id:"))))))
7821 ((eq major-mode 'rmail-mode)
7822 (save-excursion
7823 (save-restriction
7824 (rmail-narrow-to-non-pruned-header)
7825 (let ((folder buffer-file-name)
7826 (message-id (mail-fetch-field "message-id"))
7827 (author (mail-fetch-field "from"))
7828 (subject (mail-fetch-field "subject")))
7829 (setq message-id (org-remove-angle-brackets message-id))
7830 (setq cpltxt (concat author " on: " subject))
7831 (setq link (org-make-link "rmail:" folder "#" message-id))))))
7833 ((eq major-mode 'gnus-group-mode)
7834 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7835 (gnus-group-group-name)) ; version
7836 ((fboundp 'gnus-group-name)
7837 (gnus-group-name))
7838 (t "???"))))
7839 (setq cpltxt (concat
7840 (if (org-xor arg org-usenet-links-prefer-google)
7841 "http://groups.google.com/groups?group="
7842 "gnus:")
7843 group)
7844 link (org-make-link cpltxt))))
7846 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7847 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7848 (gnus-summary-beginning-of-article)
7849 (let* ((group (car gnus-article-current))
7850 (article (cdr gnus-article-current))
7851 (header (gnus-summary-article-header article))
7852 (author (mail-header-from header))
7853 (message-id (mail-header-id header))
7854 (date (mail-header-date header))
7855 (subject (gnus-summary-subject-string)))
7856 (setq cpltxt (concat author " on: " subject))
7857 (if (org-xor arg org-usenet-links-prefer-google)
7858 (setq link
7859 (concat
7860 cpltxt "\n "
7861 (format "http://groups.google.com/groups?as_umsgid=%s"
7862 (org-fixup-message-id-for-http message-id))))
7863 (setq link (org-make-link "gnus:" group
7864 "#" (number-to-string article))))))
7866 ((eq major-mode 'w3-mode)
7867 (setq cpltxt (url-view-url t)
7868 link (org-make-link cpltxt)))
7869 ((eq major-mode 'w3m-mode)
7870 (setq cpltxt w3m-current-url
7871 link (org-make-link cpltxt)))
7873 ((eq major-mode 'org-mode)
7874 ;; Just link to current headline
7875 (setq cpltxt (concat "file:"
7876 (abbreviate-file-name buffer-file-name)))
7877 ;; Add a context search string
7878 (when (org-xor org-context-in-file-links arg)
7879 ;; Check if we are on a target
7880 (if (save-excursion
7881 (skip-chars-forward "^>\n\r")
7882 (and (re-search-backward "<<" nil t)
7883 (looking-at "<<\\(.*?\\)>>")
7884 (<= (match-beginning 0) pos)
7885 (>= (match-end 0) pos)))
7886 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7887 (setq txt (cond
7888 ((org-on-heading-p) nil)
7889 ((org-region-active-p)
7890 (buffer-substring (region-beginning) (region-end)))
7891 (t (buffer-substring (point-at-bol) (point-at-eol)))))
7892 (setq cpltxt
7893 (concat cpltxt "::"
7894 (if org-file-link-context-use-camel-case
7895 (org-make-org-heading-camel txt)
7896 (org-make-org-heading-search-string txt)))
7897 desc "NONE")))
7898 (if (string-match "::\\'" cpltxt)
7899 (setq cpltxt (substring cpltxt 0 -2)))
7900 (setq link (org-make-link cpltxt)))
7902 (buffer-file-name
7903 ;; Just link to this file here.
7904 (setq cpltxt (concat "file:"
7905 (abbreviate-file-name buffer-file-name)))
7906 ;; Add a context string
7907 (when (org-xor org-context-in-file-links arg)
7908 (setq txt (if (org-region-active-p)
7909 (buffer-substring (region-beginning) (region-end))
7910 (buffer-substring (point-at-bol) (point-at-eol))))
7911 (setq cpltxt
7912 (concat cpltxt "::"
7913 (if org-file-link-context-use-camel-case
7914 (org-make-org-heading-camel txt)
7915 (org-make-org-heading-search-string txt)))
7916 desc "NONE"))
7917 (setq link (org-make-link cpltxt)))
7919 ((interactive-p)
7920 (error "Cannot link to a buffer which is not visiting a file"))
7922 (t (setq link nil)))
7924 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7925 (setq link (or link cpltxt)
7926 desc (or desc cpltxt))
7927 (if (equal desc "NONE") (setq desc nil))
7929 (if (and (interactive-p) link)
7930 (progn
7931 (setq org-stored-links
7932 (cons (list cpltxt link desc) org-stored-links))
7933 (message "Stored: %s" (or cpltxt link)))
7934 (org-make-link-string link desc))))
7936 (defun org-make-org-heading-search-string (&optional string heading)
7937 "Make search string for STRING or current headline."
7938 (interactive)
7939 (let ((s (or string (org-get-heading))))
7940 (unless (and string (not heading))
7941 ;; We are using a headline, clean up garbage in there.
7942 (if (string-match org-todo-regexp s)
7943 (setq s (replace-match "" t t s)))
7944 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7945 (setq s (replace-match "" t t s)))
7946 (setq s (org-trim s))
7947 (if (string-match (concat "^\\(" org-quote-string "\\|"
7948 org-comment-string "\\)") s)
7949 (setq s (replace-match "" t t s)))
7950 (while (string-match org-ts-regexp s)
7951 (setq s (replace-match "" t t s))))
7952 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7953 (setq s (replace-match " " t t s)))
7954 (or string (setq s (concat "*" s))) ; Add * for headlines
7955 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7957 (defun org-make-org-heading-camel (&optional string heading)
7958 "Make a CamelCase string for STRING or the current headline."
7959 (interactive)
7960 (let ((s (or string (org-get-heading))))
7961 (unless (and string (not heading))
7962 ;; We are using a headline, clean up garbage in there.
7963 (if (string-match org-todo-regexp s)
7964 (setq s (replace-match "" t t s)))
7965 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7966 (setq s (replace-match "" t t s)))
7967 (setq s (org-trim s))
7968 (if (string-match (concat "^\\(" org-quote-string "\\|"
7969 org-comment-string "\\)") s)
7970 (setq s (replace-match "" t t s)))
7971 (while (string-match org-ts-regexp s)
7972 (setq s (replace-match "" t t s))))
7973 (while (string-match "[^a-zA-Z_ \t]+" s)
7974 (setq s (replace-match " " t t s)))
7975 (or string (setq s (concat "*" s))) ; Add * for headlines
7976 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7978 (defun org-make-link (&rest strings)
7979 "Concatenate STRINGS, format resulting string with `org-link-format'."
7980 (format org-link-format (apply 'concat strings)))
7982 (defun org-make-link-string (link &optional description)
7983 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7984 (if (eq org-link-style 'plain)
7985 (if (equal description link)
7986 link
7987 (concat description "\n" link))
7988 (when (stringp description)
7989 ;; Remove brackets from the description, they are fatal.
7990 (while (string-match "\\[\\|\\]" description)
7991 (setq description (replace-match "" t t description))))
7992 (when (equal (org-link-escape link) description)
7993 ;; No description needed, it is identical
7994 (setq description nil))
7995 (when (and (not description)
7996 (not (equal link (org-link-escape link))))
7997 (setq description link))
7998 (concat "[[" (org-link-escape link) "]"
7999 (if description (concat "[" description "]") "")
8000 "]")))
8002 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
8003 "Association list of escapes for some characters problematic in links.")
8005 (defun org-link-escape (text)
8006 "Escape charaters in TEXT that are problematic for links."
8007 (when text
8008 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
8009 org-link-escape-chars "\\|")))
8010 (while (string-match re text)
8011 (setq text
8012 (replace-match
8013 (cdr (assoc (match-string 0 text) org-link-escape-chars))
8014 t t text)))
8015 text)))
8017 (defun org-link-unescape (text)
8018 "Reverse the action of `org-link-escape'."
8019 (when text
8020 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
8021 org-link-escape-chars "\\|")))
8022 (while (string-match re text)
8023 (setq text
8024 (replace-match
8025 (car (rassoc (match-string 0 text) org-link-escape-chars))
8026 t t text)))
8027 text)))
8029 (defun org-xor (a b)
8030 "Exclusive or."
8031 (if a (not b) b))
8033 (defun org-get-header (header)
8034 "Find a header field in the current buffer."
8035 (save-excursion
8036 (goto-char (point-min))
8037 (let ((case-fold-search t) s)
8038 (cond
8039 ((eq header 'from)
8040 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
8041 (setq s (match-string 1)))
8042 (while (string-match "\"" s)
8043 (setq s (replace-match "" t t s)))
8044 (if (string-match "[<(].*" s)
8045 (setq s (replace-match "" t t s))))
8046 ((eq header 'message-id)
8047 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
8048 (setq s (match-string 1))))
8049 ((eq header 'subject)
8050 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
8051 (setq s (match-string 1)))))
8052 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
8053 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
8054 s)))
8057 (defun org-fixup-message-id-for-http (s)
8058 "Replace special characters in a message id, so it can be used in an http query."
8059 (while (string-match "<" s)
8060 (setq s (replace-match "%3C" t t s)))
8061 (while (string-match ">" s)
8062 (setq s (replace-match "%3E" t t s)))
8063 (while (string-match "@" s)
8064 (setq s (replace-match "%40" t t s)))
8067 (defun org-insert-link (&optional complete-file)
8068 "Insert a link. At the prompt, enter the link.
8070 Completion can be used to select a link previously stored with
8071 `org-store-link'. When the empty string is entered (i.e. if you just
8072 press RET at the prompt), the link defaults to the most recently
8073 stored link. As SPC triggers completion in the minibuffer, you need to
8074 use M-SPC or C-q SPC to force the insertion of a space character.
8076 You will also be prompted for a description, and if one is given, it will
8077 be displayed in the buffer instead of the link.
8079 If there is already a link at point, this command will allow you to edit link
8080 and description parts.
8082 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
8083 selected using completion. The path to the file will be relative to
8084 the current directory if the file is in the current directory or a
8085 subdirectory. Otherwise, the link will be the absolute path as
8086 completed in the minibuffer (i.e. normally ~/path/to/file).
8088 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
8089 is in the current directory or below."
8090 (interactive "P")
8091 (let (link desc entry remove file (pos (point)))
8092 (cond
8093 ((save-excursion
8094 (skip-chars-forward "^]\n\r")
8095 (and (re-search-backward "\\[\\[" nil t)
8096 (looking-at org-bracket-link-regexp)
8097 (<= (match-beginning 0) pos)
8098 (>= (match-end 0) pos)))
8099 ;; We do have a link at point, and we are going to edit it.
8100 (setq remove (list (match-beginning 0) (match-end 0)))
8101 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8102 (setq link (read-string "Link: "
8103 (org-link-unescape
8104 (org-match-string-no-properties 1)))))
8105 (complete-file
8106 ;; Completing read for file names.
8107 (setq file (read-file-name "File: "))
8108 (let ((pwd (file-name-as-directory (expand-file-name "."))))
8109 (cond
8110 ((equal complete-file '(16))
8111 (setq link (org-make-link
8112 "file:"
8113 (abbreviate-file-name (expand-file-name file)))))
8114 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8115 (expand-file-name file))
8116 (setq link (org-make-link
8117 "file:" (match-string 1 (expand-file-name file)))))
8118 (t (setq link (org-make-link "file:" file))))))
8120 ;; Read link, with completion for stored links.
8121 (setq link (org-completing-read
8122 "Link: " org-stored-links nil nil nil
8123 org-insert-link-history
8124 (or (car (car org-stored-links)))))
8125 (setq entry (assoc link org-stored-links))
8126 (if (not org-keep-stored-link-after-insertion)
8127 (setq org-stored-links (delq (assoc link org-stored-links)
8128 org-stored-links)))
8129 (setq link (if entry (nth 1 entry) link)
8130 desc (or desc (nth 2 entry)))))
8132 (if (string-match org-plain-link-re link)
8133 ;; URL-like link, normalize the use of angular brackets.
8134 (setq link (org-make-link (org-remove-angle-brackets link))))
8136 ;; Check if we are linking to the current file. If yes, simplify the link.
8137 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
8138 (let* ((path (match-string 1 link))
8139 (case-fold-search nil)
8140 (search (match-string 2 link)))
8141 (when (save-match-data
8142 (equal (file-truename buffer-file-name)
8143 (file-truename path)))
8144 ;; We are linking to this same file, with a search option
8145 (setq link search))))
8146 (setq desc (read-string "Description: " desc))
8147 (unless (string-match "\\S-" desc) (setq desc nil))
8148 (if remove (apply 'delete-region remove))
8149 (insert (org-make-link-string link desc))))
8151 (defun org-completing-read (&rest args)
8152 (let ((minibuffer-local-completion-map
8153 (copy-keymap minibuffer-local-completion-map)))
8154 (define-key minibuffer-local-completion-map " " 'self-insert-command)
8155 (apply 'completing-read args)))
8157 ;;; Hooks for remember.el
8159 (defvar org-finish-function nil)
8161 ;;;###autoload
8162 (defun org-remember-annotation ()
8163 "Return a link to the current location as an annotation for remember.el.
8164 If you are using Org-mode files as target for data storage with
8165 remember.el, then the annotations should include a link compatible with the
8166 conventions in Org-mode. This function returns such a link."
8167 (org-store-link nil))
8169 (defconst org-remember-help
8170 "Select a destination location for the note.
8171 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
8172 RET at beg-of-buf -> Append to file as level 2 headline
8173 RET on headline -> Store as sublevel entry to current headline
8174 <left>/<right> -> before/after current headline, same headings level")
8176 ;;;###autoload
8177 (defun org-remember-apply-template ()
8178 "Initialize *remember* buffer with template, invode `org-mode'.
8179 This function should be placed into `remember-mode-hook' and in fact requires
8180 to be run from that hook to fucntion properly."
8181 (when org-remember-templates
8182 (let* ((entry (if (= (length org-remember-templates) 1)
8183 (cdar org-remember-templates)
8184 (message "Select template: %s"
8185 (mapconcat
8186 (lambda (x) (char-to-string (car x)))
8187 org-remember-templates " "))
8188 (cdr (assoc (read-char-exclusive) org-remember-templates))))
8189 (tpl (if (consp (cdr entry)) (cadr entry) (cdr entry)))
8190 (file (if (consp (cdr entry)) (nth 2 entry)))
8191 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
8192 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
8193 (v-u (concat "[" (substring v-t 1 -1) "]"))
8194 (v-U (concat "[" (substring v-T 1 -1) "]"))
8195 (v-a annotation) ; defined in `remember-mode'
8196 (v-i initial) ; defined in `remember-mode'
8197 (v-n user-full-name)
8199 (unless tpl (setq tpl "") (message "No template") (ding))
8200 (insert tpl) (goto-char (point-min))
8201 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
8202 (when (and initial (equal (match-string 0) "%i"))
8203 (save-match-data
8204 (let* ((lead (buffer-substring
8205 (point-at-bol) (match-beginning 0))))
8206 (setq v-i (mapconcat 'identity
8207 (org-split-string initial "\n")
8208 (concat "\n" lead))))))
8209 (replace-match
8210 (or (eval (intern (concat "v-" (match-string 1)))) "")
8211 t t))
8212 (let ((org-startup-folded nil)
8213 (org-startup-with-deadline-check nil))
8214 (org-mode))
8215 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
8216 (set (make-local-variable 'org-default-notes-file) file))
8217 (goto-char (point-min))
8218 (if (re-search-forward "%\\?" nil t) (replace-match ""))
8219 (set (make-local-variable 'org-finish-function) 'remember-buffer))))
8221 ;;;###autoload
8222 (defun org-remember-handler ()
8223 "Store stuff from remember.el into an org file.
8224 First prompts for an org file. If the user just presses return, the value
8225 of `org-default-notes-file' is used.
8226 Then the command offers the headings tree of the selected file in order to
8227 file the text at a specific location.
8228 You can either immediately press RET to get the note appended to the
8229 file, or you can use vertical cursor motion and visibility cycling (TAB) to
8230 find a better place. Then press RET or <left> or <right> in insert the note.
8232 Key Cursor position Note gets inserted
8233 -----------------------------------------------------------------------------
8234 RET buffer-start as level 2 heading at end of file
8235 RET on headline as sublevel of the heading at cursor
8236 RET no heading at cursor position, level taken from context.
8237 Or use prefix arg to specify level manually.
8238 <left> on headline as same level, before current heading
8239 <right> on headline as same level, after current heading
8241 So the fastest way to store the note is to press RET RET to append it to
8242 the default file. This way your current train of thought is not
8243 interrupted, in accordance with the principles of remember.el. But with
8244 little extra effort, you can push it directly to the correct location.
8246 Before being stored away, the function ensures that the text has a
8247 headline, i.e. a first line that starts with a \"*\". If not, a headline
8248 is constructed from the current date and some additional data.
8250 If the variable `org-adapt-indentation' is non-nil, the entire text is
8251 also indented so that it starts in the same column as the headline
8252 \(i.e. after the stars).
8254 See also the variable `org-reverse-note-order'."
8255 (catch 'quit
8256 (let* ((txt (buffer-substring (point-min) (point-max)))
8257 (fastp current-prefix-arg)
8258 (file (if fastp org-default-notes-file (org-get-org-file)))
8259 (visiting (find-buffer-visiting file))
8260 (org-startup-with-deadline-check nil)
8261 (org-startup-folded nil)
8262 (org-startup-align-all-tables nil)
8263 spos level indent reversed)
8264 ;; Modify text so that it becomes a nice subtree which can be inserted
8265 ;; into an org tree.
8266 (let* ((lines (split-string txt "\n"))
8267 first)
8268 ;; remove empty lines at the beginning
8269 (while (and lines (string-match "^[ \t]*\n" (car lines)))
8270 (setq lines (cdr lines)))
8271 (setq first (car lines) lines (cdr lines))
8272 (if (string-match "^\\*+" first)
8273 ;; Is already a headline
8274 (setq indent nil)
8275 ;; We need to add a headline: Use time and first buffer line
8276 (setq lines (cons first lines)
8277 first (concat "* " (current-time-string)
8278 " (" (remember-buffer-desc) ")")
8279 indent " "))
8280 (if (and org-adapt-indentation indent)
8281 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
8282 (setq txt (concat first "\n"
8283 (mapconcat 'identity lines "\n"))))
8284 ;; Find the file
8285 (if (not visiting)
8286 (find-file-noselect file))
8287 (with-current-buffer (get-file-buffer file)
8288 (setq reversed (org-notes-order-reversed-p))
8289 (save-excursion
8290 (save-restriction
8291 (widen)
8292 ;; Ask the User for a location
8293 (setq spos (if fastp 1 (org-get-location
8294 (current-buffer)
8295 org-remember-help)))
8296 (if (not spos) (throw 'quit nil)) ; return nil to show we did
8297 ; not handle this note
8298 (goto-char spos)
8299 (cond ((bobp)
8300 ;; Put it at the start or end, as level 2
8301 (save-restriction
8302 (widen)
8303 (goto-char (if reversed (point-min) (point-max)))
8304 (if (not (bolp)) (newline))
8305 (org-paste-subtree 2 txt)))
8306 ((and (org-on-heading-p nil) (not current-prefix-arg))
8307 ;; Put it below this entry, at the beg/end of the subtree
8308 (org-back-to-heading)
8309 (setq level (funcall outline-level))
8310 (if reversed
8311 (outline-end-of-heading)
8312 (outline-end-of-subtree))
8313 (if (not (bolp)) (newline))
8314 (beginning-of-line 1)
8315 (org-paste-subtree (1+ level) txt))
8317 ;; Put it right there, with automatic level determined by
8318 ;; org-paste-subtree or from prefix arg
8319 (org-paste-subtree current-prefix-arg txt)))
8320 (when remember-save-after-remembering
8321 (save-buffer)
8322 (if (not visiting) (kill-buffer (current-buffer)))))))))
8323 t) ;; return t to indicate that we took care of this note.
8325 (defun org-get-org-file ()
8326 "Read a filename, with default directory `org-directory'."
8327 (let ((default (or org-default-notes-file remember-data-file)))
8328 (read-file-name (format "File name [%s]: " default)
8329 (file-name-as-directory org-directory)
8330 default)))
8332 (defun org-notes-order-reversed-p ()
8333 "Check if the current file should receive notes in reversed order."
8334 (cond
8335 ((not org-reverse-note-order) nil)
8336 ((eq t org-reverse-note-order) t)
8337 ((not (listp org-reverse-note-order)) nil)
8338 (t (catch 'exit
8339 (let ((all org-reverse-note-order)
8340 entry)
8341 (while (setq entry (pop all))
8342 (if (string-match (car entry) buffer-file-name)
8343 (throw 'exit (cdr entry))))
8344 nil)))))
8346 ;;; Tables
8348 ;; Watch out: Here we are talking about two different kind of tables.
8349 ;; Most of the code is for the tables created with the Org-mode table editor.
8350 ;; Sometimes, we talk about tables created and edited with the table.el
8351 ;; Emacs package. We call the former org-type tables, and the latter
8352 ;; table.el-type tables.
8355 (defun org-before-change-function (beg end)
8356 "Every change indicates that a table might need an update."
8357 (setq org-table-may-need-update t))
8359 (defconst org-table-line-regexp "^[ \t]*|"
8360 "Detects an org-type table line.")
8361 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8362 "Detects an org-type table line.")
8363 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8364 "Detects a table line marked for automatic recalculation.")
8365 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8366 "Detects a table line marked for automatic recalculation.")
8367 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8368 "Detects a table line marked for automatic recalculation.")
8369 (defconst org-table-hline-regexp "^[ \t]*|-"
8370 "Detects an org-type table hline.")
8371 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8372 "Detects a table-type table hline.")
8373 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8374 "Detects an org-type or table-type table.")
8375 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8376 "Searching from within a table (any type) this finds the first line
8377 outside the table.")
8378 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8379 "Searching from within a table (any type) this finds the first line
8380 outside the table.")
8382 (defun org-table-create-with-table.el ()
8383 "Use the table.el package to insert a new table.
8384 If there is already a table at point, convert between Org-mode tables
8385 and table.el tables."
8386 (interactive)
8387 (require 'table)
8388 (cond
8389 ((org-at-table.el-p)
8390 (if (y-or-n-p "Convert table to Org-mode table? ")
8391 (org-table-convert)))
8392 ((org-at-table-p)
8393 (if (y-or-n-p "Convert table to table.el table? ")
8394 (org-table-convert)))
8395 (t (call-interactively 'table-insert))))
8397 (defun org-table-create-or-convert-from-region (arg)
8398 "Convert region to table, or create an empty table.
8399 If there is an active region, convert it to a table. If there is no such
8400 region, create an empty table."
8401 (interactive "P")
8402 (if (org-region-active-p)
8403 (org-table-convert-region (region-beginning) (region-end) arg)
8404 (org-table-create arg)))
8406 (defun org-table-create (&optional size)
8407 "Query for a size and insert a table skeleton.
8408 SIZE is a string Columns x Rows like for example \"3x2\"."
8409 (interactive "P")
8410 (unless size
8411 (setq size (read-string
8412 (concat "Table size Columns x Rows [e.g. "
8413 org-table-default-size "]: ")
8414 "" nil org-table-default-size)))
8416 (let* ((pos (point))
8417 (indent (make-string (current-column) ?\ ))
8418 (split (org-split-string size " *x *"))
8419 (rows (string-to-number (nth 1 split)))
8420 (columns (string-to-number (car split)))
8421 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8422 "\n")))
8423 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8424 (point-at-bol) (point)))
8425 (beginning-of-line 1)
8426 (newline))
8427 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8428 (dotimes (i rows) (insert line))
8429 (goto-char pos)
8430 (if (> rows 1)
8431 ;; Insert a hline after the first row.
8432 (progn
8433 (end-of-line 1)
8434 (insert "\n|-")
8435 (goto-char pos)))
8436 (org-table-align)))
8438 (defun org-table-convert-region (beg0 end0 &optional nspace)
8439 "Convert region to a table.
8440 The region goes from BEG0 to END0, but these borders will be moved
8441 slightly, to make sure a beginning of line in the first line is included.
8442 When NSPACE is non-nil, it indicates the minimum number of spaces that
8443 separate columns (default: just one space)."
8444 (interactive "rP")
8445 (let* ((beg (min beg0 end0))
8446 (end (max beg0 end0))
8447 (tabsep t)
8449 (goto-char beg)
8450 (beginning-of-line 1)
8451 (setq beg (move-marker (make-marker) (point)))
8452 (goto-char end)
8453 (if (bolp) (backward-char 1) (end-of-line 1))
8454 (setq end (move-marker (make-marker) (point)))
8455 ;; Lets see if this is tab-separated material. If every nonempty line
8456 ;; contains a tab, we will assume that it is tab-separated material
8457 (if nspace
8458 (setq tabsep nil)
8459 (goto-char beg)
8460 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
8461 (if nspace (setq tabsep nil))
8462 (if tabsep
8463 (setq re "^\\|\t")
8464 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
8465 (max 1 (prefix-numeric-value nspace)))))
8466 (goto-char beg)
8467 (while (re-search-forward re end t)
8468 (replace-match "|" t t))
8469 (goto-char beg)
8470 (insert " ")
8471 (org-table-align)))
8473 (defun org-table-import (file arg)
8474 "Import FILE as a table.
8475 The file is assumed to be tab-separated. Such files can be produced by most
8476 spreadsheet and database applications. If no tabs (at least one per line)
8477 are found, lines will be split on whitespace into fields."
8478 (interactive "f\nP")
8479 (or (bolp) (newline))
8480 (let ((beg (point))
8481 (pm (point-max)))
8482 (insert-file-contents file)
8483 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8485 (defun org-table-export ()
8486 "Export table as a tab-separated file.
8487 Such a file can be imported into a spreadsheet program like Excel."
8488 (interactive)
8489 (let* ((beg (org-table-begin))
8490 (end (org-table-end))
8491 (table (buffer-substring beg end))
8492 (file (read-file-name "Export table to: "))
8493 buf)
8494 (unless (or (not (file-exists-p file))
8495 (y-or-n-p (format "Overwrite file %s? " file)))
8496 (error "Abort"))
8497 (with-current-buffer (find-file-noselect file)
8498 (setq buf (current-buffer))
8499 (erase-buffer)
8500 (fundamental-mode)
8501 (insert table)
8502 (goto-char (point-min))
8503 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8504 (replace-match "" t t)
8505 (end-of-line 1))
8506 (goto-char (point-min))
8507 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8508 (replace-match "" t t)
8509 (goto-char (min (1+ (point)) (point-max))))
8510 (goto-char (point-min))
8511 (while (re-search-forward "^-[-+]*$" nil t)
8512 (replace-match "")
8513 (if (looking-at "\n")
8514 (delete-char 1)))
8515 (goto-char (point-min))
8516 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8517 (replace-match "\t" t t))
8518 (save-buffer))
8519 (kill-buffer buf)))
8521 (defvar org-table-aligned-begin-marker (make-marker)
8522 "Marker at the beginning of the table last aligned.
8523 Used to check if cursor still is in that table, to minimize realignment.")
8524 (defvar org-table-aligned-end-marker (make-marker)
8525 "Marker at the end of the table last aligned.
8526 Used to check if cursor still is in that table, to minimize realignment.")
8527 (defvar org-table-last-alignment nil
8528 "List of flags for flushright alignment, from the last re-alignment.
8529 This is being used to correctly align a single field after TAB or RET.")
8530 (defvar org-table-last-column-widths nil
8531 "List of max width of fields in each column.
8532 This is being used to correctly align a single field after TAB or RET.")
8534 (defvar org-last-recalc-line nil)
8535 (defconst org-narrow-column-arrow "=>"
8536 "Used as display property in narrowed table columns.")
8538 (defun org-table-align ()
8539 "Align the table at point by aligning all vertical bars."
8540 (interactive)
8541 (let* (
8542 ;; Limits of table
8543 (beg (org-table-begin))
8544 (end (org-table-end))
8545 ;; Current cursor position
8546 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8547 (colpos (org-table-current-column))
8548 (winstart (window-start))
8549 text lines (new "") lengths l typenums ty fields maxfields i
8550 column
8551 (indent "") cnt frac
8552 rfmt hfmt
8553 (spaces '(1 . 1))
8554 (sp1 (car spaces))
8555 (sp2 (cdr spaces))
8556 (rfmt1 (concat
8557 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8558 (hfmt1 (concat
8559 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8560 emptystrings xx links narrow fmax fmin f1 len c e)
8561 (untabify beg end)
8562 (remove-text-properties beg end '(org-cwidth t display t))
8563 ;; Check if we have links
8564 (goto-char beg)
8565 (setq links (re-search-forward org-bracket-link-regexp end t))
8566 ;; Make sure the link properties are right FIXME: Can this be optimized????
8567 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8568 ;; Check if we are narrowing any columns
8569 (goto-char beg)
8570 (setq narrow (and org-format-transports-properties-p
8571 (re-search-forward "<[0-9]+>" end t)))
8572 ;; Get the rows
8573 (setq lines (org-split-string
8574 (buffer-substring beg end) "\n"))
8575 ;; Store the indentation of the first line
8576 (if (string-match "^ *" (car lines))
8577 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8578 ;; Mark the hlines by setting the corresponding element to nil
8579 ;; At the same time, we remove trailing space.
8580 (setq lines (mapcar (lambda (l)
8581 (if (string-match "^ *|-" l)
8583 (if (string-match "[ \t]+$" l)
8584 (substring l 0 (match-beginning 0))
8585 l)))
8586 lines))
8587 ;; Get the data fields by splitting the lines.
8588 (setq fields (mapcar
8589 (lambda (l)
8590 (org-split-string l " *| *"))
8591 (delq nil (copy-sequence lines))))
8592 ;; How many fields in the longest line?
8593 (condition-case nil
8594 (setq maxfields (apply 'max (mapcar 'length fields)))
8595 (error
8596 (kill-region beg end)
8597 (org-table-create org-table-default-size)
8598 (error "Empty table - created default table")))
8599 ;; A list of empty string to fill any short rows on output
8600 (setq emptystrings (make-list maxfields ""))
8601 ;; Check for special formatting.
8602 (setq i -1)
8603 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8604 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8605 ;; Check if there is an explicit width specified
8606 (when (and org-table-limit-column-width narrow)
8607 (setq c column fmax nil)
8608 (while c
8609 (setq e (pop c))
8610 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8611 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8612 ;; Find fields that are wider than fmax, and shorten them
8613 (when fmax
8614 (loop for xx in column do
8615 (when (and (stringp xx)
8616 (> (org-string-width xx) fmax))
8617 (org-add-props xx nil
8618 'help-echo
8619 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (copy-sequence xx)))
8620 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8621 (unless (> f1 1)
8622 (error "Cannot narrow field starting with wide link \"%s\""
8623 (match-string 0 xx)))
8624 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8625 (add-text-properties (- f1 2) f1
8626 (list 'display org-narrow-column-arrow)
8627 xx)))))
8628 ;; Get the maximum width for each column
8629 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8630 ;; Get the fraction of numbers, to decide about alignment of the column
8631 (setq cnt 0 frac 0.0)
8632 (loop for x in column do
8633 (if (equal x "")
8635 (setq frac ( / (+ (* frac cnt)
8636 (if (string-match org-table-number-regexp x) 1 0))
8637 (setq cnt (1+ cnt))))))
8638 (push (>= frac org-table-number-fraction) typenums))
8639 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8641 ;; Store the alignment of this table, for later editing of single fields
8642 (setq org-table-last-alignment typenums
8643 org-table-last-column-widths lengths)
8645 ;; With invisible characters, `format' does not get the field width right
8646 ;; So we need to make these fields wide by hand.
8647 (when links
8648 (loop for i from 0 upto (1- maxfields) do
8649 (setq len (nth i lengths))
8650 (loop for j from 0 upto (1- (length fields)) do
8651 (setq c (nthcdr i (car (nthcdr j fields))))
8652 (if (and (stringp (car c))
8653 (string-match org-bracket-link-regexp (car c))
8654 (< (org-string-width (car c)) len))
8655 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8657 ;; Compute the formats needed for output of the table
8658 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8659 (while (setq l (pop lengths))
8660 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8661 (setq rfmt (concat rfmt (format rfmt1 ty l))
8662 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8663 (setq rfmt (concat rfmt "\n")
8664 hfmt (concat (substring hfmt 0 -1) "|\n"))
8666 (setq new (mapconcat
8667 (lambda (l)
8668 (if l (apply 'format rfmt
8669 (append (pop fields) emptystrings))
8670 hfmt))
8671 lines ""))
8672 ;; Replace the old one
8673 (delete-region beg end)
8674 (move-marker end nil)
8675 (move-marker org-table-aligned-begin-marker (point))
8676 (insert new)
8677 (move-marker org-table-aligned-end-marker (point))
8678 (when (and orgtbl-mode (not (eq major-mode 'org-mode)))
8679 (goto-char org-table-aligned-begin-marker)
8680 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8681 ;; Try to move to the old location (approximately)
8682 (goto-line linepos)
8683 (set-window-start (selected-window) winstart 'noforce)
8684 (org-table-goto-column colpos)
8685 (setq org-table-may-need-update nil)
8688 (defun org-string-width (s)
8689 "Compute width of string, ignoring invisible characters.
8690 This ignores character with invisibility property `org-link', and also
8691 characters with property `org-cwidth', because these will become invisible
8692 upon the next fontification round."
8693 (let (b)
8694 (when (or (eq t buffer-invisibility-spec)
8695 (assq 'org-link buffer-invisibility-spec))
8696 (while (setq b (text-property-any 0 (length s)
8697 'invisible 'org-link s))
8698 (setq s (concat (substring s 0 b)
8699 (substring s (or (next-single-property-change
8700 b 'invisible s) (length s)))))))
8701 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8702 (setq s (concat (substring s 0 b)
8703 (substring s (or (next-single-property-change
8704 b 'org-cwidth s) (length s))))))
8705 (string-width s)))
8707 (defun org-table-begin (&optional table-type)
8708 "Find the beginning of the table and return its position.
8709 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8710 (save-excursion
8711 (if (not (re-search-backward
8712 (if table-type org-table-any-border-regexp
8713 org-table-border-regexp)
8714 nil t))
8715 (error "Can't find beginning of table")
8716 (goto-char (match-beginning 0))
8717 (beginning-of-line 2)
8718 (point))))
8720 (defun org-table-end (&optional table-type)
8721 "Find the end of the table and return its position.
8722 With argument TABLE-TYPE, go to the end of a table.el-type table."
8723 (save-excursion
8724 (if (not (re-search-forward
8725 (if table-type org-table-any-border-regexp
8726 org-table-border-regexp)
8727 nil t))
8728 (goto-char (point-max))
8729 (goto-char (match-beginning 0)))
8730 (point-marker)))
8732 (defun org-table-justify-field-maybe (&optional new)
8733 "Justify the current field, text to left, number to right.
8734 Optional argument NEW may specify text to replace the current field content."
8735 (cond
8736 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8737 ((org-at-table-hline-p))
8738 ((and (not new)
8739 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8740 (current-buffer)))
8741 (< (point) org-table-aligned-begin-marker)
8742 (>= (point) org-table-aligned-end-marker)))
8743 ;; This is not the same table, force a full re-align
8744 (setq org-table-may-need-update t))
8745 (t ;; realign the current field, based on previous full realign
8746 (let* ((pos (point)) s
8747 (col (org-table-current-column))
8748 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8749 l f n o e)
8750 (when (> col 0)
8751 (skip-chars-backward "^|\n")
8752 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8753 (progn
8754 (setq s (match-string 1)
8755 o (match-string 0)
8756 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8757 e (not (= (match-beginning 2) (match-end 2))))
8758 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8759 l (if e "|" (setq org-table-may-need-update t) ""))
8760 n (format f s t t))
8761 (if new
8762 (if (<= (length new) l)
8763 (setq n (format f new t t)) ;; FIXME: why t t?????
8764 (setq n (concat new "|") org-table-may-need-update t)))
8765 (or (equal n o)
8766 (let (org-table-may-need-update)
8767 (replace-match n))))
8768 (setq org-table-may-need-update t))
8769 (goto-char pos))))))
8771 (defun org-table-next-field ()
8772 "Go to the next field in the current table, creating new lines as needed.
8773 Before doing so, re-align the table if necessary."
8774 (interactive)
8775 (org-table-maybe-eval-formula)
8776 (org-table-maybe-recalculate-line)
8777 (if (and org-table-automatic-realign
8778 org-table-may-need-update)
8779 (org-table-align))
8780 (let ((end (org-table-end)))
8781 (if (org-at-table-hline-p)
8782 (end-of-line 1))
8783 (condition-case nil
8784 (progn
8785 (re-search-forward "|" end)
8786 (if (looking-at "[ \t]*$")
8787 (re-search-forward "|" end))
8788 (if (and (looking-at "-")
8789 org-table-tab-jumps-over-hlines
8790 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8791 (goto-char (match-beginning 1)))
8792 (if (looking-at "-")
8793 (progn
8794 (beginning-of-line 0)
8795 (org-table-insert-row 'below))
8796 (if (looking-at " ") (forward-char 1))))
8797 (error
8798 (org-table-insert-row 'below)))))
8800 (defun org-table-previous-field ()
8801 "Go to the previous field in the table.
8802 Before doing so, re-align the table if necessary."
8803 (interactive)
8804 (org-table-justify-field-maybe)
8805 (org-table-maybe-recalculate-line)
8806 (if (and org-table-automatic-realign
8807 org-table-may-need-update)
8808 (org-table-align))
8809 (if (org-at-table-hline-p)
8810 (end-of-line 1))
8811 (re-search-backward "|" (org-table-begin))
8812 (re-search-backward "|" (org-table-begin))
8813 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8814 (re-search-backward "|" (org-table-begin)))
8815 (if (looking-at "| ?")
8816 (goto-char (match-end 0))))
8818 (defun org-table-next-row ()
8819 "Go to the next row (same column) in the current table.
8820 Before doing so, re-align the table if necessary."
8821 (interactive)
8822 (org-table-maybe-eval-formula)
8823 (org-table-maybe-recalculate-line)
8824 (if (or (looking-at "[ \t]*$")
8825 (save-excursion (skip-chars-backward " \t") (bolp)))
8826 (newline)
8827 (if (and org-table-automatic-realign
8828 org-table-may-need-update)
8829 (org-table-align))
8830 (let ((col (org-table-current-column)))
8831 (beginning-of-line 2)
8832 (if (or (not (org-at-table-p))
8833 (org-at-table-hline-p))
8834 (progn
8835 (beginning-of-line 0)
8836 (org-table-insert-row 'below)))
8837 (org-table-goto-column col)
8838 (skip-chars-backward "^|\n\r")
8839 (if (looking-at " ") (forward-char 1)))))
8841 (defun org-table-copy-down (n)
8842 "Copy a field down in the current column.
8843 If the field at the cursor is empty, copy into it the content of the nearest
8844 non-empty field above. With argument N, use the Nth non-empty field.
8845 If the current field is not empty, it is copied down to the next row, and
8846 the cursor is moved with it. Therefore, repeating this command causes the
8847 column to be filled row-by-row.
8848 If the variable `org-table-copy-increment' is non-nil and the field is an
8849 integer, it will be incremented while copying."
8850 (interactive "p")
8851 (let* ((colpos (org-table-current-column))
8852 (field (org-table-get-field))
8853 (non-empty (string-match "[^ \t]" field))
8854 (beg (org-table-begin))
8855 txt)
8856 (org-table-check-inside-data-field)
8857 (if non-empty
8858 (progn
8859 (setq txt (org-trim field))
8860 (org-table-next-row)
8861 (org-table-blank-field))
8862 (save-excursion
8863 (setq txt
8864 (catch 'exit
8865 (while (progn (beginning-of-line 1)
8866 (re-search-backward org-table-dataline-regexp
8867 beg t))
8868 (org-table-goto-column colpos t)
8869 (if (and (looking-at
8870 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8871 (= (setq n (1- n)) 0))
8872 (throw 'exit (match-string 1))))))))
8873 (if txt
8874 (progn
8875 (if (and org-table-copy-increment
8876 (string-match "^[0-9]+$" txt))
8877 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8878 (insert txt)
8879 (org-table-maybe-recalculate-line)
8880 (org-table-align))
8881 (error "No non-empty field found"))))
8883 (defun org-table-check-inside-data-field ()
8884 "Is point inside a table data field?
8885 I.e. not on a hline or before the first or after the last column?
8886 This actually throws an error, so it aborts the current command."
8887 (if (or (not (org-at-table-p))
8888 (= (org-table-current-column) 0)
8889 (org-at-table-hline-p)
8890 (looking-at "[ \t]*$"))
8891 (error "Not in table data field")))
8893 (defvar org-table-clip nil
8894 "Clipboard for table regions.")
8896 (defun org-table-blank-field ()
8897 "Blank the current table field or active region."
8898 (interactive)
8899 (org-table-check-inside-data-field)
8900 (if (and (interactive-p) (org-region-active-p))
8901 (let (org-table-clip)
8902 (org-table-cut-region (region-beginning) (region-end)))
8903 (skip-chars-backward "^|")
8904 (backward-char 1)
8905 (if (looking-at "|[^|\n]+")
8906 (let* ((pos (match-beginning 0))
8907 (match (match-string 0))
8908 (len (org-string-width match)))
8909 (replace-match (concat "|" (make-string (1- len) ?\ )))
8910 (goto-char (+ 2 pos))
8911 (substring match 1)))))
8913 (defun org-table-get-field (&optional n replace)
8914 "Return the value of the field in column N of current row.
8915 N defaults to current field.
8916 If REPLACE is a string, replace field with this value. The return value
8917 is always the old value."
8918 (and n (org-table-goto-column n))
8919 (skip-chars-backward "^|\n")
8920 (backward-char 1)
8921 (if (looking-at "|[^|\r\n]*")
8922 (let* ((pos (match-beginning 0))
8923 (val (buffer-substring (1+ pos) (match-end 0))))
8924 (if replace
8925 (replace-match (concat "|" replace)))
8926 (goto-char (min (point-at-eol) (+ 2 pos)))
8927 val)
8928 (forward-char 1) ""))
8930 (defun org-table-current-column ()
8931 "Find out which column we are in.
8932 When called interactively, column is also displayed in echo area."
8933 (interactive)
8934 (if (interactive-p) (org-table-check-inside-data-field))
8935 (save-excursion
8936 (let ((cnt 0) (pos (point)))
8937 (beginning-of-line 1)
8938 (while (search-forward "|" pos t)
8939 (setq cnt (1+ cnt)))
8940 (if (interactive-p) (message "This is table column %d" cnt))
8941 cnt)))
8943 (defun org-table-goto-column (n &optional on-delim force)
8944 "Move the cursor to the Nth column in the current table line.
8945 With optional argument ON-DELIM, stop with point before the left delimiter
8946 of the field.
8947 If there are less than N fields, just go to after the last delimiter.
8948 However, when FORCE is non-nil, create new columns if necessary."
8949 (interactive "p")
8950 (let ((pos (point-at-eol)))
8951 (beginning-of-line 1)
8952 (when (> n 0)
8953 (while (and (> (setq n (1- n)) -1)
8954 (or (search-forward "|" pos t)
8955 (and force
8956 (progn (end-of-line 1)
8957 (skip-chars-backward "^|")
8958 (insert " | "))))))
8959 ; (backward-char 2) t)))))
8960 (when (and force (not (looking-at ".*|")))
8961 (save-excursion (end-of-line 1) (insert " | ")))
8962 (if on-delim
8963 (backward-char 1)
8964 (if (looking-at " ") (forward-char 1))))))
8966 (defun org-at-table-p (&optional table-type)
8967 "Return t if the cursor is inside an org-type table.
8968 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8969 (if org-enable-table-editor
8970 (save-excursion
8971 (beginning-of-line 1)
8972 (looking-at (if table-type org-table-any-line-regexp
8973 org-table-line-regexp)))
8974 nil))
8976 (defun org-at-table.el-p ()
8977 "Return t if and only if we are at a table.el table."
8978 (and (org-at-table-p 'any)
8979 (save-excursion
8980 (goto-char (org-table-begin 'any))
8981 (looking-at org-table1-hline-regexp))))
8983 (defun org-table-recognize-table.el ()
8984 "If there is a table.el table nearby, recognize it and move into it."
8985 (if org-table-tab-recognizes-table.el
8986 (if (org-at-table.el-p)
8987 (progn
8988 (beginning-of-line 1)
8989 (if (looking-at org-table-dataline-regexp)
8991 (if (looking-at org-table1-hline-regexp)
8992 (progn
8993 (beginning-of-line 2)
8994 (if (looking-at org-table-any-border-regexp)
8995 (beginning-of-line -1)))))
8996 (if (re-search-forward "|" (org-table-end t) t)
8997 (progn
8998 (require 'table)
8999 (if (table--at-cell-p (point))
9001 (message "recognizing table.el table...")
9002 (table-recognize-table)
9003 (message "recognizing table.el table...done")))
9004 (error "This should not happen..."))
9006 nil)
9007 nil))
9009 (defun org-at-table-hline-p ()
9010 "Return t if the cursor is inside a hline in a table."
9011 (if org-enable-table-editor
9012 (save-excursion
9013 (beginning-of-line 1)
9014 (looking-at org-table-hline-regexp))
9015 nil))
9017 (defun org-table-insert-column ()
9018 "Insert a new column into the table."
9019 (interactive)
9020 (if (not (org-at-table-p))
9021 (error "Not at a table"))
9022 (org-table-find-dataline)
9023 (let* ((col (max 1 (org-table-current-column)))
9024 (beg (org-table-begin))
9025 (end (org-table-end))
9026 ;; Current cursor position
9027 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9028 (colpos col))
9029 (goto-char beg)
9030 (while (< (point) end)
9031 (if (org-at-table-hline-p)
9033 (org-table-goto-column col t)
9034 (insert "| "))
9035 (beginning-of-line 2))
9036 (move-marker end nil)
9037 (goto-line linepos)
9038 (org-table-goto-column colpos)
9039 (org-table-align)
9040 (org-table-modify-formulas 'insert col)))
9042 (defun org-table-find-dataline ()
9043 "Find a dataline in the current table, which is needed for column commands."
9044 (if (and (org-at-table-p)
9045 (not (org-at-table-hline-p)))
9047 (let ((col (current-column))
9048 (end (org-table-end)))
9049 (move-to-column col)
9050 (while (and (< (point) end)
9051 (or (not (= (current-column) col))
9052 (org-at-table-hline-p)))
9053 (beginning-of-line 2)
9054 (move-to-column col))
9055 (if (and (org-at-table-p)
9056 (not (org-at-table-hline-p)))
9058 (error
9059 "Please position cursor in a data line for column operations")))))
9061 (defun org-table-delete-column ()
9062 "Delete a column into the table."
9063 (interactive)
9064 (if (not (org-at-table-p))
9065 (error "Not at a table"))
9066 (org-table-find-dataline)
9067 (org-table-check-inside-data-field)
9068 (let* ((col (org-table-current-column))
9069 (beg (org-table-begin))
9070 (end (org-table-end))
9071 ;; Current cursor position
9072 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9073 (colpos col))
9074 (goto-char beg)
9075 (while (< (point) end)
9076 (if (org-at-table-hline-p)
9078 (org-table-goto-column col t)
9079 (and (looking-at "|[^|\n]+|")
9080 (replace-match "|")))
9081 (beginning-of-line 2))
9082 (move-marker end nil)
9083 (goto-line linepos)
9084 (org-table-goto-column colpos)
9085 (org-table-align)
9086 (org-table-modify-formulas 'remove col)))
9088 (defun org-table-move-column-right ()
9089 "Move column to the right."
9090 (interactive)
9091 (org-table-move-column nil))
9092 (defun org-table-move-column-left ()
9093 "Move column to the left."
9094 (interactive)
9095 (org-table-move-column 'left))
9097 (defun org-table-move-column (&optional left)
9098 "Move the current column to the right. With arg LEFT, move to the left."
9099 (interactive "P")
9100 (if (not (org-at-table-p))
9101 (error "Not at a table"))
9102 (org-table-find-dataline)
9103 (org-table-check-inside-data-field)
9104 (let* ((col (org-table-current-column))
9105 (col1 (if left (1- col) col))
9106 (beg (org-table-begin))
9107 (end (org-table-end))
9108 ;; Current cursor position
9109 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9110 (colpos (if left (1- col) (1+ col))))
9111 (if (and left (= col 1))
9112 (error "Cannot move column further left"))
9113 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9114 (error "Cannot move column further right"))
9115 (goto-char beg)
9116 (while (< (point) end)
9117 (if (org-at-table-hline-p)
9119 (org-table-goto-column col1 t)
9120 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9121 (replace-match "|\\2|\\1|")))
9122 (beginning-of-line 2))
9123 (move-marker end nil)
9124 (goto-line linepos)
9125 (org-table-goto-column colpos)
9126 (org-table-align)
9127 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
9129 (defun org-table-move-row-down ()
9130 "Move table row down."
9131 (interactive)
9132 (org-table-move-row nil))
9133 (defun org-table-move-row-up ()
9134 "Move table row up."
9135 (interactive)
9136 (org-table-move-row 'up))
9138 (defun org-table-move-row (&optional up)
9139 "Move the current table line down. With arg UP, move it up."
9140 (interactive "P")
9141 (let ((col (current-column))
9142 (pos (point))
9143 (tonew (if up 0 2))
9144 txt)
9145 (beginning-of-line tonew)
9146 (if (not (org-at-table-p))
9147 (progn
9148 (goto-char pos)
9149 (error "Cannot move row further")))
9150 (goto-char pos)
9151 (beginning-of-line 1)
9152 (setq pos (point))
9153 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9154 (delete-region (point) (1+ (point-at-eol)))
9155 (beginning-of-line tonew)
9156 (insert txt)
9157 (beginning-of-line 0)
9158 (move-to-column col)))
9160 (defun org-table-insert-row (&optional arg)
9161 "Insert a new row above the current line into the table.
9162 With prefix ARG, insert below the current line."
9163 (interactive "P")
9164 (if (not (org-at-table-p))
9165 (error "Not at a table"))
9166 (let* ((line
9167 (org-expand-wide-chars
9168 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
9169 new)
9170 (if (string-match "^[ \t]*|-" line)
9171 (setq new (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) line))
9172 (setq new (mapcar (lambda (x) (if (equal x ?|) ?| ?\ )) line)))
9173 ;; Fix the first field if necessary
9174 (setq new (concat new))
9175 (if (string-match "^[ \t]*| *[#$] *|" line)
9176 (setq new (replace-match (match-string 0 line) t t new)))
9177 (beginning-of-line (if arg 2 1))
9178 (let (org-table-may-need-update)
9179 (insert-before-markers new)
9180 (insert-before-markers "\n"))
9181 (beginning-of-line 0)
9182 (re-search-forward "| ?" (point-at-eol) t)
9183 (and org-table-may-need-update (org-table-align))))
9185 (defun org-table-insert-hline (&optional arg)
9186 "Insert a horizontal-line below the current line into the table.
9187 With prefix ARG, insert above the current line."
9188 (interactive "P")
9189 (if (not (org-at-table-p))
9190 (error "Not at a table"))
9191 (let ((line
9192 (org-expand-wide-chars
9193 (buffer-substring-no-properties (point-at-bol) (point-at-eol))))
9194 (col (current-column))
9195 start)
9196 (if (string-match "^[ \t]*|-" line)
9197 (setq line
9198 (mapcar (lambda (x) (if (member x '(?| ?+))
9199 (prog1 (if start ?+ ?|) (setq start t))
9200 (if start ?- ?\ )))
9201 line))
9202 (setq line
9203 (mapcar (lambda (x) (if (equal x ?|)
9204 (prog1 (if start ?+ ?|) (setq start t))
9205 (if start ?- ?\ )))
9206 line)))
9207 (beginning-of-line (if arg 1 2))
9208 (apply 'insert line)
9209 (if (equal (char-before (point)) ?+)
9210 (progn (backward-delete-char 1) (insert "|")))
9211 (insert "\n")
9212 (beginning-of-line (if arg 1 -1))
9213 (move-to-column col)))
9215 (defun org-expand-wide-chars (s)
9216 "Expand wide characters to spaces."
9217 (let (w a)
9218 (mapconcat
9219 (lambda (x)
9220 (if (> (setq w (string-width (setq a (char-to-string x)))) 1)
9221 (make-string w ?\ )
9223 s "")))
9225 (defun org-table-kill-row ()
9226 "Delete the current row or horizontal line from the table."
9227 (interactive)
9228 (if (not (org-at-table-p))
9229 (error "Not at a table"))
9230 (let ((col (current-column)))
9231 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9232 (if (not (org-at-table-p)) (beginning-of-line 0))
9233 (move-to-column col)))
9235 (defun org-table-sort-lines (beg end numericp)
9236 "Sort table lines in region.
9237 Point and mark define the first and last line to include. Both point and
9238 mark should be in the column that is used for sorting. For example, to
9239 sort according to column 3, put the mark in the first line to sort, in
9240 table column 3. Put point into the last line to be included in the sorting,
9241 also in table column 3. The command will prompt for the sorting method
9242 \(n for numerical, a for alphanumeric)."
9243 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
9244 (setq numericp (string-match "[nN]" numericp))
9245 (org-table-align) ;; Just to be safe
9246 (let* (bcol ecol cmp column lns)
9247 (goto-char beg)
9248 (org-table-check-inside-data-field)
9249 (setq column (org-table-current-column)
9250 beg (move-marker (make-marker) (point-at-bol)))
9251 (goto-char end)
9252 (org-table-check-inside-data-field)
9253 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
9254 (untabify beg end)
9255 (goto-char beg)
9256 (org-table-goto-column column)
9257 (skip-chars-backward "^|")
9258 (setq bcol (current-column))
9259 (org-table-goto-column (1+ column))
9260 (skip-chars-backward "^|")
9261 (setq ecol (1- (current-column)))
9262 (setq cmp (if numericp
9263 (lambda (a b) (< (car a) (car b)))
9264 (lambda (a b) (string< (car a) (car b)))))
9265 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
9266 (split-string (buffer-substring beg end) "\n")))
9267 (if numericp
9268 (setq lns (mapcar (lambda(x)
9269 (cons (string-to-number (car x)) (cdr x)))
9270 lns)))
9271 (delete-region beg end)
9272 (move-marker beg nil)
9273 (move-marker end nil)
9274 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
9275 (message "%d lines sorted %s based on column %d"
9276 (length lns)
9277 (if numericp "numerically" "alphabetically") column)))
9279 (defun org-table-cut-region (beg end)
9280 "Copy region in table to the clipboard and blank all relevant fields."
9281 (interactive "r")
9282 (org-table-copy-region beg end 'cut))
9284 (defun org-table-copy-region (beg end &optional cut)
9285 "Copy rectangular region in table to clipboard.
9286 A special clipboard is used which can only be accessed
9287 with `org-table-paste-rectangle'."
9288 (interactive "rP")
9289 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9290 region cols
9291 (rpl (if cut " " nil)))
9292 (goto-char beg)
9293 (org-table-check-inside-data-field)
9294 (setq l01 (count-lines (point-min) (point))
9295 c01 (org-table-current-column))
9296 (goto-char end)
9297 (org-table-check-inside-data-field)
9298 (setq l02 (count-lines (point-min) (point))
9299 c02 (org-table-current-column))
9300 (setq l1 (min l01 l02) l2 (max l01 l02)
9301 c1 (min c01 c02) c2 (max c01 c02))
9302 (catch 'exit
9303 (while t
9304 (catch 'nextline
9305 (if (> l1 l2) (throw 'exit t))
9306 (goto-line l1)
9307 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9308 (setq cols nil ic1 c1 ic2 c2)
9309 (while (< ic1 (1+ ic2))
9310 (push (org-table-get-field ic1 rpl) cols)
9311 (setq ic1 (1+ ic1)))
9312 (push (nreverse cols) region)
9313 (setq l1 (1+ l1)))))
9314 (setq org-table-clip (nreverse region))
9315 (if cut (org-table-align))
9316 org-table-clip))
9318 (defun org-table-paste-rectangle ()
9319 "Paste a rectangular region into a table.
9320 The upper right corner ends up in the current field. All involved fields
9321 will be overwritten. If the rectangle does not fit into the present table,
9322 the table is enlarged as needed. The process ignores horizontal separator
9323 lines."
9324 (interactive)
9325 (unless (and org-table-clip (listp org-table-clip))
9326 (error "First cut/copy a region to paste!"))
9327 (org-table-check-inside-data-field)
9328 (let* ((clip org-table-clip)
9329 (line (count-lines (point-min) (point)))
9330 (col (org-table-current-column))
9331 (org-enable-table-editor t)
9332 (org-table-automatic-realign nil)
9333 c cols field)
9334 (while (setq cols (pop clip))
9335 (while (org-at-table-hline-p) (beginning-of-line 2))
9336 (if (not (org-at-table-p))
9337 (progn (end-of-line 0) (org-table-next-field)))
9338 (setq c col)
9339 (while (setq field (pop cols))
9340 (org-table-goto-column c nil 'force)
9341 (org-table-get-field nil field)
9342 (setq c (1+ c)))
9343 (beginning-of-line 2))
9344 (goto-line line)
9345 (org-table-goto-column col)
9346 (org-table-align)))
9348 (defun org-table-convert ()
9349 "Convert from `org-mode' table to table.el and back.
9350 Obviously, this only works within limits. When an Org-mode table is
9351 converted to table.el, all horizontal separator lines get lost, because
9352 table.el uses these as cell boundaries and has no notion of horizontal lines.
9353 A table.el table can be converted to an Org-mode table only if it does not
9354 do row or column spanning. Multiline cells will become multiple cells.
9355 Beware, Org-mode does not test if the table can be successfully converted - it
9356 blindly applies a recipe that works for simple tables."
9357 (interactive)
9358 (require 'table)
9359 (if (org-at-table.el-p)
9360 ;; convert to Org-mode table
9361 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9362 (end (move-marker (make-marker) (org-table-end t))))
9363 (table-unrecognize-region beg end)
9364 (goto-char beg)
9365 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9366 (replace-match ""))
9367 (goto-char beg))
9368 (if (org-at-table-p)
9369 ;; convert to table.el table
9370 (let ((beg (move-marker (make-marker) (org-table-begin)))
9371 (end (move-marker (make-marker) (org-table-end))))
9372 ;; first, get rid of all horizontal lines
9373 (goto-char beg)
9374 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9375 (replace-match ""))
9376 ;; insert a hline before first
9377 (goto-char beg)
9378 (org-table-insert-hline 'above)
9379 (beginning-of-line -1)
9380 ;; insert a hline after each line
9381 (while (progn (beginning-of-line 3) (< (point) end))
9382 (org-table-insert-hline))
9383 (goto-char beg)
9384 (setq end (move-marker end (org-table-end)))
9385 ;; replace "+" at beginning and ending of hlines
9386 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9387 (replace-match "\\1+-"))
9388 (goto-char beg)
9389 (while (re-search-forward "-|[ \t]*$" end t)
9390 (replace-match "-+"))
9391 (goto-char beg)))))
9393 (defun org-table-wrap-region (arg)
9394 "Wrap several fields in a column like a paragraph.
9395 This is useful if you'd like to spread the contents of a field over several
9396 lines, in order to keep the table compact.
9398 If there is an active region, and both point and mark are in the same column,
9399 the text in the column is wrapped to minimum width for the given number of
9400 lines. Generally, this makes the table more compact. A prefix ARG may be
9401 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9402 formats the selected text to two lines. If the region was longer than two
9403 lines, the remaining lines remain empty. A negative prefix argument reduces
9404 the current number of lines by that amount. The wrapped text is pasted back
9405 into the table. If you formatted it to more lines than it was before, fields
9406 further down in the table get overwritten - so you might need to make space in
9407 the table first.
9409 If there is no region, the current field is split at the cursor position and
9410 the text fragment to the right of the cursor is prepended to the field one
9411 line down.
9413 If there is no region, but you specify a prefix ARG, the current field gets
9414 blank, and the content is appended to the field above."
9415 (interactive "P")
9416 (org-table-check-inside-data-field)
9417 (if (org-region-active-p)
9418 ;; There is a region: fill as a paragraph
9419 (let ((beg (region-beginning))
9420 nlines)
9421 (org-table-cut-region (region-beginning) (region-end))
9422 (if (> (length (car org-table-clip)) 1)
9423 (error "Region must be limited to single column"))
9424 (setq nlines (if arg
9425 (if (< arg 1)
9426 (+ (length org-table-clip) arg)
9427 arg)
9428 (length org-table-clip)))
9429 (setq org-table-clip
9430 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9431 nil nlines)))
9432 (goto-char beg)
9433 (org-table-paste-rectangle))
9434 ;; No region, split the current field at point
9435 (if arg
9436 ;; combine with field above
9437 (let ((s (org-table-blank-field))
9438 (col (org-table-current-column)))
9439 (beginning-of-line 0)
9440 (while (org-at-table-hline-p) (beginning-of-line 0))
9441 (org-table-goto-column col)
9442 (skip-chars-forward "^|")
9443 (skip-chars-backward " ")
9444 (insert " " (org-trim s))
9445 (org-table-align))
9446 ;; split field
9447 (when (looking-at "\\([^|]+\\)+|")
9448 (let ((s (match-string 1)))
9449 (replace-match " |")
9450 (goto-char (match-beginning 0))
9451 (org-table-next-row)
9452 (insert (org-trim s) " ")
9453 (org-table-align))))))
9455 (defvar org-field-marker nil)
9457 (defun org-table-edit-field (arg)
9458 "Edit table field in a different window.
9459 This is mainly useful for fields that contain hidden parts.
9460 When called with a \\[universal-argument] prefix, just make the full field visible so that
9461 it can be edited in place."
9462 (interactive "P")
9463 (if arg
9464 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9465 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9466 (remove-text-properties b e '(org-cwidth t invisible t
9467 display t intangible t))
9468 (if (and (boundp 'font-lock-mode) font-lock-mode)
9469 (font-lock-fontify-block)))
9470 (let ((pos (move-marker (make-marker) (point)))
9471 (field (org-table-get-field))
9472 (cw (current-window-configuration))
9474 (switch-to-buffer-other-window "*Org tmp*")
9475 (erase-buffer)
9476 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9477 (org-mode)
9478 (goto-char (setq p (point-max)))
9479 (insert (org-trim field))
9480 (remove-text-properties p (point-max)
9481 '(invisible t org-cwidth t display t
9482 intangible t))
9483 (goto-char p)
9484 (set (make-local-variable 'org-finish-function)
9485 'org-table-finish-edit-field)
9486 (set (make-local-variable 'org-window-configuration) cw)
9487 (set (make-local-variable 'org-field-marker) pos)
9488 (message "Edit and finish with C-c C-c"))))
9490 (defun org-table-finish-edit-field ()
9491 "Finish editing a table data field.
9492 Remove all newline characters, insert the result into the table, realign
9493 the table and kill the editing buffer."
9494 (let ((pos org-field-marker)
9495 (cw org-window-configuration)
9496 (cb (current-buffer))
9497 text)
9498 (goto-char (point-min))
9499 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9500 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9501 (replace-match " "))
9502 (setq text (org-trim (buffer-string)))
9503 (set-window-configuration cw)
9504 (kill-buffer cb)
9505 (select-window (get-buffer-window (marker-buffer pos)))
9506 (goto-char pos)
9507 (move-marker pos nil)
9508 (org-table-check-inside-data-field)
9509 (org-table-get-field nil text)
9510 (org-table-align)
9511 (message "New field value inserted")))
9513 (defun org-trim (s)
9514 "Remove whitespace at beginning and end of string."
9515 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
9516 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
9519 (defun org-wrap (string &optional width lines)
9520 "Wrap string to either a number of lines, or a width in characters.
9521 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9522 that costs. If there is a word longer than WIDTH, the text is actually
9523 wrapped to the length of that word.
9524 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9525 many lines, whatever width that takes.
9526 The return value is a list of lines, without newlines at the end."
9527 (let* ((words (org-split-string string "[ \t\n]+"))
9528 (maxword (apply 'max (mapcar 'org-string-width words)))
9529 w ll)
9530 (cond (width
9531 (org-do-wrap words (max maxword width)))
9532 (lines
9533 (setq w maxword)
9534 (setq ll (org-do-wrap words maxword))
9535 (if (<= (length ll) lines)
9537 (setq ll words)
9538 (while (> (length ll) lines)
9539 (setq w (1+ w))
9540 (setq ll (org-do-wrap words w)))
9541 ll))
9542 (t (error "Cannot wrap this")))))
9545 (defun org-do-wrap (words width)
9546 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9547 (let (lines line)
9548 (while words
9549 (setq line (pop words))
9550 (while (and words (< (+ (length line) (length (car words))) width))
9551 (setq line (concat line " " (pop words))))
9552 (setq lines (push line lines)))
9553 (nreverse lines)))
9555 (defun org-split-string (string &optional separators)
9556 "Splits STRING into substrings at SEPARATORS.
9557 No empty strings are returned if there are matches at the beginning
9558 and end of string."
9559 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9560 (start 0)
9561 notfirst
9562 (list nil))
9563 (while (and (string-match rexp string
9564 (if (and notfirst
9565 (= start (match-beginning 0))
9566 (< start (length string)))
9567 (1+ start) start))
9568 (< (match-beginning 0) (length string)))
9569 (setq notfirst t)
9570 (or (eq (match-beginning 0) 0)
9571 (and (eq (match-beginning 0) (match-end 0))
9572 (eq (match-beginning 0) start))
9573 (setq list
9574 (cons (substring string start (match-beginning 0))
9575 list)))
9576 (setq start (match-end 0)))
9577 (or (eq start (length string))
9578 (setq list
9579 (cons (substring string start)
9580 list)))
9581 (nreverse list)))
9583 (defun org-table-map-tables (function)
9584 "Apply FUNCTION to the start of all tables in the buffer."
9585 (save-excursion
9586 (save-restriction
9587 (widen)
9588 (goto-char (point-min))
9589 (while (re-search-forward org-table-any-line-regexp nil t)
9590 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9591 (beginning-of-line 1)
9592 (if (looking-at org-table-line-regexp)
9593 (save-excursion (funcall function)))
9594 (re-search-forward org-table-any-border-regexp nil 1))))
9595 (message "Mapping tables: done"))
9597 (defun org-table-sum (&optional beg end nlast)
9598 "Sum numbers in region of current table column.
9599 The result will be displayed in the echo area, and will be available
9600 as kill to be inserted with \\[yank].
9602 If there is an active region, it is interpreted as a rectangle and all
9603 numbers in that rectangle will be summed. If there is no active
9604 region and point is located in a table column, sum all numbers in that
9605 column.
9607 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9608 numbers are assumed to be times as well (in decimal hours) and the
9609 numbers are added as such.
9611 If NLAST is a number, only the NLAST fields will actually be summed."
9612 (interactive)
9613 (save-excursion
9614 (let (col (timecnt 0) diff h m s org-table-clip)
9615 (cond
9616 ((and beg end)) ; beg and end given explicitly
9617 ((org-region-active-p)
9618 (setq beg (region-beginning) end (region-end)))
9620 (setq col (org-table-current-column))
9621 (goto-char (org-table-begin))
9622 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9623 (error "No table data"))
9624 (org-table-goto-column col)
9625 ;not needed? (skip-chars-backward "^|")
9626 (setq beg (point))
9627 (goto-char (org-table-end))
9628 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9629 (error "No table data"))
9630 (org-table-goto-column col)
9631 ;not needed? (skip-chars-forward "^|")
9632 (setq end (point))))
9633 (let* ((items (apply 'append (org-table-copy-region beg end)))
9634 (items1 (cond ((not nlast) items)
9635 ((>= nlast (length items)) items)
9636 (t (setq items (reverse items))
9637 (setcdr (nthcdr (1- nlast) items) nil)
9638 (nreverse items))))
9639 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9640 items1)))
9641 (res (apply '+ numbers))
9642 (sres (if (= timecnt 0)
9643 (format "%g" res)
9644 (setq diff (* 3600 res)
9645 h (floor (/ diff 3600)) diff (mod diff 3600)
9646 m (floor (/ diff 60)) diff (mod diff 60)
9647 s diff)
9648 (format "%d:%02d:%02d" h m s))))
9649 (kill-new sres)
9650 (if (interactive-p)
9651 (message "%s"
9652 (substitute-command-keys
9653 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9654 (length numbers) sres))))
9655 sres))))
9657 (defun org-table-get-number-for-summing (s)
9658 (let (n)
9659 (if (string-match "^ *|? *" s)
9660 (setq s (replace-match "" nil nil s)))
9661 (if (string-match " *|? *$" s)
9662 (setq s (replace-match "" nil nil s)))
9663 (setq n (string-to-number s))
9664 (cond
9665 ((and (string-match "0" s)
9666 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9667 ((string-match "\\`[ \t]+\\'" s) nil)
9668 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9669 (let ((h (string-to-number (or (match-string 1 s) "0")))
9670 (m (string-to-number (or (match-string 2 s) "0")))
9671 (s (string-to-number (or (match-string 4 s) "0"))))
9672 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9673 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9674 ((equal n 0) nil)
9675 (t n))))
9677 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9678 "Get a calc vector from a column, accorting to descriptor DESC.
9679 Optional arguments TBEG and COL can give the beginning of the table and
9680 the current column, to avoid unnecessary parsing."
9681 (save-excursion
9682 (or tbeg (setq tbeg (org-table-begin)))
9683 (or col (setq col (org-table-current-column)))
9684 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9685 (cond
9686 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9687 (setq n1 (- (match-end 1) (match-beginning 1)))
9688 (if (match-beginning 3)
9689 (setq n2 (- (match-end 2) (match-beginning 3))))
9690 (setq n (if n2 (max n1 n2) n1))
9691 (setq n1 (if n2 (min n1 n2)))
9692 (setq nn n)
9693 (while (and (> nn 0)
9694 (re-search-backward org-table-hline-regexp tbeg t))
9695 (push (org-current-line) hline-list)
9696 (setq nn (1- nn)))
9697 (setq hline-list (nreverse hline-list))
9698 (goto-line (nth (1- n) hline-list))
9699 (when (re-search-forward org-table-dataline-regexp)
9700 (org-table-goto-column col)
9701 (setq beg (point)))
9702 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9703 (when (re-search-backward org-table-dataline-regexp)
9704 (org-table-goto-column col)
9705 (setq end (point)))
9706 (setq l (apply 'append (org-table-copy-region beg end)))
9707 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9708 (if (equal x "") "0" x))
9709 l ",") "]"))
9710 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9711 (setq n1 (string-to-number (match-string 1 desc))
9712 n2 (string-to-number (match-string 2 desc)))
9713 (beginning-of-line 1)
9714 (save-excursion
9715 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9716 (org-table-goto-column col)
9717 (setq beg (point))))
9718 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9719 (org-table-goto-column col)
9720 (setq end (point)))
9721 (setq l (apply 'append (org-table-copy-region beg end)))
9722 (concat "[" (mapconcat
9723 (lambda (x) (setq x (org-trim x))
9724 (if (equal x "") "0" x))
9725 l ",") "]"))
9726 ((string-match "\\([0-9]+\\)" desc)
9727 (beginning-of-line 1)
9728 (when (re-search-backward org-table-dataline-regexp tbeg t
9729 (string-to-number (match-string 0 desc)))
9730 (org-table-goto-column col)
9731 (org-trim (org-table-get-field))))))))
9733 (defvar org-table-formula-history nil)
9735 (defvar org-table-column-names nil
9736 "Alist with column names, derived from the `!' line.")
9737 (defvar org-table-column-name-regexp nil
9738 "Regular expression matching the current column names.")
9739 (defvar org-table-local-parameters nil
9740 "Alist with parameter names, derived from the `$' line.")
9741 (defvar org-table-named-field-locations nil
9742 "Alist with locations of named fields.")
9744 (defun org-table-get-formula (&optional equation named)
9745 "Read a formula from the minibuffer, offer stored formula as default."
9746 (let* ((name (car (rassoc (list (org-current-line)
9747 (org-table-current-column))
9748 org-table-named-field-locations)))
9749 (scol (if named
9750 (if name name
9751 (error "Not in a named field"))
9752 (int-to-string (org-table-current-column))))
9753 (dummy (and name (not named)
9754 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9755 (error "Abort")))
9756 (org-table-may-need-update nil)
9757 (stored-list (org-table-get-stored-formulas))
9758 (stored (cdr (assoc scol stored-list)))
9759 (eq (cond
9760 ((and stored equation (string-match "^ *=? *$" equation))
9761 stored)
9762 ((stringp equation)
9763 equation)
9764 (t (read-string
9765 (format "%s formula $%s=" (if named "Field" "Column") scol)
9766 (or stored "") 'org-table-formula-history
9767 ;stored
9768 ))))
9769 mustsave)
9770 (when (not (string-match "\\S-" eq))
9771 ;; remove formula
9772 (setq stored-list (delq (assoc scol stored-list) stored-list))
9773 (org-table-store-formulas stored-list)
9774 (error "Formula removed"))
9775 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9776 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9777 (if (and name (not named))
9778 ;; We set the column equation, delete the named one.
9779 (setq stored-list (delq (assoc name stored-list) stored-list)
9780 mustsave t))
9781 (if stored
9782 (setcdr (assoc scol stored-list) eq)
9783 (setq stored-list (cons (cons scol eq) stored-list)))
9784 (if (or mustsave (not (equal stored eq)))
9785 (org-table-store-formulas stored-list))
9786 eq))
9788 (defun org-table-store-formulas (alist)
9789 "Store the list of formulas below the current table."
9790 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9791 (save-excursion
9792 (goto-char (org-table-end))
9793 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9794 (delete-region (point) (match-end 0)))
9795 (insert "#+TBLFM: "
9796 (mapconcat (lambda (x)
9797 (concat "$" (car x) "=" (cdr x)))
9798 alist "::")
9799 "\n")))
9801 (defun org-table-get-stored-formulas ()
9802 "Return an alist with the t=stored formulas directly after current table."
9803 (interactive)
9804 (let (scol eq eq-alist strings string seen)
9805 (save-excursion
9806 (goto-char (org-table-end))
9807 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9808 (setq strings (org-split-string (match-string 2) " *:: *"))
9809 (while (setq string (pop strings))
9810 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9811 (setq scol (match-string 1 string)
9812 eq (match-string 2 string)
9813 eq-alist (cons (cons scol eq) eq-alist))
9814 (if (member scol seen)
9815 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9816 (push scol seen))))))
9817 (nreverse eq-alist)))
9819 (defun org-table-modify-formulas (action &rest columns)
9820 "Modify the formulas stored below the current table.
9821 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
9822 expected, for the other actions only a single column number is needed."
9823 (let ((list (org-table-get-stored-formulas))
9824 (nmax (length (org-split-string
9825 (buffer-substring (point-at-bol) (point-at-eol))
9826 "|")))
9827 col col1 col2 scol si sc1 sc2)
9828 (cond
9829 ((null list)) ; No action needed if there are no stored formulas
9830 ((eq action 'remove)
9831 (setq col (car columns)
9832 scol (int-to-string col))
9833 (org-table-replace-in-formulas list scol "INVALID")
9834 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
9835 (loop for i from (1+ col) upto nmax by 1 do
9836 (setq si (int-to-string i))
9837 (org-table-replace-in-formulas list si (int-to-string (1- i)))
9838 (if (assoc si list) (setcar (assoc si list)
9839 (int-to-string (1- i))))))
9840 ((eq action 'insert)
9841 (setq col (car columns))
9842 (loop for i from nmax downto col by 1 do
9843 (setq si (int-to-string i))
9844 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
9845 (if (assoc si list) (setcar (assoc si list)
9846 (int-to-string (1+ i))))))
9847 ((eq action 'swap)
9848 (setq col1 (car columns) col2 (nth 1 columns)
9849 sc1 (int-to-string col1) sc2 (int-to-string col2))
9850 ;; Hopefully, ZqZtZ will never be a name in a table
9851 (org-table-replace-in-formulas list sc1 "ZqZtZ")
9852 (org-table-replace-in-formulas list sc2 sc1)
9853 (org-table-replace-in-formulas list "ZqZtZ" sc2)
9854 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
9855 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
9856 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
9857 (t (error "Invalid action in `org-table-modify-formulas'")))
9858 (if list (org-table-store-formulas list))))
9860 (defun org-table-replace-in-formulas (list s1 s2)
9861 (let (elt re s)
9862 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
9863 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
9864 re (concat (regexp-quote s1) "\\>"))
9865 (while (setq elt (pop list))
9866 (setq s (cdr elt))
9867 (while (string-match re s)
9868 (setq s (replace-match s2 t t s)))
9869 (setcdr elt s))))
9871 (defun org-table-get-specials ()
9872 "Get the column names and local parameters for this table."
9873 (save-excursion
9874 (let ((beg (org-table-begin)) (end (org-table-end))
9875 names name fields fields1 field cnt c v line col)
9876 (setq org-table-column-names nil
9877 org-table-local-parameters nil
9878 org-table-named-field-locations nil)
9879 (goto-char beg)
9880 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9881 (setq names (org-split-string (match-string 1) " *| *")
9882 cnt 1)
9883 (while (setq name (pop names))
9884 (setq cnt (1+ cnt))
9885 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9886 (push (cons name (int-to-string cnt)) org-table-column-names))))
9887 (setq org-table-column-names (nreverse org-table-column-names))
9888 (setq org-table-column-name-regexp
9889 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9890 (goto-char beg)
9891 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9892 (setq fields (org-split-string (match-string 1) " *| *"))
9893 (while (setq field (pop fields))
9894 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9895 (push (cons (match-string 1 field) (match-string 2 field))
9896 org-table-local-parameters))))
9897 (goto-char beg)
9898 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9899 (setq c (match-string 1)
9900 fields (org-split-string (match-string 2) " *| *"))
9901 (save-excursion
9902 (beginning-of-line (if (equal c "_") 2 0))
9903 (setq line (org-current-line) col 1)
9904 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9905 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9906 (while (and fields1 (setq field (pop fields)))
9907 (setq v (pop fields1) col (1+ col))
9908 (when (and (stringp field) (stringp v)
9909 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9910 (push (cons field v) org-table-local-parameters)
9911 (push (list field line col) org-table-named-field-locations)))))))
9913 (defun org-this-word ()
9914 ;; Get the current word
9915 (save-excursion
9916 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
9917 (end (progn (skip-chars-forward "^ \t\n") (point))))
9918 (buffer-substring-no-properties beg end))))
9920 (defun org-table-maybe-eval-formula ()
9921 "Check if the current field starts with \"=\" or \":=\".
9922 If yes, store the formula and apply it."
9923 ;; We already know we are in a table. Get field will only return a formula
9924 ;; when appropriate. It might return a separator line, but no problem.
9925 (when org-table-formula-evaluate-inline
9926 (let* ((field (org-trim (or (org-table-get-field) "")))
9927 named eq)
9928 (when (string-match "^:?=\\(.*\\)" field)
9929 (setq named (equal (string-to-char field) ?:)
9930 eq (match-string 1 field))
9931 (if (fboundp 'calc-eval)
9932 (org-table-eval-formula (if named '(4) nil) eq))))))
9934 (defvar org-recalc-commands nil
9935 "List of commands triggering the recalculation of a line.
9936 Will be filled automatically during use.")
9938 (defvar org-recalc-marks
9939 '((" " . "Unmarked: no special line, no automatic recalculation")
9940 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9941 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9942 ("!" . "Column name definition line. Reference in formula as $name.")
9943 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9944 ("_" . "Names for values in row below this one.")
9945 ("^" . "Names for values in row above this one.")))
9947 (defun org-table-rotate-recalc-marks (&optional newchar)
9948 "Rotate the recalculation mark in the first column.
9949 If in any row, the first field is not consistent with a mark,
9950 insert a new column for the markers.
9951 When there is an active region, change all the lines in the region,
9952 after prompting for the marking character.
9953 After each change, a message will be displayed indicating the meaning
9954 of the new mark."
9955 (interactive)
9956 (unless (org-at-table-p) (error "Not at a table"))
9957 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9958 (beg (org-table-begin))
9959 (end (org-table-end))
9960 (l (org-current-line))
9961 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9962 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9963 (have-col
9964 (save-excursion
9965 (goto-char beg)
9966 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9967 (col (org-table-current-column))
9968 (forcenew (car (assoc newchar org-recalc-marks)))
9969 epos new)
9970 (when l1
9971 (message "Change region to what mark? Type # * ! $ or SPC: ")
9972 (setq newchar (char-to-string (read-char-exclusive))
9973 forcenew (car (assoc newchar org-recalc-marks))))
9974 (if (and newchar (not forcenew))
9975 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9976 newchar))
9977 (if l1 (goto-line l1))
9978 (save-excursion
9979 (beginning-of-line 1)
9980 (unless (looking-at org-table-dataline-regexp)
9981 (error "Not at a table data line")))
9982 (unless have-col
9983 (org-table-goto-column 1)
9984 (org-table-insert-column)
9985 (org-table-goto-column (1+ col)))
9986 (setq epos (point-at-eol))
9987 (save-excursion
9988 (beginning-of-line 1)
9989 (org-table-get-field
9990 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9991 (concat " "
9992 (setq new (or forcenew
9993 (cadr (member (match-string 1) marks))))
9994 " ")
9995 " # ")))
9996 (if (and l1 l2)
9997 (progn
9998 (goto-line l1)
9999 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10000 (and (looking-at org-table-dataline-regexp)
10001 (org-table-get-field 1 (concat " " new " "))))
10002 (goto-line l1)))
10003 (if (not (= epos (point-at-eol))) (org-table-align))
10004 (goto-line l)
10005 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
10007 (defun org-table-maybe-recalculate-line ()
10008 "Recompute the current line if marked for it, and if we haven't just done it."
10009 (interactive)
10010 (and org-table-allow-automatic-line-recalculation
10011 (not (and (memq last-command org-recalc-commands)
10012 (equal org-last-recalc-line (org-current-line))))
10013 (save-excursion (beginning-of-line 1)
10014 (looking-at org-table-auto-recalculate-regexp))
10015 (fboundp 'calc-eval)
10016 (org-table-recalculate) t))
10018 (defvar org-table-formula-debug nil
10019 "Non-nil means, debug table formulas.
10020 When nil, simply write \"#ERROR\" in corrupted fields.")
10022 (defvar modes)
10023 (defsubst org-set-calc-mode (var &optional value)
10024 (if (stringp var)
10025 (setq var (assoc var '(("D" calc-angle-mode deg)
10026 ("R" calc-angle-mode rad)
10027 ("F" calc-prefer-frac t)
10028 ("S" calc-symbolic-mode t)))
10029 value (nth 2 var) var (nth 1 var)))
10030 (if (memq var modes)
10031 (setcar (cdr (memq var modes)) value)
10032 (cons var (cons value modes)))
10033 modes)
10035 (defun org-table-eval-formula (&optional arg equation
10036 suppress-align suppress-const
10037 suppress-store)
10038 "Replace the table field value at the cursor by the result of a calculation.
10040 This function makes use of Dave Gillespie's Calc package, in my view the
10041 most exciting program ever written for GNU Emacs. So you need to have Calc
10042 installed in order to use this function.
10044 In a table, this command replaces the value in the current field with the
10045 result of a formula. It also installs the formula as the \"current\" column
10046 formula, by storing it in a special line below the table. When called
10047 with a `C-u' prefix, the current field must ba a named field, and the
10048 formula is installed as valid in only this specific field.
10050 When called, the command first prompts for a formula, which is read in
10051 the minibuffer. Previously entered formulas are available through the
10052 history list, and the last used formula is offered as a default.
10053 These stored formulas are adapted correctly when moving, inserting, or
10054 deleting columns with the corresponding commands.
10056 The formula can be any algebraic expression understood by the Calc package.
10057 For details, see the Org-mode manual.
10059 This function can also be called from Lisp programs and offers
10060 additional arguments: EQUATION can be the formula to apply. If this
10061 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10062 used to speed-up recursive calls by by-passing unnecessary aligns.
10063 SUPPRESS-CONST suppresses the interpretation of constants in the
10064 formula, assuming that this has been done already outside the function.
10065 SUPPRESS-STORE means the formula should not be stored, either because
10066 it is already stored, or because it is a modified equation that should
10067 not overwrite the stored one."
10068 (interactive "P")
10069 (require 'calc)
10070 (org-table-check-inside-data-field)
10071 (org-table-get-specials)
10072 (let* (fields
10073 (ndown (if (integerp arg) arg 1))
10074 (org-table-automatic-realign nil)
10075 (case-fold-search nil)
10076 (down (> ndown 1))
10077 (formula (if (and equation suppress-store)
10078 equation
10079 (org-table-get-formula equation (equal arg '(4)))))
10080 (n0 (org-table-current-column))
10081 (modes (copy-sequence org-calc-default-modes))
10082 n form fmt x ev orig c)
10083 ;; Parse the format string. Since we have a lot of modes, this is
10084 ;; a lot of work. However, I think calc still uses most of the time.
10085 (if (string-match ";" formula)
10086 (let ((tmp (org-split-string formula ";")))
10087 (setq formula (car tmp)
10088 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10089 (nth 1 tmp)))
10090 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
10091 (setq c (string-to-char (match-string 1 fmt))
10092 n (string-to-number (or (match-string 1 fmt) "")))
10093 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
10094 (setq modes (org-set-calc-mode
10095 'calc-float-format
10096 (list (cdr (assoc c '((?n . float) (?f . fix)
10097 (?s . sci) (?e . eng))))
10098 n))))
10099 (setq fmt (replace-match "" t t fmt)))
10100 (while (string-match "[DRFS]" fmt)
10101 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10102 (setq fmt (replace-match "" t t fmt)))
10103 (unless (string-match "\\S-" fmt)
10104 (setq fmt nil))))
10105 (if (and (not suppress-const) org-table-formula-use-constants)
10106 (setq formula (org-table-formula-substitute-names formula)))
10107 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10108 (while (> ndown 0)
10109 (setq fields (org-split-string
10110 (buffer-substring
10111 (point-at-bol) (point-at-eol)) " *| *"))
10112 (if org-table-formula-numbers-only
10113 (setq fields (mapcar
10114 (lambda (x) (number-to-string (string-to-number x)))
10115 fields)))
10116 (setq ndown (1- ndown))
10117 (setq form (copy-sequence formula))
10118 ;; Insert the references to fields in same row
10119 (while (string-match "\\$\\([0-9]+\\)?" form)
10120 (setq n (if (match-beginning 1)
10121 (string-to-number (match-string 1 form))
10123 x (nth (1- n) fields))
10124 (unless x (error "Invalid field specifier \"%s\""
10125 (match-string 0 form)))
10126 (if (equal x "") (setq x "0"))
10127 (setq form (replace-match (concat "(" x ")") t t form)))
10128 ;; Insert ranges in current column
10129 (while (string-match "\\&[-I0-9]+" form)
10130 (setq form (replace-match
10131 (save-match-data
10132 (org-table-get-vertical-vector (match-string 0 form)
10133 nil n0))
10134 t t form)))
10135 (setq ev (calc-eval (cons form modes)
10136 (if org-table-formula-numbers-only 'num)))
10138 (when org-table-formula-debug
10139 (with-output-to-temp-buffer "*Help*"
10140 (princ (format "Substitution history of formula
10141 Orig: %s
10142 $xyz-> %s
10143 $1-> %s\n" orig formula form))
10144 (if (listp ev)
10145 (princ (format " %s^\nError: %s"
10146 (make-string (car ev) ?\-) (nth 1 ev)))
10147 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10148 ev (or fmt "NONE")
10149 (if fmt (format fmt (string-to-number ev)) ev)))))
10150 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
10151 (unless (and (interactive-p) (not ndown))
10152 (unless (let (inhibit-redisplay)
10153 (y-or-n-p "Debugging Formula. Continue to next? "))
10154 (org-table-align)
10155 (error "Abort"))
10156 (delete-window (get-buffer-window "*Help*"))
10157 (message "")))
10158 (if (listp ev) (setq fmt nil ev "#ERROR"))
10159 (org-table-justify-field-maybe
10160 (if fmt (format fmt (string-to-number ev)) ev))
10161 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10162 (call-interactively 'org-return)
10163 (setq ndown 0)))
10164 (and down (org-table-maybe-recalculate-line))
10165 (or suppress-align (and org-table-may-need-update
10166 (org-table-align)))))
10168 (defun org-table-recalculate (&optional all noalign)
10169 "Recalculate the current table line by applying all stored formulas."
10170 (interactive "P")
10171 (or (memq this-command org-recalc-commands)
10172 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10173 (unless (org-at-table-p) (error "Not at a table"))
10174 (org-table-get-specials)
10175 (let* ((eqlist (sort (org-table-get-stored-formulas)
10176 (lambda (a b) (string< (car a) (car b)))))
10177 (inhibit-redisplay t)
10178 (line-re org-table-dataline-regexp)
10179 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10180 (thiscol (org-table-current-column))
10181 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
10182 ;; Insert constants in all formulas
10183 (setq eqlist
10184 (mapcar (lambda (x)
10185 (setcdr x (org-table-formula-substitute-names (cdr x)))
10187 eqlist))
10188 ;; Split the equation list
10189 (while (setq eq (pop eqlist))
10190 (if (<= (string-to-char (car eq)) ?9)
10191 (push eq eqlnum)
10192 (push eq eqlname)))
10193 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10194 (if all
10195 (progn
10196 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10197 (goto-char (setq beg (org-table-begin)))
10198 (if (re-search-forward org-table-calculate-mark-regexp end t)
10199 ;; This is a table with marked lines, only compute selected lines
10200 (setq line-re org-table-recalculate-regexp)
10201 ;; Move forward to the first non-header line
10202 (if (and (re-search-forward org-table-dataline-regexp end t)
10203 (re-search-forward org-table-hline-regexp end t)
10204 (re-search-forward org-table-dataline-regexp end t))
10205 (setq beg (match-beginning 0))
10206 nil))) ;; just leave beg where it is
10207 (setq beg (point-at-bol)
10208 end (move-marker (make-marker) (1+ (point-at-eol)))))
10209 (goto-char beg)
10210 (and all (message "Re-applying formulas to full table..."))
10211 (while (re-search-forward line-re end t)
10212 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
10213 ;; Unprotected line, recalculate
10214 (and all (message "Re-applying formulas to full table...(line %d)"
10215 (setq cnt (1+ cnt))))
10216 (setq org-last-recalc-line (org-current-line))
10217 (setq eql eqlnum)
10218 (while (setq entry (pop eql))
10219 (goto-line org-last-recalc-line)
10220 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10221 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
10222 (goto-line thisline)
10223 (org-table-goto-column thiscol)
10224 (or noalign (and org-table-may-need-update (org-table-align))
10225 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10226 ;; Now do the names fields
10227 (while (setq eq (pop eqlname))
10228 (setq name (car eq)
10229 a (assoc name org-table-named-field-locations))
10230 (when a
10231 (message "Re-applying formula to named field: %s" name)
10232 (goto-line (nth 1 a))
10233 (org-table-goto-column (nth 2 a))
10234 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
10235 ;; back to initial position
10236 (goto-line thisline)
10237 (org-table-goto-column thiscol)
10238 (or noalign (and org-table-may-need-update (org-table-align))
10239 (and all (message "Re-applying formulas...done")))))
10241 (defun org-table-formula-substitute-names (f)
10242 "Replace $const with values in string F."
10243 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
10244 ;; First, check for column names
10245 (while (setq start (string-match org-table-column-name-regexp f start))
10246 (setq start (1+ start))
10247 (setq a (assoc (match-string 1 f) org-table-column-names))
10248 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10249 ;; Expand ranges to vectors
10250 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
10251 (setq n1 (string-to-number (match-string 1 f))
10252 n2 (string-to-number (match-string 2 f))
10253 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
10254 s (concat "[($" (number-to-string (1- nn1)) ")"))
10255 (loop for i from nn1 upto nn2 do
10256 (setq s (concat s ",($" (int-to-string i) ")")))
10257 (setq s (concat s "]"))
10258 (if (< n2 n1) (setq s (concat "rev(" s ")")))
10259 (setq f (replace-match s t t f)))
10260 ;; Parameters and constants
10261 (setq start 0)
10262 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
10263 (setq start (1+ start))
10264 (if (setq a (save-match-data
10265 (org-table-get-constant (match-string 1 f))))
10266 (setq f (replace-match (concat "(" a ")") t t f))))
10267 (if org-table-formula-debug
10268 (put-text-property 0 (length f) :orig-formula f1 f))
10271 (defun org-table-get-constant (const)
10272 "Find the value for a parameter or constant in a formula.
10273 Parameters get priority."
10274 (or (cdr (assoc const org-table-local-parameters))
10275 (cdr (assoc const org-table-formula-constants))
10276 (and (fboundp 'constants-get) (constants-get const))
10277 "#UNDEFINED_NAME"))
10279 (defvar org-edit-formulas-map (make-sparse-keymap))
10280 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
10281 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
10282 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
10284 (defvar org-pos)
10286 (defun org-table-edit-formulas ()
10287 "Edit the formulas of the current table in a separate buffer."
10288 (interactive)
10289 (unless (org-at-table-p)
10290 (error "Not at a table"))
10291 (org-table-get-specials)
10292 (let ((eql (org-table-get-stored-formulas))
10293 (pos (move-marker (make-marker) (point)))
10294 (wc (current-window-configuration))
10295 entry loc s)
10296 (switch-to-buffer-other-window "*Edit Formulas*")
10297 (erase-buffer)
10298 (fundamental-mode)
10299 (set (make-local-variable 'org-pos) pos)
10300 (set (make-local-variable 'org-window-configuration) wc)
10301 (use-local-map org-edit-formulas-map)
10302 (setq s "# Edit formulas and finish with `C-c C-c'.
10303 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
10304 # Use `C-c ?' to get information about $name at point.
10305 # To cancel editing, press `C-c C-q'.\n")
10306 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10307 (insert s)
10308 (while (setq entry (pop eql))
10309 (when (setq loc (assoc (car entry) org-table-named-field-locations))
10310 (setq s (format "# Named formula, referring to column %d in line %d\n"
10311 (nth 2 loc) (nth 1 loc)))
10312 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10313 (insert s))
10314 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
10315 (remove-text-properties 0 (length s) '(face nil) s)
10316 (insert s))
10317 (goto-char (point-min))
10318 (message "Edit formulas and finish with `C-c C-c'.")))
10320 (defun org-show-variable ()
10321 "Show the location/value of the $ expression at point."
10322 (interactive)
10323 (let (var (pos org-pos) (win (selected-window)) e)
10324 (save-excursion
10325 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
10326 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
10327 (setq var (match-string 1))
10328 (error "No variable at point")))
10329 (cond
10330 ((setq e (assoc var org-table-named-field-locations))
10331 (switch-to-buffer-other-window (marker-buffer pos))
10332 (goto-line (nth 1 e))
10333 (org-table-goto-column (nth 2 e))
10334 (select-window win)
10335 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10336 ((setq e (assoc var org-table-column-names))
10337 (switch-to-buffer-other-window (marker-buffer pos))
10338 (goto-char pos)
10339 (goto-char (org-table-begin))
10340 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10341 (org-table-end) t)
10342 (progn
10343 (goto-char (match-beginning 1))
10344 (message "Named column (column %s)" (cdr e)))
10345 (error "Column name not found"))
10346 (select-window win))
10347 ((string-match "^[0-9]$" var)
10348 ;; column number
10349 (switch-to-buffer-other-window (marker-buffer pos))
10350 (goto-char pos)
10351 (goto-char (org-table-begin))
10352 (recenter 1)
10353 (if (re-search-forward org-table-dataline-regexp
10354 (org-table-end) t)
10355 (progn
10356 (goto-char (match-beginning 0))
10357 (org-table-goto-column (string-to-number var))
10358 (message "Column %s" var))
10359 (error "Column name not found"))
10360 (select-window win))
10361 ((setq e (assoc var org-table-local-parameters))
10362 (switch-to-buffer-other-window (marker-buffer pos))
10363 (goto-char pos)
10364 (goto-char (org-table-begin))
10365 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10366 (progn
10367 (goto-char (match-beginning 1))
10368 (message "Local parameter."))
10369 (error "Parameter not found"))
10370 (select-window win))
10372 (cond
10373 ((setq e (assoc var org-table-formula-constants))
10374 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
10375 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10376 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
10377 (t (error "Undefined name $%s" var)))))))
10379 (defun org-finish-edit-formulas (&optional arg)
10380 "Parse the buffer for formula definitions and install them.
10381 With prefix ARG, apply the new formulas to the table."
10382 (interactive "P")
10383 (let ((pos org-pos) eql)
10384 (goto-char (point-min))
10385 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
10386 (push (cons (match-string 1) (match-string 2)) eql))
10387 (set-window-configuration org-window-configuration)
10388 (select-window (get-buffer-window (marker-buffer pos)))
10389 (goto-char pos)
10390 (unless (org-at-table-p)
10391 (error "Lost table position - cannot install formulae"))
10392 (org-table-store-formulas eql)
10393 (move-marker pos nil)
10394 (kill-buffer "*Edit Formulas*")
10395 (if arg
10396 (org-table-recalculate 'all)
10397 (message "New formulas installed - press C-u C-c C-c to apply."))))
10399 (defun org-abort-edit-formulas ()
10400 "Abort editing formulas, without installing the changes."
10401 (interactive)
10402 (let ((pos org-pos))
10403 (set-window-configuration org-window-configuration)
10404 (select-window (get-buffer-window (marker-buffer pos)))
10405 (goto-char pos)
10406 (message "Formula editing aborted without installing changes")))
10408 ;;; The orgtbl minor mode
10410 ;; Define a minor mode which can be used in other modes in order to
10411 ;; integrate the org-mode table editor.
10413 ;; This is really a hack, because the org-mode table editor uses several
10414 ;; keys which normally belong to the major mode, for example the TAB and
10415 ;; RET keys. Here is how it works: The minor mode defines all the keys
10416 ;; necessary to operate the table editor, but wraps the commands into a
10417 ;; function which tests if the cursor is currently inside a table. If that
10418 ;; is the case, the table editor command is executed. However, when any of
10419 ;; those keys is used outside a table, the function uses `key-binding' to
10420 ;; look up if the key has an associated command in another currently active
10421 ;; keymap (minor modes, major mode, global), and executes that command.
10422 ;; There might be problems if any of the keys used by the table editor is
10423 ;; otherwise used as a prefix key.
10425 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10426 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10427 ;; addresses this by checking explicitly for both bindings.
10429 ;; The optimized version (see variable `orgtbl-optimized') takes over
10430 ;; all keys which are bound to `self-insert-command' in the *global map*.
10431 ;; Some modes bind other commands to simple characters, for example
10432 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10433 ;; active, this binding is ignored inside tables and replaced with a
10434 ;; modified self-insert.
10436 (defvar orgtbl-mode nil
10437 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10438 table editor in arbitrary modes.")
10439 (make-variable-buffer-local 'orgtbl-mode)
10441 (defvar orgtbl-mode-map (make-keymap)
10442 "Keymap for `orgtbl-mode'.")
10444 ;;;###autoload
10445 (defun turn-on-orgtbl ()
10446 "Unconditionally turn on `orgtbl-mode'."
10447 (orgtbl-mode 1))
10449 ;;;###autoload
10450 (defun orgtbl-mode (&optional arg)
10451 "The `org-mode' table editor as a minor mode for use in other modes."
10452 (interactive)
10453 (if (eq major-mode 'org-mode)
10454 ;; Exit without error, in case some hook functions calls this
10455 ;; by accident in org-mode.
10456 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10457 (setq orgtbl-mode
10458 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10459 (if orgtbl-mode
10460 (progn
10461 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10462 ;; Make sure we are first in minor-mode-map-alist
10463 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10464 (and c (setq minor-mode-map-alist
10465 (cons c (delq c minor-mode-map-alist)))))
10466 (set (make-local-variable (quote org-table-may-need-update)) t)
10467 (org-add-hook 'before-change-functions 'org-before-change-function
10468 nil 'local)
10469 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
10470 auto-fill-inhibit-regexp)
10471 (set (make-local-variable 'auto-fill-inhibit-regexp)
10472 (if auto-fill-inhibit-regexp
10473 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
10474 "[ \t]*|"))
10475 (org-add-to-invisibility-spec '(org-cwidth))
10476 (easy-menu-add orgtbl-mode-menu)
10477 (run-hooks 'orgtbl-mode-hook))
10478 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10479 (org-cleanup-narrow-column-properties)
10480 (org-remove-from-invisibility-spec '(org-cwidth))
10481 (remove-hook 'before-change-functions 'org-before-change-function t)
10482 (easy-menu-remove orgtbl-mode-menu)
10483 (force-mode-line-update 'all))))
10485 (defun org-cleanup-narrow-column-properties ()
10486 "Remove all properties related to narrow-column invisibility."
10487 (let ((s 1))
10488 (while (setq s (text-property-any s (point-max)
10489 'display org-narrow-column-arrow))
10490 (remove-text-properties s (1+ s) '(display t)))
10491 (setq s 1)
10492 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10493 (remove-text-properties s (1+ s) '(org-cwidth t)))
10494 (setq s 1)
10495 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10496 (remove-text-properties s (1+ s) '(invisible t)))))
10498 ;; Install it as a minor mode.
10499 (put 'orgtbl-mode :included t)
10500 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10501 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10503 (defun orgtbl-make-binding (fun n &rest keys)
10504 "Create a function for binding in the table minor mode.
10505 FUN is the command to call inside a table. N is used to create a unique
10506 command name. KEYS are keys that should be checked in for a command
10507 to execute outside of tables."
10508 (eval
10509 (list 'defun
10510 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10511 '(arg)
10512 (concat "In tables, run `" (symbol-name fun) "'.\n"
10513 "Outside of tables, run the binding of `"
10514 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10515 "'.")
10516 '(interactive "p")
10517 (list 'if
10518 '(org-at-table-p)
10519 (list 'call-interactively (list 'quote fun))
10520 (list 'let '(orgtbl-mode)
10521 (list 'call-interactively
10522 (append '(or)
10523 (mapcar (lambda (k)
10524 (list 'key-binding k))
10525 keys)
10526 '('orgtbl-error))))))))
10528 (defun orgtbl-error ()
10529 "Error when there is no default binding for a table key."
10530 (interactive)
10531 (error "This key is has no function outside tables"))
10533 (defun orgtbl-setup ()
10534 "Setup orgtbl keymaps."
10535 (let ((nfunc 0)
10536 (bindings
10537 (list
10538 '([(meta shift left)] org-table-delete-column)
10539 '([(meta left)] org-table-move-column-left)
10540 '([(meta right)] org-table-move-column-right)
10541 '([(meta shift right)] org-table-insert-column)
10542 '([(meta shift up)] org-table-kill-row)
10543 '([(meta shift down)] org-table-insert-row)
10544 '([(meta up)] org-table-move-row-up)
10545 '([(meta down)] org-table-move-row-down)
10546 '("\C-c\C-w" org-table-cut-region)
10547 '("\C-c\M-w" org-table-copy-region)
10548 '("\C-c\C-y" org-table-paste-rectangle)
10549 '("\C-c-" org-table-insert-hline)
10550 ; '([(shift tab)] org-table-previous-field)
10551 '("\C-m" org-table-next-row)
10552 (list (org-key 'S-return) 'org-table-copy-down)
10553 '([(meta return)] org-table-wrap-region)
10554 '("\C-c\C-q" org-table-wrap-region)
10555 '("\C-c?" org-table-current-column)
10556 '("\C-c " org-table-blank-field)
10557 '("\C-c+" org-table-sum)
10558 '("\C-c=" org-table-eval-formula)
10559 '("\C-c'" org-table-edit-formulas)
10560 '("\C-c`" org-table-edit-field)
10561 '("\C-c*" org-table-recalculate)
10562 '("\C-c|" org-table-create-or-convert-from-region)
10563 '("\C-c^" org-table-sort-lines)
10564 '([(control ?#)] org-table-rotate-recalc-marks)))
10565 elt key fun cmd)
10566 (while (setq elt (pop bindings))
10567 (setq nfunc (1+ nfunc))
10568 (setq key (car elt)
10569 fun (nth 1 elt)
10570 cmd (orgtbl-make-binding fun nfunc key))
10571 (define-key orgtbl-mode-map key cmd))
10572 ;; Special treatment needed for TAB and RET
10573 (define-key orgtbl-mode-map [(return)]
10574 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10575 (define-key orgtbl-mode-map "\C-m"
10576 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10577 (define-key orgtbl-mode-map [(tab)]
10578 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10579 (define-key orgtbl-mode-map "\C-i"
10580 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
10581 (define-key orgtbl-mode-map "\C-i"
10582 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
10583 (define-key orgtbl-mode-map "\C-c\C-c"
10584 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
10585 (when orgtbl-optimized
10586 ;; If the user wants maximum table support, we need to hijack
10587 ;; some standard editing functions
10588 (org-remap orgtbl-mode-map
10589 'self-insert-command 'orgtbl-self-insert-command
10590 'delete-char 'org-delete-char
10591 'delete-backward-char 'org-delete-backward-char)
10592 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
10593 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10594 '("OrgTbl"
10595 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10596 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10597 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10598 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10599 "--"
10600 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10601 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10602 ["Copy Field from Above"
10603 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10604 "--"
10605 ("Column"
10606 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10607 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10608 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10609 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
10610 "--"
10611 ["Enable Narrowing" (setq org-table-limit-column-width (not org-table-limit-column-width)) :active (org-at-table-p) :selected org-table-limit-column-width :style toggle])
10612 ("Row"
10613 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10614 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10615 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10616 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10617 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10618 "--"
10619 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10620 ("Rectangle"
10621 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10622 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10623 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10624 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10625 "--"
10626 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10627 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10628 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10629 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10630 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10631 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10632 ["Sum Column/Rectangle" org-table-sum
10633 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10634 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10635 ["Debug Formulas"
10636 (setq org-table-formula-debug (not org-table-formula-debug))
10637 :style toggle :selected org-table-formula-debug]
10641 (defun orgtbl-tab (arg)
10642 "Justification and field motion for `orgtbl-mode'."
10643 (interactive "P")
10644 (if arg (org-table-edit-field t)
10645 (org-table-justify-field-maybe)
10646 (org-table-next-field)))
10648 (defun orgtbl-ret ()
10649 "Justification and field motion for `orgtbl-mode'."
10650 (interactive)
10651 (org-table-justify-field-maybe)
10652 (org-table-next-row))
10654 (defun orgtbl-self-insert-command (N)
10655 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10656 If the cursor is in a table looking at whitespace, the whitespace is
10657 overwritten, and the table is not marked as requiring realignment."
10658 (interactive "p")
10659 (if (and (org-at-table-p)
10661 (and org-table-auto-blank-field
10662 (member last-command
10663 '(orgtbl-hijacker-command-100
10664 orgtbl-hijacker-command-101
10665 orgtbl-hijacker-command-102
10666 orgtbl-hijacker-command-103
10667 orgtbl-hijacker-command-104
10668 orgtbl-hijacker-command-105))
10669 (org-table-blank-field))
10671 (eq N 1)
10672 (looking-at "[^|\n]* +|"))
10673 (let (org-table-may-need-update)
10674 (goto-char (1- (match-end 0)))
10675 (delete-backward-char 1)
10676 (goto-char (match-beginning 0))
10677 (self-insert-command N))
10678 (setq org-table-may-need-update t)
10679 (let (orgtbl-mode)
10680 (call-interactively (key-binding (vector last-input-event))))))
10682 (defun org-force-self-insert (N)
10683 "Needed to enforce self-insert under remapping."
10684 (interactive "p")
10685 (self-insert-command N))
10687 ;;; Exporting
10689 (defconst org-level-max 20)
10691 (defun org-export-find-first-heading-line (list)
10692 "Remove all lines from LIST which are before the first headline."
10693 (let ((orig-list list)
10694 (re (concat "^" outline-regexp)))
10695 (while (and list
10696 (not (string-match re (car list))))
10697 (pop list))
10698 (or list orig-list)))
10700 (defun org-skip-comments (lines)
10701 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10702 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10703 (re2 "^\\(\\*+\\)[ \t\n\r]")
10704 rtn line level)
10705 (while (setq line (pop lines))
10706 (cond
10707 ((and (string-match re1 line)
10708 (setq level (- (match-end 1) (match-beginning 1))))
10709 ;; Beginning of a COMMENT subtree. Skip it.
10710 (while (and (setq line (pop lines))
10711 (or (not (string-match re2 line))
10712 (> (- (match-end 1) (match-beginning 1)) level))))
10713 (setq lines (cons line lines)))
10714 ((string-match "^#" line)
10715 ;; an ordinary comment line
10717 ((and org-export-table-remove-special-lines
10718 (string-match "^[ \t]*| *[!_^] *|" line))
10719 ;; a special table line that should be removed
10721 (t (setq rtn (cons line rtn)))))
10722 (nreverse rtn)))
10724 ;; ASCII
10726 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10727 "Characters for underlining headings in ASCII export.")
10729 (defconst org-html-entities
10730 '(("nbsp")
10731 ("iexcl")
10732 ("cent")
10733 ("pound")
10734 ("curren")
10735 ("yen")
10736 ("brvbar")
10737 ("sect")
10738 ("uml")
10739 ("copy")
10740 ("ordf")
10741 ("laquo")
10742 ("not")
10743 ("shy")
10744 ("reg")
10745 ("macr")
10746 ("deg")
10747 ("plusmn")
10748 ("sup2")
10749 ("sup3")
10750 ("acute")
10751 ("micro")
10752 ("para")
10753 ("middot")
10754 ("odot"."o")
10755 ("star"."*")
10756 ("cedil")
10757 ("sup1")
10758 ("ordm")
10759 ("raquo")
10760 ("frac14")
10761 ("frac12")
10762 ("frac34")
10763 ("iquest")
10764 ("Agrave")
10765 ("Aacute")
10766 ("Acirc")
10767 ("Atilde")
10768 ("Auml")
10769 ("Aring") ("AA"."&Aring;")
10770 ("AElig")
10771 ("Ccedil")
10772 ("Egrave")
10773 ("Eacute")
10774 ("Ecirc")
10775 ("Euml")
10776 ("Igrave")
10777 ("Iacute")
10778 ("Icirc")
10779 ("Iuml")
10780 ("ETH")
10781 ("Ntilde")
10782 ("Ograve")
10783 ("Oacute")
10784 ("Ocirc")
10785 ("Otilde")
10786 ("Ouml")
10787 ("times")
10788 ("Oslash")
10789 ("Ugrave")
10790 ("Uacute")
10791 ("Ucirc")
10792 ("Uuml")
10793 ("Yacute")
10794 ("THORN")
10795 ("szlig")
10796 ("agrave")
10797 ("aacute")
10798 ("acirc")
10799 ("atilde")
10800 ("auml")
10801 ("aring")
10802 ("aelig")
10803 ("ccedil")
10804 ("egrave")
10805 ("eacute")
10806 ("ecirc")
10807 ("euml")
10808 ("igrave")
10809 ("iacute")
10810 ("icirc")
10811 ("iuml")
10812 ("eth")
10813 ("ntilde")
10814 ("ograve")
10815 ("oacute")
10816 ("ocirc")
10817 ("otilde")
10818 ("ouml")
10819 ("divide")
10820 ("oslash")
10821 ("ugrave")
10822 ("uacute")
10823 ("ucirc")
10824 ("uuml")
10825 ("yacute")
10826 ("thorn")
10827 ("yuml")
10828 ("fnof")
10829 ("Alpha")
10830 ("Beta")
10831 ("Gamma")
10832 ("Delta")
10833 ("Epsilon")
10834 ("Zeta")
10835 ("Eta")
10836 ("Theta")
10837 ("Iota")
10838 ("Kappa")
10839 ("Lambda")
10840 ("Mu")
10841 ("Nu")
10842 ("Xi")
10843 ("Omicron")
10844 ("Pi")
10845 ("Rho")
10846 ("Sigma")
10847 ("Tau")
10848 ("Upsilon")
10849 ("Phi")
10850 ("Chi")
10851 ("Psi")
10852 ("Omega")
10853 ("alpha")
10854 ("beta")
10855 ("gamma")
10856 ("delta")
10857 ("epsilon")
10858 ("varepsilon"."&epsilon;")
10859 ("zeta")
10860 ("eta")
10861 ("theta")
10862 ("iota")
10863 ("kappa")
10864 ("lambda")
10865 ("mu")
10866 ("nu")
10867 ("xi")
10868 ("omicron")
10869 ("pi")
10870 ("rho")
10871 ("sigmaf") ("varsigma"."&sigmaf;")
10872 ("sigma")
10873 ("tau")
10874 ("upsilon")
10875 ("phi")
10876 ("chi")
10877 ("psi")
10878 ("omega")
10879 ("thetasym") ("vartheta"."&thetasym;")
10880 ("upsih")
10881 ("piv")
10882 ("bull") ("bullet"."&bull;")
10883 ("hellip") ("dots"."&hellip;")
10884 ("prime")
10885 ("Prime")
10886 ("oline")
10887 ("frasl")
10888 ("weierp")
10889 ("image")
10890 ("real")
10891 ("trade")
10892 ("alefsym")
10893 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
10894 ("uarr") ("uparrow"."&uarr;")
10895 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
10896 ("darr")("downarrow"."&darr;")
10897 ("harr") ("leftrightarrow"."&harr;")
10898 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
10899 ("lArr") ("Leftarrow"."&lArr;")
10900 ("uArr") ("Uparrow"."&uArr;")
10901 ("rArr") ("Rightarrow"."&rArr;")
10902 ("dArr") ("Downarrow"."&dArr;")
10903 ("hArr") ("Leftrightarrow"."&hArr;")
10904 ("forall")
10905 ("part") ("partial"."&part;")
10906 ("exist") ("exists"."&exist;")
10907 ("empty") ("emptyset"."&empty;")
10908 ("nabla")
10909 ("isin") ("in"."&isin;")
10910 ("notin")
10911 ("ni")
10912 ("prod")
10913 ("sum")
10914 ("minus")
10915 ("lowast") ("ast"."&lowast;")
10916 ("radic")
10917 ("prop") ("proptp"."&prop;")
10918 ("infin") ("infty"."&infin;")
10919 ("ang") ("angle"."&ang;")
10920 ("and") ("vee"."&and;")
10921 ("or") ("wedge"."&or;")
10922 ("cap")
10923 ("cup")
10924 ("int")
10925 ("there4")
10926 ("sim")
10927 ("cong") ("simeq"."&cong;")
10928 ("asymp")("approx"."&asymp;")
10929 ("ne") ("neq"."&ne;")
10930 ("equiv")
10931 ("le")
10932 ("ge")
10933 ("sub") ("subset"."&sub;")
10934 ("sup") ("supset"."&sup;")
10935 ("nsub")
10936 ("sube")
10937 ("supe")
10938 ("oplus")
10939 ("otimes")
10940 ("perp")
10941 ("sdot") ("cdot"."&sdot;")
10942 ("lceil")
10943 ("rceil")
10944 ("lfloor")
10945 ("rfloor")
10946 ("lang")
10947 ("rang")
10948 ("loz") ("Diamond"."&loz;")
10949 ("spades") ("spadesuit"."&spades;")
10950 ("clubs") ("clubsuit"."&clubs;")
10951 ("hearts") ("diamondsuit"."&hearts;")
10952 ("diams") ("diamondsuit"."&diams;")
10953 ("quot")
10954 ("amp")
10955 ("lt")
10956 ("gt")
10957 ("OElig")
10958 ("oelig")
10959 ("Scaron")
10960 ("scaron")
10961 ("Yuml")
10962 ("circ")
10963 ("tilde")
10964 ("ensp")
10965 ("emsp")
10966 ("thinsp")
10967 ("zwnj")
10968 ("zwj")
10969 ("lrm")
10970 ("rlm")
10971 ("ndash")
10972 ("mdash")
10973 ("lsquo")
10974 ("rsquo")
10975 ("sbquo")
10976 ("ldquo")
10977 ("rdquo")
10978 ("bdquo")
10979 ("dagger")
10980 ("Dagger")
10981 ("permil")
10982 ("lsaquo")
10983 ("rsaquo")
10984 ("euro")
10986 ("arccos"."arccos")
10987 ("arcsin"."arcsin")
10988 ("arctan"."arctan")
10989 ("arg"."arg")
10990 ("cos"."cos")
10991 ("cosh"."cosh")
10992 ("cot"."cot")
10993 ("coth"."coth")
10994 ("csc"."csc")
10995 ("deg"."deg")
10996 ("det"."det")
10997 ("dim"."dim")
10998 ("exp"."exp")
10999 ("gcd"."gcd")
11000 ("hom"."hom")
11001 ("inf"."inf")
11002 ("ker"."ker")
11003 ("lg"."lg")
11004 ("lim"."lim")
11005 ("liminf"."liminf")
11006 ("limsup"."limsup")
11007 ("ln"."ln")
11008 ("log"."log")
11009 ("max"."max")
11010 ("min"."min")
11011 ("Pr"."Pr")
11012 ("sec"."sec")
11013 ("sin"."sin")
11014 ("sinh"."sinh")
11015 ("sup"."sup")
11016 ("tan"."tan")
11017 ("tanh"."tanh")
11019 "Entities for TeX->HTML translation.
11020 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
11021 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
11022 In that case, \"\\ent\" will be translated to \"&other;\".
11023 The list contains HTML entities for Latin-1, Greek and other symbols.
11024 It is supplemented by a number of commonly used TeX macros with appropriate
11025 translations. There is currently no way for users to extend this.")
11027 (defun org-cleaned-string-for-export (string)
11028 "Cleanup a buffer substring so that links can be created safely."
11029 (interactive)
11030 (let* ((cb (current-buffer))
11031 (re-radio (and org-target-link-regexp
11032 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
11033 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
11034 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
11035 rtn)
11036 (save-excursion
11037 (set-buffer (get-buffer-create " org-mode-tmp"))
11038 (erase-buffer)
11039 (insert string)
11040 (org-mode)
11041 ;; Find targets in comments and move them out of comments,
11042 ;; but mark them as targets that should be invisible
11043 (goto-char (point-min))
11044 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
11045 (replace-match "\\1(INVISIBLE)"))
11046 ;; Find matches for radio targets and turn them into internal links
11047 (goto-char (point-min))
11048 (when re-radio
11049 (while (re-search-forward re-radio nil t)
11050 (replace-match "\\1[[\\2]]")))
11051 ;; Find all links that contain a newline and put them into a single line
11052 (goto-char (point-min))
11053 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
11054 (replace-match "\\1 \\3")
11055 (goto-char (match-beginning 0)))
11056 ;; Normalize links: Convert angle and plain links into bracket links
11057 (goto-char (point-min))
11058 (while (re-search-forward re-plain-link nil t)
11059 (replace-match
11060 (concat
11061 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11062 t t))
11063 (goto-char (point-min))
11064 (while (re-search-forward re-angle-link nil t)
11065 (replace-match
11066 (concat
11067 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11068 t t))
11070 ;; Remove comments
11071 (goto-char (point-min))
11072 (while (re-search-forward "^#.*\n?" nil t)
11073 (replace-match ""))
11074 (setq rtn (buffer-string)))
11075 (kill-buffer " org-mode-tmp")
11076 rtn))
11078 (defun org-solidify-link-text (s &optional alist)
11079 "Take link text and make a safe target out of it."
11080 (save-match-data
11081 (let* ((rtn
11082 (mapconcat
11083 'identity
11084 (org-split-string s "[ \t\r\n]+") "--"))
11085 (a (assoc rtn alist)))
11086 (or (cdr a) rtn))))
11088 (defun org-convert-to-odd-levels ()
11089 "Convert an org-mode file with all levels allowed to one with odd levels.
11090 This will leave level 1 alone, convert level 2 to level 3, level 3 to
11091 level 5 etc."
11092 (interactive)
11093 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
11094 (let ((org-odd-levels-only nil) n)
11095 (save-excursion
11096 (goto-char (point-min))
11097 (while (re-search-forward "^\\*\\*+" nil t)
11098 (setq n (1- (length (match-string 0))))
11099 (while (>= (setq n (1- n)) 0)
11100 (org-demote))
11101 (end-of-line 1))))))
11104 (defun org-convert-to-oddeven-levels ()
11105 "Convert an org-mode file with only odd levels to one with odd and even levels.
11106 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
11107 section with an even level, conversion would destroy the structure of the file. An error
11108 is signaled in this case."
11109 (interactive)
11110 (goto-char (point-min))
11111 ;; First check if there are no even levels
11112 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
11113 (org-show-hierarchy-above)
11114 (error "Not all levels are odd in this file. Conversion not possible."))
11115 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
11116 (let ((org-odd-levels-only nil) n)
11117 (save-excursion
11118 (goto-char (point-min))
11119 (while (re-search-forward "^\\*\\*+" nil t)
11120 (setq n (/ (length (match-string 0)) 2))
11121 (while (>= (setq n (1- n)) 0)
11122 (org-promote))
11123 (end-of-line 1))))))
11125 (defun org-tr-level (n)
11126 "Make N odd if required."
11127 (if org-odd-levels-only (1+ (/ n 2)) n))
11129 (defvar org-last-level nil) ; dynamically scoped variable
11131 (defun org-export-as-ascii (arg)
11132 "Export the outline as a pretty ASCII file.
11133 If there is an active region, export only the region.
11134 The prefix ARG specifies how many levels of the outline should become
11135 underlined headlines. The default is 3."
11136 (interactive "P")
11137 (setq-default org-todo-line-regexp org-todo-line-regexp)
11138 (let* ((region
11139 (buffer-substring
11140 (if (org-region-active-p) (region-beginning) (point-min))
11141 (if (org-region-active-p) (region-end) (point-max))))
11142 (lines (org-export-find-first-heading-line
11143 (org-skip-comments
11144 (org-split-string
11145 (org-cleaned-string-for-export region)
11146 "[\r\n]"))))
11147 (org-startup-with-deadline-check nil)
11148 (level 0) line txt
11149 (umax nil)
11150 (case-fold-search nil)
11151 (filename (concat (file-name-sans-extension buffer-file-name)
11152 ".txt"))
11153 (buffer (find-file-noselect filename))
11154 (levels-open (make-vector org-level-max nil))
11155 (date (format-time-string "%Y/%m/%d" (current-time)))
11156 (time (format-time-string "%X" (org-current-time)))
11157 (author user-full-name)
11158 (title (buffer-name))
11159 (options nil)
11160 (email user-mail-address)
11161 (language org-export-default-language)
11162 (text nil)
11163 (todo nil)
11164 (lang-words nil))
11166 (setq org-last-level 1)
11167 (org-init-section-numbers)
11169 (find-file-noselect filename)
11171 ;; Search for the export key lines
11172 (org-parse-key-lines)
11174 (setq lang-words (or (assoc language org-export-language-setup)
11175 (assoc "en" org-export-language-setup)))
11176 (if org-export-ascii-show-new-buffer
11177 (switch-to-buffer-other-window buffer)
11178 (set-buffer buffer))
11179 (erase-buffer)
11180 (fundamental-mode)
11181 (if options (org-parse-export-options options))
11182 (setq umax (if arg (prefix-numeric-value arg)
11183 org-export-headline-levels))
11185 ;; File header
11186 (if title (org-insert-centered title ?=))
11187 (insert "\n")
11188 (if (or author email)
11189 (insert (concat (nth 1 lang-words) ": " (or author "")
11190 (if email (concat " <" email ">") "")
11191 "\n")))
11192 (if (and date time)
11193 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
11194 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
11196 (insert "\n\n")
11198 (if org-export-with-toc
11199 (progn
11200 (insert (nth 3 lang-words) "\n"
11201 (make-string (length (nth 3 lang-words)) ?=) "\n")
11202 (mapcar '(lambda (line)
11203 (if (string-match org-todo-line-regexp
11204 line)
11205 ;; This is a headline
11206 (progn
11207 (setq level (- (match-end 1) (match-beginning 1))
11208 level (org-tr-level level)
11209 txt (match-string 3 line)
11210 todo
11211 (or (and (match-beginning 2)
11212 (not (equal (match-string 2 line)
11213 org-done-string)))
11214 ; TODO, not DONE
11215 (and org-export-mark-todo-in-toc
11216 (= level umax)
11217 (org-search-todo-below
11218 line lines level))))
11219 (setq txt (org-html-expand-for-ascii txt))
11221 (if org-export-with-section-numbers
11222 (setq txt (concat (org-section-number level)
11223 " " txt)))
11224 (if (<= level umax)
11225 (progn
11226 (insert
11227 (make-string (* (1- level) 4) ?\ )
11228 (format (if todo "%s (*)\n" "%s\n") txt))
11229 (setq org-last-level level))
11230 ))))
11231 lines)))
11233 (org-init-section-numbers)
11234 (while (setq line (pop lines))
11235 ;; Remove the quoted HTML tags.
11236 (setq line (org-html-expand-for-ascii line))
11237 ;; Remove targets
11238 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
11239 (setq line (replace-match "" t t line)))
11240 ;; Replace internal links
11241 (while (string-match org-bracket-link-regexp line)
11242 (setq line (replace-match
11243 (if (match-end 3) "[\\3]" "[\\1]")
11244 t nil line)))
11245 (cond
11246 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11247 ;; a Headline
11248 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11249 txt (match-string 2 line))
11250 (org-ascii-level-start level txt umax))
11251 (t (insert line "\n"))))
11252 (normal-mode)
11253 (save-buffer)
11254 (goto-char (point-min))))
11256 (defun org-search-todo-below (line lines level)
11257 "Search the subtree below LINE for any TODO entries."
11258 (let ((rest (cdr (memq line lines)))
11259 (re org-todo-line-regexp)
11260 line lv todo)
11261 (catch 'exit
11262 (while (setq line (pop rest))
11263 (if (string-match re line)
11264 (progn
11265 (setq lv (- (match-end 1) (match-beginning 1))
11266 todo (and (match-beginning 2)
11267 (not (equal (match-string 2 line)
11268 org-done-string))))
11269 ; TODO, not DONE
11270 (if (<= lv level) (throw 'exit nil))
11271 (if todo (throw 'exit t))))))))
11273 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
11274 ;; We could also implement *bold*,/italic/ and _underline_ for ASCII export
11275 (defun org-html-expand-for-ascii (line)
11276 "Handle quoted HTML for ASCII export."
11277 (if org-export-html-expand
11278 (while (string-match "@<[^<>\n]*>" line)
11279 ;; We just remove the tags for now.
11280 (setq line (replace-match "" nil nil line))))
11281 line)
11283 (defun org-insert-centered (s &optional underline)
11284 "Insert the string S centered and underline it with character UNDERLINE."
11285 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
11286 (insert (make-string ind ?\ ) s "\n")
11287 (if underline
11288 (insert (make-string ind ?\ )
11289 (make-string (string-width s) underline)
11290 "\n"))))
11292 (defun org-ascii-level-start (level title umax)
11293 "Insert a new level in ASCII export."
11294 (let (char)
11295 (if (> level umax)
11296 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
11297 (if (or (not (equal (char-before) ?\n))
11298 (not (equal (char-before (1- (point))) ?\n)))
11299 (insert "\n"))
11300 (setq char (nth (- umax level) (reverse org-ascii-underline)))
11301 (if org-export-with-section-numbers
11302 (setq title (concat (org-section-number level) " " title)))
11303 (insert title "\n" (make-string (string-width title) char) "\n"))))
11305 (defun org-export-copy-visible ()
11306 "Copy the visible part of the buffer to another buffer, for printing.
11307 Also removes the first line of the buffer if it specifies a mode,
11308 and all options lines."
11309 (interactive)
11310 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
11311 ".txt"))
11312 (buffer (find-file-noselect filename))
11313 (ore (concat
11314 (org-make-options-regexp
11315 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
11316 "STARTUP" "ARCHIVE"
11317 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
11318 (if org-noutline-p "\\(\n\\|$\\)" "")))
11319 s e)
11320 (with-current-buffer buffer
11321 (erase-buffer)
11322 (text-mode))
11323 (save-excursion
11324 (setq s (goto-char (point-min)))
11325 (while (not (= (point) (point-max)))
11326 (goto-char (org-find-invisible))
11327 (append-to-buffer buffer s (point))
11328 (setq s (goto-char (org-find-visible)))))
11329 (switch-to-buffer-other-window buffer)
11330 (newline)
11331 (goto-char (point-min))
11332 (if (looking-at ".*-\\*- mode:.*\n")
11333 (replace-match ""))
11334 (while (re-search-forward ore nil t)
11335 (replace-match ""))
11336 (goto-char (point-min))))
11338 (defun org-find-visible ()
11339 (if (featurep 'noutline)
11340 (let ((s (point)))
11341 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11342 (get-char-property s 'invisible)))
11344 (skip-chars-forward "^\n")
11345 (point)))
11346 (defun org-find-invisible ()
11347 (if (featurep 'noutline)
11348 (let ((s (point)))
11349 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11350 (not (get-char-property s 'invisible))))
11352 (skip-chars-forward "^\r")
11353 (point)))
11355 ;; HTML
11357 (defun org-get-current-options ()
11358 "Return a string with current options as keyword options.
11359 Does include HTML export options as well as TODO and CATEGORY stuff."
11360 (format
11361 "#+TITLE: %s
11362 #+AUTHOR: %s
11363 #+EMAIL: %s
11364 #+LANGUAGE: %s
11365 #+TEXT: Some descriptive text to be emitted. Several lines OK.
11366 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
11367 #+CATEGORY: %s
11368 #+SEQ_TODO: %s
11369 #+TYP_TODO: %s
11370 #+STARTUP: %s %s %s %s %s
11371 #+ARCHIVE: %s
11373 (buffer-name) (user-full-name) user-mail-address org-export-default-language
11374 org-export-headline-levels
11375 org-export-with-section-numbers
11376 org-export-with-toc
11377 org-export-preserve-breaks
11378 org-export-html-expand
11379 org-export-with-fixed-width
11380 org-export-with-tables
11381 org-export-with-sub-superscripts
11382 org-export-with-emphasize
11383 org-export-with-TeX-macros
11384 (file-name-nondirectory buffer-file-name)
11385 (if (equal org-todo-interpretation 'sequence)
11386 (mapconcat 'identity org-todo-keywords " ")
11387 "TODO FEEDBACK VERIFY DONE")
11388 (if (equal org-todo-interpretation 'type)
11389 (mapconcat 'identity org-todo-keywords " ")
11390 "Me Jason Marie DONE")
11391 (cdr (assoc org-startup-folded
11392 '((nil . "nofold")(t . "fold")(content . "content"))))
11393 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
11394 (if org-odd-levels-only "odd" "oddeven")
11395 (if org-hide-leading-stars "hidestars" "showstars")
11396 (if org-startup-align-all-tables "align" "noalign")
11397 org-archive-location
11400 (defun org-insert-export-options-template ()
11401 "Insert into the buffer a template with information for exporting."
11402 (interactive)
11403 (if (not (bolp)) (newline))
11404 (let ((s (org-get-current-options)))
11405 (and (string-match "#\\+CATEGORY" s)
11406 (setq s (substring s 0 (match-beginning 0))))
11407 (insert s)))
11409 (defun org-toggle-fixed-width-section (arg)
11410 "Toggle the fixed-width export.
11411 If there is no active region, the QUOTE keyword at the current headline is
11412 inserted or removed. When present, it causes the text between this headline
11413 and the next to be exported as fixed-width text, and unmodified.
11414 If there is an active region, this command adds or removes a colon as the
11415 first character of this line. If the first character of a line is a colon,
11416 this line is also exported in fixed-width font."
11417 (interactive "P")
11418 (let* ((cc 0)
11419 (regionp (org-region-active-p))
11420 (beg (if regionp (region-beginning) (point)))
11421 (end (if regionp (region-end)))
11422 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
11423 (re "[ \t]*\\(:\\)")
11424 off)
11425 (if regionp
11426 (save-excursion
11427 (goto-char beg)
11428 (setq cc (current-column))
11429 (beginning-of-line 1)
11430 (setq off (looking-at re))
11431 (while (> nlines 0)
11432 (setq nlines (1- nlines))
11433 (beginning-of-line 1)
11434 (cond
11435 (arg
11436 (move-to-column cc t)
11437 (insert ":\n")
11438 (forward-line -1))
11439 ((and off (looking-at re))
11440 (replace-match "" t t nil 1))
11441 ((not off) (move-to-column cc t) (insert ":")))
11442 (forward-line 1)))
11443 (save-excursion
11444 (org-back-to-heading)
11445 (if (looking-at (concat outline-regexp
11446 "\\( +\\<" org-quote-string "\\>\\)"))
11447 (replace-match "" t t nil 1)
11448 (if (looking-at outline-regexp)
11449 (progn
11450 (goto-char (match-end 0))
11451 (insert " " org-quote-string))))))))
11453 (defun org-export-as-html-and-open (arg)
11454 "Export the outline as HTML and immediately open it with a browser.
11455 If there is an active region, export only the region.
11456 The prefix ARG specifies how many levels of the outline should become
11457 headlines. The default is 3. Lower levels will become bulleted lists."
11458 (interactive "P")
11459 (org-export-as-html arg 'hidden)
11460 (org-open-file buffer-file-name))
11462 (defun org-export-as-html-batch ()
11463 "Call `org-export-as-html', may be used in batch processing as
11464 emacs --batch
11465 --load=$HOME/lib/emacs/org.el
11466 --eval \"(setq org-export-headline-levels 2)\"
11467 --visit=MyFile --funcall org-export-as-html-batch"
11468 (org-export-as-html org-export-headline-levels 'hidden))
11470 (defun org-export-as-html (arg &optional hidden)
11471 "Export the outline as a pretty HTML file.
11472 If there is an active region, export only the region.
11473 The prefix ARG specifies how many levels of the outline should become
11474 headlines. The default is 3. Lower levels will become bulleted lists."
11475 (interactive "P")
11476 (setq-default org-todo-line-regexp org-todo-line-regexp)
11477 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
11478 (setq-default org-done-string org-done-string)
11479 (let* ((style org-export-html-style)
11480 (odd org-odd-levels-only)
11481 (region-p (org-region-active-p))
11482 (region
11483 (buffer-substring
11484 (if region-p (region-beginning) (point-min))
11485 (if region-p (region-end) (point-max))))
11486 (all_lines
11487 (org-skip-comments (org-split-string
11488 (org-cleaned-string-for-export region)
11489 "[\r\n]")))
11490 (lines (org-export-find-first-heading-line all_lines))
11491 (level 0) (line "") (origline "") txt todo
11492 (umax nil)
11493 (filename (concat (file-name-sans-extension buffer-file-name)
11494 ".html"))
11495 (buffer (find-file-noselect filename))
11496 (levels-open (make-vector org-level-max nil))
11497 (date (format-time-string "%Y/%m/%d" (current-time)))
11498 (time (format-time-string "%X" (org-current-time)))
11499 (author user-full-name)
11500 (title (buffer-name))
11501 (options nil)
11502 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
11503 (inquote nil)
11504 (infixed nil)
11505 (in-local-list nil)
11506 (local-list-num nil)
11507 (local-list-indent nil)
11508 (llt org-plain-list-ordered-item-terminator)
11509 (email user-mail-address)
11510 (language org-export-default-language)
11511 (text nil)
11512 (lang-words nil)
11513 (target-alist nil) tg
11514 (head-count 0) cnt
11515 (start 0)
11516 ;; FIXME: The following returns always nil under XEmacs
11517 (coding-system (and (fboundp 'coding-system-get)
11518 (boundp 'buffer-file-coding-system)
11519 buffer-file-coding-system))
11520 (coding-system-for-write (or coding-system coding-system-for-write))
11521 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
11522 (charset (and coding-system
11523 (coding-system-get coding-system 'mime-charset)))
11524 table-open type
11525 table-buffer table-orig-buffer
11526 ind start-is-num starter
11527 rpl path desc desc1 desc2 link
11529 (message "Exporting...")
11531 (setq org-last-level 1)
11532 (org-init-section-numbers)
11534 ;; Search for the export key lines
11535 (org-parse-key-lines)
11536 (setq lang-words (or (assoc language org-export-language-setup)
11537 (assoc "en" org-export-language-setup)))
11539 ;; Switch to the output buffer
11540 (if (or hidden (not org-export-html-show-new-buffer))
11541 (set-buffer buffer)
11542 (switch-to-buffer-other-window buffer))
11543 (erase-buffer)
11544 (fundamental-mode)
11545 (let ((case-fold-search nil)
11546 (org-odd-levels-only odd))
11547 (if options (org-parse-export-options options))
11548 (setq umax (if arg (prefix-numeric-value arg)
11549 org-export-headline-levels))
11551 ;; File header
11552 (insert (format
11553 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
11554 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
11555 <html lang=\"%s\"><head>
11556 <title>%s</title>
11557 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
11558 <meta name=generator content=\"Org-mode\">
11559 <meta name=generated content=\"%s %s\">
11560 <meta name=author content=\"%s\">
11562 </head><body>
11564 language (org-html-expand title) (or charset "iso-8859-1")
11565 date time author style))
11566 (if title (insert (concat "<H1 class=\"title\">"
11567 (org-html-expand title) "</H1>\n")))
11568 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
11569 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
11570 email "&gt;</a>\n")))
11571 (if (or author email) (insert "<br>\n"))
11572 (if (and date time) (insert (concat (nth 2 lang-words) ": "
11573 date " " time "<br>\n")))
11574 (if text (insert (concat "<p>\n" (org-html-expand text))))
11575 (if org-export-with-toc
11576 (progn
11577 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
11578 (insert "<ul>\n")
11579 (setq lines
11580 (mapcar '(lambda (line)
11581 (if (string-match org-todo-line-regexp line)
11582 ;; This is a headline
11583 (progn
11584 (setq level (- (match-end 1) (match-beginning 1))
11585 level (org-tr-level level)
11586 txt (save-match-data
11587 (org-html-expand
11588 (match-string 3 line)))
11589 todo
11590 (or (and (match-beginning 2)
11591 (not (equal (match-string 2 line)
11592 org-done-string)))
11593 ; TODO, not DONE
11594 (and org-export-mark-todo-in-toc
11595 (= level umax)
11596 (org-search-todo-below
11597 line lines level))))
11598 (if org-export-with-section-numbers
11599 (setq txt (concat (org-section-number level)
11600 " " txt)))
11601 (if (<= level umax)
11602 (progn
11603 (setq head-count (+ head-count 1))
11604 (if (> level org-last-level)
11605 (progn
11606 (setq cnt (- level org-last-level))
11607 (while (>= (setq cnt (1- cnt)) 0)
11608 (insert "<ul>"))
11609 (insert "\n")))
11610 (if (< level org-last-level)
11611 (progn
11612 (setq cnt (- org-last-level level))
11613 (while (>= (setq cnt (1- cnt)) 0)
11614 (insert "</ul>"))
11615 (insert "\n")))
11616 ;; Check for targets
11617 (while (string-match org-target-regexp line)
11618 (setq tg (match-string 1 line)
11619 line (replace-match
11620 (concat "@<span class=\"target\">" tg "@</span> ")
11621 t t line))
11622 (push (cons (org-solidify-link-text tg)
11623 (format "sec-%d" head-count))
11624 target-alist))
11625 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
11626 (setq txt (replace-match "" t t txt)))
11627 (insert
11628 (format
11629 (if todo
11630 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
11631 "<li><a href=\"#sec-%d\">%s</a>\n")
11632 head-count txt))
11634 (setq org-last-level level))
11636 line)
11637 lines))
11638 (while (> org-last-level 0)
11639 (setq org-last-level (1- org-last-level))
11640 (insert "</ul>\n"))
11642 (setq head-count 0)
11643 (org-init-section-numbers)
11645 (while (setq line (pop lines) origline line)
11646 (catch 'nextline
11648 ;; end of quote section?
11649 (when (and inquote (string-match "^\\*+" line))
11650 (insert "</pre>\n")
11651 (setq inquote nil))
11652 ;; inside a quote section?
11653 (when inquote
11654 (insert (org-html-protect line) "\n")
11655 (throw 'nextline nil))
11657 ;; verbatim lines
11658 (when (and org-export-with-fixed-width
11659 (string-match "^[ \t]*:\\(.*\\)" line))
11660 (when (not infixed)
11661 (setq infixed t)
11662 (insert "<pre>\n"))
11663 (insert (org-html-protect (match-string 1 line)) "\n")
11664 (when (and lines
11665 (not (string-match "^[ \t]*\\(:.*\\)"
11666 (car lines))))
11667 (setq infixed nil)
11668 (insert "</pre>\n"))
11669 (throw 'nextline nil))
11672 ;; make targets to anchors
11673 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
11674 (cond
11675 ((match-end 2)
11676 (setq line (replace-match
11677 (concat "@<a name=\""
11678 (org-solidify-link-text (match-string 1 line))
11679 "\">\\nbsp@</a>")
11680 t t line)))
11681 ((and org-export-with-toc (equal (string-to-char line) ?*))
11682 (setq line (replace-match
11683 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
11684 ; (concat "@<i>" (match-string 1 line) "@</i> ")
11685 t t line)))
11687 (setq line (replace-match
11688 (concat "@<a name=\""
11689 (org-solidify-link-text (match-string 1 line))
11690 "\" class=\"target\">" (match-string 1 line) "@</a> ")
11691 t t line)))))
11693 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
11694 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
11695 (setq line (org-html-expand line))
11697 ;; Format the links
11698 (setq start 0)
11699 (while (string-match org-bracket-link-analytic-regexp line start)
11700 (setq start (match-beginning 0))
11701 (setq type (if (match-end 2) (match-string 2 line) "internal"))
11702 (setq path (match-string 3 line))
11703 (setq desc1 (if (match-end 5) (match-string 5 line))
11704 desc2 (if (match-end 2) (concat type ":" path) path)
11705 desc (or desc1 desc2))
11706 (cond
11707 ((equal type "internal")
11708 (setq rpl
11709 (concat
11710 "<a href=\"#"
11711 (org-solidify-link-text path target-alist)
11712 "\">" desc "</a>")))
11713 ((member type '("http" "https" "ftp" "mailto" "news"))
11714 ;; standard URL
11715 (setq link (concat type ":" path))
11716 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
11717 ((string= type "file")
11718 ;; FILE link
11719 (let* ((filename path)
11720 (abs-p (file-name-absolute-p filename))
11721 (thefile (if abs-p (expand-file-name filename) filename))
11722 (thefile (save-match-data
11723 (if (string-match ":[0-9]+$" thefile)
11724 (replace-match "" t t thefile)
11725 thefile)))
11726 (file-is-image-p
11727 (save-match-data
11728 (string-match (org-image-file-name-regexp) thefile))))
11729 (setq rpl (if (and org-export-html-inline-images
11730 file-is-image-p)
11731 (concat "<img src=\"" thefile "\"/>")
11732 (concat "<a href=\"" thefile "\">" desc "</a>")))))
11733 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11734 (setq rpl (concat "<i>&lt;" type ":" path "&gt;</i>"))))
11735 ;; FIXME: We get to see the escaped links!!!!!
11736 (setq line (replace-match rpl t t line)
11737 start (+ start (length rpl))))
11738 ;; TODO items
11739 (if (and (string-match org-todo-line-regexp line)
11740 (match-beginning 2))
11741 (if (equal (match-string 2 line) org-done-string)
11742 (setq line (replace-match
11743 "<span class=\"done\">\\2</span>"
11744 nil nil line 2))
11745 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11746 nil nil line 2))))
11748 ;; DEADLINES
11749 (if (string-match org-deadline-line-regexp line)
11750 (progn
11751 (if (save-match-data
11752 (string-match "<a href"
11753 (substring line 0 (match-beginning 0))))
11754 nil ; Don't do the replacement - it is inside a link
11755 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11756 nil nil line 1)))))
11757 (cond
11758 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11759 ;; This is a headline
11760 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11761 txt (match-string 2 line))
11762 (if (<= level umax) (setq head-count (+ head-count 1)))
11763 (when in-local-list
11764 ;; Close any local lists before inserting a new header line
11765 (while local-list-num
11766 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11767 (pop local-list-num))
11768 (setq local-list-indent nil
11769 in-local-list nil))
11770 (org-html-level-start level txt umax
11771 (and org-export-with-toc (<= level umax))
11772 head-count)
11773 ;; QUOTES
11774 (when (string-match quote-re line)
11775 (insert "<pre>")
11776 (setq inquote t)))
11778 ((and org-export-with-tables
11779 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11780 (if (not table-open)
11781 ;; New table starts
11782 (setq table-open t table-buffer nil table-orig-buffer nil))
11783 ;; Accumulate lines
11784 (setq table-buffer (cons line table-buffer)
11785 table-orig-buffer (cons origline table-orig-buffer))
11786 (when (or (not lines)
11787 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11788 (car lines))))
11789 (setq table-open nil
11790 table-buffer (nreverse table-buffer)
11791 table-orig-buffer (nreverse table-orig-buffer))
11792 (insert (org-format-table-html table-buffer table-orig-buffer))))
11794 ;; Normal lines
11795 (when (and (string-match
11796 (cond
11797 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11798 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11799 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11800 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
11801 line))
11802 (setq ind (org-get-string-indentation line)
11803 start-is-num (match-beginning 4)
11804 starter (if (match-beginning 2) (match-string 2 line))
11805 line (substring line (match-beginning 5)))
11806 (unless (string-match "[^ \t]" line)
11807 ;; empty line. Pretend indentation is large.
11808 (setq ind (1+ (or (car local-list-indent) 1))))
11809 (while (and in-local-list
11810 (or (and (= ind (car local-list-indent))
11811 (not starter))
11812 (< ind (car local-list-indent))))
11813 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11814 (pop local-list-num) (pop local-list-indent)
11815 (setq in-local-list local-list-indent))
11816 (cond
11817 ((and starter
11818 (or (not in-local-list)
11819 (> ind (car local-list-indent))))
11820 ;; Start new (level of ) list
11821 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
11822 (push start-is-num local-list-num)
11823 (push ind local-list-indent)
11824 (setq in-local-list t))
11825 (starter
11826 ;; continue current list
11827 (insert "<li>\n"))))
11828 ;; Empty lines start a new paragraph. If hand-formatted lists
11829 ;; are not fully interpreted, lines starting with "-", "+", "*"
11830 ;; also start a new paragraph.
11831 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
11832 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
11834 (if org-export-html-with-timestamp
11835 (insert org-export-html-html-helper-timestamp))
11836 (insert "</body>\n</html>\n")
11837 (normal-mode)
11838 (save-buffer)
11839 (goto-char (point-min)))))
11841 (defun org-format-table-html (lines olines)
11842 "Find out which HTML converter to use and return the HTML code."
11843 (if (string-match "^[ \t]*|" (car lines))
11844 ;; A normal org table
11845 (org-format-org-table-html lines)
11846 ;; Table made by table.el - test for spanning
11847 (let* ((hlines (delq nil (mapcar
11848 (lambda (x)
11849 (if (string-match "^[ \t]*\\+-" x) x
11850 nil))
11851 lines)))
11852 (first (car hlines))
11853 (ll (and (string-match "\\S-+" first)
11854 (match-string 0 first)))
11855 (re (concat "^[ \t]*" (regexp-quote ll)))
11856 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
11857 hlines))))
11858 (if (and (not spanning)
11859 (not org-export-prefer-native-exporter-for-tables))
11860 ;; We can use my own converter with HTML conversions
11861 (org-format-table-table-html lines)
11862 ;; Need to use the code generator in table.el, with the original text.
11863 (org-format-table-table-html-using-table-generate-source olines)))))
11865 (defun org-format-org-table-html (lines)
11866 "Format a table into HTML."
11867 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11868 (setq lines (nreverse lines))
11869 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11870 (setq lines (nreverse lines))
11871 (when org-export-table-remove-special-lines
11872 ;; Check if the table has a marking column. If yes remove the
11873 ;; column and the special lines
11874 (let* ((special
11875 (not
11876 (memq nil
11877 (mapcar
11878 (lambda (x)
11879 (or (string-match "^[ \t]*|-" x)
11880 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
11881 lines)))))
11882 (if special
11883 (setq lines
11884 (delq nil
11885 (mapcar
11886 (lambda (x)
11887 (if (string-match "^[ \t]*| *[!_^] *|" x)
11888 nil ; ignore this line
11889 (and (or (string-match "^[ \t]*|-+\\+" x)
11890 (string-match "^[ \t]*|[^|]*|" x))
11891 (replace-match "|" t t x))))
11892 lines))))))
11894 (let ((head (and org-export-highlight-first-table-line
11895 (delq nil (mapcar
11896 (lambda (x) (string-match "^[ \t]*|-" x))
11897 (cdr lines)))))
11898 line fields html)
11899 (setq html (concat org-export-html-table-tag "\n"))
11900 (while (setq line (pop lines))
11901 (catch 'next-line
11902 (if (string-match "^[ \t]*|-" line)
11903 (progn
11904 (setq head nil) ;; head ends here, first time around
11905 ;; ignore this line
11906 (throw 'next-line t)))
11907 ;; Break the line into fields
11908 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11909 (setq html (concat
11910 html
11911 "<tr>"
11912 (mapconcat (lambda (x)
11913 (if head
11914 (concat "<th>" x "</th>")
11915 (concat "<td>" x "</td>")))
11916 fields "")
11917 "</tr>\n"))))
11918 (setq html (concat html "</table>\n"))
11919 html))
11921 (defun org-fake-empty-table-line (line)
11922 "Replace everything except \"|\" with spaces."
11923 (let ((i (length line))
11924 (newstr (copy-sequence line)))
11925 (while (> i 0)
11926 (setq i (1- i))
11927 (if (not (eq (aref newstr i) ?|))
11928 (aset newstr i ?\ )))
11929 newstr))
11931 (defun org-format-table-table-html (lines)
11932 "Format a table generated by table.el into HTML.
11933 This conversion does *not* use `table-generate-source' from table.el.
11934 This has the advantage that Org-mode's HTML conversions can be used.
11935 But it has the disadvantage, that no cell- or row-spanning is allowed."
11936 (let (line field-buffer
11937 (head org-export-highlight-first-table-line)
11938 fields html empty)
11939 (setq html (concat org-export-html-table-tag "\n"))
11940 (while (setq line (pop lines))
11941 (setq empty "&nbsp")
11942 (catch 'next-line
11943 (if (string-match "^[ \t]*\\+-" line)
11944 (progn
11945 (if field-buffer
11946 (progn
11947 (setq html (concat
11948 html
11949 "<tr>"
11950 (mapconcat
11951 (lambda (x)
11952 (if (equal x "") (setq x empty))
11953 (if head
11954 (concat "<th>" x "</th>\n")
11955 (concat "<td>" x "</td>\n")))
11956 field-buffer "\n")
11957 "</tr>\n"))
11958 (setq head nil)
11959 (setq field-buffer nil)))
11960 ;; Ignore this line
11961 (throw 'next-line t)))
11962 ;; Break the line into fields and store the fields
11963 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11964 (if field-buffer
11965 (setq field-buffer (mapcar
11966 (lambda (x)
11967 (concat x "<br>" (pop fields)))
11968 field-buffer))
11969 (setq field-buffer fields))))
11970 (setq html (concat html "</table>\n"))
11971 html))
11973 (defun org-format-table-table-html-using-table-generate-source (lines)
11974 "Format a table into html, using `table-generate-source' from table.el.
11975 This has the advantage that cell- or row-spanning is allowed.
11976 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
11977 (require 'table)
11978 (with-current-buffer (get-buffer-create " org-tmp1 ")
11979 (erase-buffer)
11980 (insert (mapconcat 'identity lines "\n"))
11981 (goto-char (point-min))
11982 (if (not (re-search-forward "|[^+]" nil t))
11983 (error "Error processing table"))
11984 (table-recognize-table)
11985 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
11986 (table-generate-source 'html " org-tmp2 ")
11987 (set-buffer " org-tmp2 ")
11988 (buffer-substring (point-min) (point-max))))
11990 (defun org-html-protect (s)
11991 ;; convert & to &amp;, < to &lt; and > to &gt;
11992 (let ((start 0))
11993 (while (string-match "&" s start)
11994 (setq s (replace-match "&amp;" t t s)
11995 start (1+ (match-beginning 0))))
11996 (while (string-match "<" s)
11997 (setq s (replace-match "&lt;" t t s)))
11998 (while (string-match ">" s)
11999 (setq s (replace-match "&gt;" t t s))))
12002 (defun org-html-expand (string)
12003 "Prepare STRING for HTML export. Applies all active conversions.
12004 If there are links in the string, don't modify these."
12005 (let* (m s l res)
12006 (while (setq m (string-match org-bracket-link-regexp string))
12007 (setq s (substring string 0 m)
12008 l (match-string 0 string)
12009 string (substring string (match-end 0)))
12010 (push (org-html-do-expand s) res)
12011 (push l res))
12012 (push (org-html-do-expand string) res)
12013 (apply 'concat (nreverse res))))
12015 (defun org-html-do-expand (s)
12016 "Apply all active conversions to translate special ASCII to HTML."
12017 (setq s (org-html-protect s))
12018 (if org-export-html-expand
12019 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
12020 (setq s (replace-match "<\\1>" nil nil s))))
12021 (if org-export-with-emphasize
12022 (setq s (org-export-html-convert-emphasize s)))
12023 (if org-export-with-sub-superscripts
12024 (setq s (org-export-html-convert-sub-super s)))
12025 (if org-export-with-TeX-macros
12026 (let ((start 0) wd ass)
12027 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
12028 (setq wd (match-string 1 s))
12029 (if (setq ass (assoc wd org-html-entities))
12030 (setq s (replace-match (or (cdr ass)
12031 (concat "&" (car ass) ";"))
12032 t t s))
12033 (setq start (+ start (length wd)))))))
12036 (defun org-create-multibrace-regexp (left right n)
12037 "Create a regular expression which will match a balanced sexp.
12038 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
12039 as single character strings.
12040 The regexp returned will match the entire expression including the
12041 delimiters. It will also define a single group which contains the
12042 match except for the outermost delimiters. The maximum depth of
12043 stacked delimiters is N. Escaping delimiters is not possible."
12044 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
12045 (or "\\|")
12046 (re nothing)
12047 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
12048 (while (> n 1)
12049 (setq n (1- n)
12050 re (concat re or next)
12051 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
12052 (concat left "\\(" re "\\)" right)))
12054 (defvar org-match-substring-regexp
12055 (concat
12056 "\\([^\\]\\)\\([_^]\\)\\("
12057 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
12058 "\\|"
12059 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
12060 "\\|"
12061 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
12062 "The regular expression matching a sub- or superscript.")
12064 (defun org-export-html-convert-sub-super (string)
12065 "Convert sub- and superscripts in STRING to HTML."
12066 (let (key c)
12067 (while (string-match org-match-substring-regexp string)
12068 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
12069 (setq c (or (match-string 8 string)
12070 (match-string 6 string)
12071 (match-string 5 string)))
12072 (setq string (replace-match
12073 (concat (match-string 1 string)
12074 "<" key ">" c "</" key ">")
12075 t t string)))
12076 (while (string-match "\\\\\\([_^]\\)" string)
12077 (setq string (replace-match (match-string 1 string) t t string))))
12078 string)
12080 (defun org-export-html-convert-emphasize (string)
12081 (let (c (s 0))
12082 (while (string-match "\\(\\W\\|^\\)\\([*/_]\\)\\(\\w+\\)\\2\\(\\W\\|$\\)" string s)
12083 (setq c (cdr (assoc (match-string 2 string)
12084 '(("*" . "b") ("/" . "i") ("_" . "u"))))
12085 s (+ (match-end 0) 3)
12086 string (replace-match
12087 (concat "\\1<" c ">\\3</" c ">\\4") t nil string)))
12088 string))
12090 (defun org-parse-key-lines ()
12091 "Find the special key lines with the information for exporters."
12092 (save-excursion
12093 (goto-char 0)
12094 (let ((re (org-make-options-regexp
12095 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12096 key)
12097 (while (re-search-forward re nil t)
12098 (setq key (match-string 1))
12099 (cond ((string-equal key "TITLE")
12100 (setq title (match-string 2)))
12101 ((string-equal key "AUTHOR")
12102 (setq author (match-string 2)))
12103 ((string-equal key "EMAIL")
12104 (setq email (match-string 2)))
12105 ((string-equal key "LANGUAGE")
12106 (setq language (match-string 2)))
12107 ((string-equal key "TEXT")
12108 (setq text (concat text "\n" (match-string 2))))
12109 ((string-equal key "OPTIONS")
12110 (setq options (match-string 2))))))))
12112 (defun org-parse-export-options (s)
12113 "Parse the export options line."
12114 (let ((op '(("H" . org-export-headline-levels)
12115 ("num" . org-export-with-section-numbers)
12116 ("toc" . org-export-with-toc)
12117 ("\\n" . org-export-preserve-breaks)
12118 ("@" . org-export-html-expand)
12119 (":" . org-export-with-fixed-width)
12120 ("|" . org-export-with-tables)
12121 ("^" . org-export-with-sub-superscripts)
12122 ("*" . org-export-with-emphasize)
12123 ("TeX" . org-export-with-TeX-macros)))
12125 (while (setq o (pop op))
12126 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
12128 (set (make-local-variable (cdr o))
12129 (car (read-from-string (match-string 1 s))))))))
12131 (defun org-html-level-start (level title umax with-toc head-count)
12132 "Insert a new level in HTML export."
12133 (let ((l (1+ (max level umax))))
12134 (while (<= l org-level-max)
12135 (if (aref levels-open (1- l))
12136 (progn
12137 (org-html-level-close l)
12138 (aset levels-open (1- l) nil)))
12139 (setq l (1+ l)))
12140 (if (> level umax)
12141 (progn
12142 (if (aref levels-open (1- level))
12143 (insert "<li>" title "<p>\n")
12144 (aset levels-open (1- level) t)
12145 (insert "<ul><li>" title "<p>\n")))
12146 (if org-export-with-section-numbers
12147 (setq title (concat (org-section-number level) " " title)))
12148 (setq level (+ level 1))
12149 (if with-toc
12150 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
12151 level head-count title level))
12152 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
12154 (defun org-html-level-close (&rest args)
12155 "Terminate one level in HTML export."
12156 (insert "</ul>"))
12158 ;; Variable holding the vector with section numbers
12159 (defvar org-section-numbers (make-vector org-level-max 0))
12161 (defun org-init-section-numbers ()
12162 "Initialize the vector for the section numbers."
12163 (let* ((level -1)
12164 (numbers (nreverse (org-split-string "" "\\.")))
12165 (depth (1- (length org-section-numbers)))
12166 (i depth) number-string)
12167 (while (>= i 0)
12168 (if (> i level)
12169 (aset org-section-numbers i 0)
12170 (setq number-string (or (car numbers) "0"))
12171 (if (string-match "\\`[A-Z]\\'" number-string)
12172 (aset org-section-numbers i
12173 (- (string-to-char number-string) ?A -1))
12174 (aset org-section-numbers i (string-to-number number-string)))
12175 (pop numbers))
12176 (setq i (1- i)))))
12178 (defun org-section-number (&optional level)
12179 "Return a string with the current section number.
12180 When LEVEL is non-nil, increase section numbers on that level."
12181 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
12182 (when level
12183 (when (> level -1)
12184 (aset org-section-numbers
12185 level (1+ (aref org-section-numbers level))))
12186 (setq idx (1+ level))
12187 (while (<= idx depth)
12188 (if (not (= idx 1))
12189 (aset org-section-numbers idx 0))
12190 (setq idx (1+ idx))))
12191 (setq idx 0)
12192 (while (<= idx depth)
12193 (setq n (aref org-section-numbers idx))
12194 (setq string (concat string (if (not (string= string "")) "." "")
12195 (int-to-string n)))
12196 (setq idx (1+ idx)))
12197 (save-match-data
12198 (if (string-match "\\`\\([@0]\\.\\)+" string)
12199 (setq string (replace-match "" nil nil string)))
12200 (if (string-match "\\(\\.0\\)+\\'" string)
12201 (setq string (replace-match "" nil nil string))))
12202 string))
12205 (defun org-export-icalendar-this-file ()
12206 "Export current file as an iCalendar file.
12207 The iCalendar file will be located in the same directory as the Org-mode
12208 file, but with extension `.ics'."
12209 (interactive)
12210 (org-export-icalendar nil buffer-file-name))
12212 ;;;###autoload
12213 (defun org-export-icalendar-all-agenda-files ()
12214 "Export all files in `org-agenda-files' to iCalendar .ics files.
12215 Each iCalendar file will be located in the same directory as the Org-mode
12216 file, but with extension `.ics'."
12217 (interactive)
12218 (apply 'org-export-icalendar nil (org-agenda-files t)))
12220 ;;;###autoload
12221 (defun org-export-icalendar-combine-agenda-files ()
12222 "Export all files in `org-agenda-files' to a single combined iCalendar file.
12223 The file is stored under the name `org-combined-agenda-icalendar-file'."
12224 (interactive)
12225 (apply 'org-export-icalendar t (org-agenda-files t)))
12227 (defun org-export-icalendar (combine &rest files)
12228 "Create iCalendar files for all elements of FILES.
12229 If COMBINE is non-nil, combine all calendar entries into a single large
12230 file and store it under the name `org-combined-agenda-icalendar-file'."
12231 (save-excursion
12232 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
12233 (when combine
12234 (setq ical-file org-combined-agenda-icalendar-file
12235 ical-buffer (org-get-agenda-file-buffer ical-file))
12236 (set-buffer ical-buffer) (erase-buffer))
12237 (while (setq file (pop files))
12238 (catch 'nextfile
12239 (org-check-agenda-file file)
12240 (unless combine
12241 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
12242 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
12243 (set-buffer ical-buffer) (erase-buffer))
12244 (set-buffer (org-get-agenda-file-buffer file))
12245 (setq category (or org-category
12246 (file-name-sans-extension
12247 (file-name-nondirectory buffer-file-name))))
12248 (if (symbolp category) (setq category (symbol-name category)))
12249 (let ((standard-output ical-buffer))
12250 (if combine
12251 (and (not started) (setq started t)
12252 (org-start-icalendar-file org-icalendar-combined-name))
12253 (org-start-icalendar-file category))
12254 (org-print-icalendar-entries combine category)
12255 (when (or (and combine (not files)) (not combine))
12256 (org-finish-icalendar-file)
12257 (set-buffer ical-buffer)
12258 (save-buffer)
12259 (run-hooks 'org-after-save-iCalendar-file-hook)))))
12260 (org-release-buffers org-agenda-new-buffers))))
12262 (defvar org-after-save-iCalendar-file-hook nil
12263 "Hook run after an iCalendar file has been saved.
12264 The iCalendar buffer is still current when this hook is run.
12265 A good way to use this is to tell a desktop calenndar application to re-read
12266 the iCalendar file.")
12268 (defun org-print-icalendar-entries (&optional combine category)
12269 "Print iCalendar entries for the current Org-mode file to `standard-output'.
12270 When COMBINE is non nil, add the category to each line."
12271 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
12272 (dts (org-ical-ts-to-string
12273 (format-time-string (cdr org-time-stamp-formats) (current-time))
12274 "DTSTART"))
12275 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
12276 (save-excursion
12277 (goto-char (point-min))
12278 (while (re-search-forward org-ts-regexp nil t)
12279 (setq pos (match-beginning 0)
12280 ts (match-string 0)
12281 inc t
12282 hd (org-get-heading))
12283 (if (looking-at re2)
12284 (progn
12285 (goto-char (match-end 0))
12286 (setq ts2 (match-string 1) inc nil))
12287 (setq ts2 ts
12288 tmp (buffer-substring (max (point-min)
12289 (- pos org-ds-keyword-length))
12290 pos)
12291 deadlinep (string-match org-deadline-regexp tmp)
12292 scheduledp (string-match org-scheduled-regexp tmp)
12293 ;; donep (org-entry-is-done-p)
12295 (if (or (string-match org-tr-regexp hd)
12296 (string-match org-ts-regexp hd))
12297 (setq hd (replace-match "" t t hd)))
12298 (if combine
12299 (setq hd (concat hd " (category " category ")")))
12300 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
12301 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
12302 (princ (format "BEGIN:VEVENT
12305 SUMMARY:%s
12306 END:VEVENT\n"
12307 (org-ical-ts-to-string ts "DTSTART")
12308 (org-ical-ts-to-string ts2 "DTEND" inc)
12309 hd)))
12310 (when org-icalendar-include-todo
12311 (goto-char (point-min))
12312 (while (re-search-forward org-todo-line-regexp nil t)
12313 (setq state (match-string 1))
12314 (unless (equal state org-done-string)
12315 (setq hd (match-string 3))
12316 (if (string-match org-priority-regexp hd)
12317 (setq pri (string-to-char (match-string 2 hd))
12318 hd (concat (substring hd 0 (match-beginning 1))
12319 (substring hd (- (match-end 1)))))
12320 (setq pri org-default-priority))
12321 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
12322 (- org-lowest-priority ?A))))))
12324 (princ (format "BEGIN:VTODO
12326 SUMMARY:%s
12327 SEQUENCE:1
12328 PRIORITY:%d
12329 END:VTODO\n"
12330 dts hd pri))))))))
12332 (defun org-start-icalendar-file (name)
12333 "Start an iCalendar file by inserting the header."
12334 (let ((user user-full-name)
12335 (name (or name "unknown"))
12336 (timezone (cadr (current-time-zone))))
12337 (princ
12338 (format "BEGIN:VCALENDAR
12339 VERSION:2.0
12340 X-WR-CALNAME:%s
12341 PRODID:-//%s//Emacs with Org-mode//EN
12342 X-WR-TIMEZONE:%s
12343 CALSCALE:GREGORIAN\n" name user timezone))))
12345 (defun org-finish-icalendar-file ()
12346 "Finish an iCalendar file by inserting the END statement."
12347 (princ "END:VCALENDAR\n"))
12349 (defun org-ical-ts-to-string (s keyword &optional inc)
12350 "Take a time string S and convert it to iCalendar format.
12351 KEYWORD is added in front, to make a complete line like DTSTART....
12352 When INC is non-nil, increase the hour by two (if time string contains
12353 a time), or the day by one (if it does not contain a time)."
12354 (let ((t1 (org-parse-time-string s 'nodefault))
12355 t2 fmt have-time time)
12356 (if (and (car t1) (nth 1 t1) (nth 2 t1))
12357 (setq t2 t1 have-time t)
12358 (setq t2 (org-parse-time-string s)))
12359 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
12360 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
12361 (when inc
12362 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
12363 (setq time (encode-time s mi h d m y)))
12364 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
12365 (concat keyword (format-time-string fmt time))))
12368 ;;; Key bindings
12370 ;; - Bindings in Org-mode map are currently
12371 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
12372 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
12373 ;; e (?) useful from outline-mode
12374 ;; i k @ expendable from outline-mode
12375 ;; 0123456789 % & ()_{} " ` free
12377 ;; Make `C-c C-x' a prefix key
12378 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
12380 ;; TAB key with modifiers
12381 (define-key org-mode-map "\C-i" 'org-cycle)
12382 (define-key org-mode-map [(tab)] 'org-cycle)
12383 (define-key org-mode-map [(meta tab)] 'org-complete)
12384 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
12385 ;; The following line is necessary under Suse GNU/Linux
12386 (unless (featurep 'xemacs)
12387 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
12388 (define-key org-mode-map [(shift tab)] 'org-shifttab)
12390 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
12391 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
12392 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12393 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
12394 (define-key org-mode-map [(meta return)] 'org-meta-return)
12395 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
12396 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
12398 ;; Cursor keys with modifiers
12399 (define-key org-mode-map [(meta left)] 'org-metaleft)
12400 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
12401 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
12402 (define-key org-mode-map [(meta right)] 'org-metaright)
12403 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
12404 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
12405 (define-key org-mode-map [(meta up)] 'org-metaup)
12406 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
12407 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
12408 (define-key org-mode-map [(meta down)] 'org-metadown)
12409 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
12410 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
12412 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12413 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
12414 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
12415 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
12416 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
12417 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
12418 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
12419 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
12420 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
12421 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
12422 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
12423 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
12424 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
12425 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
12426 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
12427 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
12429 ;; All the other keys
12430 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
12431 (define-key org-mode-map "\C-c\C-j" 'org-goto)
12432 (define-key org-mode-map "\C-c\C-t" 'org-todo)
12433 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
12434 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
12435 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
12436 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12437 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
12438 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
12439 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12440 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
12441 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
12442 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
12443 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
12444 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
12445 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
12446 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
12447 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12448 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12449 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12450 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12451 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
12452 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
12453 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12454 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
12455 (define-key org-mode-map "\C-c]" 'org-remove-file)
12456 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
12457 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
12458 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
12459 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12460 (define-key org-mode-map "\C-m" 'org-return)
12461 (define-key org-mode-map "\C-c?" 'org-table-current-column)
12462 (define-key org-mode-map "\C-c " 'org-table-blank-field)
12463 (define-key org-mode-map "\C-c+" 'org-table-sum)
12464 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
12465 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
12466 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
12467 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12468 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
12469 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12470 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
12471 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12472 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
12473 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
12474 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
12475 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
12476 ;; OPML support is only an option for the future
12477 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
12478 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
12479 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
12480 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
12481 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
12482 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
12483 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
12484 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12485 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
12486 (define-key org-mode-map "\C-c\C-xx" 'org-export-as-xml)
12487 (define-key org-mode-map "\C-c\C-x\C-x" 'org-export-as-xml)
12488 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
12489 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
12491 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12492 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12493 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12494 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12496 (defsubst org-table-p () (org-at-table-p))
12498 (defun org-self-insert-command (N)
12499 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12500 If the cursor is in a table looking at whitespace, the whitespace is
12501 overwritten, and the table is not marked as requiring realignment."
12502 (interactive "p")
12503 (if (and (org-table-p)
12504 (progn
12505 ;; check if we blank the field, and if that triggers align
12506 (and org-table-auto-blank-field
12507 (member last-command
12508 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12509 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12510 ;; got extra space, this field does not determine column width
12511 (let (org-table-may-need-update) (org-table-blank-field))
12512 ;; no extra space, this field may determine column width
12513 (org-table-blank-field)))
12515 (eq N 1)
12516 (looking-at "[^|\n]* |"))
12517 (let (org-table-may-need-update)
12518 (goto-char (1- (match-end 0)))
12519 (delete-backward-char 1)
12520 (goto-char (match-beginning 0))
12521 (self-insert-command N))
12522 (setq org-table-may-need-update t)
12523 (self-insert-command N)))
12525 (defun org-delete-backward-char (N)
12526 "Like `delete-backward-char', insert whitespace at field end in tables.
12527 When deleting backwards, in tables this function will insert whitespace in
12528 front of the next \"|\" separator, to keep the table aligned. The table will
12529 still be marked for re-alignment if the field did fill the entire column,
12530 because, in this case the deletion might narrow the column."
12531 (interactive "p")
12532 (if (and (org-table-p)
12533 (eq N 1)
12534 (string-match "|" (buffer-substring (point-at-bol) (point)))
12535 (looking-at ".*?|"))
12536 (let ((pos (point))
12537 (noalign (looking-at "[^|\n\r]* |"))
12538 (c org-table-may-need-update))
12539 (backward-delete-char N)
12540 (skip-chars-forward "^|")
12541 (insert " ")
12542 (goto-char (1- pos))
12543 ;; noalign: if there were two spaces at the end, this field
12544 ;; does not determine the width of the column.
12545 (if noalign (setq org-table-may-need-update c)))
12546 (backward-delete-char N)))
12548 (defun org-delete-char (N)
12549 "Like `delete-char', but insert whitespace at field end in tables.
12550 When deleting characters, in tables this function will insert whitespace in
12551 front of the next \"|\" separator, to keep the table aligned. The table will
12552 still be marked for re-alignment if the field did fill the entire column,
12553 because, in this case the deletion might narrow the column."
12554 (interactive "p")
12555 (if (and (org-table-p)
12556 (not (bolp))
12557 (not (= (char-after) ?|))
12558 (eq N 1))
12559 (if (looking-at ".*?|")
12560 (let ((pos (point))
12561 (noalign (looking-at "[^|\n\r]* |"))
12562 (c org-table-may-need-update))
12563 (replace-match (concat
12564 (substring (match-string 0) 1 -1)
12565 " |"))
12566 (goto-char pos)
12567 ;; noalign: if there were two spaces at the end, this field
12568 ;; does not determine the width of the column.
12569 (if noalign (setq org-table-may-need-update c))))
12570 (delete-char N)))
12572 ;; How to do this: Measure non-white length of current string
12573 ;; If equal to column width, we should realign.
12575 (defun org-remap (map &rest commands)
12576 "In MAP, remap the functions given in COMMANDS.
12577 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12578 (let (new old)
12579 (while commands
12580 (setq old (pop commands) new (pop commands))
12581 (if (fboundp 'command-remapping)
12582 (define-key map (vector 'remap old) new)
12583 (substitute-key-definition old new map global-map)))))
12585 (when (eq org-enable-table-editor 'optimized)
12586 ;; If the user wants maximum table support, we need to hijack
12587 ;; some standard editing functions
12588 (org-remap org-mode-map
12589 'self-insert-command 'org-self-insert-command
12590 'delete-char 'org-delete-char
12591 'delete-backward-char 'org-delete-backward-char)
12592 (define-key org-mode-map "|" 'org-force-self-insert))
12594 (defun org-shiftcursor-error ()
12595 "Throw an error because Shift-Cursor command was applied in wrong context."
12596 (error "This command is active in special context like tables, headlines or timestamps"))
12598 (defun org-shifttab ()
12599 "Global visibility cycling or move to previous table field.
12600 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
12601 See the individual commands for more information."
12602 (interactive)
12603 (cond
12604 ((org-at-table-p) (org-table-previous-field))
12605 (t (org-cycle '(4)))))
12607 (defun org-shiftmetaleft ()
12608 "Promote subtree or delete table column.
12609 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
12610 See the individual commands for more information."
12611 (interactive)
12612 (cond
12613 ((org-at-table-p) (org-table-delete-column))
12614 ((org-on-heading-p) (org-promote-subtree))
12615 ((org-at-item-p) (call-interactively 'org-outdent-item))
12616 (t (org-shiftcursor-error))))
12618 (defun org-shiftmetaright ()
12619 "Demote subtree or insert table column.
12620 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
12621 See the individual commands for more information."
12622 (interactive)
12623 (cond
12624 ((org-at-table-p) (org-table-insert-column))
12625 ((org-on-heading-p) (org-demote-subtree))
12626 ((org-at-item-p) (call-interactively 'org-indent-item))
12627 (t (org-shiftcursor-error))))
12629 (defun org-shiftmetaup (&optional arg)
12630 "Move subtree up or kill table row.
12631 Calls `org-move-subtree-up' or `org-table-kill-row' or
12632 `org-move-item-up' depending on context. See the individual commands
12633 for more information."
12634 (interactive "P")
12635 (cond
12636 ((org-at-table-p) (org-table-kill-row))
12637 ((org-on-heading-p) (org-move-subtree-up arg))
12638 ((org-at-item-p) (org-move-item-up arg))
12639 (t (org-shiftcursor-error))))
12640 (defun org-shiftmetadown (&optional arg)
12641 "Move subtree down or insert table row.
12642 Calls `org-move-subtree-down' or `org-table-insert-row' or
12643 `org-move-item-down', depending on context. See the individual
12644 commands for more information."
12645 (interactive "P")
12646 (cond
12647 ((org-at-table-p) (org-table-insert-row arg))
12648 ((org-on-heading-p) (org-move-subtree-down arg))
12649 ((org-at-item-p) (org-move-item-down arg))
12650 (t (org-shiftcursor-error))))
12652 (defun org-metaleft (&optional arg)
12653 "Promote heading or move table column to left.
12654 Calls `org-do-promote' or `org-table-move-column', depending on context.
12655 With no specific context, calls the Emacs default `backward-word'.
12656 See the individual commands for more information."
12657 (interactive "P")
12658 (cond
12659 ((org-at-table-p) (org-table-move-column 'left))
12660 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
12661 (t (backward-word (prefix-numeric-value arg)))))
12663 (defun org-metaright (&optional arg)
12664 "Demote subtree or move table column to right.
12665 Calls `org-do-demote' or `org-table-move-column', depending on context.
12666 With no specific context, calls the Emacs default `forward-word'.
12667 See the individual commands for more information."
12668 (interactive "P")
12669 (cond
12670 ((org-at-table-p) (org-table-move-column nil))
12671 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
12672 (t (forward-word (prefix-numeric-value arg)))))
12674 (defun org-metaup (&optional arg)
12675 "Move subtree up or move table row up.
12676 Calls `org-move-subtree-up' or `org-table-move-row' or
12677 `org-move-item-up', depending on context. See the individual commands
12678 for more information."
12679 (interactive "P")
12680 (cond
12681 ((org-at-table-p) (org-table-move-row 'up))
12682 ((org-on-heading-p) (org-move-subtree-up arg))
12683 ((org-at-item-p) (org-move-item-up arg))
12684 (t (org-shiftcursor-error))))
12686 (defun org-metadown (&optional arg)
12687 "Move subtree down or move table row down.
12688 Calls `org-move-subtree-down' or `org-table-move-row' or
12689 `org-move-item-down', depending on context. See the individual
12690 commands for more information."
12691 (interactive "P")
12692 (cond
12693 ((org-at-table-p) (org-table-move-row nil))
12694 ((org-on-heading-p) (org-move-subtree-down arg))
12695 ((org-at-item-p) (org-move-item-down arg))
12696 (t (org-shiftcursor-error))))
12698 (defun org-shiftup (&optional arg)
12699 "Increase item in timestamp or increase priority of current item.
12700 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12701 See the individual commands for more information."
12702 (interactive "P")
12703 (cond
12704 ((org-at-timestamp-p) (org-timestamp-up arg))
12705 (t (org-priority-up))))
12707 (defun org-shiftdown (&optional arg)
12708 "Decrease item in timestamp or decrease priority of current item.
12709 Calls `org-timestamp-down' or `org-priority-down', depending on context.
12710 See the individual commands for more information."
12711 (interactive "P")
12712 (cond
12713 ((org-at-timestamp-p) (org-timestamp-down arg))
12714 (t (org-priority-down))))
12716 (defun org-shiftright ()
12717 "Next TODO keyword or timestamp one day later, depending on context."
12718 (interactive)
12719 (cond
12720 ((org-at-timestamp-p) (org-timestamp-up-day))
12721 ((org-on-heading-p) (org-todo 'right))
12722 (t (org-shiftcursor-error))))
12724 (defun org-shiftleft ()
12725 "Previous TODO keyword or timestamp one day earlier, depending on context."
12726 (interactive)
12727 (cond
12728 ((org-at-timestamp-p) (org-timestamp-down-day))
12729 ((org-on-heading-p) (org-todo 'left))
12730 (t (org-shiftcursor-error))))
12732 (defun org-copy-special ()
12733 "Copy region in table or copy current subtree.
12734 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12735 See the individual commands for more information."
12736 (interactive)
12737 (call-interactively
12738 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12740 (defun org-cut-special ()
12741 "Cut region in table or cut current subtree.
12742 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12743 See the individual commands for more information."
12744 (interactive)
12745 (call-interactively
12746 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12748 (defun org-paste-special (arg)
12749 "Paste rectangular region into table, or past subtree relative to level.
12750 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12751 See the individual commands for more information."
12752 (interactive "P")
12753 (if (org-at-table-p)
12754 (org-table-paste-rectangle)
12755 (org-paste-subtree arg)))
12757 (defun org-ctrl-c-ctrl-c (&optional arg)
12758 "Call realign table, or recognize a table.el table, or update keywords.
12759 When the cursor is inside a table created by the table.el package,
12760 activate that table. Otherwise, if the cursor is at a normal table
12761 created with org.el, re-align that table. This command works even if
12762 the automatic table editor has been turned off.
12764 If the cursor is in a headline, prompt for tags and insert them into
12765 the current line, aligned to `org-tags-column'. When in a headline and
12766 called with prefix arg, realign all tags in the current buffer.
12768 If the cursor is in one of the special #+KEYWORD lines, this triggers
12769 scanning the buffer for these lines and updating the information.
12770 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
12771 (interactive "P")
12772 (let ((org-enable-table-editor t))
12773 (cond
12774 ((and (local-variable-p 'org-finish-function (current-buffer))
12775 (fboundp org-finish-function))
12776 (funcall org-finish-function))
12777 ((org-on-target-p) (org-update-radio-target-regexp))
12778 ((org-on-heading-p) (org-set-tags arg))
12779 ((org-at-table.el-p)
12780 (require 'table)
12781 (beginning-of-line 1)
12782 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12783 (table-recognize-table))
12784 ((org-at-table-p)
12785 (org-table-maybe-eval-formula)
12786 (if arg
12787 (org-table-recalculate t)
12788 (org-table-maybe-recalculate-line))
12789 (org-table-align))
12790 ((org-at-item-p)
12791 (org-renumber-ordered-list (prefix-numeric-value arg)))
12792 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12793 (cond
12794 ((equal (match-string 1) "TBLFM")
12795 ;; Recalculate the table before this line
12796 (save-excursion
12797 (beginning-of-line 1)
12798 (skip-chars-backward " \r\n\t")
12799 (if (org-at-table-p) (org-table-recalculate t))))
12801 (org-mode-restart))))
12802 (t (error "C-c C-c can do nothing useful at this location.")))))
12804 (defun org-mode-restart ()
12805 "Restart Org-mode, to scan again for special lines.
12806 Also updates the keyword regular expressions."
12807 (interactive)
12808 (let ((org-inhibit-startup t)) (org-mode))
12809 (message "Org-mode restarted to refresh keyword and special line setup"))
12811 (defun org-return ()
12812 "Goto next table row or insert a newline.
12813 Calls `org-table-next-row' or `newline', depending on context.
12814 See the individual commands for more information."
12815 (interactive)
12816 (cond
12817 ((org-at-table-p)
12818 (org-table-justify-field-maybe)
12819 (org-table-next-row))
12820 (t (newline))))
12822 (defun org-meta-return (&optional arg)
12823 "Insert a new heading or wrap a region in a table.
12824 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12825 See the individual commands for more information."
12826 (interactive "P")
12827 (cond
12828 ((org-at-table-p)
12829 (org-table-wrap-region arg))
12830 (t (org-insert-heading arg))))
12832 ;;; Menu entries
12834 ;; Define the Org-mode menus
12835 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12836 '("Tbl"
12837 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
12838 ["Next Field" org-cycle (org-at-table-p)]
12839 ["Previous Field" org-shifttab (org-at-table-p)]
12840 ["Next Row" org-return (org-at-table-p)]
12841 "--"
12842 ["Blank Field" org-table-blank-field (org-at-table-p)]
12843 ["Edit Field" org-table-edit-field (org-at-table-p)]
12844 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12845 "--"
12846 ("Column"
12847 ["Move Column Left" org-metaleft (org-at-table-p)]
12848 ["Move Column Right" org-metaright (org-at-table-p)]
12849 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12850 ["Insert Column" org-shiftmetaright (org-at-table-p)]
12851 "--"
12852 ["Enable Narrowing" (setq org-table-limit-column-width (not org-table-limit-column-width)) :active (org-at-table-p) :selected org-table-limit-column-width :style toggle])
12853 ("Row"
12854 ["Move Row Up" org-metaup (org-at-table-p)]
12855 ["Move Row Down" org-metadown (org-at-table-p)]
12856 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12857 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12858 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12859 "--"
12860 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
12861 ("Rectangle"
12862 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12863 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12864 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12865 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12866 "--"
12867 ("Calculate"
12868 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12869 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12870 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12871 "--"
12872 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12873 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12874 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12875 "--"
12876 ["Sum Column/Rectangle" org-table-sum
12877 (or (org-at-table-p) (org-region-active-p))]
12878 ["Which Column?" org-table-current-column (org-at-table-p)])
12879 ["Debug Formulas"
12880 (setq org-table-formula-debug (not org-table-formula-debug))
12881 :style toggle :selected org-table-formula-debug]
12882 "--"
12883 ["Create" org-table-create (and (not (org-at-table-p))
12884 org-enable-table-editor)]
12885 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12886 ["Import from File" org-table-import (not (org-at-table-p))]
12887 ["Export to File" org-table-export (org-at-table-p)]
12888 "--"
12889 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12891 (easy-menu-define org-org-menu org-mode-map "Org menu"
12892 '("Org"
12893 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
12894 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
12895 ["Sparse Tree" org-occur t]
12896 ["Show All" show-all t]
12897 "--"
12898 ["New Heading" org-insert-heading t]
12899 ("Navigate Headings"
12900 ["Up" outline-up-heading t]
12901 ["Next" outline-next-visible-heading t]
12902 ["Previous" outline-previous-visible-heading t]
12903 ["Next Same Level" outline-forward-same-level t]
12904 ["Previous Same Level" outline-backward-same-level t]
12905 "--"
12906 ["Jump" org-goto t])
12907 ("Edit Structure"
12908 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12909 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12910 "--"
12911 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12912 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12913 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12914 "--"
12915 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12916 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12917 ["Demote Heading" org-metaright (not (org-at-table-p))]
12918 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12919 "--"
12920 ["Archive Subtree" org-archive-subtree t]
12921 "--"
12922 ["Convert to odd levels" org-convert-to-odd-levels t]
12923 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12924 "--"
12925 ("TODO Lists"
12926 ["TODO/DONE/-" org-todo t]
12927 ["Show TODO Tree" org-show-todo-tree t]
12928 ["Global TODO list" org-todo-list t]
12929 "--"
12930 ["Set Priority" org-priority t]
12931 ["Priority Up" org-shiftup t]
12932 ["Priority Down" org-shiftdown t])
12933 ("Dates and Scheduling"
12934 ["Timestamp" org-time-stamp t]
12935 ["Timestamp (inactive)" org-time-stamp-inactive t]
12936 ("Change Date"
12937 ["1 Day Later" org-timestamp-up-day t]
12938 ["1 Day Earlier" org-timestamp-down-day t]
12939 ["1 ... Later" org-shiftup t]
12940 ["1 ... Earlier" org-shiftdown t])
12941 ["Compute Time Range" org-evaluate-time-range t]
12942 ["Schedule Item" org-schedule t]
12943 ["Deadline" org-deadline t]
12944 "--"
12945 ["Goto Calendar" org-goto-calendar t]
12946 ["Date from Calendar" org-date-from-calendar t])
12947 "--"
12948 ["Agenda Command" org-agenda t]
12949 ("File List for Agenda")
12950 ("Special views current file"
12951 ["TODO Tree" org-show-todo-tree t]
12952 ["Check Deadlines" org-check-deadlines t]
12953 ["Timeline" org-timeline t]
12954 ["Tags Tree" org-tags-sparse-tree t])
12955 "--"
12956 ("Hyperlinks"
12957 ["Store Link (Global)" org-store-link t]
12958 ["Insert Link" org-insert-link t]
12959 ["Follow Link" org-open-at-point t]
12960 "--"
12961 ["Descriptive Links"
12962 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12963 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
12964 ["Literal Links"
12965 (progn
12966 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12967 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
12968 "--"
12969 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
12970 (save-excursion (goto-char (point-min))
12971 (re-search-forward "<[a-z]+:" nil t))])
12972 "--"
12973 ("Export"
12974 ["ASCII" org-export-as-ascii t]
12975 ["Extract Visible Text" org-export-copy-visible t]
12976 ["HTML" org-export-as-html t]
12977 ["HTML and Open" org-export-as-html-and-open t]
12978 ["XML (XOXO)" org-export-as-xml t]
12979 "--"
12980 ["iCalendar this file" org-export-icalendar-this-file t]
12981 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
12982 :active t :keys "C-c C-x C-i"]
12983 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
12984 "--"
12985 ["Option Template" org-insert-export-options-template t]
12986 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
12987 "--"
12988 ("Documentation"
12989 ["Show Version" org-version t]
12990 ["Info Documentation" org-info t])
12991 ("Customize"
12992 ["Browse Org Group" org-customize t]
12993 "--"
12994 ["Expand This Menu" org-create-customize-menu
12995 (fboundp 'customize-menu-create)])
12996 "--"
12997 ["Refresh setup" org-mode-restart t]
13000 (defun org-info (&optional node)
13001 "Read documentation for Org-mode in the info system.
13002 With optional NODE, go directly to that node."
13003 (interactive)
13004 (require 'info)
13005 (Info-goto-node (format "(org)%s" (or node ""))))
13007 (defun org-install-agenda-files-menu ()
13008 (let ((bl (buffer-list)))
13009 (save-excursion
13010 (while bl
13011 (set-buffer (pop bl))
13012 (if (eq major-mode 'org-mode) (setq bl nil)))
13013 (when (eq major-mode 'org-mode)
13014 (easy-menu-change
13015 '("Org") "File List for Agenda"
13016 (append
13017 (list
13018 ["Edit File List" (org-edit-agenda-file-list) t]
13019 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13020 ["Remove Current File from List" org-remove-file t]
13021 ["Cycle through agenda files" org-cycle-agenda-files t]
13022 "--")
13023 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13025 ;;; Documentation
13027 (defun org-customize ()
13028 "Call the customize function with org as argument."
13029 (interactive)
13030 (customize-browse 'org))
13032 (defun org-create-customize-menu ()
13033 "Create a full customization menu for Org-mode, insert it into the menu."
13034 (interactive)
13035 (if (fboundp 'customize-menu-create)
13036 (progn
13037 (easy-menu-change
13038 '("Org") "Customize"
13039 `(["Browse Org group" org-customize t]
13040 "--"
13041 ,(customize-menu-create 'org)
13042 ["Set" Custom-set t]
13043 ["Save" Custom-save t]
13044 ["Reset to Current" Custom-reset-current t]
13045 ["Reset to Saved" Custom-reset-saved t]
13046 ["Reset to Standard Settings" Custom-reset-standard t]))
13047 (message "\"Org\"-menu now contains full customization menu"))
13048 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13050 ;;; Miscellaneous stuff
13052 (defun org-move-line-down (arg)
13053 "Move the current line down. With prefix argument, move it past ARG lines."
13054 (interactive "p")
13055 (let ((col (current-column))
13056 beg end pos)
13057 (beginning-of-line 1) (setq beg (point))
13058 (beginning-of-line 2) (setq end (point))
13059 (beginning-of-line (+ 1 arg))
13060 (setq pos (move-marker (make-marker) (point)))
13061 (insert (delete-and-extract-region beg end))
13062 (goto-char pos)
13063 (move-to-column col)))
13065 (defun org-move-line-up (arg)
13066 "Move the current line up. With prefix argument, move it past ARG lines."
13067 (interactive "p")
13068 (let ((col (current-column))
13069 beg end pos)
13070 (beginning-of-line 1) (setq beg (point))
13071 (beginning-of-line 2) (setq end (point))
13072 (beginning-of-line (- arg))
13073 (setq pos (move-marker (make-marker) (point)))
13074 (insert (delete-and-extract-region beg end))
13075 (goto-char pos)
13076 (move-to-column col)))
13078 ;; Paragraph filling stuff.
13079 ;; We want this to be just right, so use the full arsenal.
13080 ;; FIXME: This very likely does not work correctly for XEmacs, because the
13081 ;; filladapt package works slightly differently.
13083 (defun org-set-autofill-regexps ()
13084 (interactive)
13085 ;; In the paragraph separator we include headlines, because filling
13086 ;; text in a line directly attached to a headline would otherwise
13087 ;; fill the headline as well.
13088 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
13089 ;; The paragraph starter includes hand-formatted lists.
13090 (set (make-local-variable 'paragraph-start)
13091 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13092 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13093 ;; But only if the user has not turned off tables or fixed-width regions
13094 (set (make-local-variable 'auto-fill-inhibit-regexp)
13095 (concat "\\*\\|#"
13096 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13097 (concat
13098 "\\|[ \t]*["
13099 (if org-enable-table-editor "|" "")
13100 (if org-enable-fixed-width-editor ":" "")
13101 "]"))))
13102 ;; We use our own fill-paragraph function, to make sure that tables
13103 ;; and fixed-width regions are not wrapped. That function will pass
13104 ;; through to `fill-paragraph' when appropriate.
13105 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
13106 ;; Adaptive filling: To get full control, first make sure that
13107 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
13108 (setq adaptive-fill-regexp "\000")
13109 (setq adaptive-fill-function 'org-adaptive-fill-function))
13111 (defun org-fill-paragraph (&optional justify)
13112 "Re-align a table, pass through to fill-paragraph if no table."
13113 (let ((table-p (org-at-table-p))
13114 (table.el-p (org-at-table.el-p)))
13115 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
13116 (table.el-p t) ; skip table.el tables
13117 (table-p (org-table-align) t) ; align org-mode tables
13118 (t nil)))) ; call paragraph-fill
13120 ;; For reference, this is the default value of adaptive-fill-regexp
13121 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13123 (defun org-adaptive-fill-function ()
13124 "Return a fill prefix for org-mode files.
13125 In particular, this makes sure hanging paragraphs for hand-formatted lists
13126 work correctly."
13127 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
13128 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
13130 ;; Functions needed for Emacs/XEmacs region compatibility
13132 (defun org-add-hook (hook function &optional append local)
13133 "Add-hook, compatible with both Emacsen."
13134 (if (and local (featurep 'xemacs))
13135 (add-local-hook hook function append)
13136 (add-hook hook function append local)))
13138 (defun org-region-active-p ()
13139 "Is `transient-mark-mode' on and the region active?
13140 Works on both Emacs and XEmacs."
13141 (if org-ignore-region
13143 (if (featurep 'xemacs)
13144 (and zmacs-regions (region-active-p))
13145 (and transient-mark-mode mark-active))))
13147 (defun org-add-to-invisibility-spec (arg)
13148 "Add elements to `buffer-invisibility-spec'.
13149 See documentation for `buffer-invisibility-spec' for the kind of elements
13150 that can be added."
13151 (cond
13152 ((fboundp 'add-to-invisibility-spec)
13153 (add-to-invisibility-spec arg))
13154 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
13155 (setq buffer-invisibility-spec (list arg)))
13157 (setq buffer-invisibility-spec
13158 (cons arg buffer-invisibility-spec)))))
13160 (defun org-remove-from-invisibility-spec (arg)
13161 "Remove elements from `buffer-invisibility-spec'."
13162 (if (fboundp 'remove-from-invisibility-spec)
13163 (remove-from-invisibility-spec arg)
13164 (if (consp buffer-invisibility-spec)
13165 (setq buffer-invisibility-spec
13166 (delete arg buffer-invisibility-spec)))))
13168 (defun org-in-invisibility-spec-p (arg)
13169 "Is ARG a member of `buffer-invisibility-spec'?"
13170 (if (consp buffer-invisibility-spec)
13171 (member arg buffer-invisibility-spec)
13172 nil))
13174 (defun org-image-file-name-regexp ()
13175 "Return regexp matching the file names of images."
13176 (if (fboundp 'image-file-name-regexp)
13177 (image-file-name-regexp)
13178 (let ((image-file-name-extensions
13179 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13180 "xbm" "xpm" "pbm" "pgm" "ppm")))
13181 (concat "\\."
13182 (regexp-opt (nconc (mapcar 'upcase
13183 image-file-name-extensions)
13184 image-file-name-extensions)
13186 "\\'"))))
13188 ;; Functions needed for compatibility with old outline.el.
13190 ;; Programming for the old outline.el (that uses selective display
13191 ;; instead of `invisible' text properties) is a nightmare, mostly
13192 ;; because regular expressions can no longer be anchored at
13193 ;; beginning/end of line. Therefore a number of function need special
13194 ;; treatment when the old outline.el is being used.
13196 ;; The following functions capture almost the entire compatibility code
13197 ;; between the different versions of outline-mode. The only other
13198 ;; places where this is important are the font-lock-keywords, and in
13199 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
13201 ;; C-a should go to the beginning of a *visible* line, also in the
13202 ;; new outline.el. I guess this should be patched into Emacs?
13203 (defun org-beginning-of-line ()
13204 "Go to the beginning of the current line. If that is invisible, continue
13205 to a visible line beginning. This makes the function of C-a more intuitive."
13206 (interactive)
13207 (beginning-of-line 1)
13208 (if (bobp)
13210 (backward-char 1)
13211 (if (org-invisible-p)
13212 (while (and (not (bobp)) (org-invisible-p))
13213 (backward-char 1)
13214 (beginning-of-line 1))
13215 (forward-char 1))))
13217 (when org-noutline-p
13218 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
13219 ;; FIXME: should I use substitute-key-definition to reach other bindings
13220 ;; of beginning-of-line?
13222 (defun org-invisible-p ()
13223 "Check if point is at a character currently not visible."
13224 (if org-noutline-p
13225 ;; Early versions of noutline don't have `outline-invisible-p'.
13226 (if (fboundp 'outline-invisible-p)
13227 (outline-invisible-p)
13228 (get-char-property (point) 'invisible))
13229 (save-excursion
13230 (skip-chars-backward "^\r\n")
13231 (equal (char-before) ?\r))))
13233 (defun org-invisible-p2 ()
13234 "Check if point is at a character currently not visible."
13235 (save-excursion
13236 (if org-noutline-p
13237 (progn
13238 (if (and (eolp) (not (bobp))) (backward-char 1))
13239 ;; Early versions of noutline don't have `outline-invisible-p'.
13240 (if (fboundp 'outline-invisible-p)
13241 (outline-invisible-p)
13242 (get-char-property (point) 'invisible)))
13243 (skip-chars-backward "^\r\n")
13244 (equal (char-before) ?\r))))
13246 (defun org-back-to-heading (&optional invisible-ok)
13247 "Move to previous heading line, or beg of this line if it's a heading.
13248 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
13249 (if org-noutline-p
13250 (outline-back-to-heading invisible-ok)
13251 (if (and (memq (char-before) '(?\n ?\r))
13252 (looking-at outline-regexp))
13254 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
13255 outline-regexp)
13256 nil t)
13257 (if invisible-ok
13258 (progn (goto-char (match-end 1))
13259 (looking-at outline-regexp)))
13260 (error "Before first heading")))))
13262 (defun org-on-heading-p (&optional invisible-ok)
13263 "Return t if point is on a (visible) heading line.
13264 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
13265 (if org-noutline-p
13266 (outline-on-heading-p 'invisible-ok)
13267 (save-excursion
13268 (skip-chars-backward "^\n\r")
13269 (and (looking-at outline-regexp)
13270 (or invisible-ok
13271 (bobp)
13272 (equal (char-before) ?\n))))))
13274 (defun org-on-target-p ()
13275 (let ((pos (point)))
13276 (save-excursion
13277 (skip-chars-forward "<")
13278 (and (re-search-backward "<<" nil t)
13279 (or (looking-at org-radio-target-regexp)
13280 (looking-at org-target-regexp))
13281 (<= (match-beginning 0) pos)
13282 (>= (1+ (match-end 0)) pos)))))
13284 (defun org-up-heading-all (arg)
13285 "Move to the heading line of which the present line is a subheading.
13286 This function considers both visible and invisible heading lines.
13287 With argument, move up ARG levels."
13288 (if org-noutline-p
13289 (if (fboundp 'outline-up-heading-all)
13290 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13291 (outline-up-heading arg t)) ; emacs 22 version of outline.el
13292 (org-back-to-heading t)
13293 (looking-at outline-regexp)
13294 (if (<= (- (match-end 0) (match-beginning 0)) arg)
13295 (error "Cannot move up %d levels" arg)
13296 (re-search-backward
13297 (concat "[\n\r]" (regexp-quote
13298 (make-string (- (match-end 0) (match-beginning 0) arg)
13299 ?*))
13300 "[^*]"))
13301 (forward-char 1))))
13303 (defun org-show-hidden-entry ()
13304 "Show an entry where even the heading is hidden."
13305 (save-excursion
13306 (if (not org-noutline-p)
13307 (progn
13308 (org-back-to-heading t)
13309 (org-flag-heading nil)))
13310 (org-show-entry)))
13312 (defun org-check-occur-regexp (regexp)
13313 "If REGEXP starts with \"^\", modify it to check for \\r as well.
13314 Of course, only for the old outline mode."
13315 (if org-noutline-p
13316 regexp
13317 (if (string-match "^\\^" regexp)
13318 (concat "[\n\r]" (substring regexp 1))
13319 regexp)))
13321 (defun org-flag-heading (flag &optional entry)
13322 "Flag the current heading. FLAG non-nil means make invisible.
13323 When ENTRY is non-nil, show the entire entry."
13324 (save-excursion
13325 (org-back-to-heading t)
13326 (if (not org-noutline-p)
13327 ;; Make the current headline visible
13328 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
13329 ;; Check if we should show the entire entry
13330 (if entry
13331 (progn
13332 (org-show-entry)
13333 (save-excursion ;; FIXME: Is this the fix for points in the -|
13334 ;; middle of text? |
13335 (and (outline-next-heading) ;; |
13336 (org-flag-heading nil)))) ; show the next heading _|
13337 (outline-flag-region (max 1 (1- (point)))
13338 (save-excursion (outline-end-of-heading) (point))
13339 (if org-noutline-p
13340 flag
13341 (if flag ?\r ?\n))))))
13343 (defun org-end-of-subtree (&optional invisible-OK)
13344 ;; This is an exact copy of the original function, but it uses
13345 ;; `org-back-to-heading', to make it work also in invisible
13346 ;; trees. And is uses an invisible-OK argument.
13347 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13348 (org-back-to-heading invisible-OK)
13349 (let ((first t)
13350 (level (funcall outline-level)))
13351 (while (and (not (eobp))
13352 (or first (> (funcall outline-level) level)))
13353 (setq first nil)
13354 (outline-next-heading))
13355 (if (memq (preceding-char) '(?\n ?\^M))
13356 (progn
13357 ;; Go to end of line before heading
13358 (forward-char -1)
13359 (if (memq (preceding-char) '(?\n ?\^M))
13360 ;; leave blank line before heading
13361 (forward-char -1))))))
13363 (defun org-show-subtree ()
13364 "Show everything after this heading at deeper levels."
13365 (outline-flag-region
13366 (point)
13367 (save-excursion
13368 (outline-end-of-subtree) (outline-next-heading) (point))
13369 (if org-noutline-p nil ?\n)))
13371 (defun org-show-entry ()
13372 "Show the body directly following this heading.
13373 Show the heading too, if it is currently invisible."
13374 (interactive)
13375 (save-excursion
13376 (org-back-to-heading t)
13377 (outline-flag-region
13378 (1- (point))
13379 (save-excursion
13380 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13381 (or (match-beginning 1) (point-max)))
13382 (if org-noutline-p nil ?\n))))
13385 (defun org-make-options-regexp (kwds)
13386 "Make a regular expression for keyword lines."
13387 (concat
13388 (if org-noutline-p "^" "[\n\r]")
13389 "#?[ \t]*\\+\\("
13390 (mapconcat 'regexp-quote kwds "\\|")
13391 "\\):[ \t]*"
13392 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
13394 ;; Make `bookmark-jump' show the jump location if it was hidden.
13395 (eval-after-load "bookmark"
13396 '(if (boundp 'bookmark-after-jump-hook)
13397 ;; We can use the hook
13398 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13399 ;; Hook not available, use advice
13400 (defadvice bookmark-jump (after org-make-visible activate)
13401 "Make the position visible."
13402 (org-bookmark-jump-unhide))))
13404 (defun org-bookmark-jump-unhide ()
13405 "Unhide the current position, to show the bookmark location."
13406 (and (eq major-mode 'org-mode)
13407 (or (org-invisible-p)
13408 (save-excursion (goto-char (max (point-min) (1- (point))))
13409 (org-invisible-p)))
13410 (org-show-hierarchy-above)))
13412 ;;; Finish up
13414 (provide 'org)
13416 (run-hooks 'org-load-hook)
13418 ;; Experimental code
13419 ;; FIXME: Move this code when it is ready.
13421 (defun org-upgrade-old-links (&optional query-description)
13422 "Transfer old <...> style links to new [[...]] style links.
13423 With arg query-description, ask at each match for a description text to use
13424 for this link."
13425 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
13426 (save-excursion
13427 (goto-char (point-min))
13428 (let ((re (concat "\\([^[]\\)<\\("
13429 "\\(" (mapconcat 'identity org-link-types "\\|")
13430 "\\):"
13431 "[^" org-non-link-chars "]+\\)>"))
13432 l1 l2 (cnt 0))
13433 (while (re-search-forward re nil t)
13434 (setq cnt (1+ cnt)
13435 l1 (org-match-string-no-properties 2)
13436 l2 (save-match-data (org-link-escape l1)))
13437 (when query-description (setq l1 (read-string "Desc: " l1)))
13438 (if (equal l1 l2)
13439 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
13440 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
13441 (message "%d matches have beed treated" cnt))))
13443 (defun org-export-as-xml ()
13444 "Export current buffer as XOXO XML buffer."
13445 (interactive)
13446 (cond ((eq org-export-xml-type 'xoxo)
13447 (org-export-as-xoxo (current-buffer)))))
13449 (defun org-export-as-xoxo-insert-into (buffer &rest output)
13450 (with-current-buffer buffer
13451 (apply 'insert output)))
13453 (defun org-export-as-xoxo (&optional buffer)
13454 "Export the org buffer as XOXO.
13455 The XOXO buffer is named *xoxo-<source buffer name>*"
13456 (interactive (list (current-buffer)))
13457 ;; A quickie abstraction
13459 ;; Output everything as XOXO
13460 (with-current-buffer (get-buffer buffer)
13461 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
13462 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
13463 ".xml"))
13464 (out (find-file-noselect filename))
13465 (last-level 1)
13466 (hanging-li nil))
13467 ;; Check the output buffer is empty.
13468 (with-current-buffer out (erase-buffer))
13469 ;; Kick off the output
13470 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
13471 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
13472 (let* ((hd (match-string-no-properties 1))
13473 (level (length hd))
13474 (text (concat
13475 (match-string-no-properties 2)
13476 (save-excursion
13477 (goto-char (match-end 0))
13478 (let ((str ""))
13479 (catch 'loop
13480 (while 't
13481 (forward-line)
13482 (if (looking-at "^[ \t]\\(.*\\)")
13483 (setq str (concat str (match-string-no-properties 1)))
13484 (throw 'loop str)))))))))
13486 ;; Handle level rendering
13487 (cond
13488 ((> level last-level)
13489 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
13491 ((< level last-level)
13492 (dotimes (- (- last-level level) 1)
13493 (if hanging-li
13494 (org-export-as-xoxo-insert-into out "</li>\n"))
13495 (org-export-as-xoxo-insert-into out "</ol>\n"))
13496 (when hanging-li
13497 (org-export-as-xoxo-insert-into out "</li>\n")
13498 (setq hanging-li nil)))
13500 ((equal level last-level)
13501 (if hanging-li
13502 (org-export-as-xoxo-insert-into out "</li>\n")))
13505 (setq last-level level)
13507 ;; And output the new li
13508 (setq hanging-li 't)
13509 (if (equal ?+ (elt text 0))
13510 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
13511 (org-export-as-xoxo-insert-into out "<li>" text))))
13513 ;; Finally finish off the ol
13514 (dotimes (- last-level 1)
13515 (if hanging-li
13516 (org-export-as-xoxo-insert-into out "</li>\n"))
13517 (org-export-as-xoxo-insert-into out "</ol>\n"))
13519 ;; Finish the buffer off and clean it up.
13520 (switch-to-buffer-other-window out)
13521 (indent-region (point-min) (point-max))
13522 (save-buffer)
13523 (goto-char (point-min))
13526 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13527 ;;; org.el ends here