Release 4.21
[org-mode.git] / org.el
blobafa62a7b1aa4d4d7b1784e390b1812efe80de94b
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.21
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.21
85 ;; - Bug fixes.
87 ;; Version 4.20
88 ;; - Links use now the [[link][description]] format by default.
89 ;; When inserting links, the user is prompted for a description.
90 ;; - If a link has a description, only the description is displayed
91 ;; the link part is hidden. Use C-c C-l to edit the link part.
92 ;; - TAGS are now bold, but in the same color as the headline.
93 ;; - The width of a table column can be limited by using a field "<N>".
94 ;; - New structure for the customization tree.
95 ;; - Bug fixes.
97 ;; Version 4.13
98 ;; - The list of agenda files can be maintainted in an external file.
99 ;; - Bug fixes.
101 ;; Version 4.12
102 ;; - Templates for remember buffer. Note that the remember setup changes.
103 ;; To set up templates, see `org-remember-templates'.
104 ;; - The time in new time stamps can be rounded, see new option
105 ;; `org-time-stamp-rounding-minutes'.
106 ;; - Bug fixes (there are *always* more bugs).
108 ;; Version 4.10
109 ;; - Bug fixes.
111 ;; Version 4.09
112 ;; - Bug fixes.
113 ;; - Small improvements to font-lock support.
114 ;; - MHE support finalized.
116 ;; Version 4.08
117 ;; - Bug fixes.
118 ;; - Improved MHE support
120 ;; Version 4.07
121 ;; - Bug fixes.
122 ;; - Leading stars in headlines can be hidden, so make the outline look
123 ;; cleaner.
124 ;; - Mouse-1 can be used to follow links.
126 ;; Version 4.06
127 ;; - HTML exporter treats targeted internal links.
128 ;; - Bug fixes.
130 ;; Version 4.05
131 ;; - Changes to internal link system (thanks to David Wainberg for ideas).
132 ;; - in-file links: [[Search String]] instead of <file:::Search String>
133 ;; - automatic links to "radio targets".
134 ;; - CamelCase not longer active by default, configure org-activate-camels
135 ;; if you want to turn it back on.
136 ;; - After following a link, `C-c &' jumps back to it.
137 ;; - MH-E link support (thanks to Thomas Baumann).
138 ;; - Special table lines are no longer exported.
139 ;; - Bug fixes and minor improvements.
141 ;; Version 4.04
142 ;; - Cleanup tags display in agenda.
143 ;; - Bug fixes.
145 ;; Version 4.03
146 ;; - Table alignment fixed for use with wide characters.
147 ;; - `C-c -' leaves cursor in current table line.
148 ;; - The current TAG can be incorporated into the agenda prefix.
149 ;; See option `org-agenda-prefix-format' for details.
151 ;; Version 4.02
152 ;; - Minor bug fixes and improvements around tag searches.
153 ;; - XEmacs compatibility fixes.
155 ;; Version 4.01
156 ;; - Tags can also be set remotely from agenda buffer.
157 ;; - Boolean logic for tag searches.
158 ;; - Additional agenda commands can be configured through the variable
159 ;; `org-agenda-custom-commands'.
160 ;; - Minor bug fixes.
162 ;;; Code:
164 (eval-when-compile
165 (require 'cl)
166 (require 'calendar))
167 (require 'outline)
168 (require 'time-date)
169 (require 'easymenu)
171 (defvar calc-embedded-close-formula) ; defined by the calc package
172 (defvar calc-embedded-open-formula) ; defined by the calc package
173 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
175 ;;; Customization variables
177 (defvar org-version "4.21"
178 "The version number of the file org.el.")
179 (defun org-version ()
180 (interactive)
181 (message "Org-mode version %s" org-version))
183 ;; The following constant is for compatibility with different versions
184 ;; of outline.el.
185 (defconst org-noutline-p (featurep 'noutline)
186 "Are we using the new outline mode?")
187 (defconst org-xemacs-p (featurep 'xemacs))
188 (defconst org-format-transports-properties-p
189 (let ((x "a"))
190 (add-text-properties 0 1 '(test t) x)
191 (get-text-property 0 'test (format "%s" x)))
192 "Does format transport text properties?")
194 (defgroup org nil
195 "Outline-based notes management and organizer."
196 :tag "Org"
197 :group 'outlines
198 :group 'hypermedia
199 :group 'calendar)
201 (defgroup org-startup nil
202 "Options concerning startup of Org-mode."
203 :tag "Org Startup"
204 :group 'org)
206 (defcustom org-startup-folded t
207 "Non-nil means, entering Org-mode will switch to OVERVIEW.
208 This can also be configured on a per-file basis by adding one of
209 the following lines anywhere in the buffer:
211 #+STARTUP: fold
212 #+STARTUP: nofold
213 #+STARTUP: content"
214 :group 'org-startup
215 :type '(choice
216 (const :tag "nofold: show all" nil)
217 (const :tag "fold: overview" t)
218 (const :tag "content: all headlines" content)))
220 (defcustom org-startup-truncated t
221 "Non-nil means, entering Org-mode will set `truncate-lines'.
222 This is useful since some lines containing links can be very long and
223 uninteresting. Also tables look terrible when wrapped."
224 :group 'org-startup
225 :type 'boolean)
227 (defcustom org-startup-align-all-tables nil
228 "Non-nil means, align all tables when visiting a file.
229 This is useful when the column width in tables is forced with <N> cookies
230 in table fields. Such tables will look correct only after the first re-align."
231 :group 'org-startup
232 :type 'boolean)
234 (defcustom org-startup-with-deadline-check nil
235 "Non-nil means, entering Org-mode will run the deadline check.
236 This means, if you start editing an org file, you will get an
237 immediate reminder of any due deadlines.
238 This can also be configured on a per-file basis by adding one of
239 the following lines anywhere in the buffer:
241 #+STARTUP: dlcheck
242 #+STARTUP: nodlcheck"
243 :group 'org-startup
244 :type 'boolean)
246 (defcustom org-insert-mode-line-in-empty-file nil
247 "Non-nil means insert the first line setting Org-mode in empty files.
248 When the function `org-mode' is called interactively in an empty file, this
249 normally means that the file name does not automatically trigger Org-mode.
250 To ensure that the file will always be in Org-mode in the future, a
251 line enforcing Org-mode will be inserted into the buffer, if this option
252 has been set."
253 :group 'org-startup
254 :type 'boolean)
256 (defcustom org-CUA-compatible nil
257 "Non-nil means use alternative key bindings for S-<cursor movement>.
258 Org-mode used S-<cursor movement> for changing timestamps and priorities.
259 S-<cursor movement> is also used for example by `CUA-mode' to select text.
260 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
261 alternative bindings. Setting this variable to t will replace the following
262 keys both in Org-mode and in the Org-agenda buffer.
264 S-RET -> C-S-RET
265 S-up -> M-p
266 S-down -> M-n
267 S-left -> M--
268 S-right -> M-+
270 If you do not like the alternative keys, take a look at the variable
271 `org-disputed-keys'.
273 This option is only relevant at load-time of Org-mode. Changing it requires
274 a restart of Emacs to become effective."
275 :group 'org-startup
276 :type 'boolean)
278 (defvar org-disputed-keys
279 '((S-up [(shift up)] [(meta ?p)])
280 (S-down [(shift down)] [(meta ?n)])
281 (S-left [(shift left)] [(meta ?-)])
282 (S-right [(shift right)] [(meta ?+)])
283 (S-return [(shift return)] [(control shift return)]))
284 "Keys for which Org-mode and other modes compete.
285 This is an alist, cars are symbols for lookup, 1st element is the default key,
286 second element will be used when `org-CUA-compatible' is t.")
288 (defun org-key (key)
289 "Select a key according to `org-CUA-compatible'."
290 (nth (if org-CUA-compatible 2 1)
291 (or (assq key org-disputed-keys)
292 (error "Invalid Key %s in `org-key'" key))))
294 (defcustom org-ellipsis nil
295 "The ellipsis to use in the Org-mode outline.
296 When nil, just use the standard three dots. When a string, use that instead,
297 and just in Org-mode (which will then use its own display table).
298 Changing this requires executing `M-x org-mode' in a buffer to become
299 effective."
300 :group 'org-startup
301 :type '(choice (const :tag "Default" nil)
302 (string :tag "String" :value "...#")))
304 (defvar org-display-table nil
305 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
307 (defgroup org-keywords nil
308 "Keywords in Org-mode."
309 :tag "Org Keywords"
310 :group 'org)
312 (defcustom org-deadline-string "DEADLINE:"
313 "String to mark deadline entries.
314 A deadline is this string, followed by a time stamp. Should be a word,
315 terminated by a colon. You can insert a schedule keyword and
316 a timestamp with \\[org-deadline].
317 Changes become only effective after restarting Emacs."
318 :group 'org-keywords
319 :type 'string)
321 (defcustom org-scheduled-string "SCHEDULED:"
322 "String to mark scheduled TODO entries.
323 A schedule is this string, followed by a time stamp. Should be a word,
324 terminated by a colon. You can insert a schedule keyword and
325 a timestamp with \\[org-schedule].
326 Changes become only effective after restarting Emacs."
327 :group 'org-keywords
328 :type 'string)
330 (defcustom org-closed-string "CLOSED:"
331 "String used as the prefix for timestamps logging closing a TODO entry."
332 :group 'org-keywords
333 :type 'string)
335 (defcustom org-comment-string "COMMENT"
336 "Entries starting with this keyword will never be exported.
337 An entry can be toggled between COMMENT and normal with
338 \\[org-toggle-comment].
339 Changes become only effective after restarting Emacs."
340 :group 'org-keywords
341 :type 'string)
343 (defcustom org-quote-string "QUOTE"
344 "Entries starting with this keyword will be exported in fixed-width font.
345 Quoting applies only to the text in the entry following the headline, and does
346 not extend beyond the next headline, even if that is lower level.
347 An entry can be toggled between QUOTE and normal with
348 \\[org-toggle-fixed-width-section]."
349 :group 'org-keywords
350 :type 'string)
352 (defgroup org-structure nil
353 "Options concerning the general structure of Org-mode files."
354 :tag "Org Structure"
355 :group 'org)
357 (defgroup org-cycle nil
358 "Options concerning visibility cycling in Org-mode."
359 :tag "Org Cycle"
360 :group 'org-structure)
362 (defcustom org-cycle-emulate-tab t
363 "Where should `org-cycle' emulate TAB.
364 nil Never
365 white Only in completely white lines
366 t Everywhere except in headlines"
367 :group 'org-cycle
368 :type '(choice (const :tag "Never" nil)
369 (const :tag "Only in completely white lines" white)
370 (const :tag "Everywhere except in headlines" t)
373 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
374 "Hook that is run after `org-cycle' has changed the buffer visibility.
375 The function(s) in this hook must accept a single argument which indicates
376 the new state that was set by the most recent `org-cycle' command. The
377 argument is a symbol. After a global state change, it can have the values
378 `overview', `content', or `all'. After a local state change, it can have
379 the values `folded', `children', or `subtree'."
380 :group 'org-cycle
381 :type 'hook)
383 (defgroup org-edit-structure nil
384 "Options concerning structure editing in Org-mode."
385 :tag "Org Edit Structure"
386 :group 'org-structure)
388 (defcustom org-odd-levels-only nil
389 "Non-nil means, skip even levels and only use odd levels for the outline.
390 This has the effect that two stars are being added/taken away in
391 promotion/demotion commands. It also influences how levels are
392 handled by the exporters.
393 Changing it requires restart of `font-lock-mode' to become effective
394 for fontification also in regions already fontified."
395 :group 'org-edit-structure
396 :group 'org-font-lock
397 :type 'boolean)
399 (defcustom org-adapt-indentation t
400 "Non-nil means, adapt indentation when promoting and demoting.
401 When this is set and the *entire* text in an entry is indented, the
402 indentation is increased by one space in a demotion command, and
403 decreased by one in a promotion command. If any line in the entry
404 body starts at column 0, indentation is not changed at all."
405 :group 'org-edit-structure
406 :type 'boolean)
408 (defcustom org-enable-fixed-width-editor t
409 "Non-nil means, lines starting with \":\" are treated as fixed-width.
410 This currently only means, they are never auto-wrapped.
411 When nil, such lines will be treated like ordinary lines.
412 See also the QUOTE keyword."
413 :group 'org-edit-structure
414 :type 'boolean)
416 (defgroup org-sparse-trees nil
417 "Options concerning sparse trees in Org-mode."
418 :tag "Org Sparse Trees"
419 :group 'org-structure)
421 (defcustom org-highlight-sparse-tree-matches t
422 "Non-nil means, highlight all matches that define a sparse tree.
423 The highlights will automatically disappear the next time the buffer is
424 changed by an edit command."
425 :group 'org-sparse-trees
426 :type 'boolean)
428 (defcustom org-show-hierarchy-above t
429 "Non-nil means, show full hierarchy when showing a spot in the tree.
430 Turning this off makes sparse trees more compact, but also less clear."
431 :group 'org-sparse-trees
432 :type 'boolean)
434 (defcustom org-show-following-heading t
435 "Non-nil means, show heading following match in `org-occur'.
436 When doing an `org-occur' it is useful to show the headline which
437 follows the match, even if they do not match the regexp. This makes it
438 easier to edit directly inside the sparse tree. However, if you use
439 `org-occur' mainly as an overview, the following headlines are
440 unnecessary clutter."
441 :group 'org-sparse-trees
442 :type 'boolean)
444 (defcustom org-occur-hook '(org-first-headline-recenter)
445 "Hook that is run after `org-occur' has constructed a sparse tree.
446 This can be used to recenter the window to show as much of the structure
447 as possible."
448 :group 'org-sparse-trees
449 :type 'hook)
451 (defgroup org-plain-lists nil
452 "Options concerning plain lists in Org-mode."
453 :tag "Org Plain lists"
454 :group 'org-structure)
456 (defcustom org-cycle-include-plain-lists nil
457 "Non-nil means, include plain lists into visibility cycling.
458 This means that during cycling, plain list items will *temporarily* be
459 interpreted as outline headlines with a level given by 1000+i where i is the
460 indentation of the bullet. In all other operations, plain list items are
461 not seen as headlines. For example, you cannot assign a TODO keyword to
462 such an item."
463 :group 'org-plain-lists
464 :type 'boolean)
467 (defcustom org-plain-list-ordered-item-terminator t
468 "The character that makes a line with leading number an ordered list item.
469 Valid values are ?. and ?\). To get both terminators, use t. While
470 ?. may look nicer, it creates the danger that a line with leading
471 number may be incorrectly interpreted as an item. ?\) therefore is
472 the safe choice."
473 :group 'org-plain-lists
474 :type '(choice (const :tag "dot like in \"2.\"" ?.)
475 (const :tag "paren like in \"2)\"" ?\))
476 (const :tab "both" t)))
478 (defcustom org-auto-renumber-ordered-lists t
479 "Non-nil means, automatically renumber ordered plain lists.
480 Renumbering happens when the sequence have been changed with
481 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
482 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
483 :group 'org-plain-lists
484 :type 'boolean)
486 (defgroup org-archive nil
487 "Options concerning archiving in Org-mode."
488 :tag "Org Archive"
489 :group 'org-structure)
491 (defcustom org-archive-location "%s_archive::"
492 "The location where subtrees should be archived.
493 This string consists of two parts, separated by a double-colon.
495 The first part is a file name - when omitted, archiving happens in the same
496 file. %s will be replaced by the current file name (without directory part).
497 Archiving to a different file is useful to keep archived entries from
498 contributing to the Org-mode Agenda.
500 The part after the double colon is a headline. The archived entries will be
501 filed under that headline. When omitted, the subtrees are simply filed away
502 at the end of the file, as top-level entries.
504 Here are a few examples:
505 \"%s_archive::\"
506 If the current file is Projects.org, archive in file
507 Projects.org_archive, as top-level trees. This is the default.
509 \"::* Archived Tasks\"
510 Archive in the current file, under the top-level headline
511 \"* Archived Tasks\".
513 \"~/org/archive.org::\"
514 Archive in file ~/org/archive.org (absolute path), as top-level trees.
516 \"basement::** Finished Tasks\"
517 Archive in file ./basement (relative path), as level 3 trees
518 below the level 2 heading \"** Finished Tasks\".
520 You may set this option on a per-file basis by adding to the buffer a
521 line like
523 #+ARCHIVE: basement::** Finished Tasks"
524 :group 'org-archive
525 :type 'string)
527 (defcustom org-archive-mark-done t
528 "Non-nil means, mark archived entries as DONE."
529 :group 'org-archive
530 :type 'boolean)
532 (defcustom org-archive-stamp-time t
533 "Non-nil means, add a time stamp to archived entries.
534 The time stamp will be added directly after the TODO state keyword in the
535 first line, so it is probably best to use this in combinations with
536 `org-archive-mark-done'."
537 :group 'org-archive
538 :type 'boolean)
540 (defgroup org-table nil
541 "Options concerning tables in Org-mode."
542 :tag "Org Table"
543 :group 'org)
545 (defcustom org-enable-table-editor 'optimized
546 "Non-nil means, lines starting with \"|\" are handled by the table editor.
547 When nil, such lines will be treated like ordinary lines.
549 When equal to the symbol `optimized', the table editor will be optimized to
550 do the following:
551 - Use automatic overwrite mode in front of whitespace in table fields.
552 This make the structure of the table stay in tact as long as the edited
553 field does not exceed the column width.
554 - Minimize the number of realigns. Normally, the table is aligned each time
555 TAB or RET are pressed to move to another field. With optimization this
556 happens only if changes to a field might have changed the column width.
557 Optimization requires replacing the functions `self-insert-command',
558 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
559 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
560 very good at guessing when a re-align will be necessary, but you can always
561 force one with \\[org-ctrl-c-ctrl-c].
563 If you would like to use the optimized version in Org-mode, but the
564 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
566 This variable can be used to turn on and off the table editor during a session,
567 but in order to toggle optimization, a restart is required.
569 See also the variable `org-table-auto-blank-field'."
570 :group 'org-table
571 :type '(choice
572 (const :tag "off" nil)
573 (const :tag "on" t)
574 (const :tag "on, optimized" optimized)))
576 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
577 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
578 In the optimized version, the table editor takes over all simple keys that
579 normally just insert a character. In tables, the characters are inserted
580 in a way to minimize disturbing the table structure (i.e. in overwrite mode
581 for empty fields). Outside tables, the correct binding of the keys is
582 restored.
584 The default for this option is t if the optimized version is also used in
585 Org-mode. See the variable `org-enable-table-editor' for details. Changing
586 this variable requires a restart of Emacs to become effective."
587 :group 'org-table
588 :type 'boolean)
590 (defgroup org-table-settings nil
591 "Settings for tables in Org-mode."
592 :tag "Org Table Settings"
593 :group 'org-table)
595 (defcustom org-table-default-size "5x2"
596 "The default size for newly created tables, Columns x Rows."
597 :group 'org-table-settings
598 :type 'string)
600 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
601 "Regular expression for recognizing numbers in table columns.
602 If a table column contains mostly numbers, it will be aligned to the
603 right. If not, it will be aligned to the left.
605 The default value of this option is a regular expression which allows
606 anything which looks remotely like a number as used in scientific
607 context. For example, all of the following will be considered a
608 number:
609 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
611 Other options offered by the customize interface are more restrictive."
612 :group 'org-table-settings
613 :type '(choice
614 (const :tag "Positive Integers"
615 "^[0-9]+$")
616 (const :tag "Integers"
617 "^[-+]?[0-9]+$")
618 (const :tag "Floating Point Numbers"
619 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
620 (const :tag "Floating Point Number or Integer"
621 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
622 (const :tag "Exponential, Floating point, Integer"
623 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
624 (const :tag "Very General Number-Like"
625 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
626 (string :tag "Regexp:")))
628 (defcustom org-table-number-fraction 0.5
629 "Fraction of numbers in a column required to make the column align right.
630 In a column all non-white fields are considered. If at least this
631 fraction of fields is matched by `org-table-number-fraction',
632 alignment to the right border applies."
633 :group 'org-table-settings
634 :type 'number)
636 (defgroup org-table-editing nil
637 "Bahavior of tables during editing in Org-mode."
638 :tag "Org Table Editing"
639 :group 'org-table)
641 (defcustom org-table-automatic-realign t
642 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
643 When nil, aligning is only done with \\[org-table-align], or after column
644 removal/insertion."
645 :group 'org-table-editing
646 :type 'boolean)
648 (defcustom org-table-limit-column-width t ;kw
649 "Non-nil means, allow to limit the width of table columns with <N> fields."
650 :group 'org-table-editing
651 :type 'boolean)
653 (defcustom org-table-auto-blank-field t
654 "Non-nil means, automatically blank table field when starting to type into it.
655 This only happens when typing immediately after a field motion
656 command (TAB, S-TAB or RET).
657 Only relevant when `org-enable-table-editor' is equal to `optimized'."
658 :group 'org-table-editing
659 :type 'boolean)
661 (defcustom org-table-tab-jumps-over-hlines t
662 "Non-nil means, tab in the last column of a table with jump over a hline.
663 If a horizontal separator line is following the current line,
664 `org-table-next-field' can either create a new row before that line, or jump
665 over the line. When this option is nil, a new line will be created before
666 this line."
667 :group 'org-table-editing
668 :type 'boolean)
670 (defcustom org-table-tab-recognizes-table.el t
671 "Non-nil means, TAB will automatically notice a table.el table.
672 When it sees such a table, it moves point into it and - if necessary -
673 calls `table-recognize-table'."
674 :group 'org-table-editing
675 :type 'boolean)
677 (defgroup org-table-calculation nil
678 "Options concerning tables in Org-mode."
679 :tag "Org Table Calculation"
680 :group 'org-table)
682 (defcustom org-table-copy-increment t
683 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
684 :group 'org-table-calculation
685 :type 'boolean)
687 (defcustom org-calc-default-modes
688 '(calc-internal-prec 12
689 calc-float-format (float 5)
690 calc-angle-mode deg
691 calc-prefer-frac nil
692 calc-symbolic-mode nil
693 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
694 calc-display-working-message t
696 "List with Calc mode settings for use in calc-eval for table formulas.
697 The list must contain alternating symbols (Calc modes variables and values).
698 Don't remove any of the default settings, just change the values. Org-mode
699 relies on the variables to be present in the list."
700 :group 'org-table-calculation
701 :type 'plist)
703 (defcustom org-table-formula-evaluate-inline t
704 "Non-nil means, TAB and RET evaluate a formula in current table field.
705 If the current field starts with an equal sign, it is assumed to be a formula
706 which should be evaluated as described in the manual and in the documentation
707 string of the command `org-table-eval-formula'. This feature requires the
708 Emacs calc package.
709 When this variable is nil, formula calculation is only available through
710 the command \\[org-table-eval-formula]."
711 :group 'org-table-calculation
712 :type 'boolean)
715 (defcustom org-table-formula-use-constants t
716 "Non-nil means, interpret constants in formulas in tables.
717 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
718 by the value given in `org-table-formula-constants', or by a value obtained
719 from the `constants.el' package."
720 :group 'org-table-calculation
721 :type 'boolean)
723 (defcustom org-table-formula-constants nil
724 "Alist with constant names and values, for use in table formulas.
725 The car of each element is a name of a constant, without the `$' before it.
726 The cdr is the value as a string. For example, if you'd like to use the
727 speed of light in a formula, you would configure
729 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
731 and then use it in an equation like `$1*$c'."
732 :group 'org-table-calculation
733 :type '(repeat
734 (cons (string :tag "name")
735 (string :tag "value"))))
737 (defcustom org-table-formula-numbers-only nil
738 "Non-nil means, calculate only with numbers in table formulas.
739 Then all input fields will be converted to a number, and the result
740 must also be a number. When nil, calc's full potential is available
741 in table calculations, including symbolics etc."
742 :group 'org-table-calculation
743 :type 'boolean)
745 (defcustom org-table-allow-automatic-line-recalculation t
746 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
747 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
748 :group 'org-table-calculation
749 :type 'boolean)
751 (defgroup org-link nil
752 "Options concerning links in Org-mode."
753 :tag "Org Link"
754 :group 'org)
756 (defcustom org-descriptive-links t
757 "Non-nil means, hide link part and only show description of bracket links.
758 Bracket links are like [[link][descritpion]]. This variable sets the initial
759 state in new org-mode buffers. The setting can then be toggled on a
760 per-buffer basis from the Org->Hyperlinks menu."
761 :group 'org-link
762 :type 'boolean)
764 (defcustom org-link-style 'bracket
765 "The style of links to be inserted with \\[org-insert-link].
766 Possible values are:
767 bracket [[link][description]]. This is recommended
768 plain Description \\n link. The old way, no longer recommended."
769 :group 'org-link
770 :type '(choice
771 (const :tag "Bracket (recommended)" bracket)
772 (const :tag "Plain (no longer recommended)" plain)))
774 (defcustom org-link-format "%s"
775 "Default format for external, URL-like linkes in the buffer.
776 This is a format string for printf, %s will be replaced by the link text.
777 The recommended value is just \"%s\", since links will be protected by
778 enclosing them in double brackets. If you prefer plain links (see variable
779 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
780 additional URL: prefix, so the format would be \"<URL:%s>\"."
781 :group 'org-link
782 :type '(choice
783 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
784 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
785 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
786 (string :tag "Other" :value "<%s>")))
788 (defcustom org-activate-links '(bracket angle plain radio tag date)
789 "Types of links that should be activated in Org-mode files.
790 This is a list of symbols, each leading to the activation of a certain link
791 type. In principle, it does not hurt to turn on most link types - there may
792 be a small gain when turning off unused link types. The types are:
794 bracket The recommended [[link][description]] or [[link]] links with hiding.
795 angular Links in angular brackes that may contain whitespace like
796 <bbdb:Carsten Dominik>.
797 plain Plain links in normal text, no whitespace, like http://google.com.
798 radio Text that is matched by a radio target, see manual for details.
799 tag Tag settings in a headline (link to tag search).
800 date Time stamps (link to calendar).
801 camel CamelCase words defining text searches.
803 Changing this variable requires a restart of Emacs to become effective."
804 :group 'org-link
805 :type '(set (const :tag "Double bracket links (new style)" bracket)
806 (const :tag "Angular bracket links (old style)" angular)
807 (const :tag "plain text links" plain)
808 (const :tag "Radio target matches" radio)
809 (const :tag "Tags" tag)
810 (const :tag "Timestamps" date)
811 (const :tag "CamelCase words" camel)))
813 (defgroup org-link-store nil
814 "Options concerning storing links in Org-mode"
815 :tag "Org Store Link"
816 :group 'org-link)
818 (defcustom org-context-in-file-links t
819 "Non-nil means, file links from `org-store-link' contain context.
820 A search string will be added to the file name with :: as separator and
821 used to find the context when the link is activated by the command
822 `org-open-at-point'.
823 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
824 negates this setting for the duration of the command."
825 :group 'org-link-store
826 :type 'boolean)
828 (defcustom org-file-link-context-use-camel-case nil
829 "Non-nil means, use CamelCase to store a search context in a file link.
830 When nil, the search string simply consists of the words of the string.
831 CamelCase is deprecated, and support for it may be dropped in the future."
832 :group 'org-link-store
833 :type 'boolean)
835 (defcustom org-keep-stored-link-after-insertion nil
836 "Non-nil means, keep link in list for entire session.
838 The command `org-store-link' adds a link pointing to the current
839 location to an internal list. These links accumulate during a session.
840 The command `org-insert-link' can be used to insert links into any
841 Org-mode file (offering completion for all stored links). When this
842 option is nil, every link which has been inserted once using \\[org-insert-link]
843 will be removed from the list, to make completing the unused links
844 more efficient."
845 :group 'org-link-store
846 :type 'boolean)
848 (defcustom org-usenet-links-prefer-google nil
849 "Non-nil means, `org-store-link' will create web links to Google groups.
850 When nil, Gnus will be used for such links.
851 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
852 negates this setting for the duration of the command."
853 :group 'org-link-store
854 :type 'boolean)
856 (defgroup org-link-follow nil
857 "Options concerning following links in Org-mode"
858 :tag "Org Follow Link"
859 :group 'org-link)
861 (defcustom org-tab-follows-link nil
862 "Non-nil means, on links TAB will follow the link.
863 Needs to be set before org.el is loaded."
864 :group 'org-link-follow
865 :type 'boolean)
867 (defcustom org-return-follows-link nil
868 "Non-nil means, on links RET will follow the link.
869 Needs to be set before org.el is loaded."
870 :group 'org-link-follow
871 :type 'boolean)
873 (defcustom org-mark-ring-length 4
874 "Number of different positions to be recorded in the ring
875 Changing this requires a restart of Emacs to work correctly."
876 :group 'org-link-follow
877 :type 'interger)
879 (defcustom org-link-frame-setup
880 '((vm . vm-visit-folder-other-frame)
881 (gnus . gnus-other-frame)
882 (file . find-file-other-window))
883 "Setup the frame configuration for following links.
884 When following a link with Emacs, it may often be useful to display
885 this link in another window or frame. This variable can be used to
886 set this up for the different types of links.
887 For VM, use any of
888 `vm-visit-folder'
889 `vm-visit-folder-other-frame'
890 For Gnus, use any of
891 `gnus'
892 `gnus-other-frame'
893 For FILE, use any of
894 `find-file'
895 `find-file-other-window'
896 `find-file-other-frame'
897 For the calendar, use the variable `calendar-setup'.
898 For BBDB, it is currently only possible to display the matches in
899 another window."
900 :group 'org-link-follow
901 :type '(list
902 (cons (const vm)
903 (choice
904 (const vm-visit-folder)
905 (const vm-visit-folder-other-window)
906 (const vm-visit-folder-other-frame)))
907 (cons (const gnus)
908 (choice
909 (const gnus)
910 (const gnus-other-frame)))
911 (cons (const file)
912 (choice
913 (const find-file)
914 (const find-file-other-window)
915 (const find-file-other-frame)))))
917 (defcustom org-open-non-existing-files nil
918 "Non-nil means, `org-open-file' will open non-existing file.
919 When nil, an error will be generated."
920 :group 'org-link-follow
921 :type 'boolean)
923 (defcustom org-confirm-shell-links 'yes-or-no-p
924 "Non-nil means, ask for confirmation before executing shell links.
925 Shell links can be dangerous, just thing about a link
927 [[shell:rm -rf ~/*][Google Search]]
929 This link would show up in your Org-mode document as \"Google Search\"
930 but really it would remove your entire home directory. Dangerous indeed.
931 Therefore I *definitely* advise agains setting this varaiable to nil.
932 Just change it to `y-or-n-p' of you want to confirm with a single key press
933 rather than having to type \"yes\"."
934 :group 'org-link-follow
935 :type '(choice
936 (const :tag "with yes-or-no (safer)" yes-or-no-p)
937 (const :tag "with y-or-n (faster)" y-or-n-p)
938 (const :tag "no confirmation (dangerous)" nil)))
940 (defconst org-file-apps-defaults-gnu
941 '((t . mailcap))
942 "Default file applications on a UNIX or GNU/Linux system.
943 See `org-file-apps'.")
945 (defconst org-file-apps-defaults-macosx
946 '((t . "open %s")
947 ("ps" . "gv %s")
948 ("ps.gz" . "gv %s")
949 ("eps" . "gv %s")
950 ("eps.gz" . "gv %s")
951 ("dvi" . "xdvi %s")
952 ("fig" . "xfig %s"))
953 "Default file applications on a MacOS X system.
954 The system \"open\" is known as a default, but we use X11 applications
955 for some files for which the OS does not have a good default.
956 See `org-file-apps'.")
958 (defconst org-file-apps-defaults-windowsnt
959 '((t . (w32-shell-execute "open" file)))
960 "Default file applications on a Windows NT system.
961 The system \"open\" is used for most files.
962 See `org-file-apps'.")
964 (defcustom org-file-apps
966 ("txt" . emacs)
967 ("tex" . emacs)
968 ("ltx" . emacs)
969 ("org" . emacs)
970 ("el" . emacs)
972 "External applications for opening `file:path' items in a document.
973 Org-mode uses system defaults for different file types, but
974 you can use this variable to set the application for a given file
975 extension. The entries in this list are cons cells with a file extension
976 and the corresponding command. Possible values for the command are:
977 `emacs' The file will be visited by the current Emacs process.
978 `default' Use the default application for this file type.
979 string A command to be executed by a shell; %s will be replaced
980 by the path to the file.
981 sexp A Lisp form which will be evaluated. The file path will
982 be available in the Lisp variable `file'.
983 For more examples, see the system specific constants
984 `org-file-apps-defaults-macosx'
985 `org-file-apps-defaults-windowsnt'
986 `org-file-apps-defaults-gnu'."
987 :group 'org-link-follow
988 :type '(repeat
989 (cons (choice :value ""
990 (string :tag "Extension")
991 (const :tag "Default for unrecognized files" t)
992 (const :tag "Links to a directory" directory))
993 (choice :value ""
994 (const :tag "Visit with Emacs" emacs)
995 (const :tag "Use system default" default)
996 (string :tag "Command")
997 (sexp :tag "Lisp form")))))
999 (defcustom org-mhe-search-all-folders nil
1000 "Non-nil means, that the search for the mh-message will be extended to
1001 all folders if the message cannot be found in the folder given in the link.
1002 Searching all folders is very effective with one of the search engines
1003 supported by MH-E, but will be slow with pick."
1004 :group 'org-link-follow
1005 :type 'boolean)
1007 (defgroup org-remember nil
1008 "Options concerning interaction with remember.el."
1009 :tag "Org Remember"
1010 :group 'org)
1012 (defcustom org-directory "~/org"
1013 "Directory with org files.
1014 This directory will be used as default to prompt for org files.
1015 Used by the hooks for remember.el."
1016 :group 'org-remember
1017 :type 'directory)
1019 (defcustom org-default-notes-file "~/.notes"
1020 "Default target for storing notes.
1021 Used by the hooks for remember.el. This can be a string, or nil to mean
1022 the value of `remember-data-file'."
1023 :group 'org-remember
1024 :type '(choice
1025 (const :tag "Default from remember-data-file" nil)
1026 file))
1028 (defcustom org-remember-templates nil
1029 "Templates for the creation of remember buffers.
1030 When nil, just let remember make the buffer.
1031 When not nil, this is a list of 3-element lists. In each entry, the first
1032 element is a character, a unique key to select this template.
1033 The second element is the template. The third element is optional and can
1034 specify a destination file for remember items created with this template.
1035 The default file is given by `org-default-notes-file'.
1037 The template specifies the structure of the remember buffer. It should have
1038 a first line starting with a star, to act as the org-mode headline.
1039 Furthermore, the following %-escapes will be replaced with content:
1040 %t time stamp, date only
1041 %T time stamp with date and time
1042 %u inactive time stamp, date only
1043 %U inactive time stamp with date and time
1044 %n user name
1045 %a annotation, normally the link created with org-store-link
1046 %i initial content, the region when remember is called with C-u.
1047 If %i is indented, the entire inserted text will be indented as well.
1048 %? This will be removed, and the cursor placed at this position."
1049 :group 'org-remember
1050 :type '(repeat :tag "enabled"
1051 (list :value (?a "\n" nil)
1052 (character :tag "Selection Key")
1053 (string :tag "Template")
1054 (file :tag "Destination file (optional)"))))
1056 (defcustom org-reverse-note-order nil
1057 "Non-nil means, store new notes at the beginning of a file or entry.
1058 When nil, new notes will be filed to the end of a file or entry."
1059 :group 'org-remember
1060 :type '(choice
1061 (const :tag "Reverse always" t)
1062 (const :tag "Reverse never" nil)
1063 (repeat :tag "By file name regexp"
1064 (cons regexp boolean))))
1066 (defgroup org-todo nil
1067 "Options concerning TODO items in Org-mode."
1068 :tag "Org TODO"
1069 :group 'org)
1071 (defcustom org-todo-keywords '("TODO" "DONE")
1072 "List of TODO entry keywords.
1073 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1074 considered to mean that the entry is \"done\". All the other mean that
1075 action is required, and will make the entry show up in todo lists, diaries
1076 etc.
1077 The command \\[org-todo] cycles an entry through these states, and an
1078 additional state where no keyword is present. For details about this
1079 cycling, see also the variable `org-todo-interpretation'
1080 Changes become only effective after restarting Emacs."
1081 :group 'org-todo
1082 :group 'org-keywords
1083 :type '(repeat (string :tag "Keyword")))
1085 (defcustom org-todo-interpretation 'sequence
1086 "Controls how TODO keywords are interpreted.
1087 This variable is only relevant if `org-todo-keywords' contains more than two
1088 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1090 When `sequence', \\[org-todo] will always switch to the next state in the
1091 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1092 to state when executed several times in direct succession. Otherwise, it
1093 switches directly to DONE from any state.
1094 See the manual for more information."
1095 :group 'org-todo
1096 :group 'org-keywords
1097 :type '(choice (const sequence)
1098 (const type)))
1100 (defcustom org-after-todo-state-change-hook nil
1101 "Hook which is run after the state of a TODO item was changed.
1102 The new state (a string with a TODO keyword, or nil) is available in the
1103 Lisp variable `state'."
1104 :group 'org-todo
1105 :type 'hook)
1107 (defcustom org-log-done nil
1108 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1109 When the state of an entry is changed from nothing to TODO, remove a previous
1110 closing date."
1111 :group 'org-todo
1112 :type 'boolean)
1114 (defgroup org-priorities nil
1115 "Keywords in Org-mode."
1116 :tag "Org Priorities"
1117 :group 'org-todo)
1119 (defcustom org-default-priority ?B
1120 "The default priority of TODO items.
1121 This is the priority an item get if no explicit priority is given."
1122 :group 'org-priorities
1123 :type 'character)
1125 (defcustom org-lowest-priority ?C
1126 "The lowest priority of TODO items. A character like ?A, ?B etc."
1127 :group 'org-priorities
1128 :type 'character)
1130 (defgroup org-time nil
1131 "Options concerning time stamps and deadlines in Org-mode."
1132 :tag "Org Time"
1133 :group 'org)
1135 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1136 "Formats for `format-time-string' which are used for time stamps.
1137 It is not recommended to change this constant.")
1139 (defcustom org-time-stamp-rounding-minutes 0
1140 "Number of minutes to round time stamps to upon insertion.
1141 When zero, insert the time unmodified. Useful rounding numbers
1142 should be factors of 60, so for example 5, 10, 15.
1143 When this is not zero, you can still force an exact time-stamp by using
1144 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1145 :group 'org-time
1146 :type 'integer)
1148 (defcustom org-deadline-warning-days 30
1149 "No. of days before expiration during which a deadline becomes active.
1150 This variable governs the display in the org file."
1151 :group 'org-time
1152 :type 'number)
1154 (defcustom org-popup-calendar-for-date-prompt t
1155 "Non-nil means, pop up a calendar when prompting for a date.
1156 In the calendar, the date can be selected with mouse-1. However, the
1157 minibuffer will also be active, and you can simply enter the date as well.
1158 When nil, only the minibuffer will be available."
1159 :group 'org-time
1160 :type 'boolean)
1162 (defcustom org-calendar-follow-timestamp-change t
1163 "Non-nil means, make the calendar window follow timestamp changes.
1164 When a timestamp is modified and the calendar window is visible, it will be
1165 moved to the new date."
1166 :group 'org-time
1167 :type 'boolean)
1169 (defgroup org-tags nil
1170 "Options concerning startup of Org-mode."
1171 :tag "Org Tags"
1172 :group 'org)
1174 (defcustom org-tags-column 48
1175 "The column to which tags should be indented in a headline.
1176 If this number is positive, it specifies the column. If it is negative,
1177 it means that the tags should be flushright to that column. For example,
1178 -79 works well for a normal 80 character screen."
1179 :group 'org-tags
1180 :type 'integer)
1182 (defcustom org-auto-align-tags t
1183 "Non-nil means, realign tags after pro/demotion of TODO state change.
1184 These operations change the length of a headline and therefore shift
1185 the tags around. With this options turned on, after each such operation
1186 the tags are again aligned to `org-tags-column'."
1187 :group 'org-tags
1188 :type 'boolean)
1190 (defcustom org-use-tag-inheritance t
1191 "Non-nil means, tags in levels apply also for sublevels.
1192 When nil, only the tags directly given in a specific line apply there.
1193 If you turn off this option, you very likely want to turn on the
1194 companion option `org-tags-match-list-sublevels'."
1195 :group 'org-tags
1196 :type 'boolean)
1198 (defcustom org-tags-match-list-sublevels nil
1199 "Non-nil means list also sublevels of headlines matching tag search.
1200 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1201 the sublevels of a headline matching a tag search often also match
1202 the same search. Listing all of them can create very long lists.
1203 Setting this variable to nil causes subtrees of a match to be skipped.
1204 This option is off by default, because inheritance in on. If you turn
1205 inheritance off, you very likely want to turn this option on.
1207 As a special case, if the tag search is restricted to TODO items, the
1208 value of this variable is ignored and sublevels are always checked, to
1209 make sure all corresponding TODO items find their way into the list."
1210 :group 'org-tags
1211 :type 'boolean)
1213 (defvar org-tags-history nil
1214 "History of minibuffer reads for tags.")
1215 (defvar org-last-tags-completion-table nil
1216 "The last used completion table for tags.")
1218 (defgroup org-agenda nil
1219 "Options concerning agenda display Org-mode."
1220 :tag "Org Agenda"
1221 :group 'org)
1223 (defvar org-category nil
1224 "Variable used by org files to set a category for agenda display.
1225 Such files should use a file variable to set it, for example
1227 -*- mode: org; org-category: \"ELisp\"
1229 or contain a special line
1231 #+CATEGORY: ELisp
1233 If the file does not specify a category, then file's base name
1234 is used instead.")
1235 (make-variable-buffer-local 'org-category)
1237 (defcustom org-agenda-files nil
1238 "The files to be used for agenda display.
1239 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1240 \\[org-remove-file]. You can also use customize to edit the list.
1242 If the value of the variable is not a list but a single file name, then
1243 the list of agenda files is actually stored and maintained in that file, one
1244 agenda file per line."
1245 :group 'org-agenda
1246 :type '(choice
1247 (repeat :tag "List of files" file)
1248 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1250 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1251 "Custom commands for the agenda.
1252 These commands will be offered on the splash screen displayed by the
1253 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1255 key The key (a single char as a string) to be associated with the command.
1256 type The command type, any of the following symbols:
1257 todo Entries with a specific TODO keyword, in all agenda files.
1258 tags Tags match in all agenda files.
1259 todo-tree Sparse tree of specific TODO keyword in *current* file.
1260 tags-tree Sparse tree with all tags matches in *current* file.
1261 occur-tree Occur sparse tree for current file.
1262 match What to search for:
1263 - a single keyword for TODO keyword searches
1264 - a tags match expression for tags searches
1265 - a regular expression for occur searches"
1266 :group 'org-agenda
1267 :type '(repeat
1268 (list (string :tag "Key")
1269 (choice :tag "Type"
1270 (const :tag "Tags search in all agenda files" tags)
1271 (const :tag "TODO keyword search in all agenda files" todo)
1272 (const :tag "Tags sparse tree in current buffer" tags-tree)
1273 (const :tag "TODO keyword tree in current buffer" todo-tree)
1274 (const :tag "Occur tree in current buffer" occur-tree))
1275 (string :tag "Match"))))
1277 (defcustom org-agenda-include-all-todo t
1278 "Non-nil means, the agenda will always contain all TODO entries.
1279 When nil, date-less entries will only be shown if `org-agenda' is called
1280 with a prefix argument.
1281 When non-nil, the TODO entries will be listed at the top of the agenda, before
1282 the entries for specific days."
1283 :group 'org-agenda
1284 :type 'boolean)
1286 (defcustom org-agenda-include-diary nil
1287 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1288 :group 'org-agenda
1289 :type 'boolean)
1291 (defcustom org-calendar-to-agenda-key [?c]
1292 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1293 The command `org-calendar-goto-agenda' will be bound to this key. The
1294 default is the character `c' because then `c' can be used to switch back and
1295 forth between agenda and calendar."
1296 :group 'org-agenda
1297 :type 'sexp)
1299 (defgroup org-agenda-window-setup nil
1300 "Options concerning setting up the Agenda window in Org Mode."
1301 :tag "Org Agenda Window Setup"
1302 :group 'org-agenda)
1304 (defcustom org-select-timeline-window t
1305 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1306 When nil, cursor will remain in the current window."
1307 :group 'org-agenda-window-setup
1308 :type 'boolean)
1310 (defcustom org-select-agenda-window t
1311 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1312 When nil, cursor will remain in the current window."
1313 :group 'org-agenda-window-setup
1314 :type 'boolean)
1316 (defcustom org-fit-agenda-window t
1317 "Non-nil means, change window size of agenda to fit content."
1318 :group 'org-agenda-window-setup
1319 :type 'boolean)
1321 (defgroup org-agenda-display nil
1322 "Options concerning what to display initially in Agenda."
1323 :tag "Org Agenda Display"
1324 :group 'org-agenda)
1326 (defcustom org-agenda-show-all-dates t
1327 "Non-nil means, `org-agenda' shows every day in the selected range.
1328 When nil, only the days which actually have entries are shown."
1329 :group 'org-agenda-display
1330 :type 'boolean)
1332 (defcustom org-agenda-start-on-weekday 1
1333 "Non-nil means, start the overview always on the specified weekday.
1334 0 denotes Sunday, 1 denotes Monday etc.
1335 When nil, always start on the current day."
1336 :group 'org-agenda-display
1337 :type '(choice (const :tag "Today" nil)
1338 (number :tag "Weekday No.")))
1340 (defcustom org-agenda-ndays 7
1341 "Number of days to include in overview display.
1342 Should be 1 or 7."
1343 :group 'org-agenda-display
1344 :type 'number)
1346 (defcustom org-agenda-use-time-grid t
1347 "Non-nil means, show a time grid in the agenda schedule.
1348 A time grid is a set of lines for specific times (like every two hours between
1349 8:00 and 20:00). The items scheduled for a day at specific times are
1350 sorted in between these lines.
1351 For details about when the grid will be shown, and what it will look like, see
1352 the variable `org-agenda-time-grid'."
1353 :group 'org-agenda-display
1354 :type 'boolean)
1356 (defcustom org-agenda-time-grid
1357 '((daily today require-timed)
1358 "----------------"
1359 (800 1000 1200 1400 1600 1800 2000))
1361 "The settings for time grid for agenda display.
1362 This is a list of three items. The first item is again a list. It contains
1363 symbols specifying conditions when the grid should be displayed:
1365 daily if the agenda shows a single day
1366 weekly if the agenda shows an entire week
1367 today show grid on current date, independent of daily/weekly display
1368 require-timed show grid only if at least on item has a time specification
1370 The second item is a string which will be places behing the grid time.
1372 The third item is a list of integers, indicating the times that should have
1373 a grid line."
1374 :group 'org-agenda-display
1375 :type
1376 '(list
1377 (set :greedy t :tag "Grid Display Options"
1378 (const :tag "Show grid in single day agenda display" daily)
1379 (const :tag "Show grid in weekly agenda display" weekly)
1380 (const :tag "Always show grid for today" today)
1381 (const :tag "Show grid only if any timed entries are present"
1382 require-timed)
1383 (const :tag "Skip grid times already present in an entry"
1384 remove-match))
1385 (string :tag "Grid String")
1386 (repeat :tag "Grid Times" (integer :tag "Time"))))
1388 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1389 "Sorting structure for the agenda items of a single day.
1390 This is a list of symbols which will be used in sequence to determine
1391 if an entry should be listed before another entry. The following
1392 symbols are recognized:
1394 time-up Put entries with time-of-day indications first, early first
1395 time-down Put entries with time-of-day indications first, late first
1396 category-keep Keep the default order of categories, corresponding to the
1397 sequence in `org-agenda-files'.
1398 category-up Sort alphabetically by category, A-Z.
1399 category-down Sort alphabetically by category, Z-A.
1400 priority-up Sort numerically by priority, high priority last.
1401 priority-down Sort numerically by priority, high priority first.
1403 The different possibilities will be tried in sequence, and testing stops
1404 if one comparison returns a \"not-equal\". For example, the default
1405 '(time-up category-keep priority-down)
1406 means: Pull out all entries having a specified time of day and sort them,
1407 in order to make a time schedule for the current day the first thing in the
1408 agenda listing for the day. Of the entries without a time indication, keep
1409 the grouped in categories, don't sort the categories, but keep them in
1410 the sequence given in `org-agenda-files'. Within each category sort by
1411 priority.
1413 Leaving out `category-keep' would mean that items will be sorted across
1414 categories by priority."
1415 :group 'org-agenda-display
1416 :type '(repeat
1417 (choice
1418 (const time-up)
1419 (const time-down)
1420 (const category-keep)
1421 (const category-up)
1422 (const category-down)
1423 (const priority-up)
1424 (const priority-down))))
1426 (defcustom org-sort-agenda-notime-is-late t
1427 "Non-nil means, items without time are considered late.
1428 This is only relevant for sorting. When t, items which have no explicit
1429 time like 15:30 will be considered as 24:01, i.e. later than any items which
1430 do have a time. When nil, the default time is before 0:00. You can use this
1431 option to decide if the schedule for today should come before or after timeless
1432 agenda entries."
1433 :group 'org-agenda-display
1434 :type 'boolean)
1437 (defgroup org-agenda-prefix nil
1438 "Options concerning the entry prefix in the Org-mode agenda display."
1439 :tag "Org Agenda Prefix"
1440 :group 'org-agenda)
1442 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1443 "Format specification for the prefix of items in the agenda buffer.
1444 This format works similar to a printf format, with the following meaning:
1446 %c the category of the item, \"Diary\" for entries from the diary, or
1447 as given by the CATEGORY keyword or derived from the file name.
1448 %T the first tag of the item.
1449 %t the time-of-day specification if one applies to the entry, in the
1450 format HH:MM
1451 %s Scheduling/Deadline information, a short string
1453 All specifiers work basically like the standard `%s' of printf, but may
1454 contain two additional characters: A question mark just after the `%' and
1455 a whitespace/punctuation character just before the final letter.
1457 If the first character after `%' is a question mark, the entire field
1458 will only be included if the corresponding value applies to the
1459 current entry. This is useful for fields which should have fixed
1460 width when present, but zero width when absent. For example,
1461 \"%?-12t\" will result in a 12 character time field if a time of the
1462 day is specified, but will completely disappear in entries which do
1463 not contain a time.
1465 If there is punctuation or whitespace character just before the final
1466 format letter, this character will be appended to the field value if
1467 the value is not empty. For example, the format \"%-12:c\" leads to
1468 \"Diary: \" if the category is \"Diary\". If the category were be
1469 empty, no additional colon would be interted.
1471 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1472 - Indent the line with two space characters
1473 - Give the category in a 12 chars wide field, padded with whitespace on
1474 the right (because of `-'). Append a colon if there is a category
1475 (because of `:').
1476 - If there is a time-of-day, put it into a 12 chars wide field. If no
1477 time, don't put in an empty field, just skip it (because of '?').
1478 - Finally, put the scheduling information and append a whitespace.
1480 As another example, if you don't want the time-of-day of entries in
1481 the prefix, you could use:
1483 (setq org-agenda-prefix-format \" %-11:c% s\")
1485 See also the variables `org-agenda-remove-times-when-in-prefix' and
1486 `org-agenda-remove-tags-when-in-prefix'."
1487 :type 'string
1488 :group 'org-agenda-prefix)
1490 (defcustom org-timeline-prefix-format " % s"
1491 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1492 :type 'string
1493 :group 'org-agenda-prefix)
1495 (defvar org-prefix-format-compiled nil
1496 "The compiled version of the most recently used prefix format.
1497 Depending on which command was used last, this may be the compiled version
1498 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1500 ;; FIXME: There seem to be situations where this does no work.
1501 (defcustom org-agenda-remove-times-when-in-prefix t
1502 "Non-nil means, remove duplicate time specifications in agenda items.
1503 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1504 time-of-day specification in a headline or diary entry is extracted and
1505 placed into the prefix. If this option is non-nil, the original specification
1506 \(a timestamp or -range, or just a plain time(range) specification like
1507 11:30-4pm) will be removed for agenda display. This makes the agenda less
1508 cluttered.
1509 The option can be t or nil. It may also be the symbol `beg', indicating
1510 that the time should only be removed what it is located at the beginning of
1511 the headline/diary entry."
1512 :group 'org-agenda-prefix
1513 :type '(choice
1514 (const :tag "Always" t)
1515 (const :tag "Never" nil)
1516 (const :tag "When at beginning of entry" beg)))
1518 (defcustom org-agenda-remove-tags-when-in-prefix nil
1519 "Non-nil means, remove the tags from the headline copy in the agenda.
1520 When this is the symbol `prefix', only remove tags when
1521 `org-agenda-prefix-format' contains a `%T' specifier."
1522 :group 'org-agenda-prefix
1523 :type '(choice
1524 (const :tag "Always" t)
1525 (const :tag "Never" nil)
1526 (const :tag "When prefix format contains %T" prefix)))
1528 (defgroup org-export nil
1529 "Options for exporting org-listings."
1530 :tag "Org Export"
1531 :group 'org)
1533 (defgroup org-export-general nil
1534 "General options for exporting Org-mode files."
1535 :tag "Org Export General"
1536 :group 'org-export)
1538 (defcustom org-export-language-setup
1539 '(("en" "Author" "Date" "Table of Contents")
1540 ("da" "Ophavsmand" "Dato" "Indhold")
1541 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1542 ("es" "Autor" "Fecha" "\xccndice")
1543 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1544 ("it" "Autore" "Data" "Indice")
1545 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1546 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1547 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1548 "Terms used in export text, translated to different languages.
1549 Use the variable `org-export-default-language' to set the language,
1550 or use the +OPTION lines for a per-file setting."
1551 :group 'org-export-general
1552 :type '(repeat
1553 (list
1554 (string :tag "HTML language tag")
1555 (string :tag "Author")
1556 (string :tag "Date")
1557 (string :tag "Table of Contents"))))
1559 (defcustom org-export-default-language "en"
1560 "The default language of HTML export, as a string.
1561 This should have an association in `org-export-language-setup'."
1562 :group 'org-export-general
1563 :type 'string)
1565 (defcustom org-export-headline-levels 3
1566 "The last level which is still exported as a headline.
1567 Inferior levels will produce itemize lists when exported.
1568 Note that a numeric prefix argument to an exporter function overrides
1569 this setting.
1571 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1572 :group 'org-export-general
1573 :type 'number)
1575 (defcustom org-export-with-section-numbers t
1576 "Non-nil means, add section numbers to headlines when exporting.
1578 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1579 :group 'org-export-general
1580 :type 'boolean)
1582 (defcustom org-export-with-toc t
1583 "Non-nil means, create a table of contents in exported files.
1584 The TOC contains headlines with levels up to`org-export-headline-levels'.
1586 Headlines which contain any TODO items will be marked with \"(*)\" in
1587 ASCII export, and with red color in HTML output.
1589 In HTML output, the TOC will be clickable.
1591 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1592 :group 'org-export-general
1593 :type 'boolean)
1595 (defcustom org-export-mark-todo-in-toc nil
1596 "Non-nil means, mark TOC lines that contain any open TODO items."
1597 :group 'org-export-general
1598 :type 'boolean)
1600 (defcustom org-export-preserve-breaks nil
1601 "Non-nil means, preserve all line breaks when exporting.
1602 Normally, in HTML output paragraphs will be reformatted. In ASCII
1603 export, line breaks will always be preserved, regardless of this variable.
1605 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1606 :group 'org-export-general
1607 :type 'boolean)
1609 (defgroup org-export-translation nil
1610 "Options for translating special ascii sequences for the export backends."
1611 :tag "Org Export Translation"
1612 :group 'org-export)
1614 (defcustom org-export-with-emphasize t
1615 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1616 If the export target supports emphasizing text, the word will be
1617 typeset in bold, italic, or underlined, respectively. Works only for
1618 single words, but you can say: I *really* *mean* *this*.
1619 Not all export backends support this.
1621 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1622 :group 'org-export-translation
1623 :type 'boolean)
1625 (defcustom org-export-with-sub-superscripts t
1626 "Non-nil means, interpret \"_\" and \"^\" for export.
1627 When this option is turned on, you can use TeX-like syntax for sub- and
1628 superscripts. Several characters after \"_\" or \"^\" will be
1629 considered as a single item - so grouping with {} is normally not
1630 needed. For example, the following things will be parsed as single
1631 sub- or superscripts.
1633 10^24 or 10^tau several digits will be considered 1 item.
1634 10^-12 or 10^-tau a leading sign with digits or a word
1635 x^2-y^3 will be read as x^2 - y^3, because items are
1636 terminated by almost any nonword/nondigit char.
1637 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1639 Still, ambiguity is possible - so when in doubt use {} to enclose the
1640 sub/superscript.
1641 Not all export backends support this, but HTML does.
1643 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1644 :group 'org-export-translation
1645 :type 'boolean)
1647 (defcustom org-export-with-TeX-macros t
1648 "Non-nil means, interpret simple TeX-like macros when exporting.
1649 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1650 No only real TeX macros will work here, but the standard HTML entities
1651 for math can be used as macro names as well. For a list of supported
1652 names in HTML export, see the constant `org-html-entities'.
1653 Not all export backends support this.
1655 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1656 :group 'org-export-translation
1657 :type 'boolean)
1659 (defcustom org-export-with-fixed-width t
1660 "Non-nil means, lines starting with \":\" will be in fixed width font.
1661 This can be used to have pre-formatted text, fragments of code etc. For
1662 example:
1663 : ;; Some Lisp examples
1664 : (while (defc cnt)
1665 : (ding))
1666 will be looking just like this in also HTML. See also the QUOTE keyword.
1667 Not all export backends support this.
1669 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1670 :group 'org-export-translation
1671 :type 'boolean)
1673 (defcustom org-match-sexp-depth 3
1674 "Number of stacked braces for sub/superscript matching.
1675 This has to be set before loading org.el to be effective."
1676 :group 'org-export-translation
1677 :type 'integer)
1679 (defgroup org-export-tables nil
1680 "Options for exporting tables in Org-mode."
1681 :tag "Org Export Tables"
1682 :group 'org-export)
1684 (defcustom org-export-with-tables t
1685 "If non-nil, lines starting with \"|\" define a table.
1686 For example:
1688 | Name | Address | Birthday |
1689 |-------------+----------+-----------|
1690 | Arthur Dent | England | 29.2.2100 |
1692 Not all export backends support this.
1694 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1695 :group 'org-export-tables
1696 :type 'boolean)
1698 (defcustom org-export-highlight-first-table-line t
1699 "Non-nil means, highlight the first table line.
1700 In HTML export, this means use <th> instead of <td>.
1701 In tables created with table.el, this applies to the first table line.
1702 In Org-mode tables, all lines before the first horizontal separator
1703 line will be formatted with <th> tags."
1704 :group 'org-export-tables
1705 :type 'boolean)
1707 (defcustom org-export-table-remove-special-lines t
1708 "Remove special lines and marking characters in calculating tables.
1709 This removes the special marking character column from tables that are set
1710 up for spreadsheet calculations. It also removes the entire lines
1711 marked with `!', `_', or `^'. The lines with `$' are kept, because
1712 the values of constants may be useful to have."
1713 :group 'org-export-tables
1714 :type 'boolean)
1716 (defcustom org-export-prefer-native-exporter-for-tables nil
1717 "Non-nil means, always export tables created with table.el natively.
1718 Natively means, use the HTML code generator in table.el.
1719 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1720 the table does not use row- or column-spanning). This has the
1721 advantage, that the automatic HTML conversions for math symbols and
1722 sub/superscripts can be applied. Org-mode's HTML generator is also
1723 much faster."
1724 :group 'org-export-tables
1725 :type 'boolean)
1727 (defgroup org-export-ascii nil
1728 "Options specific for ASCII export of Org-mode files."
1729 :tag "Org Export ASCII"
1730 :group 'org-export)
1732 (defcustom org-export-ascii-show-new-buffer t
1733 "Non-nil means, popup buffer containing the exported ASCII text.
1734 Otherwise the buffer will just be saved to a file and stay hidden."
1735 :group 'org-export-ascii
1736 :type 'boolean)
1738 (defgroup org-export-xml nil
1739 "Options specific for XML export of Org-mode files."
1740 :tag "Org Export XML"
1741 :group 'org-export)
1743 (defcustom org-export-xml-type 'xoxo ;kw, if we have only one.
1744 "The kind of XML to be produced by the XML exporter.
1745 Allowed values are:
1746 xoxo The XOXO exporter."
1747 :group 'org-export-xml
1748 :type '(choice
1749 (const :tag "XOXO" xoxo)))
1751 (defgroup org-export-html nil
1752 "Options specific for HTML export of Org-mode files."
1753 :tag "Org Export HTML"
1754 :group 'org-export)
1756 (defcustom org-export-html-style
1757 "<style type=\"text/css\">
1758 html {
1759 font-family: Times, serif;
1760 font-size: 12pt;
1762 .title { text-align: center; }
1763 .todo, .deadline { color: red; }
1764 .done { color: green; }
1765 .target { background-color: lavender; }
1766 pre {
1767 border: 1pt solid #AEBDCC;
1768 background-color: #F3F5F7;
1769 padding: 5pt;
1770 font-family: courier, monospace;
1772 table { border-collapse: collapse; }
1773 td, th {
1774 vertical-align: top;
1775 border: 1pt solid #ADB9CC;
1777 </style>"
1778 "The default style specification for exported HTML files.
1779 Since there are different ways of setting style information, this variable
1780 needs to contain the full HTML structure to provide a style, including the
1781 surrounding HTML tags. The style specifications should include definitions
1782 for new classes todo, done, title, and deadline. For example, legal values
1783 would be:
1785 <style type=\"text/css\">
1786 p { font-weight: normal; color: gray; }
1787 h1 { color: black; }
1788 .title { text-align: center; }
1789 .todo, .deadline { color: red; }
1790 .done { color: green; }
1791 </style>
1793 or, if you want to keep the style in a file,
1795 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1797 As the value of this option simply gets inserted into the HTML <head> header,
1798 you can \"misuse\" it to add arbitrary text to the header."
1799 :group 'org-export-html
1800 :type 'string)
1802 (defcustom org-export-html-inline-images t
1803 "Non-nil means, inline images into exported HTML pages.
1804 The link will still be to the original location of the image file.
1805 So if you are moving the page, lets say to your public HTML site,
1806 you will have to move the image and maybe change the link."
1807 :group 'org-export-html
1808 :type 'boolean)
1810 (defcustom org-export-html-expand t
1811 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1812 When nil, these tags will be exported as plain text and therefore
1813 not be interpreted by a browser.
1815 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1816 :group 'org-export-html
1817 :type 'boolean)
1819 (defcustom org-export-html-table-tag
1820 "<table border=1 cellspacing=0 cellpadding=6>"
1821 "The HTML tag used to start a table.
1822 This must be a <table> tag, but you may change the options like
1823 borders and spacing."
1824 :group 'org-export-html
1825 :type 'string)
1827 (defcustom org-export-html-with-timestamp nil
1828 "If non-nil, write `org-export-html-html-helper-timestamp'
1829 into the exported HTML text. Otherwise, the buffer will just be saved
1830 to a file."
1831 :group 'org-export-html
1832 :type 'boolean)
1834 (defcustom org-export-html-html-helper-timestamp
1835 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1836 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1837 :group 'org-export-html
1838 :type 'string)
1840 (defcustom org-export-html-show-new-buffer nil
1841 "Non-nil means, popup buffer containing the exported html text.
1842 Otherwise, the buffer will just be saved to a file and stay hidden."
1843 :group 'org-export-html
1844 :type 'boolean)
1846 (defgroup org-export-icalendar nil
1847 "Options specific for iCalendar export of Org-mode files."
1848 :tag "Org Export iCalendar"
1849 :group 'org-export)
1851 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1852 "The file name for the iCalendar file covering all agenda files.
1853 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1854 :group 'org-export-icalendar
1855 :type 'file)
1857 (defcustom org-icalendar-include-todo nil
1858 "Non-nil means, export to iCalendar files should also cover TODO items."
1859 :group 'org-export-icalendar
1860 :type 'boolean)
1862 (defcustom org-icalendar-combined-name "OrgMode"
1863 "Calendar name for the combined iCalendar representing all agenda files."
1864 :group 'org-export-icalendar
1865 :type 'string)
1867 (defgroup org-font-lock nil
1868 "Font-lock settings for highlighting in Org-mode."
1869 :tag "Org Font Lock"
1870 :group 'org)
1872 (defcustom org-level-color-stars-only nil
1873 "Non-nil means fontify only the stars in each headline.
1874 When nil, the entire headline is fontified.
1875 Changing it requires restart of `font-lock-mode' to become effective
1876 also in regions already fontified."
1877 :group 'org-font-lock
1878 :type 'boolean)
1880 (defcustom org-hide-leading-stars nil
1881 "Non-nil means, hide the first N-1 stars in a headline.
1882 This works by using the face `org-hide' for these stars. This
1883 face is white for a light background, and black for a dark
1884 background. You may have to customize the face `org-hide' to
1885 make this work.
1886 Changing it requires restart of `font-lock-mode' to become effective
1887 also in regions already fontified."
1888 :group 'org-font-lock
1889 :type 'boolean)
1891 (defcustom org-fontify-done-headline nil
1892 "Non-nil means, change the face of a headline if it is marked DONE.
1893 Normally, only the TODO/DONE keyword indicates the state of a headline.
1894 When this is non-nil, the headline after the keyword is set to the
1895 `org-headline-done' as an additional indication."
1896 :group 'org-font-lock
1897 :type 'boolean)
1899 (defcustom org-fontify-emphasized-text t
1900 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
1901 Changing this variable requires a restart of Emacs to take effect."
1902 :group 'org-font-lock
1903 :type 'boolean)
1905 (defgroup org-faces nil
1906 "Faces in Org-mode."
1907 :tag "Org Faces"
1908 :group 'org-font-lock)
1910 (defface org-hide
1912 (((type tty) (class color)) (:foreground "white"))
1913 (((class color) (background light)) (:foreground "white"))
1914 (((class color) (background dark)) (:foreground "black"))
1915 (t (:inverse-video nil)))
1916 "Face used for level 1 headlines."
1917 :group 'org-faces)
1919 (defface org-level-1 ;; font-lock-function-name-face
1920 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1921 (((class color) (background light)) (:foreground "Blue"))
1922 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1923 (t (:inverse-video t :bold t)))
1924 "Face used for level 1 headlines."
1925 :group 'org-faces)
1927 (defface org-level-2 ;; font-lock-variable-name-face
1928 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1929 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1930 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1931 (t (:bold t :italic t)))
1932 "Face used for level 2 headlines."
1933 :group 'org-faces)
1935 (defface org-level-3 ;; font-lock-keyword-face
1936 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1937 (((class color) (background light)) (:foreground "Purple"))
1938 (((class color) (background dark)) (:foreground "Cyan"))
1939 (t (:bold t)))
1940 "Face used for level 3 headlines."
1941 :group 'org-faces)
1943 (defface org-level-4 ;; font-lock-comment-face
1944 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1945 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1946 (((class color) (background light)) (:foreground "Firebrick"))
1947 (((class color) (background dark)) (:foreground "chocolate1"))
1948 (t (:bold t :italic t)))
1949 "Face used for level 4 headlines."
1950 :group 'org-faces)
1952 (defface org-level-5 ;; font-lock-type-face
1953 '((((type tty) (class color)) (:foreground "green"))
1954 (((class color) (background light)) (:foreground "ForestGreen"))
1955 (((class color) (background dark)) (:foreground "PaleGreen"))
1956 (t (:bold t :underline t)))
1957 "Face used for level 5 headlines."
1958 :group 'org-faces)
1960 (defface org-level-6 ;; font-lock-constant-face
1961 '((((type tty) (class color)) (:foreground "magenta"))
1962 (((class color) (background light)) (:foreground "CadetBlue"))
1963 (((class color) (background dark)) (:foreground "Aquamarine"))
1964 (t (:bold t :underline t)))
1965 "Face used for level 6 headlines."
1966 :group 'org-faces)
1968 (defface org-level-7 ;; font-lock-builtin-face
1969 '((((type tty) (class color)) (:foreground "blue" :weight light))
1970 (((class color) (background light)) (:foreground "Orchid"))
1971 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1972 (t (:bold t)))
1973 "Face used for level 7 headlines."
1974 :group 'org-faces)
1976 (defface org-level-8 ;; font-lock-string-face
1977 '((((type tty) (class color)) (:foreground "green"))
1978 (((class color) (background light)) (:foreground "RosyBrown"))
1979 (((class color) (background dark)) (:foreground "LightSalmon"))
1980 (t (:italic t)))
1981 "Face used for level 8 headlines."
1982 :group 'org-faces)
1984 (defface org-special-keyword ;; font-lock-string-face
1985 '((((type tty) (class color)) (:foreground "green"))
1986 (((class color) (background light)) (:foreground "RosyBrown"))
1987 (((class color) (background dark)) (:foreground "LightSalmon"))
1988 (t (:italic t)))
1989 "Face used for special keywords."
1990 :group 'org-faces)
1992 (defface org-warning ;; font-lock-warning-face
1993 '((((type tty) (class color)) (:foreground "red"))
1994 (((class color) (background light)) (:foreground "Red" :bold t))
1995 (((class color) (background dark)) (:foreground "Red1" :bold t))
1996 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
1997 (t (:inverse-video t :bold t)))
1998 "Face for deadlines and TODO keywords."
1999 :group 'org-faces)
2001 (defface org-headline-done ;; font-lock-string-face
2002 '((((type tty) (class color)) (:foreground "green"))
2003 (((class color) (background light)) (:foreground "RosyBrown"))
2004 (((class color) (background dark)) (:foreground "LightSalmon"))
2005 (t (:italic t)))
2006 "Face used to indicate that a headline is DONE. See also the variable
2007 `org-fontify-done-headline'."
2008 :group 'org-faces)
2010 ;; Inheritance does not work for xemacs. So we just copy...
2012 (defface org-deadline-announce
2013 '((((type tty) (class color)) (:foreground "blue" :weight bold))
2014 (((class color) (background light)) (:foreground "Blue"))
2015 (((class color) (background dark)) (:foreground "LightSkyBlue"))
2016 (t (:inverse-video t :bold t)))
2017 "Face for upcoming deadlines."
2018 :group 'org-faces)
2020 (defface org-scheduled-today
2021 '((((type tty) (class color)) (:foreground "green"))
2022 (((class color) (background light)) (:foreground "DarkGreen"))
2023 (((class color) (background dark)) (:foreground "PaleGreen"))
2024 (t (:bold t :underline t)))
2025 "Face for items scheduled for a certain day."
2026 :group 'org-faces)
2028 (defface org-scheduled-previously
2029 '((((type tty pc) (class color) (background light)) (:foreground "red"))
2030 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
2031 (((class color) (background light)) (:foreground "Firebrick"))
2032 (((class color) (background dark)) (:foreground "chocolate1"))
2033 (t (:bold t :italic t)))
2034 "Face for items scheduled previously, and not yet done."
2035 :group 'org-faces)
2037 (defface org-formula
2038 '((((type tty pc) (class color) (background light)) (:foreground "red"))
2039 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
2040 (((class color) (background light)) (:foreground "Firebrick"))
2041 (((class color) (background dark)) (:foreground "chocolate1"))
2042 (t (:bold t :italic t)))
2043 "Face for formulas."
2044 :group 'org-faces)
2046 (defface org-link
2047 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
2048 (((class color) (background light)) (:foreground "Purple" :underline t))
2049 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2050 (t (:bold t)))
2051 "Face for links."
2052 :group 'org-faces)
2054 (defface org-tag
2055 '((((type tty) (class color)) (:weight bold))
2056 (((class color) (background light)) (:weight bold))
2057 (((class color) (background dark)) (:weight bold))
2058 (t (:bold t)))
2059 "Face for tags."
2060 :group 'org-faces)
2062 (defface org-done ;; font-lock-type-face
2063 '((((type tty) (class color)) (:foreground "green"))
2064 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
2065 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
2066 (t (:bold t :underline t)))
2067 "Face used for DONE."
2068 :group 'org-faces)
2070 (defface org-table ;; font-lock-function-name-face
2071 '((((type tty) (class color)) (:foreground "blue" :weight bold))
2072 (((class color) (background light)) (:foreground "Blue"))
2073 (((class color) (background dark)) (:foreground "LightSkyBlue"))
2074 (t (:inverse-video t :bold t)))
2075 "Face used for tables."
2076 :group 'org-faces)
2078 (defface org-time-grid ;; font-lock-variable-name-face
2079 '((((type tty) (class color)) (:foreground "yellow" :weight light))
2080 (((class color) (background light)) (:foreground "DarkGoldenrod"))
2081 (((class color) (background dark)) (:foreground "LightGoldenrod"))
2082 (t (:bold t :italic t)))
2083 "Face used for time grids."
2084 :group 'org-faces)
2086 (defvar org-level-faces
2087 '(org-level-1 org-level-2 org-level-3 org-level-4
2088 org-level-5 org-level-6 org-level-7 org-level-8
2090 (defvar org-n-levels (length org-level-faces))
2093 ;; Variables for pre-computed regular expressions, all buffer local
2094 (defvar org-done-string nil
2095 "The last string in `org-todo-keywords', indicating an item is DONE.")
2096 (make-variable-buffer-local 'org-done-string)
2097 (defvar org-todo-regexp nil
2098 "Matches any of the TODO state keywords.")
2099 (make-variable-buffer-local 'org-todo-regexp)
2100 (defvar org-not-done-regexp nil
2101 "Matches any of the TODO state keywords except the last one.")
2102 (make-variable-buffer-local 'org-not-done-regexp)
2103 (defvar org-todo-line-regexp nil
2104 "Matches a headline and puts TODO state into group 2 if present.")
2105 (make-variable-buffer-local 'org-todo-line-regexp)
2106 (defvar org-nl-done-regexp nil
2107 "Matches newline followed by a headline with the DONE keyword.")
2108 (make-variable-buffer-local 'org-nl-done-regexp)
2109 (defvar org-looking-at-done-regexp nil
2110 "Matches the DONE keyword a point.")
2111 (make-variable-buffer-local 'org-looking-at-done-regexp)
2112 (defvar org-todo-kwd-priority-p nil
2113 "Do TODO items have priorities?")
2114 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2115 (defvar org-todo-kwd-max-priority nil
2116 "Maximum priority of TODO items.")
2117 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2118 (defvar org-ds-keyword-length 12
2119 "Maximum length of the Deadline and SCHEDULED keywords.")
2120 (make-variable-buffer-local 'org-ds-keyword-length)
2121 (defvar org-deadline-regexp nil
2122 "Matches the DEADLINE keyword.")
2123 (make-variable-buffer-local 'org-deadline-regexp)
2124 (defvar org-deadline-time-regexp nil
2125 "Matches the DEADLINE keyword together with a time stamp.")
2126 (make-variable-buffer-local 'org-deadline-time-regexp)
2127 (defvar org-deadline-line-regexp nil
2128 "Matches the DEADLINE keyword and the rest of the line.")
2129 (make-variable-buffer-local 'org-deadline-line-regexp)
2130 (defvar org-scheduled-regexp nil
2131 "Matches the SCHEDULED keyword.")
2132 (make-variable-buffer-local 'org-scheduled-regexp)
2133 (defvar org-scheduled-time-regexp nil
2134 "Matches the SCHEDULED keyword together with a time stamp.")
2135 (make-variable-buffer-local 'org-scheduled-time-regexp)
2137 (defun org-set-regexps-and-options ()
2138 "Precompute regular expressions for current buffer."
2139 (when (eq major-mode 'org-mode)
2140 (let ((re (org-make-options-regexp
2141 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2142 "STARTUP" "ARCHIVE")))
2143 (splitre "[ \t]+")
2144 kwds int key value cat arch)
2145 (save-excursion
2146 (save-restriction
2147 (widen)
2148 (goto-char (point-min))
2149 (while (re-search-forward re nil t)
2150 (setq key (match-string 1) value (match-string 2))
2151 (cond
2152 ((equal key "CATEGORY")
2153 (if (string-match "[ \t]+$" value)
2154 (setq value (replace-match "" t t value)))
2155 (setq cat (intern value)))
2156 ((equal key "SEQ_TODO")
2157 (setq int 'sequence
2158 kwds (append kwds (org-split-string value splitre))))
2159 ((equal key "PRI_TODO")
2160 (setq int 'priority
2161 kwds (append kwds (org-split-string value splitre))))
2162 ((equal key "TYP_TODO")
2163 (setq int 'type
2164 kwds (append kwds (org-split-string value splitre))))
2165 ((equal key "STARTUP")
2166 (let ((opts (org-split-string value splitre))
2167 (set '(("fold" org-startup-folded t)
2168 ("nofold" org-startup-folded nil)
2169 ("content" org-startup-folded content)
2170 ("hidestars" org-hide-leading-stars t)
2171 ("showstars" org-hide-leading-stars nil)
2172 ("odd" org-odd-levels-only t)
2173 ("oddeven" org-odd-levels-only nil)
2174 ("align" org-startup-align-all-tables t)
2175 ("noalign" org-startup-align-all-tables nil)
2176 ("dlcheck" org-startup-with-deadline-check t)
2177 ("nodlcheck" org-startup-with-deadline-check nil)))
2178 l var val)
2179 (while (setq l (assoc (pop opts) set))
2180 (setq var (nth 1 l) val (nth 2 l))
2181 (set (make-local-variable var) val))))
2182 ((equal key "ARCHIVE")
2183 (string-match " *$" value)
2184 (setq arch (replace-match "" t t value))
2185 (remove-text-properties 0 (length arch)
2186 '(face t fontified t) arch)))
2188 (and cat (set (make-local-variable 'org-category) cat))
2189 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2190 (and arch (set (make-local-variable 'org-archive-location) arch))
2191 (and int (set (make-local-variable 'org-todo-interpretation) int)))
2192 ;; Compute the regular expressions and other local variables
2193 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2194 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2195 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2196 (length org-scheduled-string)))
2197 org-done-string
2198 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2199 org-todo-regexp
2200 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2201 "\\|") "\\)\\>")
2202 org-not-done-regexp
2203 (concat "\\<\\("
2204 (mapconcat 'regexp-quote
2205 (nreverse (cdr (reverse org-todo-keywords)))
2206 "\\|")
2207 "\\)\\>")
2208 org-todo-line-regexp
2209 (concat "^\\(\\*+\\)[ \t]*\\("
2210 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2211 "\\)? *\\(.*\\)")
2212 org-nl-done-regexp
2213 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2214 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2215 org-deadline-regexp (concat "\\<" org-deadline-string)
2216 org-deadline-time-regexp
2217 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2218 org-deadline-line-regexp
2219 (concat "\\<\\(" org-deadline-string "\\).*")
2220 org-scheduled-regexp
2221 (concat "\\<" org-scheduled-string)
2222 org-scheduled-time-regexp
2223 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
2224 (org-set-font-lock-defaults)))
2226 ;; Tell the compiler about dynamically scoped variables,
2227 ;; and variables from other packages
2228 (defvar zmacs-regions) ; XEmacs regions
2229 (defvar original-date) ; dynamically scoped in calendar
2230 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2231 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2232 (defvar org-html-entities) ; defined later in this file
2233 (defvar org-goto-start-pos) ; dynamically scoped parameter
2234 (defvar org-time-was-given) ; dynamically scoped parameter
2235 (defvar org-ts-what) ; dynamically scoped parameter
2236 (defvar mark-active) ; Emacs only, not available in XEmacs.
2237 (defvar timecnt) ; dynamically scoped parameter
2238 (defvar levels-open) ; dynamically scoped parameter
2239 (defvar title) ; dynamically scoped parameter
2240 (defvar author) ; dynamically scoped parameter
2241 (defvar email) ; dynamically scoped parameter
2242 (defvar text) ; dynamically scoped parameter
2243 (defvar entry) ; dynamically scoped parameter
2244 (defvar date) ; dynamically scoped parameter
2245 (defvar language) ; dynamically scoped parameter
2246 (defvar options) ; dynamically scoped parameter
2247 (defvar ans1) ; dynamically scoped parameter
2248 (defvar ans2) ; dynamically scoped parameter
2249 (defvar starting-day) ; local variable
2250 (defvar include-all-loc) ; local variable
2251 (defvar vm-message-pointer) ; from vm
2252 (defvar vm-folder-directory) ; from vm
2253 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2254 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2255 (defvar gnus-group-name) ; from gnus
2256 (defvar gnus-article-current) ; from gnus
2257 (defvar w3m-current-url) ; from w3m
2258 (defvar mh-progs) ; from MH-E
2259 (defvar mh-current-folder) ; from MH-E
2260 (defvar mh-show-folder-buffer) ; from MH-E
2261 (defvar mh-index-folder) ; from MH-E
2262 (defvar mh-searcher) ; from MH-E
2263 (defvar org-selected-point) ; dynamically scoped parameter
2264 (defvar calendar-mode-map) ; from calendar.el
2265 (defvar last-arg) ; local variable
2266 (defvar remember-save-after-remembering) ; from remember.el
2267 (defvar remember-data-file) ; from remember.el
2268 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2269 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2270 (defvar orgtbl-mode) ; defined later in this file
2271 ;;; Define the mode
2273 (defvar org-mode-map (copy-keymap outline-mode-map)
2274 "Keymap for Org-mode.")
2276 (defvar org-struct-menu) ; defined later in this file
2277 (defvar org-org-menu) ; defined later in this file
2278 (defvar org-tbl-menu) ; defined later in this file
2280 ;; We use a before-change function to check if a table might need
2281 ;; an update.
2282 (defvar org-table-may-need-update t
2283 "Indicates that a table might need an update.
2284 This variable is set by `org-before-change-function'.
2285 `org-table-align' sets it back to nil.")
2286 (defvar org-mode-hook nil)
2287 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2288 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2291 ;;;###autoload
2292 (define-derived-mode org-mode outline-mode "Org"
2293 "Outline-based notes management and organizer, alias
2294 \"Carsten's outline-mode for keeping track of everything.\"
2296 Org-mode develops organizational tasks around a NOTES file which
2297 contains information about projects as plain text. Org-mode is
2298 implemented on top of outline-mode, which is ideal to keep the content
2299 of large files well structured. It supports ToDo items, deadlines and
2300 time stamps, which magically appear in the diary listing of the Emacs
2301 calendar. Tables are easily created with a built-in table editor.
2302 Plain text URL-like links connect to websites, emails (VM), Usenet
2303 messages (Gnus), BBDB entries, and any files related to the project.
2304 For printing and sharing of notes, an Org-mode file (or a part of it)
2305 can be exported as a structured ASCII or HTML file.
2307 The following commands are available:
2309 \\{org-mode-map}"
2310 (easy-menu-add org-org-menu)
2311 (easy-menu-add org-tbl-menu)
2312 (org-install-agenda-files-menu)
2313 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2314 (org-add-to-invisibility-spec '(org-cwidth))
2315 (setq outline-regexp "\\*+")
2316 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2317 (setq outline-level 'org-outline-level)
2318 (when (and org-ellipsis (stringp org-ellipsis))
2319 (unless org-display-table
2320 (setq org-display-table (make-display-table)))
2321 (set-display-table-slot org-display-table
2322 4 (string-to-vector org-ellipsis))
2323 (setq buffer-display-table org-display-table))
2324 (org-set-regexps-and-options)
2325 (if org-startup-truncated (setq truncate-lines t))
2326 (set (make-local-variable 'font-lock-unfontify-region-function)
2327 'org-unfontify-region)
2328 ;; Activate before-change-function
2329 (set (make-local-variable 'org-table-may-need-update) t)
2330 (org-add-hook 'before-change-functions 'org-before-change-function nil
2331 'local)
2332 ;; Paragraphs and auto-filling
2333 (org-set-autofill-regexps)
2334 (org-update-radio-target-regexp)
2335 ;; Settings for Calc embedded mode
2336 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2337 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2338 (if (and org-insert-mode-line-in-empty-file
2339 (interactive-p)
2340 (= (point-min) (point-max)))
2341 (insert " -*- mode: org -*-\n\n"))
2343 ;; Get rid of Outline menus, they are not needed
2344 ;; Need to do this here because define-derived-mode sets up
2345 ;; the keymap so late.
2346 (if (featurep 'xemacs)
2347 (progn
2348 (delete-menu-item '("Headings"))
2349 (delete-menu-item '("Show"))
2350 (delete-menu-item '("Hide"))
2351 (set-menubar-dirty-flag))
2352 (define-key org-mode-map [menu-bar headings] 'undefined)
2353 (define-key org-mode-map [menu-bar hide] 'undefined)
2354 (define-key org-mode-map [menu-bar show] 'undefined))
2356 (unless org-inhibit-startup
2357 (if org-startup-align-all-tables
2358 (org-table-map-tables 'org-table-align))
2359 (if org-startup-with-deadline-check
2360 (call-interactively 'org-check-deadlines)
2361 (cond
2362 ((eq org-startup-folded t)
2363 (org-cycle '(4)))
2364 ((eq org-startup-folded 'content)
2365 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2366 (org-cycle '(4)) (org-cycle '(4))))))))
2368 (defsubst org-current-line (&optional pos)
2369 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2371 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2372 mouse-map t)
2373 "Properties to remove when a string without properties is wanted.")
2375 (defsubst org-match-string-no-properties (num &optional string)
2376 (if (featurep 'xemacs)
2377 (let ((s (match-string num string)))
2378 (remove-text-properties 0 (length s) org-rm-props s)
2380 (match-string-no-properties num string)))
2382 (defun org-current-time ()
2383 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2384 (if (> org-time-stamp-rounding-minutes 0)
2385 (let ((r org-time-stamp-rounding-minutes)
2386 (time (decode-time)))
2387 (apply 'encode-time
2388 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2389 (nthcdr 2 time))))
2390 (current-time)))
2392 (defun org-add-props (string plist &rest props)
2393 "Add text properties to entire string, from beginning to end.
2394 PLIST may be a list of properties, PROPS are individual properties and values
2395 that will be added to PLIST. Returns the string that was modified."
2396 (add-text-properties
2397 0 (length string) (if props (append plist props) plist) string)
2398 string)
2399 (put 'org-add-props 'lisp-indent-function 2)
2402 ;;; Font-Lock stuff
2404 (defvar org-mouse-map (make-sparse-keymap))
2405 (define-key org-mouse-map
2406 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
2407 (define-key org-mouse-map
2408 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
2409 (define-key org-mouse-map [follow-link] 'mouse-face)
2410 (when org-tab-follows-link
2411 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2412 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2413 (when org-return-follows-link
2414 (define-key org-mouse-map [(return)] 'org-open-at-point)
2415 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2417 (require 'font-lock)
2419 (defconst org-non-link-chars "]\t\n\r<>")
2420 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
2421 "wl" "mhe" "rmail" "gnus" "shell"))
2422 (defconst org-link-re-with-space
2423 (concat
2424 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2425 "\\([^" org-non-link-chars " ]"
2426 "[^" org-non-link-chars "]*"
2427 "[^" org-non-link-chars " ]\\)>?")
2428 "Matches a link with spaces, optional angular brackets around it.")
2430 (defconst org-link-re-with-space2
2431 (concat
2432 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2433 "\\([^" org-non-link-chars " ]"
2434 "[^]\t\n\r]*"
2435 "[^" org-non-link-chars " ]\\)>?")
2436 "Matches a link with spaces, optional angular brackets around it.")
2438 (defconst org-angle-link-re
2439 (concat
2440 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2441 "\\([^" org-non-link-chars " ]"
2442 "[^" org-non-link-chars "]*"
2443 "\\)>")
2444 "Matches link with angular brackets, spaces are allowed.")
2445 (defconst org-plain-link-re
2446 (concat
2447 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2448 "\\([^]\t\n\r<>,;() ]+\\)")
2449 "Matches plain link, without spaces.")
2451 (defconst org-bracket-link-regexp
2452 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2453 "Matches a link in double brackets.")
2455 (defconst org-bracket-link-analytic-regexp
2456 (concat
2457 "\\[\\["
2458 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
2459 "\\([^]]+\\)"
2460 "\\]"
2461 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
2462 "\\]"))
2463 ; 1: http:
2464 ; 2: http
2465 ; 3: path
2466 ; 4: [desc]
2467 ; 5: desc
2470 (defconst org-ts-lengths
2471 (cons (length (format-time-string (car org-time-stamp-formats)))
2472 (length (format-time-string (cdr org-time-stamp-formats))))
2473 "This holds the lengths of the two different time formats.")
2474 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2475 "Regular expression for fast time stamp matching.")
2476 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2477 "Regular expression for fast time stamp matching.")
2478 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2479 "Regular expression matching time strings for analysis.")
2480 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2481 "Regular expression matching time stamps, with groups.")
2482 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2483 "Regular expression matching a time stamp range.")
2484 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2485 org-ts-regexp "\\)?")
2486 "Regular expression matching a time stamp or time stamp range.")
2488 (defun org-activate-plain-links (limit)
2489 "Run through the buffer and add overlays to links."
2490 (if (re-search-forward org-plain-link-re limit t)
2491 (progn
2492 (add-text-properties (match-beginning 0) (match-end 0)
2493 (list 'mouse-face 'highlight
2494 'keymap org-mouse-map
2496 t)))
2498 (defun org-activate-angle-links (limit)
2499 "Run through the buffer and add overlays to links."
2500 (if (re-search-forward org-angle-link-re limit t)
2501 (progn
2502 (add-text-properties (match-beginning 0) (match-end 0)
2503 (list 'mouse-face 'highlight
2504 'keymap org-mouse-map
2506 t)))
2508 (defun org-activate-bracket-links (limit)
2509 "Run through the buffer and add overlays to bracketed links."
2510 (if (re-search-forward org-bracket-link-regexp limit t)
2511 (let* ((help (concat "LINK: " (org-match-string-no-properties 1)))
2512 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
2513 'keymap org-mouse-map 'mouse-face 'highlight
2514 'help-echo help))
2515 (vp (list 'rear-nonsticky t
2516 'keymap org-mouse-map 'mouse-face 'highlight
2517 'help-echo help)))
2518 ;; We need to remove the invisible property here. Table narrowing
2519 ;; may have made some of this invisible.
2520 (remove-text-properties (match-beginning 0) (match-end 0)
2521 '(invisible nil))
2522 (if (match-end 3)
2523 (progn
2524 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
2525 (add-text-properties (match-beginning 3) (match-end 3) vp)
2526 (add-text-properties (match-end 3) (match-end 0) ip))
2527 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
2528 (add-text-properties (match-beginning 1) (match-end 1) vp)
2529 (add-text-properties (match-end 1) (match-end 0) ip))
2530 t)))
2532 (defun org-activate-dates (limit)
2533 "Run through the buffer and add overlays to dates."
2534 (if (re-search-forward org-tsr-regexp limit t)
2535 (progn
2536 (add-text-properties (match-beginning 0) (match-end 0)
2537 (list 'mouse-face 'highlight
2538 'keymap org-mouse-map))
2539 t)))
2541 (defvar org-target-link-regexp nil
2542 "Regular expression matching radio targets in plain text.")
2543 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2544 "Regular expression matching a link target.")
2545 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2546 "Regular expression matching a link target.")
2548 (defun org-activate-target-links (limit)
2549 "Run through the buffer and add overlays to target matches."
2550 (when org-target-link-regexp
2551 (let ((case-fold-search t))
2552 (if (re-search-forward org-target-link-regexp limit t)
2553 (progn
2554 (add-text-properties (match-beginning 0) (match-end 0)
2555 (list 'mouse-face 'highlight
2556 'keymap org-mouse-map
2557 'help-echo "Radio target link"
2558 'org-linked-text t))
2559 t)))))
2561 (defun org-update-radio-target-regexp ()
2562 "Find all radio targets in this file and update the regular expression."
2563 (interactive)
2564 (when (memq 'radio org-activate-links)
2565 (setq org-target-link-regexp
2566 (org-make-target-link-regexp (org-all-targets 'radio)))
2567 (org-restart-font-lock)))
2569 (defun org-hide-wide-columns (limit)
2570 (let (s e)
2571 (setq s (text-property-any (point) (or limit (point-max))
2572 'org-cwidth t))
2573 (when s
2574 (setq e (next-single-property-change s 'org-cwidth))
2575 (add-text-properties s e '(invisible org-cwidth intangible t))
2576 (goto-char e)
2577 t)))
2579 (defun org-restart-font-lock ()
2580 "Restart font-lock-mode, to force refontification."
2581 (when (and (boundp 'font-lock-mode) font-lock-mode)
2582 (font-lock-mode -1)
2583 (font-lock-mode 1)))
2585 (defun org-all-targets (&optional radio)
2586 "Return a list of all targets in this file.
2587 With optional argument RADIO, only find radio targets."
2588 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2589 rtn)
2590 (save-excursion
2591 (goto-char (point-min))
2592 (while (re-search-forward re nil t)
2593 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
2594 rtn)))
2596 (defun org-make-target-link-regexp (targets)
2597 "Make regular expression matching all strings in TARGETS.
2598 The regular expression finds the targets also if there is a line break
2599 between words."
2600 (and targets
2601 (concat
2602 "\\<\\("
2603 (mapconcat
2604 (lambda (x)
2605 (while (string-match " +" x)
2606 (setq x (replace-match "\\s-+" t t x)))
2608 targets
2609 "\\|")
2610 "\\)\\>")))
2612 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2613 "Matches CamelCase words, possibly with a star before it.")
2615 (defun org-activate-camels (limit)
2616 "Run through the buffer and add overlays to dates."
2617 (if (re-search-forward org-camel-regexp limit t)
2618 (progn
2619 (add-text-properties (match-beginning 0) (match-end 0)
2620 (list 'mouse-face 'highlight
2621 'keymap org-mouse-map))
2622 t)))
2624 (defun org-activate-tags (limit)
2625 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2626 (progn
2627 (add-text-properties (match-beginning 1) (match-end 1)
2628 (list 'mouse-face 'highlight
2629 'keymap org-mouse-map))
2630 t)))
2632 (defun org-font-lock-level ()
2633 (save-excursion
2634 (org-back-to-heading t)
2635 (- (match-end 0) (match-beginning 0))))
2637 (defun org-outline-level ()
2638 (save-excursion
2639 (looking-at outline-regexp)
2640 (if (match-beginning 1)
2641 (+ (org-get-string-indentation (match-string 1)) 1000)
2642 (- (match-end 0) (match-beginning 0)))))
2644 (defvar org-font-lock-keywords nil)
2646 (defun org-set-font-lock-defaults ()
2647 (let* ((em org-fontify-emphasized-text)
2648 (lk org-activate-links)
2649 (org-font-lock-extra-keywords
2650 (list
2651 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
2652 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
2653 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2654 (1 'org-table))
2655 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
2656 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
2657 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
2658 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
2659 (if (memq 'date lk) '(org-activate-dates (0 'org-link t)))
2660 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
2661 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
2662 (if org-table-limit-column-width
2663 '(org-hide-wide-columns (0 nil append)))
2664 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2665 '(1 'org-warning t))
2666 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2667 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2668 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2669 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2670 (if em '("\\(\\W\\|^\\)\\(\\*\\w+\\*\\)\\(\\W\\|$\\)" 2 'bold prepend))
2671 (if em '("\\(\\W\\|^\\)\\(/\\w+/\\)\\(\\W\\|$\\)" 2 'italic prepend))
2672 (if em '("\\(\\W\\|^\\)\\(_\\w+_\\)\\(\\W\\|$\\)" 2 'underline prepend))
2673 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2674 "\\|" org-quote-string "\\)\\>")
2675 '(1 'org-special-keyword t))
2676 '("^#.*" (0 'font-lock-comment-face t))
2677 (if org-fontify-done-headline
2678 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2679 '(1 'org-done t) '(2 'org-headline-done t))
2680 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2681 '(1 'org-done t)))
2682 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2683 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2684 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2685 (if org-format-transports-properties-p
2686 '("| *\\(<[0-9]+>\\) *|" (1 'org-formula t)))
2688 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
2689 ;; Now set the full font-lock-keywords
2690 (set (make-local-variable 'org-font-lock-keywords)
2691 org-font-lock-extra-keywords)
2692 (set (make-local-variable 'font-lock-defaults)
2693 '(org-font-lock-keywords t nil nil backward-paragraph))
2694 (kill-local-variable 'font-lock-keywords) nil))
2696 (defvar org-m nil)
2697 (defvar org-l nil)
2698 (defvar org-f nil)
2699 (defun org-get-level-face (n)
2700 "Get the right face for match N in font-lock matching of healdines."
2701 (setq org-l (- (match-end 2) (match-beginning 1)))
2702 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
2703 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
2704 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
2705 (cond
2706 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
2707 ((eq n 2) org-f)
2708 (t (if org-level-color-stars-only nil org-f))))
2710 (defun org-unfontify-region (beg end &optional maybe_loudly)
2711 "Remove fontification and activation overlays from links."
2712 (font-lock-default-unfontify-region beg end)
2713 (let* ((buffer-undo-list t)
2714 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2715 (inhibit-modification-hooks t)
2716 deactivate-mark buffer-file-name buffer-file-truename)
2717 (remove-text-properties beg end
2718 '(mouse-face nil keymap nil org-linked-text nil
2719 invisible nil intangible nil))))
2720 ;;; Visibility cycling
2722 (defvar org-cycle-global-status nil)
2723 (defvar org-cycle-subtree-status nil)
2724 (defun org-cycle (&optional arg)
2725 "Visibility cycling for Org-mode.
2727 - When this function is called with a prefix argument, rotate the entire
2728 buffer through 3 states (global cycling)
2729 1. OVERVIEW: Show only top-level headlines.
2730 2. CONTENTS: Show all headlines of all levels, but no body text.
2731 3. SHOW ALL: Show everything.
2733 - When point is at the beginning of a headline, rotate the subtree started
2734 by this line through 3 different states (local cycling)
2735 1. FOLDED: Only the main headline is shown.
2736 2. CHILDREN: The main headline and the direct children are shown.
2737 From this state, you can move to one of the children
2738 and zoom in further.
2739 3. SUBTREE: Show the entire subtree, including body text.
2741 - When there is a numeric prefix, go up to a heading with level ARG, do
2742 a `show-subtree' and return to the previous cursor position. If ARG
2743 is negative, go up that many levels.
2745 - When point is not at the beginning of a headline, execute
2746 `indent-relative', like TAB normally does. See the option
2747 `org-cycle-emulate-tab' for details.
2749 - Special case: if point is the the beginning of the buffer and there is
2750 no headline in line 1, this function will act as if called with prefix arg."
2751 (interactive "P")
2753 (if (or (and (bobp) (not (looking-at outline-regexp)))
2754 (equal arg '(4)))
2755 ;; special case: use global cycling
2756 (setq arg t))
2758 (let ((outline-regexp
2759 (if org-cycle-include-plain-lists
2760 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2761 outline-regexp)))
2763 (cond
2765 ((org-at-table-p 'any)
2766 ;; Enter the table or move to the next field in the table
2767 (or (org-table-recognize-table.el)
2768 (progn
2769 (if arg (org-table-edit-field t)
2770 (org-table-justify-field-maybe)
2771 (org-table-next-field)))))
2773 ((eq arg t) ;; Global cycling
2775 (cond
2776 ((and (eq last-command this-command)
2777 (eq org-cycle-global-status 'overview))
2778 ;; We just created the overview - now do table of contents
2779 ;; This can be slow in very large buffers, so indicate action
2780 (message "CONTENTS...")
2781 (save-excursion
2782 ;; Visit all headings and show their offspring
2783 (goto-char (point-max))
2784 (catch 'exit
2785 (while (and (progn (condition-case nil
2786 (outline-previous-visible-heading 1)
2787 (error (goto-char (point-min))))
2789 (looking-at outline-regexp))
2790 (show-branches)
2791 (if (bobp) (throw 'exit nil))))
2792 (message "CONTENTS...done"))
2793 (setq org-cycle-global-status 'contents)
2794 (run-hook-with-args 'org-cycle-hook 'contents))
2796 ((and (eq last-command this-command)
2797 (eq org-cycle-global-status 'contents))
2798 ;; We just showed the table of contents - now show everything
2799 (show-all)
2800 (message "SHOW ALL")
2801 (setq org-cycle-global-status 'all)
2802 (run-hook-with-args 'org-cycle-hook 'all))
2805 ;; Default action: go to overview
2806 (hide-sublevels 1)
2807 (message "OVERVIEW")
2808 (setq org-cycle-global-status 'overview)
2809 (run-hook-with-args 'org-cycle-hook 'overview))))
2811 ((integerp arg)
2812 ;; Show-subtree, ARG levels up from here.
2813 (save-excursion
2814 (org-back-to-heading)
2815 (outline-up-heading (if (< arg 0) (- arg)
2816 (- (funcall outline-level) arg)))
2817 (org-show-subtree)))
2819 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2820 ;; At a heading: rotate between three different views
2821 (org-back-to-heading)
2822 (let ((goal-column 0) eoh eol eos)
2823 ;; First, some boundaries
2824 (save-excursion
2825 (org-back-to-heading)
2826 (save-excursion
2827 (beginning-of-line 2)
2828 (while (and (not (eobp)) ;; this is like `next-line'
2829 (get-char-property (1- (point)) 'invisible))
2830 (beginning-of-line 2)) (setq eol (point)))
2831 (outline-end-of-heading) (setq eoh (point))
2832 (org-end-of-subtree t) (setq eos (point))
2833 (outline-next-heading))
2834 ;; Find out what to do next and set `this-command'
2835 (cond
2836 ((= eos eoh)
2837 ;; Nothing is hidden behind this heading
2838 (message "EMPTY ENTRY")
2839 (setq org-cycle-subtree-status nil))
2840 ((>= eol eos)
2841 ;; Entire subtree is hidden in one line: open it
2842 (org-show-entry)
2843 (show-children)
2844 (message "CHILDREN")
2845 (setq org-cycle-subtree-status 'children)
2846 (run-hook-with-args 'org-cycle-hook 'children))
2847 ((and (eq last-command this-command)
2848 (eq org-cycle-subtree-status 'children))
2849 ;; We just showed the children, now show everything.
2850 (org-show-subtree)
2851 (message "SUBTREE")
2852 (setq org-cycle-subtree-status 'subtree)
2853 (run-hook-with-args 'org-cycle-hook 'subtree))
2855 ;; Default action: hide the subtree.
2856 (hide-subtree)
2857 (message "FOLDED")
2858 (setq org-cycle-subtree-status 'folded)
2859 (run-hook-with-args 'org-cycle-hook 'folded)))))
2861 ;; TAB emulation
2862 (buffer-read-only (org-back-to-heading))
2863 ((if (and (eq org-cycle-emulate-tab 'white)
2864 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2866 (eq org-cycle-emulate-tab t))
2867 (if (and (looking-at "[ \n\r\t]")
2868 (string-match "^[ \t]*$" (buffer-substring
2869 (point-at-bol) (point))))
2870 (progn
2871 (beginning-of-line 1)
2872 (and (looking-at "[ \t]+") (replace-match ""))))
2873 (indent-relative))
2875 (t (save-excursion
2876 (org-back-to-heading)
2877 (org-cycle))))))
2879 (defun org-optimize-window-after-visibility-change (state)
2880 "Adjust the window after a change in outline visibility.
2881 This function is the default value of the hook `org-cycle-hook'."
2882 (when (get-buffer-window (current-buffer))
2883 (cond
2884 ((eq state 'overview) (org-first-headline-recenter 1))
2885 ((eq state 'content) nil)
2886 ((eq state 'all) nil)
2887 ((eq state 'folded) nil)
2888 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2889 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
2891 (defun org-subtree-end-visible-p ()
2892 "Is the end of the current subtree visible?"
2893 (pos-visible-in-window-p
2894 (save-excursion (org-end-of-subtree t) (point))))
2896 (defun org-first-headline-recenter (&optional N)
2897 "Move cursor to the first headline and recenter the headline.
2898 Optional argument N means, put the headline into the Nth line of the window."
2899 (goto-char (point-min))
2900 (when (re-search-forward (concat "^" outline-regexp) nil t)
2901 (beginning-of-line)
2902 (recenter (prefix-numeric-value N))))
2904 (defvar org-goto-window-configuration nil)
2905 (defvar org-goto-marker nil)
2906 (defvar org-goto-map (make-sparse-keymap))
2907 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2908 (while (setq cmd (pop cmds))
2909 (substitute-key-definition cmd cmd org-goto-map global-map)))
2910 (define-key org-goto-map "\C-m" 'org-goto-ret)
2911 (define-key org-goto-map [(left)] 'org-goto-left)
2912 (define-key org-goto-map [(right)] 'org-goto-right)
2913 (define-key org-goto-map [(?q)] 'org-goto-quit)
2914 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2915 (define-key org-goto-map "\C-i" 'org-cycle)
2916 (define-key org-goto-map [(tab)] 'org-cycle)
2917 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2918 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2919 (define-key org-goto-map "n" 'outline-next-visible-heading)
2920 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2921 (define-key org-goto-map "f" 'outline-forward-same-level)
2922 (define-key org-goto-map "b" 'outline-backward-same-level)
2923 (define-key org-goto-map "u" 'outline-up-heading)
2924 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2925 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2926 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2927 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2928 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2929 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2930 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2932 (defconst org-goto-help
2933 "Select a location to jump to, press RET
2934 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2936 (defun org-goto ()
2937 "Go to a different location of the document, keeping current visibility.
2939 When you want to go to a different location in a document, the fastest way
2940 is often to fold the entire buffer and then dive into the tree. This
2941 method has the disadvantage, that the previous location will be folded,
2942 which may not be what you want.
2944 This command works around this by showing a copy of the current buffer in
2945 overview mode. You can dive into the tree in that copy, to find the
2946 location you want to reach. When pressing RET, the command returns to the
2947 original buffer in which the visibility is still unchanged. It then jumps
2948 to the new location, making it and the headline hierarchy above it visible."
2949 (interactive)
2950 (let* ((org-goto-start-pos (point))
2951 (selected-point
2952 (org-get-location (current-buffer) org-goto-help)))
2953 (if selected-point
2954 (progn
2955 (org-mark-ring-push org-goto-start-pos)
2956 (goto-char selected-point)
2957 (if (or (org-invisible-p) (org-invisible-p2))
2958 (org-show-hierarchy-above)))
2959 (error "Quit"))))
2961 (defun org-get-location (buf help)
2962 "Let the user select a location in the Org-mode buffer BUF.
2963 This function uses a recursive edit. It returns the selected position
2964 or nil."
2965 (let (org-selected-point)
2966 (save-excursion
2967 (save-window-excursion
2968 (delete-other-windows)
2969 (switch-to-buffer (get-buffer-create "*org-goto*"))
2970 (with-output-to-temp-buffer "*Help*"
2971 (princ help))
2972 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2973 (setq buffer-read-only nil)
2974 (erase-buffer)
2975 (insert-buffer-substring buf)
2976 (let ((org-startup-truncated t)
2977 (org-startup-folded t)
2978 (org-startup-align-all-tables nil)
2979 (org-startup-with-deadline-check nil))
2980 (org-mode))
2981 (setq buffer-read-only t)
2982 (if (boundp 'org-goto-start-pos)
2983 (goto-char org-goto-start-pos)
2984 (goto-char (point-min)))
2985 (org-beginning-of-line)
2986 (message "Select location and press RET")
2987 ;; now we make sure that during selection, ony very few keys work
2988 ;; and that it is impossible to switch to another window.
2989 (let ((gm (current-global-map))
2990 (overriding-local-map org-goto-map))
2991 (unwind-protect
2992 (progn
2993 (use-global-map org-goto-map)
2994 (recursive-edit))
2995 (use-global-map gm)))))
2996 (kill-buffer "*org-goto*")
2997 org-selected-point))
2999 ;; FIXME: It may not be a good idea to temper with the prefix argument...
3000 (defun org-goto-ret (&optional arg)
3001 "Finish `org-goto' by going to the new location."
3002 (interactive "P")
3003 (setq org-selected-point (point)
3004 current-prefix-arg arg)
3005 (throw 'exit nil))
3007 (defun org-goto-left ()
3008 "Finish `org-goto' by going to the new location."
3009 (interactive)
3010 (if (org-on-heading-p)
3011 (progn
3012 (beginning-of-line 1)
3013 (setq org-selected-point (point)
3014 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3015 (throw 'exit nil))
3016 (error "Not on a heading")))
3018 (defun org-goto-right ()
3019 "Finish `org-goto' by going to the new location."
3020 (interactive)
3021 (if (org-on-heading-p)
3022 (progn
3023 (outline-end-of-subtree)
3024 (or (eobp) (forward-char 1))
3025 (setq org-selected-point (point)
3026 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3027 (throw 'exit nil))
3028 (error "Not on a heading")))
3030 (defun org-goto-quit ()
3031 "Finish `org-goto' without cursor motion."
3032 (interactive)
3033 (setq org-selected-point nil)
3034 (throw 'exit nil))
3036 ;;; Promotion, Demotion, Inserting new headlines
3038 (defvar org-ignore-region nil
3039 "To temporarily disable the active region.")
3041 (defun org-insert-heading (&optional force-heading)
3042 "Insert a new heading or item with same depth at point."
3043 (interactive "P")
3044 (when (or force-heading (not (org-insert-item)))
3045 (let* ((head (save-excursion
3046 (condition-case nil
3047 (org-back-to-heading)
3048 (error (outline-next-heading)))
3049 (prog1 (match-string 0)
3050 (funcall outline-level)))))
3051 (unless (bolp) (newline))
3052 (insert head)
3053 (if (looking-at "[ \t]*")
3054 (replace-match " "))
3055 (run-hooks 'org-insert-heading-hook))))
3057 (defun org-insert-item ()
3058 "Insert a new item at the current level.
3059 Return t when things worked, nil when we are not in an item."
3060 (when (save-excursion
3061 (condition-case nil
3062 (progn
3063 (org-beginning-of-item)
3064 (org-at-item-p)
3066 (error nil)))
3067 (unless (bolp) (newline))
3068 (insert (match-string 0))
3069 (org-maybe-renumber-ordered-list)
3072 (defun org-insert-todo-heading (arg)
3073 "Insert a new heading with the same level and TODO state as current heading.
3074 If the heading has no TODO state, or if the state is DONE, use the first
3075 state (TODO by default). Also with prefix arg, force first state."
3076 (interactive "P")
3077 (org-insert-heading)
3078 (save-excursion
3079 (org-back-to-heading)
3080 (outline-previous-heading)
3081 (looking-at org-todo-line-regexp))
3082 (if (or arg
3083 (not (match-beginning 2))
3084 (equal (match-string 2) org-done-string))
3085 (insert (car org-todo-keywords) " ")
3086 (insert (match-string 2) " ")))
3088 (defun org-promote-subtree ()
3089 "Promote the entire subtree.
3090 See also `org-promote'."
3091 (interactive)
3092 (save-excursion
3093 (org-map-tree 'org-promote)))
3095 (defun org-demote-subtree ()
3096 "Demote the entire subtree. See `org-demote'.
3097 See also `org-promote'."
3098 (interactive)
3099 (save-excursion
3100 (org-map-tree 'org-demote)))
3102 (defun org-do-promote ()
3103 "Promote the current heading higher up the tree.
3104 If the region is active in `transient-mark-mode', promote all headings
3105 in the region."
3106 (interactive)
3107 (save-excursion
3108 (if (org-region-active-p)
3109 (org-map-region 'org-promote (region-beginning) (region-end))
3110 (org-promote)))
3111 (org-fix-position-after-promote))
3113 (defun org-do-demote ()
3114 "Demote the current heading lower down the tree.
3115 If the region is active in `transient-mark-mode', demote all headings
3116 in the region."
3117 (interactive)
3118 (save-excursion
3119 (if (org-region-active-p)
3120 (org-map-region 'org-demote (region-beginning) (region-end))
3121 (org-demote)))
3122 (org-fix-position-after-promote))
3124 (defun org-fix-position-after-promote ()
3125 "Make sure that after pro/demotion cursor position is right."
3126 (and (equal (char-after) ?\ )
3127 (equal (char-before) ?*)
3128 (forward-char 1)))
3130 (defun org-get-legal-level (level change)
3131 "Rectify a level change under the influence of `org-odd-levels-only'
3132 LEVEL is a current level, CHANGE is by how much the level should be
3133 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3134 even level numbers will become the next higher odd number."
3135 (if org-odd-levels-only
3136 (cond ((not change) (1+ (* 2 (/ level 2))))
3137 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3138 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3139 (max 1 (+ level change))))
3141 (defun org-promote ()
3142 "Promote the current heading higher up the tree.
3143 If the region is active in `transient-mark-mode', promote all headings
3144 in the region."
3145 (org-back-to-heading t)
3146 (let* ((level (save-match-data (funcall outline-level)))
3147 (up-head (make-string (org-get-legal-level level -1) ?*))
3148 (diff (abs (- level (length up-head)))))
3149 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3150 (replace-match up-head nil t)
3151 ;; Fixup tag positioning
3152 (and org-auto-align-tags (org-set-tags nil t))
3153 (if org-adapt-indentation
3154 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
3155 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
3157 (defun org-demote ()
3158 "Demote the current heading lower down the tree.
3159 If the region is active in `transient-mark-mode', demote all headings
3160 in the region."
3161 (org-back-to-heading t)
3162 (let* ((level (save-match-data (funcall outline-level)))
3163 (down-head (make-string (org-get-legal-level level 1) ?*))
3164 (diff (abs (- level (length down-head)))))
3165 (replace-match down-head nil t)
3166 ;; Fixup tag positioning
3167 (and org-auto-align-tags (org-set-tags nil t))
3168 (if org-adapt-indentation
3169 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
3171 (defun org-map-tree (fun)
3172 "Call FUN for every heading underneath the current one."
3173 (org-back-to-heading)
3174 (let ((level (funcall outline-level)))
3175 (save-excursion
3176 (funcall fun)
3177 (while (and (progn
3178 (outline-next-heading)
3179 (> (funcall outline-level) level))
3180 (not (eobp)))
3181 (funcall fun)))))
3183 (defun org-map-region (fun beg end)
3184 "Call FUN for every heading between BEG and END."
3185 (let ((org-ignore-region t))
3186 (save-excursion
3187 (setq end (copy-marker end))
3188 (goto-char beg)
3189 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3190 (< (point) end))
3191 (funcall fun))
3192 (while (and (progn
3193 (outline-next-heading)
3194 (< (point) end))
3195 (not (eobp)))
3196 (funcall fun)))))
3198 (defun org-fixup-indentation (from to prohibit)
3199 "Change the indentation in the current entry by re-replacing FROM with TO.
3200 However, if the regexp PROHIBIT matches at all, don't do anything.
3201 This is being used to change indentation along with the length of the
3202 heading marker. But if there are any lines which are not indented, nothing
3203 is changed at all."
3204 (save-excursion
3205 (let ((end (save-excursion (outline-next-heading)
3206 (point-marker))))
3207 (unless (save-excursion (re-search-forward prohibit end t))
3208 (while (re-search-forward from end t)
3209 (replace-match to)
3210 (beginning-of-line 2)))
3211 (move-marker end nil))))
3213 ;;; Vertical tree motion, cutting and pasting of subtrees
3215 (defun org-move-subtree-up (&optional arg)
3216 "Move the current subtree up past ARG headlines of the same level."
3217 (interactive "p")
3218 (org-move-subtree-down (- (prefix-numeric-value arg))))
3220 (defun org-move-subtree-down (&optional arg)
3221 "Move the current subtree down past ARG headlines of the same level."
3222 (interactive "p")
3223 (setq arg (prefix-numeric-value arg))
3224 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3225 'outline-get-last-sibling))
3226 (ins-point (make-marker))
3227 (cnt (abs arg))
3228 beg end txt folded)
3229 ;; Select the tree
3230 (org-back-to-heading)
3231 (setq beg (point))
3232 (save-match-data
3233 (save-excursion (outline-end-of-heading)
3234 (setq folded (org-invisible-p)))
3235 (outline-end-of-subtree))
3236 (outline-next-heading)
3237 (setq end (point))
3238 ;; Find insertion point, with error handling
3239 (goto-char beg)
3240 (while (> cnt 0)
3241 (or (and (funcall movfunc) (looking-at outline-regexp))
3242 (progn (goto-char beg)
3243 (error "Cannot move past superior level or buffer limit")))
3244 (setq cnt (1- cnt)))
3245 (if (> arg 0)
3246 ;; Moving forward - still need to move over subtree
3247 (progn (outline-end-of-subtree)
3248 (outline-next-heading)
3249 (if (not (or (looking-at (concat "^" outline-regexp))
3250 (bolp)))
3251 (newline))))
3252 (move-marker ins-point (point))
3253 (setq txt (buffer-substring beg end))
3254 (delete-region beg end)
3255 (insert txt)
3256 (goto-char ins-point)
3257 (if folded (hide-subtree))
3258 (move-marker ins-point nil)))
3260 (defvar org-subtree-clip ""
3261 "Clipboard for cut and paste of subtrees.
3262 This is actually only a copy of the kill, because we use the normal kill
3263 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3265 (defvar org-subtree-clip-folded nil
3266 "Was the last copied subtree folded?
3267 This is used to fold the tree back after pasting.")
3269 (defun org-cut-subtree ()
3270 "Cut the current subtree into the clipboard.
3271 This is a short-hand for marking the subtree and then cutting it."
3272 (interactive)
3273 (org-copy-subtree 'cut))
3275 (defun org-copy-subtree (&optional cut)
3276 "Cut the current subtree into the clipboard.
3277 This is a short-hand for marking the subtree and then copying it.
3278 If CUT is non nil, actually cut the subtree."
3279 (interactive)
3280 (let (beg end folded)
3281 (org-back-to-heading)
3282 (setq beg (point))
3283 (save-match-data
3284 (save-excursion (outline-end-of-heading)
3285 (setq folded (org-invisible-p)))
3286 (outline-end-of-subtree))
3287 (if (equal (char-after) ?\n) (forward-char 1))
3288 (setq end (point))
3289 (goto-char beg)
3290 (when (> end beg)
3291 (setq org-subtree-clip-folded folded)
3292 (if cut (kill-region beg end) (copy-region-as-kill beg end))
3293 (setq org-subtree-clip (current-kill 0))
3294 (message "%s: Subtree with %d characters"
3295 (if cut "Cut" "Copied")
3296 (length org-subtree-clip)))))
3298 (defun org-paste-subtree (&optional level tree)
3299 "Paste the clipboard as a subtree, with modification of headline level.
3300 The entire subtree is promoted or demoted in order to match a new headline
3301 level. By default, the new level is derived from the visible headings
3302 before and after the insertion point, and taken to be the inferior headline
3303 level of the two. So if the previous visible heading is level 3 and the
3304 next is level 4 (or vice versa), level 4 will be used for insertion.
3305 This makes sure that the subtree remains an independent subtree and does
3306 not swallow low level entries.
3308 You can also force a different level, either by using a numeric prefix
3309 argument, or by inserting the heading marker by hand. For example, if the
3310 cursor is after \"*****\", then the tree will be shifted to level 5.
3312 If you want to insert the tree as is, just use \\[yank].
3314 If optional TREE is given, use this text instead of the kill ring."
3315 (interactive "P")
3316 (unless (org-kill-is-subtree-p tree)
3317 (error
3318 (substitute-command-keys
3319 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
3320 (let* ((txt (or tree (current-kill 0)))
3321 (^re (concat "^\\(" outline-regexp "\\)"))
3322 (re (concat "\\(" outline-regexp "\\)"))
3323 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3325 (old-level (if (string-match ^re txt)
3326 (- (match-end 0) (match-beginning 0))
3327 -1))
3328 (force-level (cond (level (prefix-numeric-value level))
3329 ((string-match
3330 ^re_ (buffer-substring (point-at-bol) (point)))
3331 (- (match-end 0) (match-beginning 0)))
3332 (t nil)))
3333 (previous-level (save-excursion
3334 (condition-case nil
3335 (progn
3336 (outline-previous-visible-heading 1)
3337 (if (looking-at re)
3338 (- (match-end 0) (match-beginning 0))
3340 (error 1))))
3341 (next-level (save-excursion
3342 (condition-case nil
3343 (progn
3344 (outline-next-visible-heading 1)
3345 (if (looking-at re)
3346 (- (match-end 0) (match-beginning 0))
3348 (error 1))))
3349 (new-level (or force-level (max previous-level next-level)))
3350 (shift (if (or (= old-level -1)
3351 (= new-level -1)
3352 (= old-level new-level))
3354 (- new-level old-level)))
3355 (shift1 shift)
3356 (delta (if (> shift 0) -1 1))
3357 (func (if (> shift 0) 'org-demote 'org-promote))
3358 (org-odd-levels-only nil)
3359 beg end)
3360 ;; Remove the forces level indicator
3361 (if force-level
3362 (delete-region (point-at-bol) (point)))
3363 ;; Make sure we start at the beginning of an empty line
3364 (if (not (bolp)) (insert "\n"))
3365 (if (not (looking-at "[ \t]*$"))
3366 (progn (insert "\n") (backward-char 1)))
3367 ;; Paste
3368 (setq beg (point))
3369 (insert txt)
3370 (setq end (point))
3371 (goto-char beg)
3372 ;; Shift if necessary
3373 (if (= shift 0)
3374 (message "Pasted at level %d, without shift" new-level)
3375 (save-restriction
3376 (narrow-to-region beg end)
3377 (while (not (= shift 0))
3378 (org-map-region func (point-min) (point-max))
3379 (setq shift (+ delta shift)))
3380 (goto-char (point-min))
3381 (message "Pasted at level %d, with shift by %d levels"
3382 new-level shift1)))
3383 (if (and (eq org-subtree-clip (current-kill 0))
3384 org-subtree-clip-folded)
3385 ;; The tree was folded before it was killed/copied
3386 (hide-subtree))))
3388 (defun org-kill-is-subtree-p (&optional txt)
3389 "Check if the current kill is an outline subtree, or a set of trees.
3390 Returns nil if kill does not start with a headline, or if the first
3391 headline level is not the largest headline level in the tree.
3392 So this will actually accept several entries of equal levels as well,
3393 which is OK for `org-paste-subtree'.
3394 If optional TXT is given, check this string instead of the current kill."
3395 (let* ((kill (or txt (current-kill 0) ""))
3396 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3397 (- (match-end 0) (match-beginning 0))))
3398 (re (concat "^" outline-regexp))
3399 (start 1))
3400 (if (not start-level)
3401 nil ;; does not even start with a heading
3402 (catch 'exit
3403 (while (setq start (string-match re kill (1+ start)))
3404 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3405 (throw 'exit nil)))
3406 t))))
3408 ;;; Plain list items
3410 (defun org-at-item-p ()
3411 "Is point in a line starting a hand-formatted item?"
3412 (let ((llt org-plain-list-ordered-item-terminator))
3413 (save-excursion
3414 (goto-char (point-at-bol))
3415 (looking-at
3416 (cond
3417 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3418 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3419 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3420 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3422 (defun org-get-indentation ()
3423 "Get the indentation of the current line, interpreting tabs."
3424 (save-excursion
3425 (beginning-of-line 1)
3426 (skip-chars-forward " \t")
3427 (current-column)))
3429 (defun org-beginning-of-item ()
3430 "Go to the beginning of the current hand-formatted item.
3431 If the cursor is not in an item, throw an error."
3432 (let ((pos (point))
3433 (limit (save-excursion (org-back-to-heading)
3434 (beginning-of-line 2) (point)))
3435 ind ind1)
3436 (if (org-at-item-p)
3437 (beginning-of-line 1)
3438 (beginning-of-line 1)
3439 (skip-chars-forward " \t")
3440 (setq ind (current-column))
3441 (if (catch 'exit
3442 (while t
3443 (beginning-of-line 0)
3444 (if (< (point) limit) (throw 'exit nil))
3445 (unless (looking-at " \t]*$")
3446 (skip-chars-forward " \t")
3447 (setq ind1 (current-column))
3448 (if (< ind1 ind)
3449 (throw 'exit (org-at-item-p))))))
3451 (goto-char pos)
3452 (error "Not in an item")))))
3454 (defun org-end-of-item ()
3455 "Go to the end of the current hand-formatted item.
3456 If the cursor is not in an item, throw an error."
3457 (let ((pos (point))
3458 (limit (save-excursion (outline-next-heading) (point)))
3459 (ind (save-excursion
3460 (org-beginning-of-item)
3461 (skip-chars-forward " \t")
3462 (current-column)))
3463 ind1)
3464 (if (catch 'exit
3465 (while t
3466 (beginning-of-line 2)
3467 (if (>= (point) limit) (throw 'exit t))
3468 (unless (looking-at "[ \t]*$")
3469 (skip-chars-forward " \t")
3470 (setq ind1 (current-column))
3471 (if (<= ind1 ind) (throw 'exit t)))))
3472 (beginning-of-line 1)
3473 (goto-char pos)
3474 (error "Not in an item"))))
3476 (defun org-move-item-down (arg)
3477 "Move the plain list item at point down, i.e. swap with following item.
3478 Subitems (items with larger indentation) are considered part of the item,
3479 so this really moves item trees."
3480 (interactive "p")
3481 (let (beg end ind ind1 (pos (point)) txt)
3482 (org-beginning-of-item)
3483 (setq beg (point))
3484 (setq ind (org-get-indentation))
3485 (org-end-of-item)
3486 (setq end (point))
3487 (setq ind1 (org-get-indentation))
3488 (if (and (org-at-item-p) (= ind ind1))
3489 (progn
3490 (org-end-of-item)
3491 (setq txt (buffer-substring beg end))
3492 (save-excursion
3493 (delete-region beg end))
3494 (setq pos (point))
3495 (insert txt)
3496 (goto-char pos)
3497 (org-maybe-renumber-ordered-list))
3498 (goto-char pos)
3499 (error "Cannot move this item further down"))))
3501 (defun org-move-item-up (arg)
3502 "Move the plain list item at point up, i.e. swap with previous item.
3503 Subitems (items with larger indentation) are considered part of the item,
3504 so this really moves item trees."
3505 (interactive "p")
3506 (let (beg end ind ind1 (pos (point)) txt)
3507 (org-beginning-of-item)
3508 (setq beg (point))
3509 (setq ind (org-get-indentation))
3510 (org-end-of-item)
3511 (setq end (point))
3512 (goto-char beg)
3513 (catch 'exit
3514 (while t
3515 (beginning-of-line 0)
3516 (if (looking-at "[ \t]*$")
3518 (if (<= (setq ind1 (org-get-indentation)) ind)
3519 (throw 'exit t)))))
3520 (condition-case nil
3521 (org-beginning-of-item)
3522 (error (goto-char beg)
3523 (error "Cannot move this item further up")))
3524 (setq ind1 (org-get-indentation))
3525 (if (and (org-at-item-p) (= ind ind1))
3526 (progn
3527 (setq txt (buffer-substring beg end))
3528 (save-excursion
3529 (delete-region beg end))
3530 (setq pos (point))
3531 (insert txt)
3532 (goto-char pos)
3533 (org-maybe-renumber-ordered-list))
3534 (goto-char pos)
3535 (error "Cannot move this item further up"))))
3537 (defun org-maybe-renumber-ordered-list ()
3538 "Renumber the ordered list at point if setup allows it.
3539 This tests the user option `org-auto-renumber-ordered-lists' before
3540 doing the renumbering."
3541 (and org-auto-renumber-ordered-lists
3542 (org-at-item-p)
3543 (match-beginning 3)
3544 (org-renumber-ordered-list 1)))
3546 (defun org-get-string-indentation (s)
3547 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3548 (let ((n -1) (i 0) (w tab-width) c)
3549 (catch 'exit
3550 (while (< (setq n (1+ n)) (length s))
3551 (setq c (aref s n))
3552 (cond ((= c ?\ ) (setq i (1+ i)))
3553 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3554 (t (throw 'exit t)))))
3557 (defun org-renumber-ordered-list (arg)
3558 "Renumber an ordered plain list.
3559 Cursor next to be in the first line of an item, the line that starts
3560 with something like \"1.\" or \"2)\"."
3561 (interactive "p")
3562 (unless (and (org-at-item-p)
3563 (match-beginning 3))
3564 (error "This is not an ordered list"))
3565 (let ((line (org-current-line))
3566 (col (current-column))
3567 (ind (org-get-string-indentation
3568 (buffer-substring (point-at-bol) (match-beginning 3))))
3569 ;; (term (substring (match-string 3) -1))
3570 ind1 (n (1- arg)))
3571 ;; find where this list begins
3572 (catch 'exit
3573 (while t
3574 (catch 'next
3575 (beginning-of-line 0)
3576 (if (looking-at "[ \t]*$") (throw 'next t))
3577 (skip-chars-forward " \t") (setq ind1 (current-column))
3578 (if (or (< ind1 ind)
3579 (and (= ind1 ind)
3580 (not (org-at-item-p))))
3581 (throw 'exit t)))))
3582 ;; Walk forward and replace these numbers
3583 (catch 'exit
3584 (while t
3585 (catch 'next
3586 (beginning-of-line 2)
3587 (if (eobp) (throw 'exit nil))
3588 (if (looking-at "[ \t]*$") (throw 'next nil))
3589 (skip-chars-forward " \t") (setq ind1 (current-column))
3590 (if (> ind1 ind) (throw 'next t))
3591 (if (< ind1 ind) (throw 'exit t))
3592 (if (not (org-at-item-p)) (throw 'exit nil))
3593 (if (not (match-beginning 3))
3594 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3595 (delete-region (match-beginning 3) (1- (match-end 3)))
3596 (goto-char (match-beginning 3))
3597 (insert (format "%d" (setq n (1+ n)))))))
3598 (goto-line line)
3599 (move-to-column col)))
3601 (defvar org-last-indent-begin-marker (make-marker))
3602 (defvar org-last-indent-end-marker (make-marker))
3604 (defun org-outdent-item (arg)
3605 "Outdent a local list item."
3606 (interactive "p")
3607 (org-indent-item (- arg)))
3609 (defun org-indent-item (arg)
3610 "Indent a local list item."
3611 (interactive "p")
3612 (unless (org-at-item-p)
3613 (error "Not on an item"))
3614 (let (beg end ind ind1)
3615 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3616 (setq beg org-last-indent-begin-marker
3617 end org-last-indent-end-marker)
3618 (org-beginning-of-item)
3619 (setq beg (move-marker org-last-indent-begin-marker (point)))
3620 (org-end-of-item)
3621 (setq end (move-marker org-last-indent-end-marker (point))))
3622 (goto-char beg)
3623 (skip-chars-forward " \t") (setq ind (current-column))
3624 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3625 (while (< (point) end)
3626 (beginning-of-line 1)
3627 (skip-chars-forward " \t") (setq ind1 (current-column))
3628 (delete-region (point-at-bol) (point))
3629 (indent-to-column (+ ind1 arg))
3630 (beginning-of-line 2))
3631 (goto-char beg)))
3633 ;;; Archiving
3635 (defun org-archive-subtree ()
3636 "Move the current subtree to the archive.
3637 The archive can be a certain top-level heading in the current file, or in
3638 a different file. The tree will be moved to that location, the subtree
3639 heading be marked DONE, and the current time will be added."
3640 (interactive)
3641 ;; Save all relevant TODO keyword-relatex variables
3642 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3643 (tr-org-todo-keywords org-todo-keywords)
3644 (tr-org-todo-interpretation org-todo-interpretation)
3645 (tr-org-done-string org-done-string)
3646 (tr-org-todo-regexp org-todo-regexp)
3647 (tr-org-todo-line-regexp org-todo-line-regexp)
3648 (this-buffer (current-buffer))
3649 file heading buffer level newfile-p)
3650 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3651 (progn
3652 (setq file (format (match-string 1 org-archive-location)
3653 (file-name-nondirectory buffer-file-name))
3654 heading (match-string 2 org-archive-location)))
3655 (error "Invalid `org-archive-location'"))
3656 (if (> (length file) 0)
3657 (setq newfile-p (not (file-exists-p file))
3658 buffer (find-file-noselect file))
3659 (setq buffer (current-buffer)))
3660 (unless buffer
3661 (error "Cannot access file \"%s\"" file))
3662 (if (and (> (length heading) 0)
3663 (string-match "^\\*+" heading))
3664 (setq level (match-end 0))
3665 (setq heading nil level 0))
3666 (save-excursion
3667 ;; We first only copy, in case something goes wrong
3668 ;; we need to protect this-command, to avoid kill-region sets it,
3669 ;; which would lead to duplication of subtrees
3670 (let (this-command) (org-copy-subtree))
3671 (set-buffer buffer)
3672 ;; Enforce org-mode for the archive buffer
3673 (if (not (eq major-mode 'org-mode))
3674 ;; Force the mode for future visits.
3675 (let ((org-insert-mode-line-in-empty-file t))
3676 (call-interactively 'org-mode)))
3677 (when newfile-p
3678 (goto-char (point-max))
3679 (insert (format "\nArchived entries from file %s\n\n"
3680 (buffer-file-name this-buffer))))
3681 ;; Force the TODO keywords of the original buffer
3682 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3683 (org-todo-keywords tr-org-todo-keywords)
3684 (org-todo-interpretation tr-org-todo-interpretation)
3685 (org-done-string tr-org-done-string)
3686 (org-todo-regexp tr-org-todo-regexp)
3687 (org-todo-line-regexp tr-org-todo-line-regexp))
3688 (goto-char (point-min))
3689 (if heading
3690 (progn
3691 (if (re-search-forward
3692 (concat "\\(^\\|\r\\)"
3693 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3694 nil t)
3695 (goto-char (match-end 0))
3696 ;; Heading not found, just insert it at the end
3697 (goto-char (point-max))
3698 (or (bolp) (insert "\n"))
3699 (insert "\n" heading "\n")
3700 (end-of-line 0))
3701 ;; Make the heading visible, and the following as well
3702 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3703 (if (re-search-forward
3704 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3705 nil t)
3706 (progn (goto-char (match-beginning 0)) (insert "\n")
3707 (beginning-of-line 0))
3708 (goto-char (point-max)) (insert "\n")))
3709 (goto-char (point-max)) (insert "\n"))
3710 ;; Paste
3711 (org-paste-subtree (1+ level))
3712 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3713 (if org-archive-mark-done
3714 (org-todo (length org-todo-keywords)))
3715 ;; Move cursor to right after the TODO keyword
3716 (when org-archive-stamp-time
3717 (beginning-of-line 1)
3718 (looking-at org-todo-line-regexp)
3719 (goto-char (or (match-end 2) (match-beginning 3)))
3720 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3721 (org-current-time))
3722 ")"))
3723 ;; Save the buffer, if it is not the same buffer.
3724 (if (not (eq this-buffer buffer)) (save-buffer))))
3725 ;; Here we are back in the original buffer. Everything seems to have
3726 ;; worked. So now cut the tree and finish up.
3727 (let (this-command) (org-cut-subtree))
3728 (if (looking-at "[ \t]*$") (kill-line))
3729 (message "Subtree archived %s"
3730 (if (eq this-buffer buffer)
3731 (concat "under heading: " heading)
3732 (concat "in file: " (abbreviate-file-name file))))))
3734 ;;; Completion
3736 (defun org-complete (&optional arg)
3737 "Perform completion on word at point.
3738 At the beginning of a headline, this completes TODO keywords as given in
3739 `org-todo-keywords'.
3740 If the current word is preceded by a backslash, completes the TeX symbols
3741 that are supported for HTML support.
3742 If the current word is preceded by \"#+\", completes special words for
3743 setting file options.
3744 At all other locations, this simply calls `ispell-complete-word'."
3745 (interactive "P")
3746 (catch 'exit
3747 (let* ((end (point))
3748 (beg1 (save-excursion
3749 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3750 (skip-chars-backward "a-zA-Z_@0-9")
3751 (point)))
3752 (beg (save-excursion
3753 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3754 (skip-chars-backward "a-zA-Z0-9_:$")
3755 (point)))
3756 (camel (equal (char-before beg) ?*))
3757 (tag (equal (char-before beg1) ?:))
3758 (texp (equal (char-before beg) ?\\))
3759 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3760 beg)
3761 "#+"))
3762 (completion-ignore-case opt)
3763 (type nil)
3764 (tbl nil)
3765 (table (cond
3766 (opt
3767 (setq type :opt)
3768 (mapcar (lambda (x)
3769 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3770 (cons (match-string 2 x) (match-string 1 x)))
3771 (org-split-string (org-get-current-options) "\n")))
3772 (texp
3773 (setq type :tex)
3774 org-html-entities)
3775 ((string-match "\\`\\*+[ \t]*\\'"
3776 (buffer-substring (point-at-bol) beg))
3777 (setq type :todo)
3778 (mapcar 'list org-todo-keywords))
3779 (camel
3780 (setq type :camel)
3781 (save-excursion
3782 (goto-char (point-min))
3783 (while (re-search-forward org-todo-line-regexp nil t)
3784 (push (list
3785 (if org-file-link-context-use-camel-case
3786 (org-make-org-heading-camel (match-string 3) t)
3787 (org-make-org-heading-search-string
3788 (match-string 3) t)))
3789 tbl)))
3790 tbl)
3791 (tag (setq type :tag beg beg1)
3792 (org-get-buffer-tags))
3793 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3794 (pattern (buffer-substring-no-properties beg end))
3795 (completion (try-completion pattern table)))
3796 (cond ((eq completion t)
3797 (if (equal type :opt)
3798 (insert (substring (cdr (assoc (upcase pattern) table))
3799 (length pattern)))))
3800 ((null completion)
3801 (message "Can't find completion for \"%s\"" pattern)
3802 (ding))
3803 ((not (string= pattern completion))
3804 (delete-region beg end)
3805 (if (string-match " +$" completion)
3806 (setq completion (replace-match "" t t completion)))
3807 (insert completion)
3808 (if (get-buffer-window "*Completions*")
3809 (delete-window (get-buffer-window "*Completions*")))
3810 (if (assoc completion table)
3811 (if (eq type :todo) (insert " ")
3812 (if (eq type :tag) (insert ":"))))
3813 (if (and (equal type :opt) (assoc completion table))
3814 (message "%s" (substitute-command-keys
3815 "Press \\[org-complete] again to insert example settings"))))
3817 (message "Making completion list...")
3818 (let ((list (sort (all-completions pattern table) 'string<)))
3819 (with-output-to-temp-buffer "*Completions*"
3820 (condition-case nil
3821 ;; Protection needed for XEmacs and emacs 21
3822 (display-completion-list list pattern)
3823 (error (display-completion-list list)))))
3824 (message "Making completion list...%s" "done"))))))
3826 ;;; Comments, TODO and DEADLINE
3828 (defun org-toggle-comment ()
3829 "Change the COMMENT state of an entry."
3830 (interactive)
3831 (save-excursion
3832 (org-back-to-heading)
3833 (if (looking-at (concat outline-regexp
3834 "\\( +\\<" org-comment-string "\\>\\)"))
3835 (replace-match "" t t nil 1)
3836 (if (looking-at outline-regexp)
3837 (progn
3838 (goto-char (match-end 0))
3839 (insert " " org-comment-string))))))
3841 (defvar org-last-todo-state-is-todo nil
3842 "This is non-nil when the last TODO state change led to a TODO state.
3843 If the last change removed the TODO tag or switched to DONE, then
3844 this is nil.")
3846 (defun org-todo (&optional arg)
3847 "Change the TODO state of an item.
3848 The state of an item is given by a keyword at the start of the heading,
3849 like
3850 *** TODO Write paper
3851 *** DONE Call mom
3853 The different keywords are specified in the variable `org-todo-keywords'.
3854 By default the available states are \"TODO\" and \"DONE\".
3855 So for this example: when the item starts with TODO, it is changed to DONE.
3856 When it starts with DONE, the DONE is removed. And when neither TODO nor
3857 DONE are present, add TODO at the beginning of the heading.
3859 With prefix arg, use completion to determine the new state. With numeric
3860 prefix arg, switch to that state."
3861 (interactive "P")
3862 (save-excursion
3863 (org-back-to-heading)
3864 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3865 (or (looking-at (concat " +" org-todo-regexp " *"))
3866 (looking-at " *"))
3867 (let* ((this (match-string 1))
3868 (completion-ignore-case t)
3869 (member (member this org-todo-keywords))
3870 (tail (cdr member))
3871 (state (cond
3872 ((equal arg '(4))
3873 ;; Read a state with completion
3874 (completing-read "State: " (mapcar (lambda(x) (list x))
3875 org-todo-keywords)
3876 nil t))
3877 ((eq arg 'right)
3878 (if this
3879 (if tail (car tail) nil)
3880 (car org-todo-keywords)))
3881 ((eq arg 'left)
3882 (if (equal member org-todo-keywords)
3884 (if this
3885 (nth (- (length org-todo-keywords) (length tail) 2)
3886 org-todo-keywords)
3887 org-done-string)))
3888 (arg
3889 ;; user requests a specific state
3890 (nth (1- (prefix-numeric-value arg))
3891 org-todo-keywords))
3892 ((null member) (car org-todo-keywords))
3893 ((null tail) nil) ;; -> first entry
3894 ((eq org-todo-interpretation 'sequence)
3895 (car tail))
3896 ((memq org-todo-interpretation '(type priority))
3897 (if (eq this-command last-command)
3898 (car tail)
3899 (if (> (length tail) 0) org-done-string nil)))
3900 (t nil)))
3901 (next (if state (concat " " state " ") " ")))
3902 (replace-match next t t)
3903 (setq org-last-todo-state-is-todo
3904 (not (equal state org-done-string)))
3905 (when org-log-done
3906 (if (equal state org-done-string)
3907 (org-log-done)
3908 (if (not this)
3909 (org-log-done t))))
3910 ;; Fixup tag positioning
3911 (and org-auto-align-tags (org-set-tags nil t))
3912 (run-hooks 'org-after-todo-state-change-hook)))
3913 ;; Fixup cursor location if close to the keyword
3914 (if (and (outline-on-heading-p)
3915 (not (bolp))
3916 (save-excursion (beginning-of-line 1)
3917 (looking-at org-todo-line-regexp))
3918 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3919 (progn
3920 (goto-char (or (match-end 2) (match-end 1)))
3921 (just-one-space))))
3923 (defun org-log-done (&optional undone)
3924 "Add a time stamp logging that a TODO entry has been closed.
3925 When UNDONE is non-nil, remove such a time stamp again."
3926 (interactive)
3927 (let (beg end col)
3928 (save-excursion
3929 (org-back-to-heading t)
3930 (setq beg (point))
3931 (looking-at (concat outline-regexp " *"))
3932 (goto-char (match-end 0))
3933 (setq col (current-column))
3934 (outline-next-heading)
3935 (setq end (point))
3936 (goto-char beg)
3937 (when (re-search-forward (concat
3938 "[\r\n]\\([ \t]*"
3939 (regexp-quote org-closed-string)
3940 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3941 (delete-region (match-beginning 1) (match-end 1)))
3942 (unless undone
3943 (org-back-to-heading t)
3944 (skip-chars-forward "^\n\r")
3945 (goto-char (min (1+ (point)) (point-max)))
3946 (when (not (member (char-before) '(?\r ?\n)))
3947 (insert "\n"))
3948 (indent-to col)
3949 (insert org-closed-string " "
3950 (format-time-string
3951 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3952 (org-current-time))
3953 "\n")))))
3955 (defun org-show-todo-tree (arg)
3956 "Make a compact tree which shows all headlines marked with TODO.
3957 The tree will show the lines where the regexp matches, and all higher
3958 headlines above the match.
3959 With \\[universal-argument] prefix, also show the DONE entries.
3960 With a numeric prefix N, construct a sparse tree for the Nth element
3961 of `org-todo-keywords'."
3962 (interactive "P")
3963 (let ((case-fold-search nil)
3964 (kwd-re
3965 (cond ((null arg) org-not-done-regexp)
3966 ((equal arg '(4)) org-todo-regexp)
3967 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3968 (regexp-quote (nth (1- (prefix-numeric-value arg))
3969 org-todo-keywords)))
3970 (t (error "Invalid prefix argument: %s" arg)))))
3971 (message "%d TODO entries found"
3972 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3974 (defun org-deadline ()
3975 "Insert the DEADLINE: string to make a deadline.
3976 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3977 to modify it to the correct date."
3978 (interactive)
3979 (insert
3980 org-deadline-string " "
3981 (format-time-string (car org-time-stamp-formats)
3982 (org-read-date nil 'to-time)))
3983 (message "%s" (substitute-command-keys
3984 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3986 (defun org-schedule ()
3987 "Insert the SCHEDULED: string to schedule a TODO item.
3988 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3989 to modify it to the correct date."
3990 (interactive)
3991 (insert
3992 org-scheduled-string " "
3993 (format-time-string (car org-time-stamp-formats)
3994 (org-read-date nil 'to-time)))
3995 (message "%s" (substitute-command-keys
3996 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
3999 (defun org-occur (regexp &optional callback)
4000 "Make a compact tree which shows all matches of REGEXP.
4001 The tree will show the lines where the regexp matches, and all higher
4002 headlines above the match. It will also show the heading after the match,
4003 to make sure editing the matching entry is easy.
4004 If CALLBACK is non-nil, it is a function which is called to confirm
4005 that the match should indeed be shown."
4006 (interactive "sRegexp: ")
4007 (org-remove-occur-highlights nil nil t)
4008 (setq regexp (org-check-occur-regexp regexp))
4009 (let ((cnt 0))
4010 (save-excursion
4011 (goto-char (point-min))
4012 (hide-sublevels 1)
4013 (while (re-search-forward regexp nil t)
4014 (when (or (not callback)
4015 (save-match-data (funcall callback)))
4016 (setq cnt (1+ cnt))
4017 (org-highlight-new-match (match-beginning 0) (match-end 0))
4018 (org-show-hierarchy-above))))
4019 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
4020 nil 'local)
4021 (run-hooks 'org-occur-hook)
4022 (if (interactive-p)
4023 (message "%d match(es) for regexp %s" cnt regexp))
4024 cnt))
4026 (defun org-show-hierarchy-above ()
4027 "Make sure point and the headings hierarchy above is visible."
4028 (catch 'exit
4029 (if (org-on-heading-p t)
4030 (org-flag-heading nil) ; only show the heading
4031 (and (or (org-invisible-p) (org-invisible-p2))
4032 (org-show-hidden-entry))) ; show entire entry
4033 (save-excursion
4034 (and org-show-following-heading
4035 (outline-next-heading)
4036 (org-flag-heading nil))) ; show the next heading
4037 (when org-show-hierarchy-above
4038 (save-excursion ; show all higher headings
4039 (while (and (condition-case nil
4040 (progn (org-up-heading-all 1) t)
4041 (error nil))
4042 (not (bobp)))
4043 (org-flag-heading nil))))))
4045 ;; Overlay compatibility functions
4046 (defun org-make-overlay (beg end &optional buffer)
4047 (if (featurep 'xemacs)
4048 (make-extent beg end buffer)
4049 (make-overlay beg end buffer)))
4050 (defun org-delete-overlay (ovl)
4051 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4052 (defun org-detatch-overlay (ovl)
4053 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4054 (defun org-move-overlay (ovl beg end &optional buffer)
4055 (if (featurep 'xemacs)
4056 (set-extent-endpoints ovl beg end buffer)
4057 (move-overlay ovl beg end buffer)))
4058 (defun org-overlay-put (ovl prop value)
4059 (if (featurep 'xemacs)
4060 (set-extent-property ovl prop value)
4061 (overlay-put ovl prop value)))
4063 (defvar org-occur-highlights nil)
4064 (defun org-highlight-new-match (beg end)
4065 "Highlight from BEG to END and mark the highlight is an occur headline."
4066 (let ((ov (org-make-overlay beg end)))
4067 (org-overlay-put ov 'face 'secondary-selection)
4068 (push ov org-occur-highlights)))
4070 (defun org-remove-occur-highlights (&optional beg end noremove)
4071 "Remove the occur highlights from the buffer.
4072 BEG and END are ignored. If NOREMOVE is nil, remove this function
4073 from the `before-change-functions' in the current buffer."
4074 (interactive)
4075 (mapc 'org-delete-overlay org-occur-highlights)
4076 (setq org-occur-highlights nil)
4077 (unless noremove
4078 (remove-hook 'before-change-functions
4079 'org-remove-occur-highlights 'local)))
4081 ;;; Priorities
4083 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
4084 "Regular expression matching the priority indicator.")
4086 (defvar org-remove-priority-next-time nil)
4088 (defun org-priority-up ()
4089 "Increase the priority of the current item."
4090 (interactive)
4091 (org-priority 'up))
4093 (defun org-priority-down ()
4094 "Decrease the priority of the current item."
4095 (interactive)
4096 (org-priority 'down))
4098 (defun org-priority (&optional action)
4099 "Change the priority of an item by ARG.
4100 ACTION can be set, up, or down."
4101 (interactive)
4102 (setq action (or action 'set))
4103 (let (current new news have remove)
4104 (save-excursion
4105 (org-back-to-heading)
4106 (if (looking-at org-priority-regexp)
4107 (setq current (string-to-char (match-string 2))
4108 have t)
4109 (setq current org-default-priority))
4110 (cond
4111 ((eq action 'set)
4112 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
4113 (setq new (read-char-exclusive))
4114 (cond ((equal new ?\ ) (setq remove t))
4115 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
4116 (error "Priority must be between `%c' and `%c'"
4117 ?A org-lowest-priority))))
4118 ((eq action 'up)
4119 (setq new (1- current)))
4120 ((eq action 'down)
4121 (setq new (1+ current)))
4122 (t (error "Invalid action")))
4123 (setq new (min (max ?A (upcase new)) org-lowest-priority))
4124 (setq news (format "%c" new))
4125 (if have
4126 (if remove
4127 (replace-match "" t t nil 1)
4128 (replace-match news t t nil 2))
4129 (if remove
4130 (error "No priority cookie found in line")
4131 (looking-at org-todo-line-regexp)
4132 (if (match-end 2)
4133 (progn
4134 (goto-char (match-end 2))
4135 (insert " [#" news "]"))
4136 (goto-char (match-beginning 3))
4137 (insert "[#" news "] ")))))
4138 (if remove
4139 (message "Priority removed")
4140 (message "Priority of current item set to %s" news))))
4143 (defun org-get-priority (s)
4144 "Find priority cookie and return priority."
4145 (save-match-data
4146 (if (not (string-match org-priority-regexp s))
4147 (* 1000 (- org-lowest-priority org-default-priority))
4148 (* 1000 (- org-lowest-priority
4149 (string-to-char (match-string 2 s)))))))
4151 ;;; Timestamps
4153 (defvar org-last-changed-timestamp nil)
4155 (defun org-time-stamp (arg)
4156 "Prompt for a date/time and insert a time stamp.
4157 If the user specifies a time like HH:MM, or if this command is called
4158 with a prefix argument, the time stamp will contain date and time.
4159 Otherwise, only the date will be included. All parts of a date not
4160 specified by the user will be filled in from the current date/time.
4161 So if you press just return without typing anything, the time stamp
4162 will represent the current date/time. If there is already a timestamp
4163 at the cursor, it will be modified."
4164 (interactive "P")
4165 (let ((fmt (if arg (cdr org-time-stamp-formats)
4166 (car org-time-stamp-formats)))
4167 (org-time-was-given nil)
4168 time)
4169 (cond
4170 ((and (org-at-timestamp-p)
4171 (eq last-command 'org-time-stamp)
4172 (eq this-command 'org-time-stamp))
4173 (insert "--")
4174 (setq time (let ((this-command this-command))
4175 (org-read-date arg 'totime)))
4176 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4177 (insert (format-time-string fmt time)))
4178 ((org-at-timestamp-p)
4179 (setq time (let ((this-command this-command))
4180 (org-read-date arg 'totime)))
4181 (and (org-at-timestamp-p) (replace-match
4182 (setq org-last-changed-timestamp
4183 (format-time-string fmt time))
4184 t t))
4185 (message "Timestamp updated"))
4187 (setq time (let ((this-command this-command))
4188 (org-read-date arg 'totime)))
4189 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4190 (insert (format-time-string fmt time))))))
4192 (defun org-time-stamp-inactive (&optional arg)
4193 "Insert an inactive time stamp.
4194 An inactive time stamp is enclosed in square brackets instead of angle
4195 brackets. It is inactive in the sense that it does not trigger agenda entries,
4196 does not link to the calendar and cannot be changed with the S-cursor keys.
4197 So these are more for recording a certain time/date."
4198 (interactive "P")
4199 (let ((fmt (if arg (cdr org-time-stamp-formats)
4200 (car org-time-stamp-formats)))
4201 (org-time-was-given nil)
4202 time)
4203 (setq time (org-read-date arg 'totime))
4204 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4205 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
4206 (insert (format-time-string fmt time))))
4208 (defvar org-date-ovl (org-make-overlay 1 1))
4209 (org-overlay-put org-date-ovl 'face 'org-warning)
4210 (org-detatch-overlay org-date-ovl)
4212 (defun org-read-date (&optional with-time to-time)
4213 "Read a date and make things smooth for the user.
4214 The prompt will suggest to enter an ISO date, but you can also enter anything
4215 which will at least partially be understood by `parse-time-string'.
4216 Unrecognized parts of the date will default to the current day, month, year,
4217 hour and minute. For example,
4218 3-2-5 --> 2003-02-05
4219 feb 15 --> currentyear-02-15
4220 sep 12 9 --> 2009-09-12
4221 12:45 --> today 12:45
4222 22 sept 0:34 --> currentyear-09-22 0:34
4223 12 --> currentyear-currentmonth-12
4224 Fri --> nearest Friday (today or later)
4225 etc.
4226 The function understands only English month and weekday abbreviations,
4227 but this can be configured with the variables `parse-time-months' and
4228 `parse-time-weekdays'.
4230 While prompting, a calendar is popped up - you can also select the
4231 date with the mouse (button 1). The calendar shows a period of three
4232 months. To scroll it to other months, use the keys `>' and `<'.
4233 If you don't like the calendar, turn it off with
4234 \(setq org-popup-calendar-for-date-prompt nil)
4236 With optional argument TO-TIME, the date will immediately be converted
4237 to an internal time.
4238 With an optional argument WITH-TIME, the prompt will suggest to also
4239 insert a time. Note that when WITH-TIME is not set, you can still
4240 enter a time, and this function will inform the calling routine about
4241 this change. The calling routine may then choose to change the format
4242 used to insert the time stamp into the buffer to include the time."
4243 (require 'parse-time)
4244 (let* ((org-time-stamp-rounding-minutes
4245 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
4246 (ct (org-current-time))
4247 (default-time
4248 ;; Default time is either today, or, when entering a range,
4249 ;; the range start.
4250 (if (save-excursion
4251 (re-search-backward
4252 (concat org-ts-regexp "--\\=")
4253 (- (point) 20) t))
4254 (apply
4255 'encode-time
4256 (mapcar (lambda(x) (or x 0))
4257 (parse-time-string (match-string 1))))
4258 ct))
4259 (calendar-move-hook nil)
4260 (view-diary-entries-initially nil)
4261 (timestr (format-time-string
4262 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
4263 (prompt (format "YYYY-MM-DD [%s]: " timestr))
4264 ans ans1 ans2
4265 second minute hour day month year tl wday wday1)
4267 (if org-popup-calendar-for-date-prompt
4268 (save-excursion
4269 (save-window-excursion
4270 (calendar)
4271 (calendar-forward-day (- (time-to-days default-time)
4272 (calendar-absolute-from-gregorian
4273 (calendar-current-date))))
4274 (org-eval-in-calendar nil)
4275 (let* ((old-map (current-local-map))
4276 (map (copy-keymap calendar-mode-map))
4277 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
4278 (define-key map (kbd "RET") 'org-calendar-select)
4279 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
4280 'org-calendar-select-mouse)
4281 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
4282 'org-calendar-select-mouse)
4283 (define-key minibuffer-local-map [(meta shift left)]
4284 (lambda () (interactive)
4285 (org-eval-in-calendar '(calendar-backward-month 1))))
4286 (define-key minibuffer-local-map [(meta shift right)]
4287 (lambda () (interactive)
4288 (org-eval-in-calendar '(calendar-forward-month 1))))
4289 (define-key minibuffer-local-map [(shift up)]
4290 (lambda () (interactive)
4291 (org-eval-in-calendar '(calendar-backward-week 1))))
4292 (define-key minibuffer-local-map [(shift down)]
4293 (lambda () (interactive)
4294 (org-eval-in-calendar '(calendar-forward-week 1))))
4295 (define-key minibuffer-local-map [(shift left)]
4296 (lambda () (interactive)
4297 (org-eval-in-calendar '(calendar-backward-day 1))))
4298 (define-key minibuffer-local-map [(shift right)]
4299 (lambda () (interactive)
4300 (org-eval-in-calendar '(calendar-forward-day 1))))
4301 (define-key minibuffer-local-map ">"
4302 (lambda () (interactive)
4303 (org-eval-in-calendar '(scroll-calendar-left 1))))
4304 (define-key minibuffer-local-map "<"
4305 (lambda () (interactive)
4306 (org-eval-in-calendar '(scroll-calendar-right 1))))
4307 (unwind-protect
4308 (progn
4309 (use-local-map map)
4310 (setq ans (read-string prompt "" nil nil))
4311 (if (not (string-match "\\S-" ans)) (setq ans nil))
4312 (setq ans (or ans1 ans ans2)))
4313 (use-local-map old-map)))))
4314 ;; Naked prompt only
4315 (setq ans (read-string prompt "" nil timestr)))
4316 (org-detatch-overlay org-date-ovl)
4318 (if (string-match
4319 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
4320 (progn
4321 (setq year (if (match-end 2)
4322 (string-to-number (match-string 2 ans))
4323 (string-to-number (format-time-string "%Y")))
4324 month (string-to-number (match-string 3 ans))
4325 day (string-to-number (match-string 4 ans)))
4326 (if (< year 100) (setq year (+ 2000 year)))
4327 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
4328 t nil ans))))
4329 (setq tl (parse-time-string ans)
4330 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
4331 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
4332 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
4333 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
4334 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
4335 second (or (nth 0 tl) 0)
4336 wday (nth 6 tl))
4337 (when (and wday (not (nth 3 tl)))
4338 ;; Weekday was given, but no day, so pick that day in the week
4339 ;; on or after the derived date.
4340 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
4341 (unless (equal wday wday1)
4342 (setq day (+ day (% (- wday wday1 -7) 7)))))
4343 (if (and (boundp 'org-time-was-given)
4344 (nth 2 tl))
4345 (setq org-time-was-given t))
4346 (if (< year 100) (setq year (+ 2000 year)))
4347 (if to-time
4348 (encode-time second minute hour day month year)
4349 (if (or (nth 1 tl) (nth 2 tl))
4350 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
4351 (format "%04d-%02d-%02d" year month day)))))
4353 (defun org-eval-in-calendar (form)
4354 "Eval FORM in the calendar window and return to current window.
4355 Also, store the cursor date in variable ans2."
4356 (let ((sw (selected-window)))
4357 (select-window (get-buffer-window "*Calendar*"))
4358 (eval form)
4359 (when (calendar-cursor-to-date)
4360 (let* ((date (calendar-cursor-to-date))
4361 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4362 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4363 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4364 (select-window sw)))
4366 (defun org-calendar-select ()
4367 "Return to `org-read-date' with the date currently selected.
4368 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4369 (interactive)
4370 (when (calendar-cursor-to-date)
4371 (let* ((date (calendar-cursor-to-date))
4372 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4373 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4374 (if (active-minibuffer-window) (exit-minibuffer))))
4376 (defun org-calendar-select-mouse (ev)
4377 "Return to `org-read-date' with the date currently selected.
4378 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4379 (interactive "e")
4380 (mouse-set-point ev)
4381 (when (calendar-cursor-to-date)
4382 (let* ((date (calendar-cursor-to-date))
4383 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4384 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4385 (if (active-minibuffer-window) (exit-minibuffer))))
4387 (defun org-check-deadlines (ndays)
4388 "Check if there are any deadlines due or past due.
4389 A deadline is considered due if it happens within `org-deadline-warning-days'
4390 days from today's date. If the deadline appears in an entry marked DONE,
4391 it is not shown. The prefix arg NDAYS can be used to test that many
4392 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4393 (interactive "P")
4394 (let* ((org-warn-days
4395 (cond
4396 ((equal ndays '(4)) 100000)
4397 (ndays (prefix-numeric-value ndays))
4398 (t org-deadline-warning-days)))
4399 (case-fold-search nil)
4400 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4401 (callback
4402 (lambda ()
4403 (and (let ((d1 (time-to-days (current-time)))
4404 (d2 (time-to-days
4405 (org-time-string-to-time (match-string 1)))))
4406 (< (- d2 d1) org-warn-days))
4407 (not (org-entry-is-done-p))))))
4408 (message "%d deadlines past-due or due within %d days"
4409 (org-occur regexp callback)
4410 org-warn-days)))
4412 (defun org-evaluate-time-range (&optional to-buffer)
4413 "Evaluate a time range by computing the difference between start and end.
4414 Normally the result is just printed in the echo area, but with prefix arg
4415 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4416 If the time range is actually in a table, the result is inserted into the
4417 next column.
4418 For time difference computation, a year is assumed to be exactly 365
4419 days in order to avoid rounding problems."
4420 (interactive "P")
4421 (save-excursion
4422 (unless (org-at-date-range-p)
4423 (goto-char (point-at-bol))
4424 (re-search-forward org-tr-regexp (point-at-eol) t))
4425 (if (not (org-at-date-range-p))
4426 (error "Not at a time-stamp range, and none found in current line")))
4427 (let* ((ts1 (match-string 1))
4428 (ts2 (match-string 2))
4429 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4430 (match-end (match-end 0))
4431 (time1 (org-time-string-to-time ts1))
4432 (time2 (org-time-string-to-time ts2))
4433 (t1 (time-to-seconds time1))
4434 (t2 (time-to-seconds time2))
4435 (diff (abs (- t2 t1)))
4436 (negative (< (- t2 t1) 0))
4437 ;; (ys (floor (* 365 24 60 60)))
4438 (ds (* 24 60 60))
4439 (hs (* 60 60))
4440 (fy "%dy %dd %02d:%02d")
4441 (fy1 "%dy %dd")
4442 (fd "%dd %02d:%02d")
4443 (fd1 "%dd")
4444 (fh "%02d:%02d")
4445 y d h m align)
4446 (if havetime
4447 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4449 d (floor (/ diff ds)) diff (mod diff ds)
4450 h (floor (/ diff hs)) diff (mod diff hs)
4451 m (floor (/ diff 60)))
4452 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4454 d (floor (+ (/ diff ds) 0.5))
4455 h 0 m 0))
4456 (if (not to-buffer)
4457 (message (org-make-tdiff-string y d h m))
4458 (when (org-at-table-p)
4459 (goto-char match-end)
4460 (setq align t)
4461 (and (looking-at " *|") (goto-char (match-end 0))))
4462 (if (looking-at
4463 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4464 (replace-match ""))
4465 (if negative (insert " -"))
4466 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4467 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4468 (insert " " (format fh h m))))
4469 (if align (org-table-align))
4470 (message "Time difference inserted"))))
4472 (defun org-make-tdiff-string (y d h m)
4473 (let ((fmt "")
4474 (l nil))
4475 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4476 l (push y l)))
4477 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4478 l (push d l)))
4479 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4480 l (push h l)))
4481 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4482 l (push m l)))
4483 (apply 'format fmt (nreverse l))))
4485 (defun org-time-string-to-time (s)
4486 (apply 'encode-time (org-parse-time-string s)))
4488 (defun org-parse-time-string (s &optional nodefault)
4489 "Parse the standard Org-mode time string.
4490 This should be a lot faster than the normal `parse-time-string'.
4491 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4492 hour and minute fields will be nil if not given."
4493 (if (string-match org-ts-regexp1 s)
4494 (list 0
4495 (if (or (match-beginning 8) (not nodefault))
4496 (string-to-number (or (match-string 8 s) "0")))
4497 (if (or (match-beginning 7) (not nodefault))
4498 (string-to-number (or (match-string 7 s) "0")))
4499 (string-to-number (match-string 4 s))
4500 (string-to-number (match-string 3 s))
4501 (string-to-number (match-string 2 s))
4502 nil nil nil)
4503 (make-list 9 0)))
4505 (defun org-timestamp-up (&optional arg)
4506 "Increase the date item at the cursor by one.
4507 If the cursor is on the year, change the year. If it is on the month or
4508 the day, change that.
4509 With prefix ARG, change by that many units."
4510 (interactive "p")
4511 (org-timestamp-change (prefix-numeric-value arg)))
4513 (defun org-timestamp-down (&optional arg)
4514 "Decrease the date item at the cursor by one.
4515 If the cursor is on the year, change the year. If it is on the month or
4516 the day, change that.
4517 With prefix ARG, change by that many units."
4518 (interactive "p")
4519 (org-timestamp-change (- (prefix-numeric-value arg))))
4521 (defun org-timestamp-up-day (&optional arg)
4522 "Increase the date in the time stamp by one day.
4523 With prefix ARG, change that many days."
4524 (interactive "p")
4525 (if (and (not (org-at-timestamp-p))
4526 (org-on-heading-p))
4527 (org-todo 'up)
4528 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4530 (defun org-timestamp-down-day (&optional arg)
4531 "Decrease the date in the time stamp by one day.
4532 With prefix ARG, change that many days."
4533 (interactive "p")
4534 (if (and (not (org-at-timestamp-p))
4535 (org-on-heading-p))
4536 (org-todo 'down)
4537 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4539 (defsubst org-pos-in-match-range (pos n)
4540 (and (match-beginning n)
4541 (<= (match-beginning n) pos)
4542 (>= (match-end n) pos)))
4544 (defun org-at-timestamp-p ()
4545 "Determine if the cursor is in or at a timestamp."
4546 (interactive)
4547 (let* ((tsr org-ts-regexp2)
4548 (pos (point))
4549 (ans (or (looking-at tsr)
4550 (save-excursion
4551 (skip-chars-backward "^<\n\r\t")
4552 (if (> (point) 1) (backward-char 1))
4553 (and (looking-at tsr)
4554 (> (- (match-end 0) pos) -1))))))
4555 (and (boundp 'org-ts-what)
4556 (setq org-ts-what
4557 (cond
4558 ((org-pos-in-match-range pos 2) 'year)
4559 ((org-pos-in-match-range pos 3) 'month)
4560 ((org-pos-in-match-range pos 7) 'hour)
4561 ((org-pos-in-match-range pos 8) 'minute)
4562 ((or (org-pos-in-match-range pos 4)
4563 (org-pos-in-match-range pos 5)) 'day)
4564 (t 'day))))
4565 ans))
4567 (defun org-timestamp-change (n &optional what)
4568 "Change the date in the time stamp at point.
4569 The date will be changed by N times WHAT. WHAT can be `day', `month',
4570 `year', `minute', `second'. If WHAT is not given, the cursor position
4571 in the timestamp determines what will be changed."
4572 (let ((fmt (car org-time-stamp-formats))
4573 org-ts-what
4574 (pos (point))
4575 ts time time0)
4576 (if (not (org-at-timestamp-p))
4577 (error "Not at a timestamp"))
4578 (setq org-ts-what (or what org-ts-what))
4579 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4580 (- (match-end 0) (match-beginning 0))))
4582 (cdr org-time-stamp-formats)
4583 (car org-time-stamp-formats)))
4584 (setq ts (match-string 0))
4585 (replace-match "")
4586 (setq time0 (org-parse-time-string ts))
4587 (setq time
4588 (apply 'encode-time
4589 (append
4590 (list (or (car time0) 0))
4591 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4592 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4593 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4594 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4595 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4596 (nthcdr 6 time0))))
4597 (if (eq what 'calendar)
4598 (let ((cal-date
4599 (save-excursion
4600 (save-match-data
4601 (set-buffer "*Calendar*")
4602 (calendar-cursor-to-date)))))
4603 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4604 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4605 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4606 (setcar time0 (or (car time0) 0))
4607 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4608 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4609 (setq time (apply 'encode-time time0))))
4610 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4611 (goto-char pos)
4612 ;; Try to recenter the calendar window, if any
4613 (if (and org-calendar-follow-timestamp-change
4614 (get-buffer-window "*Calendar*" t)
4615 (memq org-ts-what '(day month year)))
4616 (org-recenter-calendar (time-to-days time)))))
4618 (defun org-recenter-calendar (date)
4619 "If the calendar is visible, recenter it to DATE."
4620 (let* ((win (selected-window))
4621 (cwin (get-buffer-window "*Calendar*" t))
4622 (calendar-move-hook nil))
4623 (when cwin
4624 (select-window cwin)
4625 (calendar-goto-date (if (listp date) date
4626 (calendar-gregorian-from-absolute date)))
4627 (select-window win))))
4629 (defun org-goto-calendar (&optional arg)
4630 "Go to the Emacs calendar at the current date.
4631 If there is a time stamp in the current line, go to that date.
4632 A prefix ARG can be used to force the current date."
4633 (interactive "P")
4634 (let ((tsr org-ts-regexp) diff
4635 (calendar-move-hook nil)
4636 (view-diary-entries-initially nil))
4637 (if (or (org-at-timestamp-p)
4638 (save-excursion
4639 (beginning-of-line 1)
4640 (looking-at (concat ".*" tsr))))
4641 (let ((d1 (time-to-days (current-time)))
4642 (d2 (time-to-days
4643 (org-time-string-to-time (match-string 1)))))
4644 (setq diff (- d2 d1))))
4645 (calendar)
4646 (calendar-goto-today)
4647 (if (and diff (not arg)) (calendar-forward-day diff))))
4649 (defun org-date-from-calendar ()
4650 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4651 If there is already a time stamp at the cursor position, update it."
4652 (interactive)
4653 (org-timestamp-change 0 'calendar))
4655 ;;; Agenda, and Diary Integration
4657 ;;; Define the mode
4659 (defvar org-agenda-mode-map (make-sparse-keymap)
4660 "Keymap for `org-agenda-mode'.")
4662 (defvar org-agenda-menu) ; defined later in this file.
4663 (defvar org-agenda-follow-mode nil)
4664 (defvar org-agenda-show-log nil)
4665 (defvar org-agenda-buffer-name "*Org Agenda*")
4666 (defvar org-agenda-redo-command nil)
4667 (defvar org-agenda-mode-hook nil)
4668 (defvar org-agenda-type nil)
4669 (defvar org-agenda-force-single-file nil)
4671 ;;;###autoload
4672 (defun org-agenda-mode ()
4673 "Mode for time-sorted view on action items in Org-mode files.
4675 The following commands are available:
4677 \\{org-agenda-mode-map}"
4678 (interactive)
4679 (kill-all-local-variables)
4680 (setq major-mode 'org-agenda-mode)
4681 (setq mode-name "Org-Agenda")
4682 (use-local-map org-agenda-mode-map)
4683 (easy-menu-add org-agenda-menu)
4684 (if org-startup-truncated (setq truncate-lines t))
4685 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4686 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4687 (unless org-agenda-keep-modes
4688 (setq org-agenda-follow-mode nil
4689 org-agenda-show-log nil))
4690 (easy-menu-change
4691 '("Agenda") "Agenda Files"
4692 (append
4693 (list
4694 (vector
4695 (if (get 'org-agenda-files 'org-restrict)
4696 "Restricted to single file"
4697 "Edit File List")
4698 '(org-edit-agenda-file-list)
4699 (not (get 'org-agenda-files 'org-restrict)))
4700 "--")
4701 (mapcar 'org-file-menu-entry (org-agenda-files))))
4702 (org-agenda-set-mode-name)
4703 (apply
4704 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4705 (list 'org-agenda-mode-hook)))
4707 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4708 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
4709 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4710 (define-key org-agenda-mode-map " " 'org-agenda-show)
4711 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4712 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4713 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4714 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4715 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4716 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4717 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4718 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4719 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4720 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4721 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4722 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4724 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4725 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4726 (while l (define-key org-agenda-mode-map
4727 (int-to-string (pop l)) 'digit-argument)))
4729 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4730 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4731 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4732 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4733 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4734 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4735 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4736 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4737 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4738 (define-key org-agenda-mode-map "n" 'next-line)
4739 (define-key org-agenda-mode-map "p" 'previous-line)
4740 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4741 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4742 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4743 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4744 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4745 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4746 (eval-after-load "calendar"
4747 '(define-key calendar-mode-map org-calendar-to-agenda-key
4748 'org-calendar-goto-agenda))
4749 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4750 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4751 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4752 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4753 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4754 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4755 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4756 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4757 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4758 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4759 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4760 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4761 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4762 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4763 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4764 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4765 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4766 "Local keymap for agenda entries from Org-mode.")
4768 (define-key org-agenda-keymap
4769 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4770 (define-key org-agenda-keymap
4771 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4772 (define-key org-agenda-keymap [follow-link] 'mouse-face)
4773 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4774 '("Agenda"
4775 ("Agenda Files")
4776 "--"
4777 ["Show" org-agenda-show t]
4778 ["Go To (other window)" org-agenda-goto t]
4779 ["Go To (one window)" org-agenda-switch-to t]
4780 ["Follow Mode" org-agenda-follow-mode
4781 :style toggle :selected org-agenda-follow-mode :active t]
4782 "--"
4783 ["Cycle TODO" org-agenda-todo t]
4784 ("Tags"
4785 ["Show all Tags" org-agenda-show-tags t]
4786 ["Set Tags" org-agenda-set-tags t])
4787 ("Reschedule"
4788 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4789 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4790 "--"
4791 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4792 ("Priority"
4793 ["Set Priority" org-agenda-priority t]
4794 ["Increase Priority" org-agenda-priority-up t]
4795 ["Decrease Priority" org-agenda-priority-down t]
4796 ["Show Priority" org-agenda-show-priority t])
4797 "--"
4798 ;; ["New agenda command" org-agenda t]
4799 ["Rebuild buffer" org-agenda-redo t]
4800 "--"
4801 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4802 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4803 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4804 "--"
4805 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4806 :style radio :selected (equal org-agenda-ndays 1)]
4807 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4808 :style radio :selected (equal org-agenda-ndays 7)]
4809 "--"
4810 ["Show Logbook entries" org-agenda-log-mode
4811 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4812 ["Include Diary" org-agenda-toggle-diary
4813 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4814 ["Use Time Grid" org-agenda-toggle-time-grid
4815 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4816 "--"
4817 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4818 ("Calendar Commands"
4819 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4820 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4821 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4822 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4823 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4824 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4825 "--"
4826 ["Quit" org-agenda-quit t]
4827 ["Exit and Release Buffers" org-agenda-exit t]
4830 ;;;###autoload
4831 (defun org-agenda (arg)
4832 "Dispatch agenda commands to collect entries to the agenda buffer.
4833 Prompts for a character to select a command. Any prefix arg will be passed
4834 on to the selected command. The default selections are:
4836 a Call `org-agenda' to display the agenda for the current day or week.
4837 t Call `org-todo-list' to display the global todo list.
4838 T Call `org-todo-list' to display the global todo list, select only
4839 entries with a specific TODO keyword (the user gets a prompt).
4840 m Call `org-tags-view' to display headlines with tags matching
4841 a condition (the user is prompted for the condition).
4842 M Like `m', but select only TODO entries, no ordinary headlines.
4844 More commands can be added by configuring the variable
4845 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4846 searches can be pre-defined in this way.
4848 If the current buffer is in Org-mode and visiting a file, you can also
4849 first press `1' to indicate that the agenda should be temporarily (until the
4850 next use of \\[org-agenda]) restricted to the current file."
4851 (interactive "P")
4852 (catch 'exit
4853 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
4854 (custom org-agenda-custom-commands)
4855 c entry key type string)
4856 (put 'org-agenda-files 'org-restrict nil)
4857 (save-window-excursion
4858 (delete-other-windows)
4859 (switch-to-buffer-other-window " *Agenda Commands*")
4860 (erase-buffer)
4861 (insert
4862 "Press key for an agenda command:
4863 --------------------------------
4864 a Agenda for current week or day
4865 t List of all TODO entries T Entries with special TODO kwd
4866 m Match a TAGS query M Like m, but only TODO entries
4867 C Configure your own agenda commands")
4868 (while (setq entry (pop custom))
4869 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4870 (insert (format "\n%-4s%-14s: %s"
4872 (cond
4873 ((eq type 'tags) "Tags query")
4874 ((eq type 'todo) "TODO keyword")
4875 ((eq type 'tags-tree) "Tags tree")
4876 ((eq type 'todo-tree) "TODO kwd tree")
4877 ((eq type 'occur-tree) "Occur tree")
4878 (t "???"))
4879 (org-add-props string nil 'face 'org-warning))))
4880 (goto-char (point-min))
4881 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4882 (message "Press key for agenda command%s"
4883 (if restrict-ok ", or [1] to restrict to current file" ""))
4884 (setq c (read-char-exclusive))
4885 (message "")
4886 (when (equal c ?1)
4887 (if restrict-ok
4888 (put 'org-agenda-files 'org-restrict (list buffer-file-name))
4889 (error "Cannot restrict agenda to current buffer"))
4890 (message "Press key for agenda command%s"
4891 (if restrict-ok " (restricted to current file)" ""))
4892 (setq c (read-char-exclusive))
4893 (message "")))
4894 (require 'calendar) ; FIXME: can we avoid this for some commands?
4895 ;; For example the todo list should not need it (but does...)
4896 (cond
4897 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4898 ((equal c ?a) (call-interactively 'org-agenda-list))
4899 ((equal c ?t) (call-interactively 'org-todo-list))
4900 ((equal c ?T)
4901 (setq current-prefix-arg (or arg '(4)))
4902 (call-interactively 'org-todo-list))
4903 ((equal c ?m) (call-interactively 'org-tags-view))
4904 ((equal c ?M)
4905 (setq current-prefix-arg (or arg '(4)))
4906 (call-interactively 'org-tags-view))
4907 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4908 (setq type (nth 1 entry) string (nth 2 entry))
4909 (cond
4910 ((eq type 'tags)
4911 (org-tags-view current-prefix-arg string))
4912 ((eq type 'todo)
4913 (org-todo-list string))
4914 ((eq type 'tags-tree)
4915 (org-check-for-org-mode)
4916 (org-tags-sparse-tree current-prefix-arg string))
4917 ((eq type 'todo-tree)
4918 (org-check-for-org-mode)
4919 (org-occur (concat "^" outline-regexp "[ \t]*"
4920 (regexp-quote string) "\\>")))
4921 ((eq type 'occur-tree)
4922 (org-check-for-org-mode)
4923 (org-occur string))
4924 (t (error "Invalid custom agenda command type %s" type))))
4925 (t (error "Invalid key"))))))
4927 (defun org-check-for-org-mode ()
4928 "Make sure current buffer is in org-mode. Error if not."
4929 (or (eq major-mode 'org-mode)
4930 (error "Cannot execute org-mode agenda command on buffer in %s."
4931 major-mode)))
4933 (defun org-fit-agenda-window ()
4934 "Fit the window to the buffer size."
4935 (and org-fit-agenda-window
4936 (fboundp 'fit-window-to-buffer)
4937 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4938 (/ (frame-height) 2))))
4940 (defun org-agenda-files (&optional unrestricted)
4941 "Get the list of agenda files.
4942 Optional UNRESTRICTED means return the full list even if a restriction
4943 is currently in place."
4944 (cond
4945 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
4946 ((stringp org-agenda-files) (org-read-agenda-file-list))
4947 ((listp org-agenda-files) org-agenda-files)
4948 (t (error "Invalid value of `org-agenda-files'"))))
4950 (defvar org-window-configuration)
4952 (defun org-edit-agenda-file-list ()
4953 "Edit the list of agenda files.
4954 Depending on setup, this either uses customize to edit the variable
4955 `org-agenda-files', or it visits the file that is holding the list. In the
4956 latter case, the buffer is set up in a way that saving it automatically kills
4957 the buffer and restores the previous window configuration."
4958 (interactive)
4959 (if (stringp org-agenda-files)
4960 (let ((cw (current-window-configuration)))
4961 (find-file org-agenda-files)
4962 (set (make-local-variable 'org-window-configuration) cw)
4963 (org-add-hook 'after-save-hook
4964 (lambda ()
4965 (set-window-configuration
4966 (prog1 org-window-configuration
4967 (kill-buffer (current-buffer))))
4968 (org-install-agenda-files-menu)
4969 (message "New agenda file list installed"))
4970 nil 'local)
4971 (message (substitute-command-keys
4972 "Edit list and finish with \\[save-buffer]")))
4973 (customize-variable 'org-agenda-files)))
4975 (defun org-store-new-agenda-file-list (list)
4976 "Set new value for the agenda file list and save it correcly."
4977 (if (stringp org-agenda-files)
4978 (let ((f org-agenda-files) b)
4979 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
4980 (with-temp-file f
4981 (insert (mapconcat 'identity list "\n") "\n")))
4982 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
4983 (setq org-agenda-files list)
4984 (customize-save-variable 'org-agenda-files org-agenda-files))))
4986 (defun org-read-agenda-file-list ()
4987 "Read the list of agenda files from a file."
4988 (when (stringp org-agenda-files)
4989 (with-temp-buffer
4990 (insert-file-contents org-agenda-files)
4991 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
4993 (defvar org-agenda-markers nil
4994 "List of all currently active markers created by `org-agenda'.")
4995 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
4996 "Creation time of the last agenda marker.")
4998 (defun org-agenda-new-marker (&optional pos)
4999 "Return a new agenda marker.
5000 Org-mode keeps a list of these markers and resets them when they are
5001 no longer in use."
5002 (let ((m (copy-marker (or pos (point)))))
5003 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
5004 (push m org-agenda-markers)
5007 (defun org-agenda-maybe-reset-markers (&optional force)
5008 "Reset markers created by `org-agenda'. But only if they are old enough."
5009 (if (or force
5010 (> (- (time-to-seconds (current-time))
5011 org-agenda-last-marker-time)
5013 (while org-agenda-markers
5014 (move-marker (pop org-agenda-markers) nil))))
5016 (defvar org-agenda-new-buffers nil
5017 "Buffers created to visit agenda files.")
5019 (defun org-get-agenda-file-buffer (file)
5020 "Get a buffer visiting FILE. If the buffer needs to be created, add
5021 it to the list of buffers which might be released later."
5022 (let ((buf (find-buffer-visiting file)))
5023 (if buf
5024 buf ; just return it
5025 ;; Make a new buffer and remember it
5026 (setq buf (find-file-noselect file))
5027 (if buf (push buf org-agenda-new-buffers))
5028 buf)))
5030 (defun org-release-buffers (blist)
5031 "Release all buffers in list, asking the user for confirmation when needed.
5032 When a buffer is unmodified, it is just killed. When modified, it is saved
5033 \(if the user agrees) and then killed."
5034 (let (buf file)
5035 (while (setq buf (pop blist))
5036 (setq file (buffer-file-name buf))
5037 (when (and (buffer-modified-p buf)
5038 file
5039 (y-or-n-p (format "Save file %s? " file)))
5040 (with-current-buffer buf (save-buffer)))
5041 (kill-buffer buf))))
5043 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
5045 (defun org-timeline (&optional include-all keep-modes)
5046 "Show a time-sorted view of the entries in the current org file.
5047 Only entries with a time stamp of today or later will be listed. With
5048 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
5049 under the current date.
5050 If the buffer contains an active region, only check the region for
5051 dates."
5052 (interactive "P")
5053 (require 'calendar)
5054 (org-agenda-maybe-reset-markers 'force)
5055 (org-compile-prefix-format org-timeline-prefix-format)
5056 (let* ((dopast t)
5057 (dotodo include-all)
5058 (doclosed org-agenda-show-log)
5059 (org-agenda-keep-modes keep-modes)
5060 (entry buffer-file-name)
5061 (org-agenda-files (list buffer-file-name))
5062 (date (calendar-current-date))
5063 (win (selected-window))
5064 (pos1 (point))
5065 (beg (if (org-region-active-p) (region-beginning) (point-min)))
5066 (end (if (org-region-active-p) (region-end) (point-max)))
5067 (day-numbers (org-get-all-dates beg end 'no-ranges
5068 t doclosed)) ; always include today
5069 (today (time-to-days (current-time)))
5070 (org-respect-restriction t)
5071 (past t)
5072 args
5073 s e rtn d)
5074 (setq org-agenda-redo-command
5075 (list 'progn
5076 (list 'switch-to-buffer-other-window (current-buffer))
5077 (list 'org-timeline (list 'quote include-all) t)))
5078 (if (not dopast)
5079 ;; Remove past dates from the list of dates.
5080 (setq day-numbers (delq nil (mapcar (lambda(x)
5081 (if (>= x today) x nil))
5082 day-numbers))))
5083 (switch-to-buffer-other-window
5084 (get-buffer-create org-agenda-buffer-name))
5085 (setq buffer-read-only nil)
5086 (erase-buffer)
5087 (org-agenda-mode) (setq buffer-read-only nil)
5088 (set (make-local-variable 'org-agenda-type) 'timeline)
5089 (if doclosed (push :closed args))
5090 (push :timestamp args)
5091 (if dotodo (push :todo args))
5092 (while (setq d (pop day-numbers))
5093 (if (and (>= d today)
5094 dopast
5095 past)
5096 (progn
5097 (setq past nil)
5098 (insert (make-string 79 ?-) "\n")))
5099 (setq date (calendar-gregorian-from-absolute d))
5100 (setq s (point))
5101 (setq rtn (apply 'org-agenda-get-day-entries
5102 entry date args))
5103 (if (or rtn (equal d today))
5104 (progn
5105 (insert (calendar-day-name date) " "
5106 (number-to-string (extract-calendar-day date)) " "
5107 (calendar-month-name (extract-calendar-month date)) " "
5108 (number-to-string (extract-calendar-year date)) "\n")
5109 (put-text-property s (1- (point)) 'face
5110 'org-level-3)
5111 (if (equal d today)
5112 (put-text-property s (1- (point)) 'org-today t))
5113 (insert (org-finalize-agenda-entries rtn) "\n")
5114 (put-text-property s (1- (point)) 'day d))))
5115 (goto-char (point-min))
5116 (setq buffer-read-only t)
5117 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5118 (point-min)))
5119 (when (not org-select-timeline-window)
5120 (select-window win)
5121 (goto-char pos1))))
5123 ;;;###autoload
5124 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
5125 "Produce a weekly view from all files in variable `org-agenda-files'.
5126 The view will be for the current week, but from the overview buffer you
5127 will be able to go to other weeks.
5128 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
5129 also be shown, under the current date.
5130 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
5131 on the days are also shown. See the variable `org-log-done' for how
5132 to turn on logging.
5133 START-DAY defaults to TODAY, or to the most recent match for the weekday
5134 given in `org-agenda-start-on-weekday'.
5135 NDAYS defaults to `org-agenda-ndays'."
5136 (interactive "P")
5137 (org-agenda-maybe-reset-markers 'force)
5138 (org-compile-prefix-format org-agenda-prefix-format)
5139 (require 'calendar)
5140 (let* ((org-agenda-start-on-weekday
5141 (if (or (equal ndays 1)
5142 (and (null ndays) (equal 1 org-agenda-ndays)))
5143 nil org-agenda-start-on-weekday))
5144 (org-agenda-keep-modes keep-modes)
5145 (thefiles (org-agenda-files))
5146 (files thefiles)
5147 (win (selected-window))
5148 (today (time-to-days (current-time)))
5149 (sd (or start-day today))
5150 (start (if (or (null org-agenda-start-on-weekday)
5151 (< org-agenda-ndays 7))
5153 (let* ((nt (calendar-day-of-week
5154 (calendar-gregorian-from-absolute sd)))
5155 (n1 org-agenda-start-on-weekday)
5156 (d (- nt n1)))
5157 (- sd (+ (if (< d 0) 7 0) d)))))
5158 (day-numbers (list start))
5159 ;FIXME (inhibit-redisplay t)
5160 s e rtn rtnall file date d start-pos end-pos todayp nd)
5161 (setq org-agenda-redo-command
5162 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
5163 ;; Make the list of days
5164 (setq ndays (or ndays org-agenda-ndays)
5165 nd ndays)
5166 (while (> ndays 1)
5167 (push (1+ (car day-numbers)) day-numbers)
5168 (setq ndays (1- ndays)))
5169 (setq day-numbers (nreverse day-numbers))
5170 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5171 (progn
5172 (delete-other-windows)
5173 (switch-to-buffer-other-window
5174 (get-buffer-create org-agenda-buffer-name))))
5175 (setq buffer-read-only nil)
5176 (erase-buffer)
5177 (org-agenda-mode) (setq buffer-read-only nil)
5178 (set (make-local-variable 'org-agenda-type) 'agenda)
5179 (set (make-local-variable 'starting-day) (car day-numbers))
5180 (set (make-local-variable 'include-all-loc) include-all)
5181 (when (and (or include-all org-agenda-include-all-todo)
5182 (member today day-numbers))
5183 (setq files thefiles
5184 rtnall nil)
5185 (while (setq file (pop files))
5186 (catch 'nextfile
5187 (org-check-agenda-file file)
5188 (setq date (calendar-gregorian-from-absolute today)
5189 rtn (org-agenda-get-day-entries
5190 file date :todo))
5191 (setq rtnall (append rtnall rtn))))
5192 (when rtnall
5193 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
5194 (add-text-properties (point-min) (1- (point))
5195 (list 'face 'org-level-3))
5196 (insert (org-finalize-agenda-entries rtnall) "\n")))
5197 (while (setq d (pop day-numbers))
5198 (setq date (calendar-gregorian-from-absolute d)
5199 s (point))
5200 (if (or (setq todayp (= d today))
5201 (and (not start-pos) (= d sd)))
5202 (setq start-pos (point))
5203 (if (and start-pos (not end-pos))
5204 (setq end-pos (point))))
5205 (setq files thefiles
5206 rtnall nil)
5207 (while (setq file (pop files))
5208 (catch 'nextfile
5209 (org-check-agenda-file file)
5210 (if org-agenda-show-log
5211 (setq rtn (org-agenda-get-day-entries
5212 file date
5213 :deadline :scheduled :timestamp :closed))
5214 (setq rtn (org-agenda-get-day-entries
5215 file date
5216 :deadline :scheduled :timestamp)))
5217 (setq rtnall (append rtnall rtn))))
5218 (if org-agenda-include-diary
5219 (progn
5220 (require 'diary-lib)
5221 (setq rtn (org-get-entries-from-diary date))
5222 (setq rtnall (append rtnall rtn))))
5223 (if (or rtnall org-agenda-show-all-dates)
5224 (progn
5225 (insert (format "%-9s %2d %s %4d\n"
5226 (calendar-day-name date)
5227 (extract-calendar-day date)
5228 (calendar-month-name (extract-calendar-month date))
5229 (extract-calendar-year date)))
5230 (put-text-property s (1- (point)) 'face
5231 'org-level-3)
5232 (if rtnall (insert
5233 (org-finalize-agenda-entries
5234 (org-agenda-add-time-grid-maybe
5235 rtnall nd todayp))
5236 "\n"))
5237 (put-text-property s (1- (point)) 'day d))))
5238 (goto-char (point-min))
5239 (setq buffer-read-only t)
5240 (org-fit-agenda-window)
5241 (unless (and (pos-visible-in-window-p (point-min))
5242 (pos-visible-in-window-p (point-max)))
5243 (goto-char (1- (point-max)))
5244 (recenter -1)
5245 (if (not (pos-visible-in-window-p (or start-pos 1)))
5246 (progn
5247 (goto-char (or start-pos 1))
5248 (recenter 1))))
5249 (goto-char (or start-pos 1))
5250 (if (not org-select-agenda-window) (select-window win))
5251 (message "")))
5253 (defvar org-select-this-todo-keyword nil)
5255 ;;;###autoload
5256 (defun org-todo-list (arg &optional keep-modes)
5257 "Show all TODO entries from all agenda file in a single list.
5258 The prefix arg can be used to select a specific TODO keyword and limit
5259 the list to these. When using \\[universal-argument], you will be prompted
5260 for a keyword. A numeric prefix directly selects the Nth keyword in
5261 `org-todo-keywords'."
5262 (interactive "P")
5263 (org-agenda-maybe-reset-markers 'force)
5264 (org-compile-prefix-format org-agenda-prefix-format)
5265 (let* ((org-agenda-keep-modes keep-modes)
5266 (today (time-to-days (current-time)))
5267 (date (calendar-gregorian-from-absolute today))
5268 (win (selected-window))
5269 (kwds org-todo-keywords)
5270 (completion-ignore-case t)
5271 (org-select-this-todo-keyword
5272 (if (stringp arg) arg
5273 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
5274 rtn rtnall files file pos)
5275 (when (equal arg '(4))
5276 (setq org-select-this-todo-keyword
5277 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
5278 nil t)))
5279 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
5280 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5281 (progn
5282 (delete-other-windows)
5283 (switch-to-buffer-other-window
5284 (get-buffer-create org-agenda-buffer-name))))
5285 (setq buffer-read-only nil)
5286 (erase-buffer)
5287 (org-agenda-mode) (setq buffer-read-only nil)
5288 (set (make-local-variable 'org-agenda-type) 'todo)
5289 (set (make-local-variable 'last-arg) arg)
5290 (set (make-local-variable 'org-todo-keywords) kwds)
5291 (set (make-local-variable 'org-agenda-redo-command)
5292 '(org-todo-list (or current-prefix-arg last-arg) t))
5293 (setq files (org-agenda-files)
5294 rtnall nil)
5295 (while (setq file (pop files))
5296 (catch 'nextfile
5297 (org-check-agenda-file file)
5298 (setq rtn (org-agenda-get-day-entries file date :todo))
5299 (setq rtnall (append rtnall rtn))))
5300 (insert "Global list of TODO items of type: ")
5301 (add-text-properties (point-min) (1- (point))
5302 (list 'face 'org-level-3))
5303 (setq pos (point))
5304 (insert (or org-select-this-todo-keyword "ALL") "\n")
5305 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
5306 (setq pos (point))
5307 (insert
5308 "Available with `N r': (0)ALL "
5309 (let ((n 0))
5310 (mapconcat (lambda (x)
5311 (format "(%d)%s" (setq n (1+ n)) x))
5312 org-todo-keywords " "))
5313 "\n")
5314 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
5315 (when rtnall
5316 (insert (org-finalize-agenda-entries rtnall) "\n"))
5317 (goto-char (point-min))
5318 (setq buffer-read-only t)
5319 (org-fit-agenda-window)
5320 (if (not org-select-agenda-window) (select-window win))))
5322 (defun org-check-agenda-file (file)
5323 "Make sure FILE exists. If not, ask user what to do."
5324 (when (not (file-exists-p file))
5325 (message "non-existent file %s. [R]emove from list or [A]bort?"
5326 (abbreviate-file-name file))
5327 (let ((r (downcase (read-char-exclusive))))
5328 (cond
5329 ((equal r ?r)
5330 (org-remove-file file)
5331 (throw 'nextfile t))
5332 (t (error "Abort"))))))
5334 (defun org-agenda-check-type (error &rest types)
5335 "Check if agenda buffer is of allowed type.
5336 If ERROR is non-nil, throw an error, otherwise just return nil."
5337 (if (memq org-agenda-type types)
5339 (if error
5340 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
5341 nil)))
5343 (defun org-agenda-quit ()
5344 "Exit agenda by removing the window or the buffer."
5345 (interactive)
5346 (let ((buf (current-buffer)))
5347 (if (not (one-window-p)) (delete-window))
5348 (kill-buffer buf)
5349 (org-agenda-maybe-reset-markers 'force)))
5351 (defun org-agenda-exit ()
5352 "Exit agenda by removing the window or the buffer.
5353 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
5354 Org-mode buffers visited directly by the user will not be touched."
5355 (interactive)
5356 (org-release-buffers org-agenda-new-buffers)
5357 (setq org-agenda-new-buffers nil)
5358 (org-agenda-quit))
5360 (defun org-agenda-redo ()
5361 "Rebuild Agenda.
5362 When this is the global TODO list, a prefix argument will be interpreted."
5363 (interactive)
5364 (message "Rebuilding agenda buffer...")
5365 (eval org-agenda-redo-command)
5366 (message "Rebuilding agenda buffer...done"))
5368 (defun org-agenda-goto-today ()
5369 "Go to today."
5370 (interactive)
5371 (org-agenda-check-type t 'timeline 'agenda)
5372 (if (boundp 'starting-day)
5373 (let ((cmd (car org-agenda-redo-command))
5374 (iall (nth 1 org-agenda-redo-command))
5375 (nday (nth 3 org-agenda-redo-command))
5376 (keep (nth 4 org-agenda-redo-command)))
5377 (eval (list cmd iall nil nday keep)))
5378 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5379 (point-min)))))
5381 (defun org-agenda-later (arg)
5382 "Go forward in time by `org-agenda-ndays' days.
5383 With prefix ARG, go forward that many times `org-agenda-ndays'."
5384 (interactive "p")
5385 (org-agenda-check-type t 'agenda)
5386 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5387 (+ starting-day (* arg org-agenda-ndays)) nil t))
5389 (defun org-agenda-earlier (arg)
5390 "Go back in time by `org-agenda-ndays' days.
5391 With prefix ARG, go back that many times `org-agenda-ndays'."
5392 (interactive "p")
5393 (org-agenda-check-type t 'agenda)
5394 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5395 (- starting-day (* arg org-agenda-ndays)) nil t))
5397 (defun org-agenda-week-view ()
5398 "Switch to weekly view for agenda."
5399 (interactive)
5400 (org-agenda-check-type t 'agenda)
5401 (setq org-agenda-ndays 7)
5402 (org-agenda-list include-all-loc
5403 (or (get-text-property (point) 'day)
5404 starting-day)
5405 nil t)
5406 (org-agenda-set-mode-name)
5407 (message "Switched to week view"))
5409 (defun org-agenda-day-view ()
5410 "Switch to daily view for agenda."
5411 (interactive)
5412 (org-agenda-check-type t 'agenda)
5413 (setq org-agenda-ndays 1)
5414 (org-agenda-list include-all-loc
5415 (or (get-text-property (point) 'day)
5416 starting-day)
5417 nil t)
5418 (org-agenda-set-mode-name)
5419 (message "Switched to day view"))
5421 (defun org-agenda-next-date-line (&optional arg)
5422 "Jump to the next line indicating a date in agenda buffer."
5423 (interactive "p")
5424 (org-agenda-check-type t 'agenda 'timeline)
5425 (beginning-of-line 1)
5426 (if (looking-at "^\\S-") (forward-char 1))
5427 (if (not (re-search-forward "^\\S-" nil t arg))
5428 (progn
5429 (backward-char 1)
5430 (error "No next date after this line in this buffer")))
5431 (goto-char (match-beginning 0)))
5433 (defun org-agenda-previous-date-line (&optional arg)
5434 "Jump to the previous line indicating a date in agenda buffer."
5435 (interactive "p")
5436 (org-agenda-check-type t 'agenda 'timeline)
5437 (beginning-of-line 1)
5438 (if (not (re-search-backward "^\\S-" nil t arg))
5439 (error "No previous date before this line in this buffer")))
5441 ;; Initialize the highlight
5442 (defvar org-hl (org-make-overlay 1 1))
5443 (org-overlay-put org-hl 'face 'highlight)
5445 (defun org-highlight (begin end &optional buffer)
5446 "Highlight a region with overlay."
5447 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
5448 org-hl begin end (or buffer (current-buffer))))
5450 (defun org-unhighlight ()
5451 "Detach overlay INDEX."
5452 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
5455 (defun org-agenda-follow-mode ()
5456 "Toggle follow mode in an agenda buffer."
5457 (interactive)
5458 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5459 (org-agenda-set-mode-name)
5460 (message "Follow mode is %s"
5461 (if org-agenda-follow-mode "on" "off")))
5463 (defun org-agenda-log-mode ()
5464 "Toggle log mode in an agenda buffer."
5465 (interactive)
5466 (org-agenda-check-type t 'agenda 'timeline)
5467 (setq org-agenda-show-log (not org-agenda-show-log))
5468 (org-agenda-set-mode-name)
5469 (org-agenda-redo)
5470 (message "Log mode is %s"
5471 (if org-agenda-show-log "on" "off")))
5473 (defun org-agenda-toggle-diary ()
5474 "Toggle diary inclusion in an agenda buffer."
5475 (interactive)
5476 (org-agenda-check-type t 'agenda)
5477 (setq org-agenda-include-diary (not org-agenda-include-diary))
5478 (org-agenda-redo)
5479 (org-agenda-set-mode-name)
5480 (message "Diary inclusion turned %s"
5481 (if org-agenda-include-diary "on" "off")))
5483 (defun org-agenda-toggle-time-grid ()
5484 "Toggle time grid in an agenda buffer."
5485 (interactive)
5486 (org-agenda-check-type t 'agenda)
5487 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5488 (org-agenda-redo)
5489 (org-agenda-set-mode-name)
5490 (message "Time-grid turned %s"
5491 (if org-agenda-use-time-grid "on" "off")))
5493 (defun org-agenda-set-mode-name ()
5494 "Set the mode name to indicate all the small mode settings."
5495 (setq mode-name
5496 (concat "Org-Agenda"
5497 (if (equal org-agenda-ndays 1) " Day" "")
5498 (if (equal org-agenda-ndays 7) " Week" "")
5499 (if org-agenda-follow-mode " Follow" "")
5500 (if org-agenda-include-diary " Diary" "")
5501 (if org-agenda-use-time-grid " Grid" "")
5502 (if org-agenda-show-log " Log" "")))
5503 (force-mode-line-update))
5505 (defun org-agenda-post-command-hook ()
5506 (and (eolp) (not (bolp)) (backward-char 1))
5507 (if (and org-agenda-follow-mode
5508 (get-text-property (point) 'org-marker))
5509 (org-agenda-show)))
5511 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5513 (defun org-get-entries-from-diary (date)
5514 "Get the (Emacs Calendar) diary entries for DATE."
5515 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5516 (diary-display-hook '(fancy-diary-display))
5517 (list-diary-entries-hook
5518 (cons 'org-diary-default-entry list-diary-entries-hook))
5519 (diary-file-name-prefix-function nil) ; turn this feature off
5520 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5521 entries
5522 (org-disable-agenda-to-diary t))
5523 (save-excursion
5524 (save-window-excursion
5525 (list-diary-entries date 1)))
5526 (if (not (get-buffer fancy-diary-buffer))
5527 (setq entries nil)
5528 (with-current-buffer fancy-diary-buffer
5529 (setq buffer-read-only nil)
5530 (if (= (point-max) 1)
5531 ;; No entries
5532 (setq entries nil)
5533 ;; Omit the date and other unnecessary stuff
5534 (org-agenda-cleanup-fancy-diary)
5535 ;; Add prefix to each line and extend the text properties
5536 (if (= (point-max) 1)
5537 (setq entries nil)
5538 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5539 (set-buffer-modified-p nil)
5540 (kill-buffer fancy-diary-buffer)))
5541 (when entries
5542 (setq entries (org-split-string entries "\n"))
5543 (setq entries
5544 (mapcar
5545 (lambda (x)
5546 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5547 ;; Extend the text properties to the beginning of the line
5548 (org-add-props x (text-properties-at (1- (length x)) x)))
5549 entries)))))
5551 (defun org-agenda-cleanup-fancy-diary ()
5552 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5553 This gets rid of the date, the underline under the date, and
5554 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5555 date. It also removes lines that contain only whitespace."
5556 (goto-char (point-min))
5557 (if (looking-at ".*?:[ \t]*")
5558 (progn
5559 (replace-match "")
5560 (re-search-forward "\n=+$" nil t)
5561 (replace-match "")
5562 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5563 (re-search-forward "\n=+$" nil t)
5564 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5565 (goto-char (point-min))
5566 (while (re-search-forward "^ +\n" nil t)
5567 (replace-match ""))
5568 (goto-char (point-min))
5569 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5570 (replace-match "")))
5572 ;; Make sure entries from the diary have the right text properties.
5573 (eval-after-load "diary-lib"
5574 '(if (boundp 'diary-modify-entry-list-string-function)
5575 ;; We can rely on the hook, nothing to do
5577 ;; Hook not avaiable, must use advice to make this work
5578 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5579 "Make the position visible."
5580 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5581 (stringp string)
5582 buffer-file-name)
5583 (setq string (org-modify-diary-entry-string string))))))
5585 (defun org-modify-diary-entry-string (string)
5586 "Add text properties to string, allowing org-mode to act on it."
5587 (org-add-props string nil
5588 'mouse-face 'highlight
5589 'keymap org-agenda-keymap
5590 'help-echo (format "mouse-2 or RET jump to diary file %s"
5591 (abbreviate-file-name buffer-file-name))
5592 'org-agenda-diary-link t
5593 'org-marker (org-agenda-new-marker (point-at-bol))))
5595 (defun org-diary-default-entry ()
5596 "Add a dummy entry to the diary.
5597 Needed to avoid empty dates which mess up holiday display."
5598 ;; Catch the error if dealing with the new add-to-diary-alist
5599 (when org-disable-agenda-to-diary
5600 (condition-case nil
5601 (add-to-diary-list original-date "Org-mode dummy" "")
5602 (error
5603 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5605 (defun org-cycle-agenda-files ()
5606 "Cycle through the files in `org-agenda-files'.
5607 If the current buffer visits an agenda file, find the next one in the list.
5608 If the current buffer does not, find the first agenda file."
5609 (interactive)
5610 (let* ((fs (org-agenda-files t))
5611 (files (append fs (list (car fs))))
5612 (tcf (if buffer-file-name (file-truename buffer-file-name)))
5613 file)
5614 (unless files (error "No agenda files"))
5615 (catch 'exit
5616 (while (setq file (pop files))
5617 (if (equal (file-truename file) tcf)
5618 (when (car files)
5619 (find-file (car files))
5620 (throw 'exit t))))
5621 (find-file (car fs)))))
5623 (defun org-agenda-file-to-end ()
5624 "Move/add the current file to the end of the agenda file list.
5625 If the file is not present in the list, it is appended to the list. If it is
5626 present, it is moved there."
5627 (interactive)
5628 (org-agenda-file-to-front 'to-end))
5630 (defun org-agenda-file-to-front (&optional to-end)
5631 "Move/add the current file to the top of the agenda file list.
5632 If the file is not present in the list, it is added to the front. If it is
5633 present, it is moved there. With optional argument TO-END, add/move to the
5634 end of the list."
5635 (interactive "P")
5636 (let ((file-alist (mapcar (lambda (x)
5637 (cons (file-truename x) x))
5638 (org-agenda-files t)))
5639 (ctf (file-truename buffer-file-name))
5640 x had)
5641 (setq x (assoc ctf file-alist) had x)
5643 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
5644 (if to-end
5645 (setq file-alist (append (delq x file-alist) (list x)))
5646 (setq file-alist (cons x (delq x file-alist))))
5647 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
5648 (org-install-agenda-files-menu)
5649 (message "File %s to %s of agenda file list"
5650 (if had "moved" "added") (if to-end "end" "front"))))
5652 (defun org-remove-file (&optional file)
5653 "Remove current file from the list of files in variable `org-agenda-files'.
5654 These are the files which are being checked for agenda entries.
5655 Optional argument FILE means, use this file instead of the current."
5656 (interactive)
5657 (let* ((file (or file buffer-file-name))
5658 (true-file (file-truename file))
5659 (afile (abbreviate-file-name file))
5660 (files (delq nil (mapcar
5661 (lambda (x)
5662 (if (equal true-file
5663 (file-truename x))
5664 nil x))
5665 (org-agenda-files t)))))
5666 (if (not (= (length files) (length (org-agenda-files t))))
5667 (progn
5668 (org-store-new-agenda-file-list files)
5669 (org-install-agenda-files-menu)
5670 (message "Removed file: %s" afile))
5671 (message "File was not in list: %s" afile))))
5673 (defun org-file-menu-entry (file)
5674 (vector file (list 'find-file file) t))
5676 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5677 "Return a list of all relevant day numbers from BEG to END buffer positions.
5678 If NO-RANGES is non-nil, include only the start and end dates of a range,
5679 not every single day in the range. If FORCE-TODAY is non-nil, make
5680 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5681 inactive time stamps (those in square brackets) are included."
5682 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5683 dates date day day1 day2 ts1 ts2)
5684 (if force-today
5685 (setq dates (list (time-to-days (current-time)))))
5686 (save-excursion
5687 (goto-char beg)
5688 (while (re-search-forward re end t)
5689 (setq day (time-to-days (org-time-string-to-time
5690 (substring (match-string 1) 0 10))))
5691 (or (memq day dates) (push day dates)))
5692 (unless no-ranges
5693 (goto-char beg)
5694 (while (re-search-forward org-tr-regexp end t)
5695 (setq ts1 (substring (match-string 1) 0 10)
5696 ts2 (substring (match-string 2) 0 10)
5697 day1 (time-to-days (org-time-string-to-time ts1))
5698 day2 (time-to-days (org-time-string-to-time ts2)))
5699 (while (< (setq day1 (1+ day1)) day2)
5700 (or (memq day1 dates) (push day1 dates)))))
5701 (sort dates '<))))
5703 ;;;###autoload
5704 (defun org-diary (&rest args)
5705 "Return diary information from org-files.
5706 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5707 It accesses org files and extracts information from those files to be
5708 listed in the diary. The function accepts arguments specifying what
5709 items should be listed. The following arguments are allowed:
5711 :timestamp List the headlines of items containing a date stamp or
5712 date range matching the selected date. Deadlines will
5713 also be listed, on the expiration day.
5715 :deadline List any deadlines past due, or due within
5716 `org-deadline-warning-days'. The listing occurs only
5717 in the diary for *today*, not at any other date. If
5718 an entry is marked DONE, it is no longer listed.
5720 :scheduled List all items which are scheduled for the given date.
5721 The diary for *today* also contains items which were
5722 scheduled earlier and are not yet marked DONE.
5724 :todo List all TODO items from the org-file. This may be a
5725 long list - so this is not turned on by default.
5726 Like deadlines, these entries only show up in the
5727 diary for *today*, not at any other date.
5729 The call in the diary file should look like this:
5731 &%%(org-diary) ~/path/to/some/orgfile.org
5733 Use a separate line for each org file to check. Or, if you omit the file name,
5734 all files listed in `org-agenda-files' will be checked automatically:
5736 &%%(org-diary)
5738 If you don't give any arguments (as in the example above), the default
5739 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5740 also be written as
5742 &%%(org-diary :deadline :timestamp :scheduled)
5744 The function expects the lisp variables `entry' and `date' to be provided
5745 by the caller, because this is how the calendar works. Don't use this
5746 function from a program - use `org-agenda-get-day-entries' instead."
5747 (org-agenda-maybe-reset-markers)
5748 (org-compile-prefix-format org-agenda-prefix-format)
5749 (setq args (or args '(:deadline :scheduled :timestamp)))
5750 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5751 (list entry)
5752 (org-agenda-files t)))
5753 file rtn results)
5754 ;; If this is called during org-agenda, don't return any entries to
5755 ;; the calendar. Org Agenda will list these entries itself.
5756 (if org-disable-agenda-to-diary (setq files nil))
5757 (while (setq file (pop files))
5758 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5759 (setq results (append results rtn)))
5760 (if results
5761 (concat (org-finalize-agenda-entries results) "\n"))))
5762 (defvar org-category-table nil)
5763 (defun org-get-category-table ()
5764 "Get the table of categories and positions in current buffer."
5765 (let (tbl)
5766 (save-excursion
5767 (goto-char (point-min))
5768 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5769 (push (cons (point) (org-trim (match-string 2))) tbl)))
5770 tbl))
5771 (defun org-get-category (&optional pos)
5772 "Get the category applying to position POS."
5773 (if (not org-category-table)
5774 (cond
5775 ((null org-category)
5776 (setq org-category
5777 (if buffer-file-name
5778 (file-name-sans-extension
5779 (file-name-nondirectory buffer-file-name))
5780 "???")))
5781 ((symbolp org-category) (symbol-name org-category))
5782 (t org-category))
5783 (let ((tbl org-category-table)
5784 (pos (or pos (point))))
5785 (while (and tbl (> (caar tbl) pos))
5786 (pop tbl))
5787 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5788 org-category-table))))))
5790 (defun org-agenda-get-day-entries (file date &rest args)
5791 "Does the work for `org-diary' and `org-agenda'.
5792 FILE is the path to a file to be checked for entries. DATE is date like
5793 the one returned by `calendar-current-date'. ARGS are symbols indicating
5794 which kind of entries should be extracted. For details about these, see
5795 the documentation of `org-diary'."
5796 (setq args (or args '(:deadline :scheduled :timestamp)))
5797 (let* ((org-startup-with-deadline-check nil)
5798 (org-startup-folded nil)
5799 (org-startup-align-all-tables nil)
5800 (buffer (if (file-exists-p file)
5801 (org-get-agenda-file-buffer file)
5802 (error "No such file %s" file)))
5803 arg results rtn)
5804 (if (not buffer)
5805 ;; If file does not exist, make sure an error message ends up in diary
5806 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5807 (with-current-buffer buffer
5808 (unless (eq major-mode 'org-mode)
5809 (error "Agenda file %s is not in `org-mode'" file))
5810 (setq org-category-table (org-get-category-table))
5811 (let ((case-fold-search nil))
5812 (save-excursion
5813 (save-restriction
5814 (if org-respect-restriction
5815 (if (org-region-active-p)
5816 ;; Respect a region to restrict search
5817 (narrow-to-region (region-beginning) (region-end)))
5818 ;; If we work for the calendar or many files,
5819 ;; get rid of any restriction
5820 (widen))
5821 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5822 (while (setq arg (pop args))
5823 (cond
5824 ((and (eq arg :todo)
5825 (equal date (calendar-current-date)))
5826 (setq rtn (org-agenda-get-todos))
5827 (setq results (append results rtn)))
5828 ((eq arg :timestamp)
5829 (setq rtn (org-agenda-get-blocks))
5830 (setq results (append results rtn))
5831 (setq rtn (org-agenda-get-timestamps))
5832 (setq results (append results rtn)))
5833 ((eq arg :scheduled)
5834 (setq rtn (org-agenda-get-scheduled))
5835 (setq results (append results rtn)))
5836 ((eq arg :closed)
5837 (setq rtn (org-agenda-get-closed))
5838 (setq results (append results rtn)))
5839 ((and (eq arg :deadline)
5840 (equal date (calendar-current-date)))
5841 (setq rtn (org-agenda-get-deadlines))
5842 (setq results (append results rtn))))))))
5843 results))))
5845 (defun org-entry-is-done-p ()
5846 "Is the current entry marked DONE?"
5847 (save-excursion
5848 (and (re-search-backward "[\r\n]\\*" nil t)
5849 (looking-at org-nl-done-regexp))))
5851 (defun org-at-date-range-p ()
5852 "Is the cursor inside a date range?"
5853 (interactive)
5854 (save-excursion
5855 (catch 'exit
5856 (let ((pos (point)))
5857 (skip-chars-backward "^<\r\n")
5858 (skip-chars-backward "<")
5859 (and (looking-at org-tr-regexp)
5860 (>= (match-end 0) pos)
5861 (throw 'exit t))
5862 (skip-chars-backward "^<\r\n")
5863 (skip-chars-backward "<")
5864 (and (looking-at org-tr-regexp)
5865 (>= (match-end 0) pos)
5866 (throw 'exit t)))
5867 nil)))
5869 (defun org-agenda-get-todos ()
5870 "Return the TODO information for agenda display."
5871 (let* ((props (list 'face nil
5872 'done-face 'org-done
5873 'mouse-face 'highlight
5874 'keymap org-agenda-keymap
5875 'help-echo
5876 (format "mouse-2 or RET jump to org file %s"
5877 (abbreviate-file-name buffer-file-name))))
5878 (regexp (concat "[\n\r]\\*+ *\\("
5879 (if org-select-this-todo-keyword
5880 (concat "\\<\\(" org-select-this-todo-keyword
5881 "\\)\\>")
5882 org-not-done-regexp)
5883 "[^\n\r]*\\)"))
5884 marker priority category tags
5885 ee txt)
5886 (goto-char (point-min))
5887 (while (re-search-forward regexp nil t)
5888 (goto-char (match-beginning 1))
5889 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5890 category (org-get-category)
5891 tags (org-get-tags-at (point))
5892 txt (org-format-agenda-item "" (match-string 1) category tags)
5893 priority
5894 (+ (org-get-priority txt)
5895 (if org-todo-kwd-priority-p
5896 (- org-todo-kwd-max-priority -2
5897 (length
5898 (member (match-string 2) org-todo-keywords)))
5899 1)))
5900 (org-add-props txt props
5901 'org-marker marker 'org-hd-marker marker
5902 'priority priority 'category category)
5903 (push txt ee)
5904 (goto-char (match-end 1)))
5905 (nreverse ee)))
5907 (defconst org-agenda-no-heading-message
5908 "No heading for this item in buffer or region.")
5910 (defun org-agenda-get-timestamps ()
5911 "Return the date stamp information for agenda display."
5912 (let* ((props (list 'face nil
5913 'mouse-face 'highlight
5914 'keymap org-agenda-keymap
5915 'help-echo
5916 (format "mouse-2 or RET jump to org file %s"
5917 (abbreviate-file-name buffer-file-name))))
5918 (regexp (regexp-quote
5919 (substring
5920 (format-time-string
5921 (car org-time-stamp-formats)
5922 (apply 'encode-time ; DATE bound by calendar
5923 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5924 0 11)))
5925 marker hdmarker deadlinep scheduledp donep tmp priority category
5926 ee txt timestr tags)
5927 (goto-char (point-min))
5928 (while (re-search-forward regexp nil t)
5929 (if (not (save-match-data (org-at-date-range-p)))
5930 (progn
5931 (setq marker (org-agenda-new-marker (match-beginning 0))
5932 category (org-get-category (match-beginning 0))
5933 tmp (buffer-substring (max (point-min)
5934 (- (match-beginning 0)
5935 org-ds-keyword-length))
5936 (match-beginning 0))
5937 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5938 deadlinep (string-match org-deadline-regexp tmp)
5939 scheduledp (string-match org-scheduled-regexp tmp)
5940 donep (org-entry-is-done-p))
5941 (if (string-match ">" timestr)
5942 ;; substring should only run to end of time stamp
5943 (setq timestr (substring timestr 0 (match-end 0))))
5944 (save-excursion
5945 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5946 (progn
5947 (goto-char (match-end 1))
5948 (setq hdmarker (org-agenda-new-marker)
5949 tags (org-get-tags-at))
5950 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5951 (setq txt (org-format-agenda-item
5952 (format "%s%s"
5953 (if deadlinep "Deadline: " "")
5954 (if scheduledp "Scheduled: " ""))
5955 (match-string 1) category tags timestr)))
5956 (setq txt org-agenda-no-heading-message))
5957 (setq priority (org-get-priority txt))
5958 (org-add-props txt props
5959 'org-marker marker 'org-hd-marker hdmarker)
5960 (if deadlinep
5961 (org-add-props txt nil
5962 'face (if donep 'org-done 'org-warning)
5963 'undone-face 'org-warning 'done-face 'org-done
5964 'category category 'priority (+ 100 priority))
5965 (if scheduledp
5966 (org-add-props txt nil
5967 'face 'org-scheduled-today
5968 'undone-face 'org-scheduled-today 'done-face 'org-done
5969 'category category priority (+ 99 priority))
5970 (org-add-props txt nil 'priority priority 'category category)))
5971 (push txt ee))
5972 (outline-next-heading))))
5973 (nreverse ee)))
5975 (defun org-agenda-get-closed ()
5976 "Return the logged TODO entries for agenda display."
5977 (let* ((props (list 'mouse-face 'highlight
5978 'keymap org-agenda-keymap
5979 'help-echo
5980 (format "mouse-2 or RET jump to org file %s"
5981 (abbreviate-file-name buffer-file-name))))
5982 (regexp (concat
5983 "\\<" org-closed-string " *\\["
5984 (regexp-quote
5985 (substring
5986 (format-time-string
5987 (car org-time-stamp-formats)
5988 (apply 'encode-time ; DATE bound by calendar
5989 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5990 1 11))))
5991 marker hdmarker priority category tags
5992 ee txt timestr)
5993 (goto-char (point-min))
5994 (while (re-search-forward regexp nil t)
5995 (if (not (save-match-data (org-at-date-range-p)))
5996 (progn
5997 (setq marker (org-agenda-new-marker (match-beginning 0))
5998 category (org-get-category (match-beginning 0))
5999 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6000 ;; donep (org-entry-is-done-p)
6002 (if (string-match "\\]" timestr)
6003 ;; substring should only run to end of time stamp
6004 (setq timestr (substring timestr 0 (match-end 0))))
6005 (save-excursion
6006 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6007 (progn
6008 (goto-char (match-end 1))
6009 (setq hdmarker (org-agenda-new-marker)
6010 tags (org-get-tags-at))
6011 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6012 (setq txt (org-format-agenda-item
6013 "Closed: "
6014 (match-string 1) category tags timestr)))
6015 (setq txt org-agenda-no-heading-message))
6016 (setq priority 100000)
6017 (org-add-props txt props
6018 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
6019 'priority priority 'category category
6020 'undone-face 'org-warning 'done-face 'org-done)
6021 (push txt ee))
6022 (outline-next-heading))))
6023 (nreverse ee)))
6025 (defun org-agenda-get-deadlines ()
6026 "Return the deadline information for agenda display."
6027 (let* ((wdays org-deadline-warning-days)
6028 (props (list 'mouse-face 'highlight
6029 'keymap org-agenda-keymap
6030 'help-echo
6031 (format "mouse-2 or RET jump to org file %s"
6032 (abbreviate-file-name buffer-file-name))))
6033 (regexp org-deadline-time-regexp)
6034 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6035 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6036 d2 diff pos pos1 category tags
6037 ee txt head)
6038 (goto-char (point-min))
6039 (while (re-search-forward regexp nil t)
6040 (setq pos (1- (match-beginning 1))
6041 d2 (time-to-days
6042 (org-time-string-to-time (match-string 1)))
6043 diff (- d2 d1))
6044 ;; When to show a deadline in the calendar:
6045 ;; If the expiration is within wdays warning time.
6046 ;; Past-due deadlines are only shown on the current date
6047 (if (and (< diff wdays) todayp (not (= diff 0)))
6048 (save-excursion
6049 (setq category (org-get-category))
6050 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6051 (progn
6052 (goto-char (match-end 0))
6053 (setq pos1 (match-end 1))
6054 (setq tags (org-get-tags-at pos1))
6055 (setq head (buffer-substring-no-properties
6056 (point)
6057 (progn (skip-chars-forward "^\r\n")
6058 (point))))
6059 (if (string-match org-looking-at-done-regexp head)
6060 (setq txt nil)
6061 (setq txt (org-format-agenda-item
6062 (format "In %3d d.: " diff) head category tags))))
6063 (setq txt org-agenda-no-heading-message))
6064 (when txt
6065 (org-add-props txt props
6066 'org-marker (org-agenda-new-marker pos)
6067 'org-hd-marker (org-agenda-new-marker pos1)
6068 'priority (+ (- 10 diff) (org-get-priority txt))
6069 'category category
6070 'face (cond ((<= diff 0) 'org-warning)
6071 ((<= diff 5) 'org-scheduled-previously)
6072 (t nil))
6073 'undone-face (cond
6074 ((<= diff 0) 'org-warning)
6075 ((<= diff 5) 'org-scheduled-previously)
6076 (t nil))
6077 'done-face 'org-done)
6078 (push txt ee)))))
6079 ee))
6081 (defun org-agenda-get-scheduled ()
6082 "Return the scheduled information for agenda display."
6083 (let* ((props (list 'face 'org-scheduled-previously
6084 'undone-face 'org-scheduled-previously
6085 'done-face 'org-done
6086 'mouse-face 'highlight
6087 'keymap org-agenda-keymap
6088 'help-echo
6089 (format "mouse-2 or RET jump to org file %s"
6090 (abbreviate-file-name buffer-file-name))))
6091 (regexp org-scheduled-time-regexp)
6092 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6093 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6094 d2 diff pos pos1 category tags
6095 ee txt head)
6096 (goto-char (point-min))
6097 (while (re-search-forward regexp nil t)
6098 (setq pos (1- (match-beginning 1))
6099 d2 (time-to-days
6100 (org-time-string-to-time (match-string 1)))
6101 diff (- d2 d1))
6102 ;; When to show a scheduled item in the calendar:
6103 ;; If it is on or past the date.
6104 (if (and (< diff 0) todayp)
6105 (save-excursion
6106 (setq category (org-get-category))
6107 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6108 (progn
6109 (goto-char (match-end 0))
6110 (setq pos1 (match-end 1))
6111 (setq tags (org-get-tags-at))
6112 (setq head (buffer-substring-no-properties
6113 (point)
6114 (progn (skip-chars-forward "^\r\n") (point))))
6115 (if (string-match org-looking-at-done-regexp head)
6116 (setq txt nil)
6117 (setq txt (org-format-agenda-item
6118 (format "Sched.%2dx: " (- 1 diff)) head
6119 category tags))))
6120 (setq txt org-agenda-no-heading-message))
6121 (when txt
6122 (org-add-props txt props
6123 'org-marker (org-agenda-new-marker pos)
6124 'org-hd-marker (org-agenda-new-marker pos1)
6125 'priority (+ (- 5 diff) (org-get-priority txt))
6126 'category category)
6127 (push txt ee)))))
6128 ee))
6130 (defun org-agenda-get-blocks ()
6131 "Return the date-range information for agenda display."
6132 (let* ((props (list 'face nil
6133 'mouse-face 'highlight
6134 'keymap org-agenda-keymap
6135 'help-echo
6136 (format "mouse-2 or RET jump to org file %s"
6137 (abbreviate-file-name buffer-file-name))))
6138 (regexp org-tr-regexp)
6139 (d0 (calendar-absolute-from-gregorian date))
6140 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
6141 (goto-char (point-min))
6142 (while (re-search-forward regexp nil t)
6143 (setq timestr (match-string 0)
6144 s1 (match-string 1)
6145 s2 (match-string 2)
6146 d1 (time-to-days (org-time-string-to-time s1))
6147 d2 (time-to-days (org-time-string-to-time s2)))
6148 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
6149 ;; Only allow days between the limits, because the normal
6150 ;; date stamps will catch the limits.
6151 (save-excursion
6152 (setq marker (org-agenda-new-marker (point)))
6153 (setq category (org-get-category))
6154 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6155 (progn
6156 (setq hdmarker (org-agenda-new-marker (match-end 1)))
6157 (goto-char (match-end 1))
6158 (setq tags (org-get-tags-at))
6159 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6160 (setq txt (org-format-agenda-item
6161 (format (if (= d1 d2) "" "(%d/%d): ")
6162 (1+ (- d0 d1)) (1+ (- d2 d1)))
6163 (match-string 1) category tags
6164 (if (= d0 d1) timestr))))
6165 (setq txt org-agenda-no-heading-message))
6166 (org-add-props txt props
6167 'org-marker marker 'org-hd-marker hdmarker
6168 'priority (org-get-priority txt) 'category category)
6169 (push txt ee)))
6170 (outline-next-heading))
6171 ;; Sort the entries by expiration date.
6172 (nreverse ee)))
6174 (defconst org-plain-time-of-day-regexp
6175 (concat
6176 "\\(\\<[012]?[0-9]"
6177 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6178 "\\(--?"
6179 "\\(\\<[012]?[0-9]"
6180 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6181 "\\)?")
6182 "Regular expression to match a plain time or time range.
6183 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
6184 groups carry important information:
6185 0 the full match
6186 1 the first time, range or not
6187 8 the second time, if it is a range.")
6189 (defconst org-stamp-time-of-day-regexp
6190 (concat
6191 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
6192 "\\([012][0-9]:[0-5][0-9]\\)>"
6193 "\\(--?"
6194 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
6195 "Regular expression to match a timestamp time or time range.
6196 After a match, the following groups carry important information:
6197 0 the full match
6198 1 date plus weekday, for backreferencing to make sure both times on same day
6199 2 the first time, range or not
6200 4 the second time, if it is a range.")
6202 (defvar org-prefix-has-time nil
6203 "A flag, set by `org-compile-prefix-format'.
6204 The flag is set if the currently compiled format contains a `%t'.")
6205 (defvar org-prefix-has-tag nil
6206 "A flag, set by `org-compile-prefix-format'.
6207 The flag is set if the currently compiled format contains a `%T'.")
6209 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
6210 "Format TXT to be inserted into the agenda buffer.
6211 In particular, it adds the prefix and corresponding text properties. EXTRA
6212 must be a string and replaces the `%s' specifier in the prefix format.
6213 CATEGORY (string, symbol or nil) may be used to overrule the default
6214 category taken from local variable or file name. It will replace the `%c'
6215 specifier in the format. DOTIME, when non-nil, indicates that a
6216 time-of-day should be extracted from TXT for sorting of this entry, and for
6217 the `%t' specifier in the format. When DOTIME is a string, this string is
6218 searched for a time before TXT is. NOPREFIX is a flag and indicates that
6219 only the correctly processes TXT should be returned - this is used by
6220 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
6221 (save-match-data
6222 ;; Diary entries sometimes have extra whitespace at the beginning
6223 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
6224 (let* ((category (or category
6225 org-category
6226 (if buffer-file-name
6227 (file-name-sans-extension
6228 (file-name-nondirectory buffer-file-name))
6229 "")))
6230 (tag (or (nth (1- (or (length tags) 0)) tags) ""))
6231 time ;; needed for the eval of the prefix format
6232 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
6233 (time-of-day (and dotime (org-get-time-of-day ts)))
6234 stamp plain s0 s1 s2 rtn)
6235 (when (and dotime time-of-day org-prefix-has-time)
6236 ;; Extract starting and ending time and move them to prefix
6237 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
6238 (setq plain (string-match org-plain-time-of-day-regexp ts)))
6239 (setq s0 (match-string 0 ts)
6240 s1 (match-string (if plain 1 2) ts)
6241 s2 (match-string (if plain 8 4) ts))
6243 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
6244 ;; them, we might want to remove them there to avoid duplication.
6245 ;; The user can turn this off with a variable.
6246 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
6247 (string-match (concat (regexp-quote s0) " *") txt)
6248 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
6249 (= (match-beginning 0) 0)
6251 (setq txt (replace-match "" nil nil txt))))
6252 ;; Normalize the time(s) to 24 hour
6253 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
6254 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
6256 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
6257 (and org-agenda-remove-tags-when-in-prefix
6258 org-prefix-has-tag))
6259 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
6260 (setq txt (replace-match "" t t txt)))
6262 ;; Create the final string
6263 (if noprefix
6264 (setq rtn txt)
6265 ;; Prepare the variables needed in the eval of the compiled format
6266 (setq time (cond (s2 (concat s1 "-" s2))
6267 (s1 (concat s1 "......"))
6268 (t ""))
6269 extra (or extra "")
6270 category (if (symbolp category) (symbol-name category) category))
6271 ;; Evaluate the compiled format
6272 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
6274 ;; And finally add the text properties
6275 (org-add-props rtn nil
6276 'category (downcase category) 'tags tags
6277 'prefix-length (- (length rtn) (length txt))
6278 'time-of-day time-of-day
6279 'dotime dotime))))
6281 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
6282 (catch 'exit
6283 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
6284 ((and todayp (member 'today (car org-agenda-time-grid))))
6285 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
6286 ((member 'weekly (car org-agenda-time-grid)))
6287 (t (throw 'exit list)))
6288 (let* ((have (delq nil (mapcar
6289 (lambda (x) (get-text-property 1 'time-of-day x))
6290 list)))
6291 (string (nth 1 org-agenda-time-grid))
6292 (gridtimes (nth 2 org-agenda-time-grid))
6293 (req (car org-agenda-time-grid))
6294 (remove (member 'remove-match req))
6295 new time)
6296 (if (and (member 'require-timed req) (not have))
6297 ;; don't show empty grid
6298 (throw 'exit list))
6299 (while (setq time (pop gridtimes))
6300 (unless (and remove (member time have))
6301 (setq time (int-to-string time))
6302 (push (org-format-agenda-item
6303 nil string "" nil
6304 (concat (substring time 0 -2) ":" (substring time -2)))
6305 new)
6306 (put-text-property
6307 1 (length (car new)) 'face 'org-time-grid (car new))))
6308 (if (member 'time-up org-agenda-sorting-strategy)
6309 (append new list)
6310 (append list new)))))
6312 (defun org-compile-prefix-format (format)
6313 "Compile the prefix format into a Lisp form that can be evaluated.
6314 The resulting form is returned and stored in the variable
6315 `org-prefix-format-compiled'."
6316 (setq org-prefix-has-time nil org-prefix-has-tag nil)
6317 (let ((start 0) varform vars var (s format)e c f opt)
6318 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
6319 s start)
6320 (setq var (cdr (assoc (match-string 4 s)
6321 '(("c" . category) ("t" . time) ("s" . extra)
6322 ("T" . tag))))
6323 c (or (match-string 3 s) "")
6324 opt (match-beginning 1)
6325 start (1+ (match-beginning 0)))
6326 (if (equal var 'time) (setq org-prefix-has-time t))
6327 (if (equal var 'tag) (setq org-prefix-has-tag t))
6328 (setq f (concat "%" (match-string 2 s) "s"))
6329 (if opt
6330 (setq varform
6331 `(if (equal "" ,var)
6333 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
6334 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
6335 (setq s (replace-match "%s" t nil s))
6336 (push varform vars))
6337 (setq vars (nreverse vars))
6338 (setq org-prefix-format-compiled `(format ,s ,@vars))))
6340 (defun org-get-time-of-day (s &optional string)
6341 "Check string S for a time of day.
6342 If found, return it as a military time number between 0 and 2400.
6343 If not found, return nil.
6344 The optional STRING argument forces conversion into a 5 character wide string
6345 HH:MM."
6346 (save-match-data
6347 (when
6349 (string-match
6350 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
6351 (string-match
6352 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
6353 (let* ((t0 (+ (* 100
6354 (+ (string-to-number (match-string 1 s))
6355 (if (and (match-beginning 4)
6356 (equal (downcase (match-string 4 s)) "pm"))
6357 12 0)))
6358 (if (match-beginning 3)
6359 (string-to-number (match-string 3 s))
6360 0)))
6361 (t1 (concat " "
6362 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6363 (int-to-string t0))))
6364 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6366 (defun org-finalize-agenda-entries (list)
6367 "Sort and concatenate the agenda items."
6368 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6370 (defsubst org-cmp-priority (a b)
6371 "Compare the priorities of string A and B."
6372 (let ((pa (or (get-text-property 1 'priority a) 0))
6373 (pb (or (get-text-property 1 'priority b) 0)))
6374 (cond ((> pa pb) +1)
6375 ((< pa pb) -1)
6376 (t nil))))
6378 (defsubst org-cmp-category (a b)
6379 "Compare the string values of categories of strings A and B."
6380 (let ((ca (or (get-text-property 1 'category a) ""))
6381 (cb (or (get-text-property 1 'category b) "")))
6382 (cond ((string-lessp ca cb) -1)
6383 ((string-lessp cb ca) +1)
6384 (t nil))))
6386 (defsubst org-cmp-time (a b)
6387 "Compare the time-of-day values of strings A and B."
6388 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6389 (ta (or (get-text-property 1 'time-of-day a) def))
6390 (tb (or (get-text-property 1 'time-of-day b) def)))
6391 (cond ((< ta tb) -1)
6392 ((< tb ta) +1)
6393 (t nil))))
6395 (defun org-entries-lessp (a b)
6396 "Predicate for sorting agenda entries."
6397 ;; The following variables will be used when the form is evaluated.
6398 (let* ((time-up (org-cmp-time a b))
6399 (time-down (if time-up (- time-up) nil))
6400 (priority-up (org-cmp-priority a b))
6401 (priority-down (if priority-up (- priority-up) nil))
6402 (category-up (org-cmp-category a b))
6403 (category-down (if category-up (- category-up) nil))
6404 (category-keep (if category-up +1 nil)))
6405 (cdr (assoc
6406 (eval (cons 'or org-agenda-sorting-strategy))
6407 '((-1 . t) (1 . nil) (nil . nil))))))
6409 (defun org-agenda-show-priority ()
6410 "Show the priority of the current item.
6411 This priority is composed of the main priority given with the [#A] cookies,
6412 and by additional input from the age of a schedules or deadline entry."
6413 (interactive)
6414 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6415 (message "Priority is %d" (if pri pri -1000))))
6417 (defun org-agenda-show-tags ()
6418 "Show the tags applicable to the current item."
6419 (interactive)
6420 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6421 (if tags
6422 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6423 (message "No tags associated with this line"))))
6425 (defun org-agenda-goto (&optional highlight)
6426 "Go to the Org-mode file which contains the item at point."
6427 (interactive)
6428 (let* ((marker (or (get-text-property (point) 'org-marker)
6429 (org-agenda-error)))
6430 (buffer (marker-buffer marker))
6431 (pos (marker-position marker)))
6432 (switch-to-buffer-other-window buffer)
6433 (widen)
6434 (goto-char pos)
6435 (when (eq major-mode 'org-mode)
6436 (org-show-hidden-entry)
6437 (save-excursion
6438 (and (outline-next-heading)
6439 (org-flag-heading nil)))) ; show the next heading
6440 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6442 (defun org-agenda-switch-to ()
6443 "Go to the Org-mode file which contains the item at point."
6444 (interactive)
6445 (let* ((marker (or (get-text-property (point) 'org-marker)
6446 (org-agenda-error)))
6447 (buffer (marker-buffer marker))
6448 (pos (marker-position marker)))
6449 (switch-to-buffer buffer)
6450 (delete-other-windows)
6451 (widen)
6452 (goto-char pos)
6453 (when (eq major-mode 'org-mode)
6454 (org-show-hidden-entry)
6455 (save-excursion
6456 (and (outline-next-heading)
6457 (org-flag-heading nil)))))) ; show the next heading
6459 (defun org-agenda-goto-mouse (ev)
6460 "Go to the Org-mode file which contains the item at the mouse click."
6461 (interactive "e")
6462 (mouse-set-point ev)
6463 (org-agenda-goto))
6465 (defun org-agenda-show ()
6466 "Display the Org-mode file which contains the item at point."
6467 (interactive)
6468 (let ((win (selected-window)))
6469 (org-agenda-goto t)
6470 (select-window win)))
6472 (defun org-agenda-recenter (arg)
6473 "Display the Org-mode file which contains the item at point and recenter."
6474 (interactive "P")
6475 (let ((win (selected-window)))
6476 (org-agenda-goto t)
6477 (recenter arg)
6478 (select-window win)))
6480 (defun org-agenda-show-mouse (ev)
6481 "Display the Org-mode file which contains the item at the mouse click."
6482 (interactive "e")
6483 (mouse-set-point ev)
6484 (org-agenda-show))
6486 (defun org-agenda-check-no-diary ()
6487 "Check if the entry is a diary link and abort if yes."
6488 (if (get-text-property (point) 'org-agenda-diary-link)
6489 (org-agenda-error)))
6491 (defun org-agenda-error ()
6492 (error "Command not allowed in this line"))
6494 (defvar org-last-heading-marker (make-marker)
6495 "Marker pointing to the headline that last changed its TODO state
6496 by a remote command from the agenda.")
6498 (defun org-agenda-todo (&optional arg)
6499 "Cycle TODO state of line at point, also in Org-mode file.
6500 This changes the line at point, all other lines in the agenda referring to
6501 the same tree node, and the headline of the tree node in the Org-mode file."
6502 (interactive "P")
6503 (org-agenda-check-no-diary)
6504 (let* ((col (current-column))
6505 (marker (or (get-text-property (point) 'org-marker)
6506 (org-agenda-error)))
6507 (buffer (marker-buffer marker))
6508 (pos (marker-position marker))
6509 (hdmarker (get-text-property (point) 'org-hd-marker))
6510 (buffer-read-only nil)
6511 newhead)
6512 (with-current-buffer buffer
6513 (widen)
6514 (goto-char pos)
6515 (org-show-hidden-entry)
6516 (save-excursion
6517 (and (outline-next-heading)
6518 (org-flag-heading nil))) ; show the next heading
6519 (org-todo arg)
6520 (forward-char 1)
6521 (setq newhead (org-get-heading))
6522 (save-excursion
6523 (org-back-to-heading)
6524 (move-marker org-last-heading-marker (point))))
6525 (beginning-of-line 1)
6526 (save-excursion
6527 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6528 (move-to-column col)))
6530 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6531 "Change all lines in the agenda buffer which match HDMARKER.
6532 The new content of the line will be NEWHEAD (as modified by
6533 `org-format-agenda-item'). HDMARKER is checked with
6534 `equal' against all `org-hd-marker' text properties in the file.
6535 If FIXFACE is non-nil, the face of each item is modified acording to
6536 the new TODO state."
6537 (let* (props m pl undone-face done-face finish new dotime cat tags)
6538 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6539 (save-excursion
6540 (goto-char (point-max))
6541 (beginning-of-line 1)
6542 (while (not finish)
6543 (setq finish (bobp))
6544 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6545 (equal m hdmarker))
6546 (setq props (text-properties-at (point))
6547 dotime (get-text-property (point) 'dotime)
6548 cat (get-text-property (point) 'category)
6549 tags (get-text-property (point) 'tags)
6550 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6551 pl (get-text-property (point) 'prefix-length)
6552 undone-face (get-text-property (point) 'undone-face)
6553 done-face (get-text-property (point) 'done-face))
6554 (move-to-column pl)
6555 (if (looking-at ".*")
6556 (progn
6557 (replace-match new t t)
6558 (beginning-of-line 1)
6559 (add-text-properties (point-at-bol) (point-at-eol) props)
6560 (if fixface
6561 (add-text-properties
6562 (point-at-bol) (point-at-eol)
6563 (list 'face
6564 (if org-last-todo-state-is-todo
6565 undone-face done-face))))
6566 (beginning-of-line 1))
6567 (error "Line update did not work")))
6568 (beginning-of-line 0)))))
6570 (defun org-agenda-priority-up ()
6571 "Increase the priority of line at point, also in Org-mode file."
6572 (interactive)
6573 (org-agenda-priority 'up))
6575 (defun org-agenda-priority-down ()
6576 "Decrease the priority of line at point, also in Org-mode file."
6577 (interactive)
6578 (org-agenda-priority 'down))
6580 (defun org-agenda-priority (&optional force-direction)
6581 "Set the priority of line at point, also in Org-mode file.
6582 This changes the line at point, all other lines in the agenda referring to
6583 the same tree node, and the headline of the tree node in the Org-mode file."
6584 (interactive)
6585 (org-agenda-check-no-diary)
6586 (let* ((marker (or (get-text-property (point) 'org-marker)
6587 (org-agenda-error)))
6588 (buffer (marker-buffer marker))
6589 (pos (marker-position marker))
6590 (hdmarker (get-text-property (point) 'org-hd-marker))
6591 (buffer-read-only nil)
6592 newhead)
6593 (with-current-buffer buffer
6594 (widen)
6595 (goto-char pos)
6596 (org-show-hidden-entry)
6597 (save-excursion
6598 (and (outline-next-heading)
6599 (org-flag-heading nil))) ; show the next heading
6600 (funcall 'org-priority force-direction)
6601 (end-of-line 1)
6602 (setq newhead (org-get-heading)))
6603 (org-agenda-change-all-lines newhead hdmarker)
6604 (beginning-of-line 1)))
6606 (defun org-get-tags-at (&optional pos)
6607 "Get a list of all headline targs applicable at POS.
6608 POS defaults to point. If tags are inherited, the list contains
6609 the targets in the same sequence as the headlines appear, i.e.
6610 the tags of the current headline come last."
6611 (interactive)
6612 (let (tags)
6613 (save-excursion
6614 (goto-char (or pos (point)))
6615 (save-match-data
6616 (org-back-to-heading t)
6617 (condition-case nil
6618 (while t
6619 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6620 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6621 (or org-use-tag-inheritance (error ""))
6622 (org-up-heading-all 1))
6623 (error nil))))
6624 (message "%s" tags)
6625 tags))
6627 (defun org-agenda-set-tags ()
6628 "Set tags for the current headline."
6629 (interactive)
6630 (org-agenda-check-no-diary)
6631 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6632 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6633 (org-agenda-error)))
6634 (buffer (marker-buffer hdmarker))
6635 (pos (marker-position hdmarker))
6636 (buffer-read-only nil)
6637 newhead)
6638 (with-current-buffer buffer
6639 (widen)
6640 (goto-char pos)
6641 (org-show-hidden-entry)
6642 (save-excursion
6643 (and (outline-next-heading)
6644 (org-flag-heading nil))) ; show the next heading
6645 (call-interactively 'org-set-tags)
6646 (end-of-line 1)
6647 (setq newhead (org-get-heading)))
6648 (org-agenda-change-all-lines newhead hdmarker)
6649 (beginning-of-line 1)))
6651 (defun org-agenda-date-later (arg &optional what)
6652 "Change the date of this item to one day later."
6653 (interactive "p")
6654 (org-agenda-check-type t 'agenda 'timeline)
6655 (org-agenda-check-no-diary)
6656 (let* ((marker (or (get-text-property (point) 'org-marker)
6657 (org-agenda-error)))
6658 (buffer (marker-buffer marker))
6659 (pos (marker-position marker)))
6660 (with-current-buffer buffer
6661 (widen)
6662 (goto-char pos)
6663 (if (not (org-at-timestamp-p))
6664 (error "Cannot find time stamp"))
6665 (org-timestamp-change arg (or what 'day))
6666 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6668 (defun org-agenda-date-earlier (arg &optional what)
6669 "Change the date of this item to one day earlier."
6670 (interactive "p")
6671 (org-agenda-date-later (- arg) what))
6673 (defun org-agenda-date-prompt (arg)
6674 "Change the date of this item. Date is prompted for, with default today.
6675 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6676 be used to request time specification in the time stamp."
6677 (interactive "P")
6678 (org-agenda-check-type t 'agenda 'timeline)
6679 (org-agenda-check-no-diary)
6680 (let* ((marker (or (get-text-property (point) 'org-marker)
6681 (org-agenda-error)))
6682 (buffer (marker-buffer marker))
6683 (pos (marker-position marker)))
6684 (with-current-buffer buffer
6685 (widen)
6686 (goto-char pos)
6687 (if (not (org-at-timestamp-p))
6688 (error "Cannot find time stamp"))
6689 (org-time-stamp arg)
6690 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6692 (defun org-get-heading ()
6693 "Return the heading of the current entry, without the stars."
6694 (save-excursion
6695 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6696 (if (and (re-search-backward "[\r\n]\\*" nil t)
6697 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6698 (match-string 1)
6699 "")))
6701 (defun org-agenda-diary-entry ()
6702 "Make a diary entry, like the `i' command from the calendar.
6703 All the standard commands work: block, weekly etc."
6704 (interactive)
6705 (org-agenda-check-type t 'agenda 'timeline)
6706 (require 'diary-lib)
6707 (let* ((char (progn
6708 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6709 (read-char-exclusive)))
6710 (cmd (cdr (assoc char
6711 '((?d . insert-diary-entry)
6712 (?w . insert-weekly-diary-entry)
6713 (?m . insert-monthly-diary-entry)
6714 (?y . insert-yearly-diary-entry)
6715 (?a . insert-anniversary-diary-entry)
6716 (?b . insert-block-diary-entry)
6717 (?c . insert-cyclic-diary-entry)))))
6718 (oldf (symbol-function 'calendar-cursor-to-date))
6719 (point (point))
6720 (mark (or (mark t) (point))))
6721 (unless cmd
6722 (error "No command associated with <%c>" char))
6723 (unless (and (get-text-property point 'day)
6724 (or (not (equal ?b char))
6725 (get-text-property mark 'day)))
6726 (error "Don't know which date to use for diary entry"))
6727 ;; We implement this by hacking the `calendar-cursor-to-date' function
6728 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6729 (let ((calendar-mark-ring
6730 (list (calendar-gregorian-from-absolute
6731 (or (get-text-property mark 'day)
6732 (get-text-property point 'day))))))
6733 (unwind-protect
6734 (progn
6735 (fset 'calendar-cursor-to-date
6736 (lambda (&optional error)
6737 (calendar-gregorian-from-absolute
6738 (get-text-property point 'day))))
6739 (call-interactively cmd))
6740 (fset 'calendar-cursor-to-date oldf)))))
6743 (defun org-agenda-execute-calendar-command (cmd)
6744 "Execute a calendar command from the agenda, with the date associated to
6745 the cursor position."
6746 (org-agenda-check-type t 'agenda 'timeline)
6747 (require 'diary-lib)
6748 (unless (get-text-property (point) 'day)
6749 (error "Don't know which date to use for calendar command"))
6750 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6751 (point (point))
6752 (date (calendar-gregorian-from-absolute
6753 (get-text-property point 'day)))
6754 (displayed-day (extract-calendar-day date))
6755 (displayed-month (extract-calendar-month date))
6756 (displayed-year (extract-calendar-year date)))
6757 (unwind-protect
6758 (progn
6759 (fset 'calendar-cursor-to-date
6760 (lambda (&optional error)
6761 (calendar-gregorian-from-absolute
6762 (get-text-property point 'day))))
6763 (call-interactively cmd))
6764 (fset 'calendar-cursor-to-date oldf))))
6766 (defun org-agenda-phases-of-moon ()
6767 "Display the phases of the moon for the 3 months around the cursor date."
6768 (interactive)
6769 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6771 (defun org-agenda-holidays ()
6772 "Display the holidays for the 3 months around the cursor date."
6773 (interactive)
6774 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6776 (defun org-agenda-sunrise-sunset (arg)
6777 "Display sunrise and sunset for the cursor date.
6778 Latitude and longitude can be specified with the variables
6779 `calendar-latitude' and `calendar-longitude'. When called with prefix
6780 argument, latitude and longitude will be prompted for."
6781 (interactive "P")
6782 (let ((calendar-longitude (if arg nil calendar-longitude))
6783 (calendar-latitude (if arg nil calendar-latitude))
6784 (calendar-location-name
6785 (if arg "the given coordinates" calendar-location-name)))
6786 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6788 (defun org-agenda-goto-calendar ()
6789 "Open the Emacs calendar with the date at the cursor."
6790 (interactive)
6791 (org-agenda-check-type t 'agenda 'timeline)
6792 (let* ((day (or (get-text-property (point) 'day)
6793 (error "Don't know which date to open in calendar")))
6794 (date (calendar-gregorian-from-absolute day))
6795 (calendar-move-hook nil)
6796 (view-diary-entries-initially nil))
6797 (calendar)
6798 (calendar-goto-date date)))
6800 (defun org-calendar-goto-agenda ()
6801 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6802 This is a command that has to be installed in `calendar-mode-map'."
6803 (interactive)
6804 (org-agenda-list nil (calendar-absolute-from-gregorian
6805 (calendar-cursor-to-date))
6806 nil t))
6808 (defun org-agenda-convert-date ()
6809 (interactive)
6810 (org-agenda-check-type t 'agenda 'timeline)
6811 (let ((day (get-text-property (point) 'day))
6812 date s)
6813 (unless day
6814 (error "Don't know which date to convert"))
6815 (setq date (calendar-gregorian-from-absolute day))
6816 (setq s (concat
6817 "Gregorian: " (calendar-date-string date) "\n"
6818 "ISO: " (calendar-iso-date-string date) "\n"
6819 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6820 "Julian: " (calendar-julian-date-string date) "\n"
6821 "Astron. JD: " (calendar-astro-date-string date)
6822 " (Julian date number at noon UTC)\n"
6823 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6824 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6825 "French: " (calendar-french-date-string date) "\n"
6826 "Mayan: " (calendar-mayan-date-string date) "\n"
6827 "Coptic: " (calendar-coptic-date-string date) "\n"
6828 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6829 "Persian: " (calendar-persian-date-string date) "\n"
6830 "Chinese: " (calendar-chinese-date-string date) "\n"))
6831 (with-output-to-temp-buffer "*Dates*"
6832 (princ s))
6833 (if (fboundp 'fit-window-to-buffer)
6834 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6836 ;;; Tags
6838 (defun org-scan-tags (action matcher &optional todo-only)
6839 "Scan headline tags with inheritance and produce output ACTION.
6840 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6841 evaluated, testing if a given set of tags qualifies a headline for
6842 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
6843 are included in the output."
6844 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6845 (mapconcat 'regexp-quote
6846 (nreverse (cdr (reverse org-todo-keywords)))
6847 "\\|")
6848 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
6849 (props (list 'face nil
6850 'done-face 'org-done
6851 'undone-face nil
6852 'mouse-face 'highlight
6853 'keymap org-agenda-keymap
6854 'help-echo
6855 (format "mouse-2 or RET jump to org file %s"
6856 (abbreviate-file-name buffer-file-name))))
6857 lspos
6858 tags tags-list tags-alist (llast 0) rtn level category i txt
6859 todo marker)
6861 (save-excursion
6862 (goto-char (point-min))
6863 (when (eq action 'sparse-tree) (hide-sublevels 1))
6864 (while (re-search-forward re nil t)
6865 (setq todo (if (match-end 1) (match-string 2))
6866 tags (if (match-end 4) (match-string 4)))
6867 (goto-char (setq lspos (1+ (match-beginning 0))))
6868 (setq level (funcall outline-level)
6869 category (org-get-category))
6870 (setq i llast llast level)
6871 ;; remove tag lists from same and sublevels
6872 (while (>= i level)
6873 (when (setq entry (assoc i tags-alist))
6874 (setq tags-alist (delete entry tags-alist)))
6875 (setq i (1- i)))
6876 ;; add the nex tags
6877 (when tags
6878 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6879 tags-alist
6880 (cons (cons level tags) tags-alist)))
6881 ;; compile tags for current headline
6882 (setq tags-list
6883 (if org-use-tag-inheritance
6884 (apply 'append (mapcar 'cdr tags-alist))
6885 tags))
6886 (when (and (or (not todo-only) todo)
6887 (eval matcher))
6888 ;; list this headline
6889 (if (eq action 'sparse-tree)
6890 (progn
6891 (org-show-hierarchy-above))
6892 (setq txt (org-format-agenda-item
6894 (concat
6895 (if org-tags-match-list-sublevels
6896 (make-string (1- level) ?.) "")
6897 (org-get-heading))
6898 category tags-list))
6899 (goto-char lspos)
6900 (setq marker (org-agenda-new-marker))
6901 (org-add-props txt props
6902 'org-marker marker 'org-hd-marker marker 'category category)
6903 (push txt rtn))
6904 ;; if we are to skip sublevels, jump to end of subtree
6905 (point)
6906 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6907 (nreverse rtn)))
6909 (defun org-tags-sparse-tree (&optional arg match)
6910 "Create a sparse tree according to tags search string MATCH.
6911 MATCH can contain positive and negative selection of tags, like
6912 \"+WORK+URGENT-WITHBOSS\"."
6913 (interactive "P")
6914 (let ((org-show-following-heading nil)
6915 (org-show-hierarchy-above nil))
6916 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6918 (defun org-make-tags-matcher (match)
6919 "Create the TAGS matcher form for the tags-selecting string MATCH."
6920 (unless match
6921 ;; Get a new match request, with completion
6922 (setq org-last-tags-completion-table
6923 (or (org-get-buffer-tags)
6924 org-last-tags-completion-table))
6925 (setq match (completing-read
6926 "Tags: " 'org-tags-completion-function nil nil nil
6927 'org-tags-history)))
6928 ;; parse the string and create a lisp form
6929 (let ((match0 match) minus tag mm matcher orterms term orlist)
6930 (setq orterms (org-split-string match "|"))
6931 (while (setq term (pop orterms))
6932 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
6933 (setq minus (and (match-end 1)
6934 (equal (match-string 1 term) "-"))
6935 tag (match-string 2 term)
6936 term (substring term (match-end 0))
6937 mm (list 'member (downcase tag) 'tags-list)
6938 mm (if minus (list 'not mm) mm))
6939 (push mm matcher))
6940 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6941 orlist)
6942 (setq matcher nil))
6943 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6944 ;; Return the string and lisp forms of the matcher
6945 (cons match0 matcher)))
6947 ;;;###autoload
6948 (defun org-tags-view (&optional todo-only match keep-modes)
6949 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
6950 The prefix arg TODO-ONLY limits the search to TODO entries."
6951 (interactive "P")
6952 (org-agenda-maybe-reset-markers 'force)
6953 (org-compile-prefix-format org-agenda-prefix-format)
6954 (let* ((org-agenda-keep-modes keep-modes)
6955 (org-tags-match-list-sublevels
6956 (if todo-only t org-tags-match-list-sublevels))
6957 (win (selected-window))
6958 (completion-ignore-case t)
6959 rtn rtnall files file pos matcher
6960 buffer)
6961 (setq matcher (org-make-tags-matcher match)
6962 match (car matcher) matcher (cdr matcher))
6963 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6964 (progn
6965 (delete-other-windows)
6966 (switch-to-buffer-other-window
6967 (get-buffer-create org-agenda-buffer-name))))
6968 (setq buffer-read-only nil)
6969 (erase-buffer)
6970 (org-agenda-mode) (setq buffer-read-only nil)
6971 (set (make-local-variable 'org-agenda-type) 'tags)
6972 (set (make-local-variable 'org-agenda-redo-command)
6973 (list 'org-tags-view (list 'quote todo-only)
6974 (list 'if 'current-prefix-arg nil match) t))
6975 (setq files (org-agenda-files)
6976 rtnall nil)
6977 (while (setq file (pop files))
6978 (catch 'nextfile
6979 (org-check-agenda-file file)
6980 (setq buffer (if (file-exists-p file)
6981 (org-get-agenda-file-buffer file)
6982 (error "No such file %s" file)))
6983 (if (not buffer)
6984 ;; If file does not exist, merror message to agenda
6985 (setq rtn (list
6986 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6987 rtnall (append rtnall rtn))
6988 (with-current-buffer buffer
6989 (unless (eq major-mode 'org-mode)
6990 (error "Agenda file %s is not in `org-mode'" file))
6991 (save-excursion
6992 (save-restriction
6993 (if org-respect-restriction
6994 (if (org-region-active-p)
6995 ;; Respect a region to restrict search
6996 (narrow-to-region (region-beginning) (region-end)))
6997 ;; If we work for the calendar or many files,
6998 ;; get rid of any restriction
6999 (widen))
7000 (setq rtn (org-scan-tags 'agenda matcher todo-only))
7001 (setq rtnall (append rtnall rtn))))))))
7002 (insert "Headlines with TAGS match: ")
7003 (add-text-properties (point-min) (1- (point))
7004 (list 'face 'org-level-3))
7005 (setq pos (point))
7006 (insert match "\n")
7007 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7008 (setq pos (point))
7009 (insert "Press `C-u r' to search again with new search string\n")
7010 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7011 (when rtnall
7012 (insert (mapconcat 'identity rtnall "\n")))
7013 (goto-char (point-min))
7014 (setq buffer-read-only t)
7015 (org-fit-agenda-window)
7016 (if (not org-select-agenda-window) (select-window win))))
7018 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
7019 (defun org-set-tags (&optional arg just-align)
7020 "Set the tags for the current headline.
7021 With prefix ARG, realign all tags in headings in the current buffer."
7022 (interactive)
7023 (let* (;(inherit (org-get-inherited-tags))
7024 (re (concat "^" outline-regexp))
7025 (col (current-column))
7026 (current (org-get-tags))
7027 tags hd empty invis)
7028 (if arg
7029 (save-excursion
7030 (goto-char (point-min))
7031 (while (re-search-forward re nil t)
7032 (org-set-tags nil t))
7033 (message "All tags realigned to column %d" org-tags-column))
7034 (if just-align
7035 (setq tags current)
7036 (setq org-last-tags-completion-table
7037 (or (org-get-buffer-tags)
7038 org-last-tags-completion-table))
7039 (setq tags
7040 (let ((org-add-colon-after-tag-completion t))
7041 (completing-read "Tags: " 'org-tags-completion-function
7042 nil nil current 'org-tags-history)))
7043 (while (string-match "[-+&]+" tags)
7044 (setq tags (replace-match ":" t t tags))))
7045 ;; FIXME: still optimize this by not checking when JUST-ALIGN?
7046 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
7047 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
7048 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
7049 (if (equal current "")
7050 (progn
7051 (end-of-line 1)
7052 (or empty (insert-before-markers " ")))
7053 (beginning-of-line 1)
7054 (setq invis (org-invisible-p))
7055 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
7056 (setq hd (match-string 1))
7057 (delete-region (match-beginning 0) (match-end 0))
7058 (insert-before-markers (org-trim hd) (if empty "" " ")))
7059 (unless (equal tags "")
7060 (move-to-column (max (current-column)
7061 (if (> org-tags-column 0)
7062 org-tags-column
7063 (- (- org-tags-column) (length tags))))
7065 (insert-before-markers tags)
7066 (if (and (not invis) (org-invisible-p))
7067 (outline-flag-region (point-at-bol) (point) nil)))
7068 (move-to-column col))))
7070 (defun org-tags-completion-function (string predicate &optional flag)
7071 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
7072 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
7073 (setq s1 (match-string 1 string)
7074 s2 (match-string 2 string))
7075 (setq s1 "" s2 string))
7076 (cond
7077 ((eq flag nil)
7078 ;; try completion
7079 (setq rtn (try-completion s2 ctable))
7080 (if (stringp rtn)
7081 (concat s1 s2 (substring rtn (length s2))
7082 (if (and org-add-colon-after-tag-completion
7083 (assoc rtn ctable))
7084 ":" "")))
7086 ((eq flag t)
7087 ;; all-completions
7088 (all-completions s2 ctable)
7090 ((eq flag 'lambda)
7091 ;; exact match?
7092 (assoc s2 ctable)))
7095 (defun org-get-tags ()
7096 "Get the TAGS string in the current headline."
7097 (unless (org-on-heading-p)
7098 (error "Not on a heading"))
7099 (save-excursion
7100 (beginning-of-line 1)
7101 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
7102 (org-match-string-no-properties 1)
7103 "")))
7105 (defun org-get-buffer-tags ()
7106 "Get a table of all tags used in the buffer, for completion."
7107 (let (tags)
7108 (save-excursion
7109 (goto-char (point-min))
7110 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
7111 (mapc (lambda (x) (add-to-list 'tags x))
7112 (org-split-string (org-match-string-no-properties 1) ":"))))
7113 (mapcar 'list tags)))
7115 ;;; Link Stuff
7117 (defun org-find-file-at-mouse (ev)
7118 "Open file link or URL at mouse."
7119 (interactive "e")
7120 (mouse-set-point ev)
7121 (org-open-at-point 'in-emacs))
7123 (defun org-open-at-mouse (ev)
7124 "Open file link or URL at mouse."
7125 (interactive "e")
7126 (mouse-set-point ev)
7127 (org-open-at-point))
7129 (defun org-open-at-point (&optional in-emacs)
7130 "Open link at or after point.
7131 If there is no link at point, this function will search forward up to
7132 the end of the current subtree.
7133 Normally, files will be opened by an appropriate application. If the
7134 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7135 (interactive "P")
7136 (org-remove-occur-highlights nil nil t)
7137 (if (org-at-timestamp-p)
7138 (org-agenda-list nil (time-to-days (org-time-string-to-time
7139 (substring (match-string 1) 0 10)))
7141 (let (type path link line search (pos (point)))
7142 (catch 'match
7143 (save-excursion
7144 (skip-chars-forward "^]\n\r")
7145 (when (and (re-search-backward "\\[\\[" nil t)
7146 (looking-at org-bracket-link-regexp)
7147 (<= (match-beginning 0) pos)
7148 (>= (match-end 0) pos))
7149 (setq link (org-link-unescape (org-match-string-no-properties 1)))
7150 (while (string-match " *\n *" link)
7151 (setq link (replace-match " " t t link)))
7152 (if (string-match org-link-re-with-space2 link)
7153 (setq type (match-string 1 link)
7154 path (match-string 2 link))
7155 (setq type "thisfile"
7156 path link))
7157 (throw 'match t)))
7159 (when (get-text-property (point) 'org-linked-text)
7160 (setq type "thisfile"
7161 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7162 (1+ (point)) (point))
7163 path (buffer-substring
7164 (previous-single-property-change pos 'org-linked-text)
7165 (next-single-property-change pos 'org-linked-text)))
7166 (throw 'match t))
7168 (save-excursion
7169 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
7170 (if (equal (char-before) ?<) (backward-char 1))
7171 (when (or (looking-at org-angle-link-re)
7172 (looking-at org-plain-link-re)
7173 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
7174 (re-search-forward org-plain-link-re (point-at-eol) t))
7175 (<= (match-beginning 0) pos)
7176 (>= (match-end 0) pos)))
7177 (setq type (match-string 1)
7178 path (match-string 2))
7179 (throw 'match t)))
7180 (save-excursion
7181 (skip-chars-backward "^ \t\n\r")
7182 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
7183 (setq type "tags"
7184 path (match-string 1))
7185 (while (string-match ":" path)
7186 (setq path (replace-match "+" t t path)))
7187 (throw 'match t)))
7188 (save-excursion
7189 (skip-chars-backward "a-zA-Z_")
7190 (when (and (memq 'camel org-activate-links)
7191 (looking-at org-camel-regexp))
7192 (setq type "camel" path (match-string 0))
7193 (if (equal (char-before) ?*)
7194 (setq path (concat "*" path))))
7195 (throw 'match t)))
7196 (unless path
7197 (error "No link found"))
7198 ;; Remove any trailing spaces in path
7199 (if (string-match " +\\'" path)
7200 (setq path (replace-match "" t t path)))
7202 (cond
7204 ((member type '("http" "https" "ftp" "mailto" "news"))
7205 (browse-url (concat type ":" path)))
7207 ((string= type "tags")
7208 (org-tags-view in-emacs path))
7209 ((or (string= type "camel")
7210 (string= type "thisfile"))
7211 (org-mark-ring-push)
7212 (org-link-search
7213 path
7214 (cond ((equal in-emacs '(4)) 'occur)
7215 ((equal in-emacs '(16)) 'org-occur)
7216 (t nil))))
7218 ((string= type "file")
7219 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
7220 (setq line (string-to-number (match-string 1 path))
7221 path (substring path 0 (match-beginning 0)))
7222 (if (string-match "::\\(.+\\)\\'" path)
7223 (setq search (match-string 1 path)
7224 path (substring path 0 (match-beginning 0)))))
7225 (org-open-file path in-emacs line search))
7227 ((string= type "news")
7228 (org-follow-gnus-link path))
7230 ((string= type "bbdb")
7231 (org-follow-bbdb-link path))
7233 ((string= type "gnus")
7234 (let (group article)
7235 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7236 (error "Error in Gnus link"))
7237 (setq group (match-string 1 path)
7238 article (match-string 3 path))
7239 (org-follow-gnus-link group article)))
7241 ((string= type "vm")
7242 (let (folder article)
7243 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7244 (error "Error in VM link"))
7245 (setq folder (match-string 1 path)
7246 article (match-string 3 path))
7247 ;; in-emacs is the prefix arg, will be interpreted as read-only
7248 (org-follow-vm-link folder article in-emacs)))
7250 ((string= type "wl")
7251 (let (folder article)
7252 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7253 (error "Error in Wanderlust link"))
7254 (setq folder (match-string 1 path)
7255 article (match-string 3 path))
7256 (org-follow-wl-link folder article)))
7258 ((string= type "mhe")
7259 (let (folder article)
7260 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7261 (error "Error in MHE link"))
7262 (setq folder (match-string 1 path)
7263 article (match-string 3 path))
7264 (org-follow-mhe-link folder article)))
7266 ((string= type "rmail")
7267 (let (folder article)
7268 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7269 (error "Error in RMAIL link"))
7270 (setq folder (match-string 1 path)
7271 article (match-string 3 path))
7272 (org-follow-rmail-link folder article)))
7274 ((string= type "shell")
7275 (let ((cmd path))
7276 (while (string-match "@{" cmd)
7277 (setq cmd (replace-match "<" t t cmd)))
7278 (while (string-match "@}" cmd)
7279 (setq cmd (replace-match ">" t t cmd)))
7280 (if (or (not org-confirm-shell-links)
7281 (funcall org-confirm-shell-links
7282 (format "Execute \"%s\" in shell? "
7283 (org-add-props cmd nil
7284 'face 'org-warning))))
7285 (shell-command cmd)
7286 (error "Abort"))))
7289 (browse-url-at-point))))))
7291 (defun org-link-search (s &optional type)
7292 "Search for a link search option.
7293 When S is a CamelCaseWord, search for a target, or for a sentence containing
7294 the words. If S is surrounded by forward slashes, it is interpreted as a
7295 regular expression. In org-mode files, this will create an `org-occur'
7296 sparse tree. In ordinary files, `occur' will be used to list matches.
7297 If the current buffer is in `dired-mode', grep will be used to search
7298 in all files."
7299 (let ((case-fold-search t)
7300 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7301 (pos (point))
7302 (pre "") (post "")
7303 words re0 re1 re2 re3 re4 re5 re2a reall camel)
7304 (cond ((save-excursion
7305 (goto-char (point-min))
7306 (and
7307 (re-search-forward
7308 (concat "<<" (regexp-quote s0) ">>") nil t)
7309 (setq pos (match-beginning 0))))
7310 ;; There is an exact target for this
7311 (goto-char pos))
7312 ((string-match "^/\\(.*\\)/$" s)
7313 ;; A regular expression
7314 (cond
7315 ((eq major-mode 'org-mode)
7316 (org-occur (match-string 1 s)))
7317 ;;((eq major-mode 'dired-mode)
7318 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7319 (t (org-do-occur (match-string 1 s)))))
7320 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
7322 ;; A camel or a normal search string
7323 (when (equal (string-to-char s) ?*)
7324 ;; Anchor on headlines, post may include tags.
7325 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
7326 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
7327 s (substring s 1)))
7328 (remove-text-properties
7329 0 (length s)
7330 '(face nil mouse-face nil keymap nil fontified nil) s)
7331 ;; Make a series of regular expressions to find a match
7332 (setq words
7333 (if camel
7334 (org-camel-to-words s)
7335 (org-split-string s "[ \n\r\t]+"))
7336 re0 (concat "<<" (regexp-quote s0) ">>")
7337 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
7338 re2a (concat "\\<" (mapconcat 'downcase words "[ \t\r\n]+") "\\>")
7339 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
7340 re1 (concat pre re2 post)
7341 re3 (concat pre re4 post)
7342 re5 (concat pre ".*" re4)
7343 re2 (concat pre re2)
7344 re2a (concat pre re2a)
7345 re4 (concat pre re4)
7346 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7347 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7348 re5 "\\)"
7350 (cond
7351 ((eq type 'org-occur) (org-occur reall))
7352 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7353 (t (goto-char (point-min))
7354 (if (or (org-search-not-link re0 nil t)
7355 (org-search-not-link re1 nil t)
7356 (org-search-not-link re2 nil t)
7357 (org-search-not-link re2a nil t)
7358 (org-search-not-link re3 nil t)
7359 (org-search-not-link re4 nil t)
7360 (org-search-not-link re5 nil t)
7362 (goto-char (match-beginning 0))
7363 (goto-char pos)
7364 (error "No match")))))
7366 ;; Normal string-search
7367 (goto-char (point-min))
7368 (if (search-forward s nil t)
7369 (goto-char (match-beginning 0))
7370 (error "No match"))))
7371 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
7373 (defun org-search-not-link (&rest args)
7374 "Execute `re-search-forward', but only accept matches that are not a link."
7375 (catch 'exit
7376 (let ((pos (point)) p1)
7377 (while (apply 're-search-forward args)
7378 (setq p1 (point))
7379 (if (not (save-match-data
7380 (and (re-search-backward "\\[\\[" nil t)
7381 (looking-at org-bracket-link-regexp)
7382 (<= (match-beginning 0) p1)
7383 (>= (match-end 0) p1))))
7384 (progn (goto-char (match-end 0))
7385 (throw 'exit (point)))
7386 (goto-char (match-end 0)))))))
7388 (defun org-do-occur (regexp &optional cleanup)
7389 "Call the Emacs command `occur'.
7390 If CLEANUP is non-nil, remove the printout of the regular expression
7391 in the *Occur* buffer. This is useful if the regex is long and not useful
7392 to read."
7393 (occur regexp)
7394 (when cleanup
7395 (let ((cwin (selected-window)) win beg end)
7396 (when (setq win (get-buffer-window "*Occur*"))
7397 (select-window win))
7398 (goto-char (point-min))
7399 (when (re-search-forward "match[a-z]+" nil t)
7400 (setq beg (match-end 0))
7401 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7402 (setq end (1- (match-beginning 0)))))
7403 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
7404 (goto-char (point-min))
7405 (select-window cwin))))
7407 (defvar org-mark-ring nil
7408 "Mark ring for positions before jumps in Org-mode.")
7409 (defvar org-mark-ring-last-goto nil
7410 "Last position in the mark ring used to go back.")
7411 ;; Fill and close the ring
7412 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7413 (loop for i from 1 to org-mark-ring-length do
7414 (push (make-marker) org-mark-ring))
7415 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7416 org-mark-ring)
7418 (defun org-mark-ring-push (&optional pos buffer)
7419 "Put the current position or POS into the mark ring and rotate it."
7420 (interactive)
7421 (setq pos (or pos (point)))
7422 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7423 (move-marker (car org-mark-ring)
7424 (or pos (point))
7425 (or buffer (current-buffer)))
7426 (message
7427 (substitute-command-keys
7428 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7430 (defun org-mark-ring-goto (&optional n)
7431 "Jump to the previous position in the mark ring.
7432 With prefix arg N, jump back that many stored positions. When
7433 called several times in succession, walk through the entire ring.
7434 Org-mode commands jumping to a different position in the current file,
7435 or to another Org-mode file, automatically push the old position
7436 onto the ring."
7437 (interactive "p")
7438 (let (p m)
7439 (if (eq last-command this-command)
7440 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7441 (setq p org-mark-ring))
7442 (setq org-mark-ring-last-goto p)
7443 (setq m (car p))
7444 (switch-to-buffer (marker-buffer m))
7445 (goto-char m)
7446 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7448 (defun org-camel-to-words (s)
7449 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7450 (let ((case-fold-search nil)
7451 words)
7452 (while (string-match "[a-z][A-Z]" s)
7453 (push (substring s 0 (1+ (match-beginning 0))) words)
7454 (setq s (substring s (1+ (match-beginning 0)))))
7455 (nreverse (cons s words))))
7457 (defun org-remove-angle-brackets (s)
7458 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7459 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7461 (defun org-add-angle-brackets (s)
7462 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7463 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7466 (defun org-follow-bbdb-link (name)
7467 "Follow a BBDB link to NAME."
7468 (require 'bbdb)
7469 (let ((inhibit-redisplay t)
7470 (bbdb-electric-p nil))
7471 (catch 'exit
7472 ;; Exact match on name
7473 (bbdb-name (concat "\\`" name "\\'") nil)
7474 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7475 ;; Exact match on name
7476 (bbdb-company (concat "\\`" name "\\'") nil)
7477 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7478 ;; Partial match on name
7479 (bbdb-name name nil)
7480 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7481 ;; Partial match on company
7482 (bbdb-company name nil)
7483 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7484 ;; General match including network address and notes
7485 (bbdb name nil)
7486 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7487 (delete-window (get-buffer-window "*BBDB*"))
7488 (error "No matching BBDB record")))))
7490 (defun org-follow-gnus-link (&optional group article)
7491 "Follow a Gnus link to GROUP and ARTICLE."
7492 (require 'gnus)
7493 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7494 (if group (gnus-fetch-group group))
7495 (if article
7496 (or (gnus-summary-goto-article article nil 'force)
7497 (if (fboundp 'gnus-summary-insert-cached-articles)
7498 (progn
7499 (gnus-summary-insert-cached-articles)
7500 (gnus-summary-goto-article article nil 'force))
7501 (message "Message could not be found.")))))
7503 (defun org-follow-vm-link (&optional folder article readonly)
7504 "Follow a VM link to FOLDER and ARTICLE."
7505 (require 'vm)
7506 (setq article (org-add-angle-brackets article))
7507 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7508 ;; ange-ftp or efs or tramp access
7509 (let ((user (or (match-string 1 folder) (user-login-name)))
7510 (host (match-string 2 folder))
7511 (file (match-string 3 folder)))
7512 (cond
7513 ((featurep 'tramp)
7514 ;; use tramp to access the file
7515 (if (featurep 'xemacs)
7516 (setq folder (format "[%s@%s]%s" user host file))
7517 (setq folder (format "/%s@%s:%s" user host file))))
7519 ;; use ange-ftp or efs
7520 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
7521 (setq folder (format "/%s@%s:%s" user host file))))))
7522 (when folder
7523 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7524 (sit-for 0.1)
7525 (when article
7526 (vm-select-folder-buffer)
7527 (widen)
7528 (let ((case-fold-search t))
7529 (goto-char (point-min))
7530 (if (not (re-search-forward
7531 (concat "^" "message-id: *" (regexp-quote article))))
7532 (error "Could not find the specified message in this folder"))
7533 (vm-isearch-update)
7534 (vm-isearch-narrow)
7535 (vm-beginning-of-message)
7536 (vm-summarize)))))
7538 (defun org-follow-wl-link (folder article)
7539 "Follow a Wanderlust link to FOLDER and ARTICLE."
7540 (setq article (org-add-angle-brackets article))
7541 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7542 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7543 (wl-summary-redisplay))
7545 (defun org-follow-rmail-link (folder article)
7546 "Follow an RMAIL link to FOLDER and ARTICLE."
7547 (setq article (org-add-angle-brackets article))
7548 (let (message-number)
7549 (save-excursion
7550 (save-window-excursion
7551 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7552 (setq message-number
7553 (save-restriction
7554 (widen)
7555 (goto-char (point-max))
7556 (if (re-search-backward
7557 (concat "^Message-ID:\\s-+" (regexp-quote
7558 (or article "")))
7559 nil t)
7560 (rmail-what-message))))))
7561 (if message-number
7562 (progn
7563 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7564 (rmail-show-message message-number)
7565 message-number)
7566 (error "Message not found"))))
7568 ;; mh-e integration based on planner-mode
7569 (defun org-mhe-get-message-real-folder ()
7570 "Return the name of the current message real folder, so if you use
7571 sequences, it will now work."
7572 (save-excursion
7573 (let* ((folder
7574 (if (equal major-mode 'mh-folder-mode)
7575 mh-current-folder
7576 ;; Refer to the show buffer
7577 mh-show-folder-buffer))
7578 (end-index
7579 (if (boundp 'mh-index-folder)
7580 (min (length mh-index-folder) (length folder))))
7582 ;; a simple test on mh-index-data does not work, because
7583 ;; mh-index-data is always nil in a show buffer.
7584 (if (and (boundp 'mh-index-folder)
7585 (string= mh-index-folder (substring folder 0 end-index)))
7586 (if (equal major-mode 'mh-show-mode)
7587 (save-window-excursion
7588 (when (buffer-live-p (get-buffer folder))
7589 (progn
7590 (pop-to-buffer folder)
7591 (org-mhe-get-message-folder-from-index)
7594 (org-mhe-get-message-folder-from-index)
7596 folder
7600 (defun org-mhe-get-message-folder-from-index ()
7601 "Returns the name of the message folder in a index folder buffer."
7602 (save-excursion
7603 (mh-index-previous-folder)
7604 (re-search-forward "^\\(+.*\\)$" nil t)
7605 (message (match-string 1))))
7607 (defun org-mhe-get-message-folder ()
7608 "Return the name of the current message folder. Be careful if you
7609 use sequences."
7610 (save-excursion
7611 (if (equal major-mode 'mh-folder-mode)
7612 mh-current-folder
7613 ;; Refer to the show buffer
7614 mh-show-folder-buffer)))
7616 (defun org-mhe-get-message-num ()
7617 "Return the number of the current message. Be careful if you
7618 use sequences."
7619 (save-excursion
7620 (if (equal major-mode 'mh-folder-mode)
7621 (mh-get-msg-num nil)
7622 ;; Refer to the show buffer
7623 (mh-show-buffer-message-number))))
7625 (defun org-mhe-get-header (header)
7626 "Return a header of the message in folder mode. This will create a
7627 show buffer for the corresponding message. If you have a more clever
7628 idea..."
7629 (let* ((folder (org-mhe-get-message-folder))
7630 (num (org-mhe-get-message-num))
7631 (buffer (get-buffer-create (concat "show-" folder)))
7632 (header-field))
7633 (with-current-buffer buffer
7634 (mh-display-msg num folder)
7635 (if (equal major-mode 'mh-folder-mode)
7636 (mh-header-display)
7637 (mh-show-header-display))
7638 (set-buffer buffer)
7639 (setq header-field (mh-get-header-field header))
7640 (if (equal major-mode 'mh-folder-mode)
7641 (mh-show)
7642 (mh-show-show))
7643 header-field)))
7645 (defun org-follow-mhe-link (folder article)
7646 "Follow an MHE link to FOLDER and ARTICLE.
7647 If ARTICLE is nil FOLDER is shown. If the configuration variable
7648 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
7649 ARTICLE is searched in all folders. Indexed searches (swish++,
7650 namazu, and others supported by MH-E) will always search in all
7651 folders."
7652 (require 'mh-e)
7653 (require 'mh-search)
7654 (require 'mh-utils)
7655 (mh-find-path)
7656 (if (not article)
7657 (mh-visit-folder (mh-normalize-folder-name folder))
7658 (setq article (org-add-angle-brackets article))
7659 (mh-search-choose)
7660 (if (equal mh-searcher 'pick)
7661 (progn
7662 (mh-search folder (list "--message-id" article))
7663 (when (and org-mhe-search-all-folders
7664 (not (org-mhe-get-message-real-folder)))
7665 (kill-this-buffer)
7666 (mh-search "+" (list "--message-id" article))))
7667 (mh-search "+" article))
7668 (if (org-mhe-get-message-real-folder)
7669 (mh-show-msg 1)
7670 (kill-this-buffer)
7671 (error "Message not found"))))
7673 (defun org-open-file (path &optional in-emacs line search)
7674 "Open the file at PATH.
7675 First, this expands any special file name abbreviations. Then the
7676 configuration variable `org-file-apps' is checked if it contains an
7677 entry for this file type, and if yes, the corresponding command is launched.
7678 If no application is found, Emacs simply visits the file.
7679 With optional argument IN-EMACS, Emacs will visit the file.
7680 Optional LINE specifies a line to go to, optional SEARCH a string to
7681 search for. If LINE or SEARCH is given, the file will always be
7682 opened in Emacs.
7683 If the file does not exist, an error is thrown."
7684 (setq in-emacs (or in-emacs line search))
7685 (let* ((file (if (equal path "")
7686 buffer-file-name
7687 (convert-standard-filename (org-expand-file-name path))))
7688 (dirp (file-directory-p file))
7689 (dfile (downcase file))
7690 (old-buffer (current-buffer))
7691 (old-pos (point))
7692 (old-mode major-mode)
7693 ext cmd apps)
7694 (if (and (not (file-exists-p file))
7695 (not org-open-non-existing-files))
7696 (error "No such file: %s" file))
7697 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7698 (setq ext (match-string 1 dfile))
7699 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7700 (setq ext (match-string 1 dfile))))
7701 (setq apps (append org-file-apps (org-default-apps)))
7702 (if in-emacs
7703 (setq cmd 'emacs)
7704 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7705 (cdr (assoc ext apps))
7706 (cdr (assoc t apps)))))
7707 (when (eq cmd 'mailcap)
7708 (require 'mailcap)
7709 (mailcap-parse-mailcaps)
7710 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7711 (command (mailcap-mime-info mime-type)))
7712 (if (stringp command)
7713 (setq cmd command)
7714 (setq cmd 'emacs))))
7715 (cond
7716 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7717 (setq cmd (format cmd (concat "\"" file "\"")))
7718 (save-window-excursion
7719 (shell-command (concat cmd " &"))))
7720 ((or (stringp cmd)
7721 (eq cmd 'emacs))
7722 (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
7723 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7724 (if line (goto-line line)
7725 (if search (org-link-search search))))
7726 ((consp cmd)
7727 (eval cmd))
7728 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7729 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7730 (or (not (equal old-buffer (current-buffer)))
7731 (not (equal old-pos (point))))
7732 (org-mark-ring-push old-pos old-buffer))))
7734 (defun org-default-apps ()
7735 "Return the default applications for this operating system."
7736 (cond
7737 ((eq system-type 'darwin)
7738 org-file-apps-defaults-macosx)
7739 ((eq system-type 'windows-nt)
7740 org-file-apps-defaults-windowsnt)
7741 (t org-file-apps-defaults-gnu)))
7743 (defun org-expand-file-name (path)
7744 "Replace special path abbreviations and expand the file name."
7745 (expand-file-name path))
7748 (defvar org-insert-link-history nil
7749 "Minibuffer history for links inserted with `org-insert-link'.")
7751 (defvar org-stored-links nil
7752 "Contains the links stored with `org-store-link'.")
7754 ;;;###autoload
7755 (defun org-store-link (arg)
7756 "\\<org-mode-map>Store an org-link to the current location.
7757 This link can later be inserted into an org-buffer with
7758 \\[org-insert-link].
7759 For some link types, a prefix arg is interpreted:
7760 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7761 For file links, arg negates `org-context-in-file-links'."
7762 (interactive "P")
7763 (let (link cpltxt desc txt (pos (point)))
7764 (cond
7766 ((eq major-mode 'bbdb-mode)
7767 (setq cpltxt (concat
7768 "bbdb:"
7769 (or (bbdb-record-name (bbdb-current-record))
7770 (bbdb-record-company (bbdb-current-record))))
7771 link (org-make-link cpltxt)))
7773 ((eq major-mode 'calendar-mode)
7774 (let ((cd (calendar-cursor-to-date)))
7775 (setq link
7776 (format-time-string
7777 (car org-time-stamp-formats)
7778 (apply 'encode-time
7779 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7780 nil nil nil))))))
7782 ((or (eq major-mode 'vm-summary-mode)
7783 (eq major-mode 'vm-presentation-mode))
7784 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7785 (vm-follow-summary-cursor)
7786 (save-excursion
7787 (vm-select-folder-buffer)
7788 (let* ((message (car vm-message-pointer))
7789 (folder buffer-file-name)
7790 (subject (vm-su-subject message))
7791 (author (vm-su-full-name message))
7792 (message-id (vm-su-message-id message)))
7793 (setq message-id (org-remove-angle-brackets message-id))
7794 (setq folder (abbreviate-file-name folder))
7795 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7796 folder)
7797 (setq folder (replace-match "" t t folder)))
7798 (setq cpltxt (concat author " on: " subject))
7799 (setq link (org-make-link "vm:" folder "#" message-id)))))
7801 ((eq major-mode 'wl-summary-mode)
7802 (let* ((msgnum (wl-summary-message-number))
7803 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7804 msgnum 'message-id))
7805 (wl-message-entity (elmo-msgdb-overview-get-entity
7806 msgnum (wl-summary-buffer-msgdb)))
7807 (author (wl-summary-line-from)) ; FIXME: correct?
7808 (subject "???")) ; FIXME:
7809 (setq message-id (org-remove-angle-brackets message-id))
7810 (setq cpltxt (concat author " on: " subject))
7811 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
7812 "#" message-id))))
7814 ((or (equal major-mode 'mh-folder-mode)
7815 (equal major-mode 'mh-show-mode))
7816 (let ((from-header (org-mhe-get-header "From:"))
7817 (to-header (org-mhe-get-header "To:"))
7818 (subject (org-mhe-get-header "Subject:")))
7819 (setq cpltxt (concat from-header " on: " subject))
7820 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
7821 (org-remove-angle-brackets
7822 (org-mhe-get-header "Message-Id:"))))))
7824 ((eq major-mode 'rmail-mode)
7825 (save-excursion
7826 (save-restriction
7827 (rmail-narrow-to-non-pruned-header)
7828 (let ((folder buffer-file-name)
7829 (message-id (mail-fetch-field "message-id"))
7830 (author (mail-fetch-field "from"))
7831 (subject (mail-fetch-field "subject")))
7832 (setq message-id (org-remove-angle-brackets message-id))
7833 (setq cpltxt (concat author " on: " subject))
7834 (setq link (org-make-link "rmail:" folder "#" message-id))))))
7836 ((eq major-mode 'gnus-group-mode)
7837 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7838 (gnus-group-group-name)) ; version
7839 ((fboundp 'gnus-group-name)
7840 (gnus-group-name))
7841 (t "???"))))
7842 (setq cpltxt (concat
7843 (if (org-xor arg org-usenet-links-prefer-google)
7844 "http://groups.google.com/groups?group="
7845 "gnus:")
7846 group)
7847 link (org-make-link cpltxt))))
7849 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7850 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7851 (gnus-summary-beginning-of-article)
7852 (let* ((group (car gnus-article-current))
7853 (article (cdr gnus-article-current))
7854 (header (gnus-summary-article-header article))
7855 (author (mail-header-from header))
7856 (message-id (mail-header-id header))
7857 (date (mail-header-date header))
7858 (subject (gnus-summary-subject-string)))
7859 (setq cpltxt (concat author " on: " subject))
7860 (if (org-xor arg org-usenet-links-prefer-google)
7861 (setq link
7862 (concat
7863 cpltxt "\n "
7864 (format "http://groups.google.com/groups?as_umsgid=%s"
7865 (org-fixup-message-id-for-http message-id))))
7866 (setq link (org-make-link "gnus:" group
7867 "#" (number-to-string article))))))
7869 ((eq major-mode 'w3-mode)
7870 (setq cpltxt (url-view-url t)
7871 link (org-make-link cpltxt)))
7872 ((eq major-mode 'w3m-mode)
7873 (setq cpltxt w3m-current-url
7874 link (org-make-link cpltxt)))
7876 ((eq major-mode 'org-mode)
7877 ;; Just link to current headline
7878 (setq cpltxt (concat "file:"
7879 (abbreviate-file-name buffer-file-name)))
7880 ;; Add a context search string
7881 (when (org-xor org-context-in-file-links arg)
7882 ;; Check if we are on a target
7883 (if (save-excursion
7884 (skip-chars-forward "^>\n\r")
7885 (and (re-search-backward "<<" nil t)
7886 (looking-at "<<\\(.*?\\)>>")
7887 (<= (match-beginning 0) pos)
7888 (>= (match-end 0) pos)))
7889 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7890 (setq txt (cond
7891 ((org-on-heading-p) nil)
7892 ((org-region-active-p)
7893 (buffer-substring (region-beginning) (region-end)))
7894 (t (buffer-substring (point-at-bol) (point-at-eol)))))
7895 (setq cpltxt
7896 (concat cpltxt "::"
7897 (if org-file-link-context-use-camel-case
7898 (org-make-org-heading-camel txt)
7899 (org-make-org-heading-search-string txt)))
7900 desc "NONE")))
7901 (if (string-match "::\\'" cpltxt)
7902 (setq cpltxt (substring cpltxt 0 -2)))
7903 (setq link (org-make-link cpltxt)))
7905 (buffer-file-name
7906 ;; Just link to this file here.
7907 (setq cpltxt (concat "file:"
7908 (abbreviate-file-name buffer-file-name)))
7909 ;; Add a context string
7910 (when (org-xor org-context-in-file-links arg)
7911 (setq txt (if (org-region-active-p)
7912 (buffer-substring (region-beginning) (region-end))
7913 (buffer-substring (point-at-bol) (point-at-eol))))
7914 (setq cpltxt
7915 (concat cpltxt "::"
7916 (if org-file-link-context-use-camel-case
7917 (org-make-org-heading-camel txt)
7918 (org-make-org-heading-search-string txt)))
7919 desc "NONE"))
7920 (setq link (org-make-link cpltxt)))
7922 ((interactive-p)
7923 (error "Cannot link to a buffer which is not visiting a file"))
7925 (t (setq link nil)))
7927 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7928 (setq link (or link cpltxt)
7929 desc (or desc cpltxt))
7930 (if (equal desc "NONE") (setq desc nil))
7932 (if (and (interactive-p) link)
7933 (progn
7934 (setq org-stored-links
7935 (cons (list cpltxt link desc) org-stored-links))
7936 (message "Stored: %s" (or cpltxt link)))
7937 (org-make-link-string link desc))))
7939 (defun org-make-org-heading-search-string (&optional string heading)
7940 "Make search string for STRING or current headline."
7941 (interactive)
7942 (let ((s (or string (org-get-heading))))
7943 (unless (and string (not heading))
7944 ;; We are using a headline, clean up garbage in there.
7945 (if (string-match org-todo-regexp s)
7946 (setq s (replace-match "" t t s)))
7947 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7948 (setq s (replace-match "" t t s)))
7949 (setq s (org-trim s))
7950 (if (string-match (concat "^\\(" org-quote-string "\\|"
7951 org-comment-string "\\)") s)
7952 (setq s (replace-match "" t t s)))
7953 (while (string-match org-ts-regexp s)
7954 (setq s (replace-match "" t t s))))
7955 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7956 (setq s (replace-match " " t t s)))
7957 (or string (setq s (concat "*" s))) ; Add * for headlines
7958 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7960 (defun org-make-org-heading-camel (&optional string heading)
7961 "Make a CamelCase string for STRING or the current headline."
7962 (interactive)
7963 (let ((s (or string (org-get-heading))))
7964 (unless (and string (not heading))
7965 ;; We are using a headline, clean up garbage in there.
7966 (if (string-match org-todo-regexp s)
7967 (setq s (replace-match "" t t s)))
7968 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7969 (setq s (replace-match "" t t s)))
7970 (setq s (org-trim s))
7971 (if (string-match (concat "^\\(" org-quote-string "\\|"
7972 org-comment-string "\\)") s)
7973 (setq s (replace-match "" t t s)))
7974 (while (string-match org-ts-regexp s)
7975 (setq s (replace-match "" t t s))))
7976 (while (string-match "[^a-zA-Z_ \t]+" s)
7977 (setq s (replace-match " " t t s)))
7978 (or string (setq s (concat "*" s))) ; Add * for headlines
7979 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
7981 (defun org-make-link (&rest strings)
7982 "Concatenate STRINGS, format resulting string with `org-link-format'."
7983 (format org-link-format (apply 'concat strings)))
7985 (defun org-make-link-string (link &optional description)
7986 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7987 (if (eq org-link-style 'plain)
7988 (if (equal description link)
7989 link
7990 (concat description "\n" link))
7991 (when (stringp description)
7992 ;; Remove brackets from the description, they are fatal.
7993 (while (string-match "\\[\\|\\]" description)
7994 (setq description (replace-match "" t t description))))
7995 (when (equal (org-link-escape link) description)
7996 ;; No description needed, it is identical
7997 (setq description nil))
7998 (when (and (not description)
7999 (not (equal link (org-link-escape link))))
8000 (setq description link))
8001 (concat "[[" (org-link-escape link) "]"
8002 (if description (concat "[" description "]") "")
8003 "]")))
8005 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
8006 "Association list of escapes for some characters problematic in links.")
8008 (defun org-link-escape (text)
8009 "Escape charaters in TEXT that are problematic for links."
8010 (when text
8011 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
8012 org-link-escape-chars "\\|")))
8013 (while (string-match re text)
8014 (setq text
8015 (replace-match
8016 (cdr (assoc (match-string 0 text) org-link-escape-chars))
8017 t t text)))
8018 text)))
8020 (defun org-link-unescape (text)
8021 "Reverse the action of `org-link-escape'."
8022 (when text
8023 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
8024 org-link-escape-chars "\\|")))
8025 (while (string-match re text)
8026 (setq text
8027 (replace-match
8028 (car (rassoc (match-string 0 text) org-link-escape-chars))
8029 t t text)))
8030 text)))
8032 (defun org-xor (a b)
8033 "Exclusive or."
8034 (if a (not b) b))
8036 (defun org-get-header (header)
8037 "Find a header field in the current buffer."
8038 (save-excursion
8039 (goto-char (point-min))
8040 (let ((case-fold-search t) s)
8041 (cond
8042 ((eq header 'from)
8043 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
8044 (setq s (match-string 1)))
8045 (while (string-match "\"" s)
8046 (setq s (replace-match "" t t s)))
8047 (if (string-match "[<(].*" s)
8048 (setq s (replace-match "" t t s))))
8049 ((eq header 'message-id)
8050 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
8051 (setq s (match-string 1))))
8052 ((eq header 'subject)
8053 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
8054 (setq s (match-string 1)))))
8055 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
8056 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
8057 s)))
8060 (defun org-fixup-message-id-for-http (s)
8061 "Replace special characters in a message id, so it can be used in an http query."
8062 (while (string-match "<" s)
8063 (setq s (replace-match "%3C" t t s)))
8064 (while (string-match ">" s)
8065 (setq s (replace-match "%3E" t t s)))
8066 (while (string-match "@" s)
8067 (setq s (replace-match "%40" t t s)))
8070 (defun org-insert-link (&optional complete-file)
8071 "Insert a link. At the prompt, enter the link.
8073 Completion can be used to select a link previously stored with
8074 `org-store-link'. When the empty string is entered (i.e. if you just
8075 press RET at the prompt), the link defaults to the most recently
8076 stored link. As SPC triggers completion in the minibuffer, you need to
8077 use M-SPC or C-q SPC to force the insertion of a space character.
8079 You will also be prompted for a description, and if one is given, it will
8080 be displayed in the buffer instead of the link.
8082 If there is already a link at point, this command will allow you to edit link
8083 and description parts.
8085 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
8086 selected using completion. The path to the file will be relative to
8087 the current directory if the file is in the current directory or a
8088 subdirectory. Otherwise, the link will be the absolute path as
8089 completed in the minibuffer (i.e. normally ~/path/to/file).
8091 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
8092 is in the current directory or below."
8093 (interactive "P")
8094 (let (link desc entry remove file (pos (point)))
8095 (cond
8096 ((save-excursion
8097 (skip-chars-forward "^]\n\r")
8098 (and (re-search-backward "\\[\\[" nil t)
8099 (looking-at org-bracket-link-regexp)
8100 (<= (match-beginning 0) pos)
8101 (>= (match-end 0) pos)))
8102 ;; We do have a link at point, and we are going to edit it.
8103 (setq remove (list (match-beginning 0) (match-end 0)))
8104 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8105 (setq link (read-string "Link: "
8106 (org-link-unescape
8107 (org-match-string-no-properties 1)))))
8108 (complete-file
8109 ;; Completing read for file names.
8110 (setq file (read-file-name "File: "))
8111 (let ((pwd (file-name-as-directory (expand-file-name "."))))
8112 (cond
8113 ((equal complete-file '(16))
8114 (setq link (org-make-link
8115 "file:"
8116 (abbreviate-file-name (expand-file-name file)))))
8117 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8118 (expand-file-name file))
8119 (setq link (org-make-link
8120 "file:" (match-string 1 (expand-file-name file)))))
8121 (t (setq link (org-make-link "file:" file))))))
8123 ;; Read link, with completion for stored links.
8124 (setq link (org-completing-read
8125 "Link: " org-stored-links nil nil nil
8126 org-insert-link-history
8127 (or (car (car org-stored-links)))))
8128 (setq entry (assoc link org-stored-links))
8129 (if (not org-keep-stored-link-after-insertion)
8130 (setq org-stored-links (delq (assoc link org-stored-links)
8131 org-stored-links)))
8132 (setq link (if entry (nth 1 entry) link)
8133 desc (or desc (nth 2 entry)))))
8135 (if (string-match org-plain-link-re link)
8136 ;; URL-like link, normalize the use of angular brackets.
8137 (setq link (org-make-link (org-remove-angle-brackets link))))
8139 ;; Check if we are linking to the current file. If yes, simplify the link.
8140 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
8141 (let* ((path (match-string 1 link))
8142 (case-fold-search nil)
8143 (search (match-string 2 link)))
8144 (when (save-match-data
8145 (equal (file-truename buffer-file-name)
8146 (file-truename path)))
8147 ;; We are linking to this same file, with a search option
8148 (setq link search))))
8149 (setq desc (read-string "Description: " desc))
8150 (unless (string-match "\\S-" desc) (setq desc nil))
8151 (if remove (apply 'delete-region remove))
8152 (insert (org-make-link-string link desc))))
8154 (defun org-completing-read (&rest args)
8155 (let ((minibuffer-local-completion-map
8156 (copy-keymap minibuffer-local-completion-map)))
8157 (define-key minibuffer-local-completion-map " " 'self-insert-command)
8158 (apply 'completing-read args)))
8160 ;;; Hooks for remember.el
8162 (defvar org-finish-function nil)
8164 ;;;###autoload
8165 (defun org-remember-annotation ()
8166 "Return a link to the current location as an annotation for remember.el.
8167 If you are using Org-mode files as target for data storage with
8168 remember.el, then the annotations should include a link compatible with the
8169 conventions in Org-mode. This function returns such a link."
8170 (org-store-link nil))
8172 (defconst org-remember-help
8173 "Select a destination location for the note.
8174 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
8175 RET at beg-of-buf -> Append to file as level 2 headline
8176 RET on headline -> Store as sublevel entry to current headline
8177 <left>/<right> -> before/after current headline, same headings level")
8179 ;;;###autoload
8180 (defun org-remember-apply-template ()
8181 "Initialize *remember* buffer with template, invode `org-mode'.
8182 This function should be placed into `remember-mode-hook' and in fact requires
8183 to be run from that hook to fucntion properly."
8184 (when org-remember-templates
8185 (let* ((entry (if (= (length org-remember-templates) 1)
8186 (cdar org-remember-templates)
8187 (message "Select template: %s"
8188 (mapconcat
8189 (lambda (x) (char-to-string (car x)))
8190 org-remember-templates " "))
8191 (cdr (assoc (read-char-exclusive) org-remember-templates))))
8192 (tpl (if (consp (cdr entry)) (cadr entry) (cdr entry)))
8193 (file (if (consp (cdr entry)) (nth 2 entry)))
8194 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
8195 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
8196 (v-u (concat "[" (substring v-t 1 -1) "]"))
8197 (v-U (concat "[" (substring v-T 1 -1) "]"))
8198 (v-a annotation) ; defined in `remember-mode'
8199 (v-i initial) ; defined in `remember-mode'
8200 (v-n user-full-name)
8202 (unless tpl (setq tpl "") (message "No template") (ding))
8203 (insert tpl) (goto-char (point-min))
8204 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
8205 (when (and initial (equal (match-string 0) "%i"))
8206 (save-match-data
8207 (let* ((lead (buffer-substring
8208 (point-at-bol) (match-beginning 0))))
8209 (setq v-i (mapconcat 'identity
8210 (org-split-string initial "\n")
8211 (concat "\n" lead))))))
8212 (replace-match
8213 (or (eval (intern (concat "v-" (match-string 1)))) "")
8214 t t))
8215 (let ((org-startup-folded nil)
8216 (org-startup-with-deadline-check nil))
8217 (org-mode))
8218 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
8219 (set (make-local-variable 'org-default-notes-file) file))
8220 (goto-char (point-min))
8221 (if (re-search-forward "%\\?" nil t) (replace-match ""))
8222 (set (make-local-variable 'org-finish-function) 'remember-buffer))))
8224 ;;;###autoload
8225 (defun org-remember-handler ()
8226 "Store stuff from remember.el into an org file.
8227 First prompts for an org file. If the user just presses return, the value
8228 of `org-default-notes-file' is used.
8229 Then the command offers the headings tree of the selected file in order to
8230 file the text at a specific location.
8231 You can either immediately press RET to get the note appended to the
8232 file, or you can use vertical cursor motion and visibility cycling (TAB) to
8233 find a better place. Then press RET or <left> or <right> in insert the note.
8235 Key Cursor position Note gets inserted
8236 -----------------------------------------------------------------------------
8237 RET buffer-start as level 2 heading at end of file
8238 RET on headline as sublevel of the heading at cursor
8239 RET no heading at cursor position, level taken from context.
8240 Or use prefix arg to specify level manually.
8241 <left> on headline as same level, before current heading
8242 <right> on headline as same level, after current heading
8244 So the fastest way to store the note is to press RET RET to append it to
8245 the default file. This way your current train of thought is not
8246 interrupted, in accordance with the principles of remember.el. But with
8247 little extra effort, you can push it directly to the correct location.
8249 Before being stored away, the function ensures that the text has a
8250 headline, i.e. a first line that starts with a \"*\". If not, a headline
8251 is constructed from the current date and some additional data.
8253 If the variable `org-adapt-indentation' is non-nil, the entire text is
8254 also indented so that it starts in the same column as the headline
8255 \(i.e. after the stars).
8257 See also the variable `org-reverse-note-order'."
8258 (catch 'quit
8259 (let* ((txt (buffer-substring (point-min) (point-max)))
8260 (fastp current-prefix-arg)
8261 (file (if fastp org-default-notes-file (org-get-org-file)))
8262 (visiting (find-buffer-visiting file))
8263 (org-startup-with-deadline-check nil)
8264 (org-startup-folded nil)
8265 (org-startup-align-all-tables nil)
8266 spos level indent reversed)
8267 ;; Modify text so that it becomes a nice subtree which can be inserted
8268 ;; into an org tree.
8269 (let* ((lines (split-string txt "\n"))
8270 first)
8271 ;; remove empty lines at the beginning
8272 (while (and lines (string-match "^[ \t]*\n" (car lines)))
8273 (setq lines (cdr lines)))
8274 (setq first (car lines) lines (cdr lines))
8275 (if (string-match "^\\*+" first)
8276 ;; Is already a headline
8277 (setq indent nil)
8278 ;; We need to add a headline: Use time and first buffer line
8279 (setq lines (cons first lines)
8280 first (concat "* " (current-time-string)
8281 " (" (remember-buffer-desc) ")")
8282 indent " "))
8283 (if (and org-adapt-indentation indent)
8284 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
8285 (setq txt (concat first "\n"
8286 (mapconcat 'identity lines "\n"))))
8287 ;; Find the file
8288 (if (not visiting)
8289 (find-file-noselect file))
8290 (with-current-buffer (get-file-buffer file)
8291 (setq reversed (org-notes-order-reversed-p))
8292 (save-excursion
8293 (save-restriction
8294 (widen)
8295 ;; Ask the User for a location
8296 (setq spos (if fastp 1 (org-get-location
8297 (current-buffer)
8298 org-remember-help)))
8299 (if (not spos) (throw 'quit nil)) ; return nil to show we did
8300 ; not handle this note
8301 (goto-char spos)
8302 (cond ((bobp)
8303 ;; Put it at the start or end, as level 2
8304 (save-restriction
8305 (widen)
8306 (goto-char (if reversed (point-min) (point-max)))
8307 (if (not (bolp)) (newline))
8308 (org-paste-subtree 2 txt)))
8309 ((and (org-on-heading-p nil) (not current-prefix-arg))
8310 ;; Put it below this entry, at the beg/end of the subtree
8311 (org-back-to-heading)
8312 (setq level (funcall outline-level))
8313 (if reversed
8314 (outline-end-of-heading)
8315 (outline-end-of-subtree))
8316 (if (not (bolp)) (newline))
8317 (beginning-of-line 1)
8318 (org-paste-subtree (1+ level) txt))
8320 ;; Put it right there, with automatic level determined by
8321 ;; org-paste-subtree or from prefix arg
8322 (org-paste-subtree current-prefix-arg txt)))
8323 (when remember-save-after-remembering
8324 (save-buffer)
8325 (if (not visiting) (kill-buffer (current-buffer)))))))))
8326 t) ;; return t to indicate that we took care of this note.
8328 (defun org-get-org-file ()
8329 "Read a filename, with default directory `org-directory'."
8330 (let ((default (or org-default-notes-file remember-data-file)))
8331 (read-file-name (format "File name [%s]: " default)
8332 (file-name-as-directory org-directory)
8333 default)))
8335 (defun org-notes-order-reversed-p ()
8336 "Check if the current file should receive notes in reversed order."
8337 (cond
8338 ((not org-reverse-note-order) nil)
8339 ((eq t org-reverse-note-order) t)
8340 ((not (listp org-reverse-note-order)) nil)
8341 (t (catch 'exit
8342 (let ((all org-reverse-note-order)
8343 entry)
8344 (while (setq entry (pop all))
8345 (if (string-match (car entry) buffer-file-name)
8346 (throw 'exit (cdr entry))))
8347 nil)))))
8349 ;;; Tables
8351 ;; Watch out: Here we are talking about two different kind of tables.
8352 ;; Most of the code is for the tables created with the Org-mode table editor.
8353 ;; Sometimes, we talk about tables created and edited with the table.el
8354 ;; Emacs package. We call the former org-type tables, and the latter
8355 ;; table.el-type tables.
8358 (defun org-before-change-function (beg end)
8359 "Every change indicates that a table might need an update."
8360 (setq org-table-may-need-update t))
8362 (defconst org-table-line-regexp "^[ \t]*|"
8363 "Detects an org-type table line.")
8364 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8365 "Detects an org-type table line.")
8366 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8367 "Detects a table line marked for automatic recalculation.")
8368 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8369 "Detects a table line marked for automatic recalculation.")
8370 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8371 "Detects a table line marked for automatic recalculation.")
8372 (defconst org-table-hline-regexp "^[ \t]*|-"
8373 "Detects an org-type table hline.")
8374 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8375 "Detects a table-type table hline.")
8376 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8377 "Detects an org-type or table-type table.")
8378 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8379 "Searching from within a table (any type) this finds the first line
8380 outside the table.")
8381 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8382 "Searching from within a table (any type) this finds the first line
8383 outside the table.")
8385 (defun org-table-create-with-table.el ()
8386 "Use the table.el package to insert a new table.
8387 If there is already a table at point, convert between Org-mode tables
8388 and table.el tables."
8389 (interactive)
8390 (require 'table)
8391 (cond
8392 ((org-at-table.el-p)
8393 (if (y-or-n-p "Convert table to Org-mode table? ")
8394 (org-table-convert)))
8395 ((org-at-table-p)
8396 (if (y-or-n-p "Convert table to table.el table? ")
8397 (org-table-convert)))
8398 (t (call-interactively 'table-insert))))
8400 (defun org-table-create-or-convert-from-region (arg)
8401 "Convert region to table, or create an empty table.
8402 If there is an active region, convert it to a table. If there is no such
8403 region, create an empty table."
8404 (interactive "P")
8405 (if (org-region-active-p)
8406 (org-table-convert-region (region-beginning) (region-end) arg)
8407 (org-table-create arg)))
8409 (defun org-table-create (&optional size)
8410 "Query for a size and insert a table skeleton.
8411 SIZE is a string Columns x Rows like for example \"3x2\"."
8412 (interactive "P")
8413 (unless size
8414 (setq size (read-string
8415 (concat "Table size Columns x Rows [e.g. "
8416 org-table-default-size "]: ")
8417 "" nil org-table-default-size)))
8419 (let* ((pos (point))
8420 (indent (make-string (current-column) ?\ ))
8421 (split (org-split-string size " *x *"))
8422 (rows (string-to-number (nth 1 split)))
8423 (columns (string-to-number (car split)))
8424 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8425 "\n")))
8426 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8427 (point-at-bol) (point)))
8428 (beginning-of-line 1)
8429 (newline))
8430 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8431 (dotimes (i rows) (insert line))
8432 (goto-char pos)
8433 (if (> rows 1)
8434 ;; Insert a hline after the first row.
8435 (progn
8436 (end-of-line 1)
8437 (insert "\n|-")
8438 (goto-char pos)))
8439 (org-table-align)))
8441 (defun org-table-convert-region (beg0 end0 &optional nspace)
8442 "Convert region to a table.
8443 The region goes from BEG0 to END0, but these borders will be moved
8444 slightly, to make sure a beginning of line in the first line is included.
8445 When NSPACE is non-nil, it indicates the minimum number of spaces that
8446 separate columns (default: just one space)."
8447 (interactive "rP")
8448 (let* ((beg (min beg0 end0))
8449 (end (max beg0 end0))
8450 (tabsep t)
8452 (goto-char beg)
8453 (beginning-of-line 1)
8454 (setq beg (move-marker (make-marker) (point)))
8455 (goto-char end)
8456 (if (bolp) (backward-char 1) (end-of-line 1))
8457 (setq end (move-marker (make-marker) (point)))
8458 ;; Lets see if this is tab-separated material. If every nonempty line
8459 ;; contains a tab, we will assume that it is tab-separated material
8460 (if nspace
8461 (setq tabsep nil)
8462 (goto-char beg)
8463 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
8464 (if nspace (setq tabsep nil))
8465 (if tabsep
8466 (setq re "^\\|\t")
8467 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
8468 (max 1 (prefix-numeric-value nspace)))))
8469 (goto-char beg)
8470 (while (re-search-forward re end t)
8471 (replace-match "|" t t))
8472 (goto-char beg)
8473 (insert " ")
8474 (org-table-align)))
8476 (defun org-table-import (file arg)
8477 "Import FILE as a table.
8478 The file is assumed to be tab-separated. Such files can be produced by most
8479 spreadsheet and database applications. If no tabs (at least one per line)
8480 are found, lines will be split on whitespace into fields."
8481 (interactive "f\nP")
8482 (or (bolp) (newline))
8483 (let ((beg (point))
8484 (pm (point-max)))
8485 (insert-file-contents file)
8486 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8488 (defun org-table-export ()
8489 "Export table as a tab-separated file.
8490 Such a file can be imported into a spreadsheet program like Excel."
8491 (interactive)
8492 (let* ((beg (org-table-begin))
8493 (end (org-table-end))
8494 (table (buffer-substring beg end))
8495 (file (read-file-name "Export table to: "))
8496 buf)
8497 (unless (or (not (file-exists-p file))
8498 (y-or-n-p (format "Overwrite file %s? " file)))
8499 (error "Abort"))
8500 (with-current-buffer (find-file-noselect file)
8501 (setq buf (current-buffer))
8502 (erase-buffer)
8503 (fundamental-mode)
8504 (insert table)
8505 (goto-char (point-min))
8506 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8507 (replace-match "" t t)
8508 (end-of-line 1))
8509 (goto-char (point-min))
8510 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8511 (replace-match "" t t)
8512 (goto-char (min (1+ (point)) (point-max))))
8513 (goto-char (point-min))
8514 (while (re-search-forward "^-[-+]*$" nil t)
8515 (replace-match "")
8516 (if (looking-at "\n")
8517 (delete-char 1)))
8518 (goto-char (point-min))
8519 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8520 (replace-match "\t" t t))
8521 (save-buffer))
8522 (kill-buffer buf)))
8524 (defvar org-table-aligned-begin-marker (make-marker)
8525 "Marker at the beginning of the table last aligned.
8526 Used to check if cursor still is in that table, to minimize realignment.")
8527 (defvar org-table-aligned-end-marker (make-marker)
8528 "Marker at the end of the table last aligned.
8529 Used to check if cursor still is in that table, to minimize realignment.")
8530 (defvar org-table-last-alignment nil
8531 "List of flags for flushright alignment, from the last re-alignment.
8532 This is being used to correctly align a single field after TAB or RET.")
8533 (defvar org-table-last-column-widths nil
8534 "List of max width of fields in each column.
8535 This is being used to correctly align a single field after TAB or RET.")
8537 (defvar org-last-recalc-line nil)
8538 (defconst org-narrow-column-arrow "=>"
8539 "Used as display property in narrowed table columns.")
8541 (defun org-table-align ()
8542 "Align the table at point by aligning all vertical bars."
8543 (interactive)
8544 (let* (
8545 ;; Limits of table
8546 (beg (org-table-begin))
8547 (end (org-table-end))
8548 ;; Current cursor position
8549 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8550 (colpos (org-table-current-column))
8551 (winstart (window-start))
8552 text lines (new "") lengths l typenums ty fields maxfields i
8553 column
8554 (indent "") cnt frac
8555 rfmt hfmt
8556 (spaces '(1 . 1))
8557 (sp1 (car spaces))
8558 (sp2 (cdr spaces))
8559 (rfmt1 (concat
8560 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8561 (hfmt1 (concat
8562 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8563 emptystrings xx links narrow fmax fmin f1 len c e)
8564 (untabify beg end)
8565 (remove-text-properties beg end '(org-cwidth t display t))
8566 ;; Check if we have links
8567 (goto-char beg)
8568 (setq links (re-search-forward org-bracket-link-regexp end t))
8569 ;; Make sure the link properties are right FIXME: Can this be optimized????
8570 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8571 ;; Check if we are narrowing any columns
8572 (goto-char beg)
8573 (setq narrow (and org-format-transports-properties-p
8574 (re-search-forward "<[0-9]+>" end t)))
8575 ;; Get the rows
8576 (setq lines (org-split-string
8577 (buffer-substring beg end) "\n"))
8578 ;; Store the indentation of the first line
8579 (if (string-match "^ *" (car lines))
8580 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8581 ;; Mark the hlines by setting the corresponding element to nil
8582 ;; At the same time, we remove trailing space.
8583 (setq lines (mapcar (lambda (l)
8584 (if (string-match "^ *|-" l)
8586 (if (string-match "[ \t]+$" l)
8587 (substring l 0 (match-beginning 0))
8588 l)))
8589 lines))
8590 ;; Get the data fields by splitting the lines.
8591 (setq fields (mapcar
8592 (lambda (l)
8593 (org-split-string l " *| *"))
8594 (delq nil (copy-sequence lines))))
8595 ;; How many fields in the longest line?
8596 (condition-case nil
8597 (setq maxfields (apply 'max (mapcar 'length fields)))
8598 (error
8599 (kill-region beg end)
8600 (org-table-create org-table-default-size)
8601 (error "Empty table - created default table")))
8602 ;; A list of empty string to fill any short rows on output
8603 (setq emptystrings (make-list maxfields ""))
8604 ;; Check for special formatting.
8605 (setq i -1)
8606 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8607 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8608 ;; Check if there is an explicit width specified
8609 (when (and org-table-limit-column-width narrow)
8610 (setq c column fmax nil)
8611 (while c
8612 (setq e (pop c))
8613 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8614 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8615 ;; Find fields that are wider than fmax, and shorten them
8616 (when fmax
8617 (loop for xx in column do
8618 (when (and (stringp xx)
8619 (> (org-string-width xx) fmax))
8620 (org-add-props xx nil
8621 'help-echo
8622 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (copy-sequence xx)))
8623 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8624 (unless (> f1 1)
8625 (error "Cannot narrow field starting with wide link \"%s\""
8626 (match-string 0 xx)))
8627 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8628 (add-text-properties (- f1 2) f1
8629 (list 'display org-narrow-column-arrow)
8630 xx)))))
8631 ;; Get the maximum width for each column
8632 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8633 ;; Get the fraction of numbers, to decide about alignment of the column
8634 (setq cnt 0 frac 0.0)
8635 (loop for x in column do
8636 (if (equal x "")
8638 (setq frac ( / (+ (* frac cnt)
8639 (if (string-match org-table-number-regexp x) 1 0))
8640 (setq cnt (1+ cnt))))))
8641 (push (>= frac org-table-number-fraction) typenums))
8642 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8644 ;; Store the alignment of this table, for later editing of single fields
8645 (setq org-table-last-alignment typenums
8646 org-table-last-column-widths lengths)
8648 ;; With invisible characters, `format' does not get the field width right
8649 ;; So we need to make these fields wide by hand.
8650 (when links
8651 (loop for i from 0 upto (1- maxfields) do
8652 (setq len (nth i lengths))
8653 (loop for j from 0 upto (1- (length fields)) do
8654 (setq c (nthcdr i (car (nthcdr j fields))))
8655 (if (and (stringp (car c))
8656 (string-match org-bracket-link-regexp (car c))
8657 (< (org-string-width (car c)) len))
8658 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8660 ;; Compute the formats needed for output of the table
8661 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8662 (while (setq l (pop lengths))
8663 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8664 (setq rfmt (concat rfmt (format rfmt1 ty l))
8665 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8666 (setq rfmt (concat rfmt "\n")
8667 hfmt (concat (substring hfmt 0 -1) "|\n"))
8669 (setq new (mapconcat
8670 (lambda (l)
8671 (if l (apply 'format rfmt
8672 (append (pop fields) emptystrings))
8673 hfmt))
8674 lines ""))
8675 ;; Replace the old one
8676 (delete-region beg end)
8677 (move-marker end nil)
8678 (move-marker org-table-aligned-begin-marker (point))
8679 (insert new)
8680 (move-marker org-table-aligned-end-marker (point))
8681 (when (and orgtbl-mode (not (eq major-mode 'org-mode)))
8682 (goto-char org-table-aligned-begin-marker)
8683 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8684 ;; Try to move to the old location (approximately)
8685 (goto-line linepos)
8686 (set-window-start (selected-window) winstart 'noforce)
8687 (org-table-goto-column colpos)
8688 (setq org-table-may-need-update nil)
8691 (defun org-string-width (s)
8692 "Compute width of string, ignoring invisible characters.
8693 This ignores character with invisibility property `org-link', and also
8694 characters with property `org-cwidth', because these will become invisible
8695 upon the next fontification round."
8696 (let (b)
8697 (when (or (eq t buffer-invisibility-spec)
8698 (assq 'org-link buffer-invisibility-spec))
8699 (while (setq b (text-property-any 0 (length s)
8700 'invisible 'org-link s))
8701 (setq s (concat (substring s 0 b)
8702 (substring s (or (next-single-property-change
8703 b 'invisible s) (length s)))))))
8704 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8705 (setq s (concat (substring s 0 b)
8706 (substring s (or (next-single-property-change
8707 b 'org-cwidth s) (length s))))))
8708 (string-width s)))
8710 (defun org-table-begin (&optional table-type)
8711 "Find the beginning of the table and return its position.
8712 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8713 (save-excursion
8714 (if (not (re-search-backward
8715 (if table-type org-table-any-border-regexp
8716 org-table-border-regexp)
8717 nil t))
8718 (error "Can't find beginning of table")
8719 (goto-char (match-beginning 0))
8720 (beginning-of-line 2)
8721 (point))))
8723 (defun org-table-end (&optional table-type)
8724 "Find the end of the table and return its position.
8725 With argument TABLE-TYPE, go to the end of a table.el-type table."
8726 (save-excursion
8727 (if (not (re-search-forward
8728 (if table-type org-table-any-border-regexp
8729 org-table-border-regexp)
8730 nil t))
8731 (goto-char (point-max))
8732 (goto-char (match-beginning 0)))
8733 (point-marker)))
8735 (defun org-table-justify-field-maybe (&optional new)
8736 "Justify the current field, text to left, number to right.
8737 Optional argument NEW may specify text to replace the current field content."
8738 (cond
8739 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8740 ((org-at-table-hline-p))
8741 ((and (not new)
8742 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8743 (current-buffer)))
8744 (< (point) org-table-aligned-begin-marker)
8745 (>= (point) org-table-aligned-end-marker)))
8746 ;; This is not the same table, force a full re-align
8747 (setq org-table-may-need-update t))
8748 (t ;; realign the current field, based on previous full realign
8749 (let* ((pos (point)) s
8750 (col (org-table-current-column))
8751 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8752 l f n o e)
8753 (when (> col 0)
8754 (skip-chars-backward "^|\n")
8755 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8756 (progn
8757 (setq s (match-string 1)
8758 o (match-string 0)
8759 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8760 e (not (= (match-beginning 2) (match-end 2))))
8761 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8762 l (if e "|" (setq org-table-may-need-update t) ""))
8763 n (format f s t t))
8764 (if new
8765 (if (<= (length new) l)
8766 (setq n (format f new t t)) ;; FIXME: why t t?????
8767 (setq n (concat new "|") org-table-may-need-update t)))
8768 (or (equal n o)
8769 (let (org-table-may-need-update)
8770 (replace-match n))))
8771 (setq org-table-may-need-update t))
8772 (goto-char pos))))))
8774 (defun org-table-next-field ()
8775 "Go to the next field in the current table, creating new lines as needed.
8776 Before doing so, re-align the table if necessary."
8777 (interactive)
8778 (org-table-maybe-eval-formula)
8779 (org-table-maybe-recalculate-line)
8780 (if (and org-table-automatic-realign
8781 org-table-may-need-update)
8782 (org-table-align))
8783 (let ((end (org-table-end)))
8784 (if (org-at-table-hline-p)
8785 (end-of-line 1))
8786 (condition-case nil
8787 (progn
8788 (re-search-forward "|" end)
8789 (if (looking-at "[ \t]*$")
8790 (re-search-forward "|" end))
8791 (if (and (looking-at "-")
8792 org-table-tab-jumps-over-hlines
8793 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8794 (goto-char (match-beginning 1)))
8795 (if (looking-at "-")
8796 (progn
8797 (beginning-of-line 0)
8798 (org-table-insert-row 'below))
8799 (if (looking-at " ") (forward-char 1))))
8800 (error
8801 (org-table-insert-row 'below)))))
8803 (defun org-table-previous-field ()
8804 "Go to the previous field in the table.
8805 Before doing so, re-align the table if necessary."
8806 (interactive)
8807 (org-table-justify-field-maybe)
8808 (org-table-maybe-recalculate-line)
8809 (if (and org-table-automatic-realign
8810 org-table-may-need-update)
8811 (org-table-align))
8812 (if (org-at-table-hline-p)
8813 (end-of-line 1))
8814 (re-search-backward "|" (org-table-begin))
8815 (re-search-backward "|" (org-table-begin))
8816 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8817 (re-search-backward "|" (org-table-begin)))
8818 (if (looking-at "| ?")
8819 (goto-char (match-end 0))))
8821 (defun org-table-next-row ()
8822 "Go to the next row (same column) in the current table.
8823 Before doing so, re-align the table if necessary."
8824 (interactive)
8825 (org-table-maybe-eval-formula)
8826 (org-table-maybe-recalculate-line)
8827 (if (or (looking-at "[ \t]*$")
8828 (save-excursion (skip-chars-backward " \t") (bolp)))
8829 (newline)
8830 (if (and org-table-automatic-realign
8831 org-table-may-need-update)
8832 (org-table-align))
8833 (let ((col (org-table-current-column)))
8834 (beginning-of-line 2)
8835 (if (or (not (org-at-table-p))
8836 (org-at-table-hline-p))
8837 (progn
8838 (beginning-of-line 0)
8839 (org-table-insert-row 'below)))
8840 (org-table-goto-column col)
8841 (skip-chars-backward "^|\n\r")
8842 (if (looking-at " ") (forward-char 1)))))
8844 (defun org-table-copy-down (n)
8845 "Copy a field down in the current column.
8846 If the field at the cursor is empty, copy into it the content of the nearest
8847 non-empty field above. With argument N, use the Nth non-empty field.
8848 If the current field is not empty, it is copied down to the next row, and
8849 the cursor is moved with it. Therefore, repeating this command causes the
8850 column to be filled row-by-row.
8851 If the variable `org-table-copy-increment' is non-nil and the field is an
8852 integer, it will be incremented while copying."
8853 (interactive "p")
8854 (let* ((colpos (org-table-current-column))
8855 (field (org-table-get-field))
8856 (non-empty (string-match "[^ \t]" field))
8857 (beg (org-table-begin))
8858 txt)
8859 (org-table-check-inside-data-field)
8860 (if non-empty
8861 (progn
8862 (setq txt (org-trim field))
8863 (org-table-next-row)
8864 (org-table-blank-field))
8865 (save-excursion
8866 (setq txt
8867 (catch 'exit
8868 (while (progn (beginning-of-line 1)
8869 (re-search-backward org-table-dataline-regexp
8870 beg t))
8871 (org-table-goto-column colpos t)
8872 (if (and (looking-at
8873 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8874 (= (setq n (1- n)) 0))
8875 (throw 'exit (match-string 1))))))))
8876 (if txt
8877 (progn
8878 (if (and org-table-copy-increment
8879 (string-match "^[0-9]+$" txt))
8880 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8881 (insert txt)
8882 (org-table-maybe-recalculate-line)
8883 (org-table-align))
8884 (error "No non-empty field found"))))
8886 (defun org-table-check-inside-data-field ()
8887 "Is point inside a table data field?
8888 I.e. not on a hline or before the first or after the last column?
8889 This actually throws an error, so it aborts the current command."
8890 (if (or (not (org-at-table-p))
8891 (= (org-table-current-column) 0)
8892 (org-at-table-hline-p)
8893 (looking-at "[ \t]*$"))
8894 (error "Not in table data field")))
8896 (defvar org-table-clip nil
8897 "Clipboard for table regions.")
8899 (defun org-table-blank-field ()
8900 "Blank the current table field or active region."
8901 (interactive)
8902 (org-table-check-inside-data-field)
8903 (if (and (interactive-p) (org-region-active-p))
8904 (let (org-table-clip)
8905 (org-table-cut-region (region-beginning) (region-end)))
8906 (skip-chars-backward "^|")
8907 (backward-char 1)
8908 (if (looking-at "|[^|\n]+")
8909 (let* ((pos (match-beginning 0))
8910 (match (match-string 0))
8911 (len (org-string-width match)))
8912 (replace-match (concat "|" (make-string (1- len) ?\ )))
8913 (goto-char (+ 2 pos))
8914 (substring match 1)))))
8916 (defun org-table-get-field (&optional n replace)
8917 "Return the value of the field in column N of current row.
8918 N defaults to current field.
8919 If REPLACE is a string, replace field with this value. The return value
8920 is always the old value."
8921 (and n (org-table-goto-column n))
8922 (skip-chars-backward "^|\n")
8923 (backward-char 1)
8924 (if (looking-at "|[^|\r\n]*")
8925 (let* ((pos (match-beginning 0))
8926 (val (buffer-substring (1+ pos) (match-end 0))))
8927 (if replace
8928 (replace-match (concat "|" replace)))
8929 (goto-char (min (point-at-eol) (+ 2 pos)))
8930 val)
8931 (forward-char 1) ""))
8933 (defun org-table-current-column ()
8934 "Find out which column we are in.
8935 When called interactively, column is also displayed in echo area."
8936 (interactive)
8937 (if (interactive-p) (org-table-check-inside-data-field))
8938 (save-excursion
8939 (let ((cnt 0) (pos (point)))
8940 (beginning-of-line 1)
8941 (while (search-forward "|" pos t)
8942 (setq cnt (1+ cnt)))
8943 (if (interactive-p) (message "This is table column %d" cnt))
8944 cnt)))
8946 (defun org-table-goto-column (n &optional on-delim force)
8947 "Move the cursor to the Nth column in the current table line.
8948 With optional argument ON-DELIM, stop with point before the left delimiter
8949 of the field.
8950 If there are less than N fields, just go to after the last delimiter.
8951 However, when FORCE is non-nil, create new columns if necessary."
8952 (interactive "p")
8953 (let ((pos (point-at-eol)))
8954 (beginning-of-line 1)
8955 (when (> n 0)
8956 (while (and (> (setq n (1- n)) -1)
8957 (or (search-forward "|" pos t)
8958 (and force
8959 (progn (end-of-line 1)
8960 (skip-chars-backward "^|")
8961 (insert " | "))))))
8962 ; (backward-char 2) t)))))
8963 (when (and force (not (looking-at ".*|")))
8964 (save-excursion (end-of-line 1) (insert " | ")))
8965 (if on-delim
8966 (backward-char 1)
8967 (if (looking-at " ") (forward-char 1))))))
8969 (defun org-at-table-p (&optional table-type)
8970 "Return t if the cursor is inside an org-type table.
8971 If TABLE-TYPE is non-nil, also check for table.el-type tables."
8972 (if org-enable-table-editor
8973 (save-excursion
8974 (beginning-of-line 1)
8975 (looking-at (if table-type org-table-any-line-regexp
8976 org-table-line-regexp)))
8977 nil))
8979 (defun org-at-table.el-p ()
8980 "Return t if and only if we are at a table.el table."
8981 (and (org-at-table-p 'any)
8982 (save-excursion
8983 (goto-char (org-table-begin 'any))
8984 (looking-at org-table1-hline-regexp))))
8986 (defun org-table-recognize-table.el ()
8987 "If there is a table.el table nearby, recognize it and move into it."
8988 (if org-table-tab-recognizes-table.el
8989 (if (org-at-table.el-p)
8990 (progn
8991 (beginning-of-line 1)
8992 (if (looking-at org-table-dataline-regexp)
8994 (if (looking-at org-table1-hline-regexp)
8995 (progn
8996 (beginning-of-line 2)
8997 (if (looking-at org-table-any-border-regexp)
8998 (beginning-of-line -1)))))
8999 (if (re-search-forward "|" (org-table-end t) t)
9000 (progn
9001 (require 'table)
9002 (if (table--at-cell-p (point))
9004 (message "recognizing table.el table...")
9005 (table-recognize-table)
9006 (message "recognizing table.el table...done")))
9007 (error "This should not happen..."))
9009 nil)
9010 nil))
9012 (defun org-at-table-hline-p ()
9013 "Return t if the cursor is inside a hline in a table."
9014 (if org-enable-table-editor
9015 (save-excursion
9016 (beginning-of-line 1)
9017 (looking-at org-table-hline-regexp))
9018 nil))
9020 (defun org-table-insert-column ()
9021 "Insert a new column into the table."
9022 (interactive)
9023 (if (not (org-at-table-p))
9024 (error "Not at a table"))
9025 (org-table-find-dataline)
9026 (let* ((col (max 1 (org-table-current-column)))
9027 (beg (org-table-begin))
9028 (end (org-table-end))
9029 ;; Current cursor position
9030 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9031 (colpos col))
9032 (goto-char beg)
9033 (while (< (point) end)
9034 (if (org-at-table-hline-p)
9036 (org-table-goto-column col t)
9037 (insert "| "))
9038 (beginning-of-line 2))
9039 (move-marker end nil)
9040 (goto-line linepos)
9041 (org-table-goto-column colpos)
9042 (org-table-align)
9043 (org-table-modify-formulas 'insert col)))
9045 (defun org-table-find-dataline ()
9046 "Find a dataline in the current table, which is needed for column commands."
9047 (if (and (org-at-table-p)
9048 (not (org-at-table-hline-p)))
9050 (let ((col (current-column))
9051 (end (org-table-end)))
9052 (move-to-column col)
9053 (while (and (< (point) end)
9054 (or (not (= (current-column) col))
9055 (org-at-table-hline-p)))
9056 (beginning-of-line 2)
9057 (move-to-column col))
9058 (if (and (org-at-table-p)
9059 (not (org-at-table-hline-p)))
9061 (error
9062 "Please position cursor in a data line for column operations")))))
9064 (defun org-table-delete-column ()
9065 "Delete a column into the table."
9066 (interactive)
9067 (if (not (org-at-table-p))
9068 (error "Not at a table"))
9069 (org-table-find-dataline)
9070 (org-table-check-inside-data-field)
9071 (let* ((col (org-table-current-column))
9072 (beg (org-table-begin))
9073 (end (org-table-end))
9074 ;; Current cursor position
9075 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9076 (colpos col))
9077 (goto-char beg)
9078 (while (< (point) end)
9079 (if (org-at-table-hline-p)
9081 (org-table-goto-column col t)
9082 (and (looking-at "|[^|\n]+|")
9083 (replace-match "|")))
9084 (beginning-of-line 2))
9085 (move-marker end nil)
9086 (goto-line linepos)
9087 (org-table-goto-column colpos)
9088 (org-table-align)
9089 (org-table-modify-formulas 'remove col)))
9091 (defun org-table-move-column-right ()
9092 "Move column to the right."
9093 (interactive)
9094 (org-table-move-column nil))
9095 (defun org-table-move-column-left ()
9096 "Move column to the left."
9097 (interactive)
9098 (org-table-move-column 'left))
9100 (defun org-table-move-column (&optional left)
9101 "Move the current column to the right. With arg LEFT, move to the left."
9102 (interactive "P")
9103 (if (not (org-at-table-p))
9104 (error "Not at a table"))
9105 (org-table-find-dataline)
9106 (org-table-check-inside-data-field)
9107 (let* ((col (org-table-current-column))
9108 (col1 (if left (1- col) col))
9109 (beg (org-table-begin))
9110 (end (org-table-end))
9111 ;; Current cursor position
9112 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9113 (colpos (if left (1- col) (1+ col))))
9114 (if (and left (= col 1))
9115 (error "Cannot move column further left"))
9116 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9117 (error "Cannot move column further right"))
9118 (goto-char beg)
9119 (while (< (point) end)
9120 (if (org-at-table-hline-p)
9122 (org-table-goto-column col1 t)
9123 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9124 (replace-match "|\\2|\\1|")))
9125 (beginning-of-line 2))
9126 (move-marker end nil)
9127 (goto-line linepos)
9128 (org-table-goto-column colpos)
9129 (org-table-align)
9130 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
9132 (defun org-table-move-row-down ()
9133 "Move table row down."
9134 (interactive)
9135 (org-table-move-row nil))
9136 (defun org-table-move-row-up ()
9137 "Move table row up."
9138 (interactive)
9139 (org-table-move-row 'up))
9141 (defun org-table-move-row (&optional up)
9142 "Move the current table line down. With arg UP, move it up."
9143 (interactive "P")
9144 (let ((col (current-column))
9145 (pos (point))
9146 (tonew (if up 0 2))
9147 txt)
9148 (beginning-of-line tonew)
9149 (if (not (org-at-table-p))
9150 (progn
9151 (goto-char pos)
9152 (error "Cannot move row further")))
9153 (goto-char pos)
9154 (beginning-of-line 1)
9155 (setq pos (point))
9156 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9157 (delete-region (point) (1+ (point-at-eol)))
9158 (beginning-of-line tonew)
9159 (insert txt)
9160 (beginning-of-line 0)
9161 (move-to-column col)))
9163 (defun org-table-insert-row (&optional arg)
9164 "Insert a new row above the current line into the table.
9165 With prefix ARG, insert below the current line."
9166 (interactive "P")
9167 (if (not (org-at-table-p))
9168 (error "Not at a table"))
9169 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9170 (new (org-table-clean-line line)))
9171 ;; Fix the first field if necessary
9172 (if (string-match "^[ \t]*| *[#$] *|" line)
9173 (setq new (replace-match (match-string 0 line) t t new)))
9174 (beginning-of-line (if arg 2 1))
9175 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9176 (beginning-of-line 0)
9177 (re-search-forward "| ?" (point-at-eol) t)
9178 (and org-table-may-need-update (org-table-align))))
9180 (defun org-table-insert-hline (&optional arg)
9181 "Insert a horizontal-line below the current line into the table.
9182 With prefix ARG, insert above the current line."
9183 (interactive "P")
9184 (if (not (org-at-table-p))
9185 (error "Not at a table"))
9186 (let ((line (org-table-clean-line
9187 (buffer-substring (point-at-bol) (point-at-eol))))
9188 (col (current-column)))
9189 (while (string-match "|\\( +\\)|" line)
9190 (setq line (replace-match
9191 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9192 ?-) "|") t t line)))
9193 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9194 (beginning-of-line (if arg 1 2))
9195 (insert line "\n")
9196 (beginning-of-line (if arg 1 -1))
9197 (move-to-column col)))
9199 (defun org-table-clean-line (s)
9200 "Convert a table line S into a string with only \"|\" and space.
9201 In particular, this does handle wide and invisible characters."
9202 (if (string-match "^[ \t]*|-" s)
9203 ;; It's a hline, just map the characters
9204 (setq s (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) s))
9205 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9206 (setq s (replace-match
9207 (concat "|" (make-string (org-string-width (match-string 1 s))
9208 ?\ ) "|")
9209 t t s)))
9212 (defun org-table-kill-row ()
9213 "Delete the current row or horizontal line from the table."
9214 (interactive)
9215 (if (not (org-at-table-p))
9216 (error "Not at a table"))
9217 (let ((col (current-column)))
9218 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9219 (if (not (org-at-table-p)) (beginning-of-line 0))
9220 (move-to-column col)))
9222 (defun org-table-sort-lines (beg end numericp)
9223 "Sort table lines in region.
9224 Point and mark define the first and last line to include. Both point and
9225 mark should be in the column that is used for sorting. For example, to
9226 sort according to column 3, put the mark in the first line to sort, in
9227 table column 3. Put point into the last line to be included in the sorting,
9228 also in table column 3. The command will prompt for the sorting method
9229 \(n for numerical, a for alphanumeric)."
9230 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
9231 (setq numericp (string-match "[nN]" numericp))
9232 (org-table-align) ;; Just to be safe
9233 (let* (bcol ecol cmp column lns)
9234 (goto-char beg)
9235 (org-table-check-inside-data-field)
9236 (setq column (org-table-current-column)
9237 beg (move-marker (make-marker) (point-at-bol)))
9238 (goto-char end)
9239 (org-table-check-inside-data-field)
9240 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
9241 (untabify beg end)
9242 (goto-char beg)
9243 (org-table-goto-column column)
9244 (skip-chars-backward "^|")
9245 (setq bcol (current-column))
9246 (org-table-goto-column (1+ column))
9247 (skip-chars-backward "^|")
9248 (setq ecol (1- (current-column)))
9249 (setq cmp (if numericp
9250 (lambda (a b) (< (car a) (car b)))
9251 (lambda (a b) (string< (car a) (car b)))))
9252 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
9253 (split-string (buffer-substring beg end) "\n")))
9254 (if numericp
9255 (setq lns (mapcar (lambda(x)
9256 (cons (string-to-number (car x)) (cdr x)))
9257 lns)))
9258 (delete-region beg end)
9259 (move-marker beg nil)
9260 (move-marker end nil)
9261 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
9262 (message "%d lines sorted %s based on column %d"
9263 (length lns)
9264 (if numericp "numerically" "alphabetically") column)))
9266 (defun org-table-cut-region (beg end)
9267 "Copy region in table to the clipboard and blank all relevant fields."
9268 (interactive "r")
9269 (org-table-copy-region beg end 'cut))
9271 (defun org-table-copy-region (beg end &optional cut)
9272 "Copy rectangular region in table to clipboard.
9273 A special clipboard is used which can only be accessed
9274 with `org-table-paste-rectangle'."
9275 (interactive "rP")
9276 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9277 region cols
9278 (rpl (if cut " " nil)))
9279 (goto-char beg)
9280 (org-table-check-inside-data-field)
9281 (setq l01 (count-lines (point-min) (point))
9282 c01 (org-table-current-column))
9283 (goto-char end)
9284 (org-table-check-inside-data-field)
9285 (setq l02 (count-lines (point-min) (point))
9286 c02 (org-table-current-column))
9287 (setq l1 (min l01 l02) l2 (max l01 l02)
9288 c1 (min c01 c02) c2 (max c01 c02))
9289 (catch 'exit
9290 (while t
9291 (catch 'nextline
9292 (if (> l1 l2) (throw 'exit t))
9293 (goto-line l1)
9294 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9295 (setq cols nil ic1 c1 ic2 c2)
9296 (while (< ic1 (1+ ic2))
9297 (push (org-table-get-field ic1 rpl) cols)
9298 (setq ic1 (1+ ic1)))
9299 (push (nreverse cols) region)
9300 (setq l1 (1+ l1)))))
9301 (setq org-table-clip (nreverse region))
9302 (if cut (org-table-align))
9303 org-table-clip))
9305 (defun org-table-paste-rectangle ()
9306 "Paste a rectangular region into a table.
9307 The upper right corner ends up in the current field. All involved fields
9308 will be overwritten. If the rectangle does not fit into the present table,
9309 the table is enlarged as needed. The process ignores horizontal separator
9310 lines."
9311 (interactive)
9312 (unless (and org-table-clip (listp org-table-clip))
9313 (error "First cut/copy a region to paste!"))
9314 (org-table-check-inside-data-field)
9315 (let* ((clip org-table-clip)
9316 (line (count-lines (point-min) (point)))
9317 (col (org-table-current-column))
9318 (org-enable-table-editor t)
9319 (org-table-automatic-realign nil)
9320 c cols field)
9321 (while (setq cols (pop clip))
9322 (while (org-at-table-hline-p) (beginning-of-line 2))
9323 (if (not (org-at-table-p))
9324 (progn (end-of-line 0) (org-table-next-field)))
9325 (setq c col)
9326 (while (setq field (pop cols))
9327 (org-table-goto-column c nil 'force)
9328 (org-table-get-field nil field)
9329 (setq c (1+ c)))
9330 (beginning-of-line 2))
9331 (goto-line line)
9332 (org-table-goto-column col)
9333 (org-table-align)))
9335 (defun org-table-convert ()
9336 "Convert from `org-mode' table to table.el and back.
9337 Obviously, this only works within limits. When an Org-mode table is
9338 converted to table.el, all horizontal separator lines get lost, because
9339 table.el uses these as cell boundaries and has no notion of horizontal lines.
9340 A table.el table can be converted to an Org-mode table only if it does not
9341 do row or column spanning. Multiline cells will become multiple cells.
9342 Beware, Org-mode does not test if the table can be successfully converted - it
9343 blindly applies a recipe that works for simple tables."
9344 (interactive)
9345 (require 'table)
9346 (if (org-at-table.el-p)
9347 ;; convert to Org-mode table
9348 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9349 (end (move-marker (make-marker) (org-table-end t))))
9350 (table-unrecognize-region beg end)
9351 (goto-char beg)
9352 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9353 (replace-match ""))
9354 (goto-char beg))
9355 (if (org-at-table-p)
9356 ;; convert to table.el table
9357 (let ((beg (move-marker (make-marker) (org-table-begin)))
9358 (end (move-marker (make-marker) (org-table-end))))
9359 ;; first, get rid of all horizontal lines
9360 (goto-char beg)
9361 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9362 (replace-match ""))
9363 ;; insert a hline before first
9364 (goto-char beg)
9365 (org-table-insert-hline 'above)
9366 (beginning-of-line -1)
9367 ;; insert a hline after each line
9368 (while (progn (beginning-of-line 3) (< (point) end))
9369 (org-table-insert-hline))
9370 (goto-char beg)
9371 (setq end (move-marker end (org-table-end)))
9372 ;; replace "+" at beginning and ending of hlines
9373 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9374 (replace-match "\\1+-"))
9375 (goto-char beg)
9376 (while (re-search-forward "-|[ \t]*$" end t)
9377 (replace-match "-+"))
9378 (goto-char beg)))))
9380 (defun org-table-wrap-region (arg)
9381 "Wrap several fields in a column like a paragraph.
9382 This is useful if you'd like to spread the contents of a field over several
9383 lines, in order to keep the table compact.
9385 If there is an active region, and both point and mark are in the same column,
9386 the text in the column is wrapped to minimum width for the given number of
9387 lines. Generally, this makes the table more compact. A prefix ARG may be
9388 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9389 formats the selected text to two lines. If the region was longer than two
9390 lines, the remaining lines remain empty. A negative prefix argument reduces
9391 the current number of lines by that amount. The wrapped text is pasted back
9392 into the table. If you formatted it to more lines than it was before, fields
9393 further down in the table get overwritten - so you might need to make space in
9394 the table first.
9396 If there is no region, the current field is split at the cursor position and
9397 the text fragment to the right of the cursor is prepended to the field one
9398 line down.
9400 If there is no region, but you specify a prefix ARG, the current field gets
9401 blank, and the content is appended to the field above."
9402 (interactive "P")
9403 (org-table-check-inside-data-field)
9404 (if (org-region-active-p)
9405 ;; There is a region: fill as a paragraph
9406 (let ((beg (region-beginning))
9407 nlines)
9408 (org-table-cut-region (region-beginning) (region-end))
9409 (if (> (length (car org-table-clip)) 1)
9410 (error "Region must be limited to single column"))
9411 (setq nlines (if arg
9412 (if (< arg 1)
9413 (+ (length org-table-clip) arg)
9414 arg)
9415 (length org-table-clip)))
9416 (setq org-table-clip
9417 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9418 nil nlines)))
9419 (goto-char beg)
9420 (org-table-paste-rectangle))
9421 ;; No region, split the current field at point
9422 (if arg
9423 ;; combine with field above
9424 (let ((s (org-table-blank-field))
9425 (col (org-table-current-column)))
9426 (beginning-of-line 0)
9427 (while (org-at-table-hline-p) (beginning-of-line 0))
9428 (org-table-goto-column col)
9429 (skip-chars-forward "^|")
9430 (skip-chars-backward " ")
9431 (insert " " (org-trim s))
9432 (org-table-align))
9433 ;; split field
9434 (when (looking-at "\\([^|]+\\)+|")
9435 (let ((s (match-string 1)))
9436 (replace-match " |")
9437 (goto-char (match-beginning 0))
9438 (org-table-next-row)
9439 (insert (org-trim s) " ")
9440 (org-table-align))))))
9442 (defvar org-field-marker nil)
9444 (defun org-table-edit-field (arg)
9445 "Edit table field in a different window.
9446 This is mainly useful for fields that contain hidden parts.
9447 When called with a \\[universal-argument] prefix, just make the full field visible so that
9448 it can be edited in place."
9449 (interactive "P")
9450 (if arg
9451 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9452 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9453 (remove-text-properties b e '(org-cwidth t invisible t
9454 display t intangible t))
9455 (if (and (boundp 'font-lock-mode) font-lock-mode)
9456 (font-lock-fontify-block)))
9457 (let ((pos (move-marker (make-marker) (point)))
9458 (field (org-table-get-field))
9459 (cw (current-window-configuration))
9461 (switch-to-buffer-other-window "*Org tmp*")
9462 (erase-buffer)
9463 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9464 (org-mode)
9465 (goto-char (setq p (point-max)))
9466 (insert (org-trim field))
9467 (remove-text-properties p (point-max)
9468 '(invisible t org-cwidth t display t
9469 intangible t))
9470 (goto-char p)
9471 (set (make-local-variable 'org-finish-function)
9472 'org-table-finish-edit-field)
9473 (set (make-local-variable 'org-window-configuration) cw)
9474 (set (make-local-variable 'org-field-marker) pos)
9475 (message "Edit and finish with C-c C-c"))))
9477 (defun org-table-finish-edit-field ()
9478 "Finish editing a table data field.
9479 Remove all newline characters, insert the result into the table, realign
9480 the table and kill the editing buffer."
9481 (let ((pos org-field-marker)
9482 (cw org-window-configuration)
9483 (cb (current-buffer))
9484 text)
9485 (goto-char (point-min))
9486 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9487 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9488 (replace-match " "))
9489 (setq text (org-trim (buffer-string)))
9490 (set-window-configuration cw)
9491 (kill-buffer cb)
9492 (select-window (get-buffer-window (marker-buffer pos)))
9493 (goto-char pos)
9494 (move-marker pos nil)
9495 (org-table-check-inside-data-field)
9496 (org-table-get-field nil text)
9497 (org-table-align)
9498 (message "New field value inserted")))
9500 (defun org-trim (s)
9501 "Remove whitespace at beginning and end of string."
9502 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
9503 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
9506 (defun org-wrap (string &optional width lines)
9507 "Wrap string to either a number of lines, or a width in characters.
9508 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9509 that costs. If there is a word longer than WIDTH, the text is actually
9510 wrapped to the length of that word.
9511 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9512 many lines, whatever width that takes.
9513 The return value is a list of lines, without newlines at the end."
9514 (let* ((words (org-split-string string "[ \t\n]+"))
9515 (maxword (apply 'max (mapcar 'org-string-width words)))
9516 w ll)
9517 (cond (width
9518 (org-do-wrap words (max maxword width)))
9519 (lines
9520 (setq w maxword)
9521 (setq ll (org-do-wrap words maxword))
9522 (if (<= (length ll) lines)
9524 (setq ll words)
9525 (while (> (length ll) lines)
9526 (setq w (1+ w))
9527 (setq ll (org-do-wrap words w)))
9528 ll))
9529 (t (error "Cannot wrap this")))))
9532 (defun org-do-wrap (words width)
9533 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9534 (let (lines line)
9535 (while words
9536 (setq line (pop words))
9537 (while (and words (< (+ (length line) (length (car words))) width))
9538 (setq line (concat line " " (pop words))))
9539 (setq lines (push line lines)))
9540 (nreverse lines)))
9542 (defun org-split-string (string &optional separators)
9543 "Splits STRING into substrings at SEPARATORS.
9544 No empty strings are returned if there are matches at the beginning
9545 and end of string."
9546 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9547 (start 0)
9548 notfirst
9549 (list nil))
9550 (while (and (string-match rexp string
9551 (if (and notfirst
9552 (= start (match-beginning 0))
9553 (< start (length string)))
9554 (1+ start) start))
9555 (< (match-beginning 0) (length string)))
9556 (setq notfirst t)
9557 (or (eq (match-beginning 0) 0)
9558 (and (eq (match-beginning 0) (match-end 0))
9559 (eq (match-beginning 0) start))
9560 (setq list
9561 (cons (substring string start (match-beginning 0))
9562 list)))
9563 (setq start (match-end 0)))
9564 (or (eq start (length string))
9565 (setq list
9566 (cons (substring string start)
9567 list)))
9568 (nreverse list)))
9570 (defun org-table-map-tables (function)
9571 "Apply FUNCTION to the start of all tables in the buffer."
9572 (save-excursion
9573 (save-restriction
9574 (widen)
9575 (goto-char (point-min))
9576 (while (re-search-forward org-table-any-line-regexp nil t)
9577 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9578 (beginning-of-line 1)
9579 (if (looking-at org-table-line-regexp)
9580 (save-excursion (funcall function)))
9581 (re-search-forward org-table-any-border-regexp nil 1))))
9582 (message "Mapping tables: done"))
9584 (defun org-table-sum (&optional beg end nlast)
9585 "Sum numbers in region of current table column.
9586 The result will be displayed in the echo area, and will be available
9587 as kill to be inserted with \\[yank].
9589 If there is an active region, it is interpreted as a rectangle and all
9590 numbers in that rectangle will be summed. If there is no active
9591 region and point is located in a table column, sum all numbers in that
9592 column.
9594 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9595 numbers are assumed to be times as well (in decimal hours) and the
9596 numbers are added as such.
9598 If NLAST is a number, only the NLAST fields will actually be summed."
9599 (interactive)
9600 (save-excursion
9601 (let (col (timecnt 0) diff h m s org-table-clip)
9602 (cond
9603 ((and beg end)) ; beg and end given explicitly
9604 ((org-region-active-p)
9605 (setq beg (region-beginning) end (region-end)))
9607 (setq col (org-table-current-column))
9608 (goto-char (org-table-begin))
9609 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9610 (error "No table data"))
9611 (org-table-goto-column col)
9612 ;not needed? (skip-chars-backward "^|")
9613 (setq beg (point))
9614 (goto-char (org-table-end))
9615 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9616 (error "No table data"))
9617 (org-table-goto-column col)
9618 ;not needed? (skip-chars-forward "^|")
9619 (setq end (point))))
9620 (let* ((items (apply 'append (org-table-copy-region beg end)))
9621 (items1 (cond ((not nlast) items)
9622 ((>= nlast (length items)) items)
9623 (t (setq items (reverse items))
9624 (setcdr (nthcdr (1- nlast) items) nil)
9625 (nreverse items))))
9626 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9627 items1)))
9628 (res (apply '+ numbers))
9629 (sres (if (= timecnt 0)
9630 (format "%g" res)
9631 (setq diff (* 3600 res)
9632 h (floor (/ diff 3600)) diff (mod diff 3600)
9633 m (floor (/ diff 60)) diff (mod diff 60)
9634 s diff)
9635 (format "%d:%02d:%02d" h m s))))
9636 (kill-new sres)
9637 (if (interactive-p)
9638 (message "%s"
9639 (substitute-command-keys
9640 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9641 (length numbers) sres))))
9642 sres))))
9644 (defun org-table-get-number-for-summing (s)
9645 (let (n)
9646 (if (string-match "^ *|? *" s)
9647 (setq s (replace-match "" nil nil s)))
9648 (if (string-match " *|? *$" s)
9649 (setq s (replace-match "" nil nil s)))
9650 (setq n (string-to-number s))
9651 (cond
9652 ((and (string-match "0" s)
9653 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9654 ((string-match "\\`[ \t]+\\'" s) nil)
9655 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9656 (let ((h (string-to-number (or (match-string 1 s) "0")))
9657 (m (string-to-number (or (match-string 2 s) "0")))
9658 (s (string-to-number (or (match-string 4 s) "0"))))
9659 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9660 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9661 ((equal n 0) nil)
9662 (t n))))
9664 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9665 "Get a calc vector from a column, accorting to descriptor DESC.
9666 Optional arguments TBEG and COL can give the beginning of the table and
9667 the current column, to avoid unnecessary parsing."
9668 (save-excursion
9669 (or tbeg (setq tbeg (org-table-begin)))
9670 (or col (setq col (org-table-current-column)))
9671 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9672 (cond
9673 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9674 (setq n1 (- (match-end 1) (match-beginning 1)))
9675 (if (match-beginning 3)
9676 (setq n2 (- (match-end 2) (match-beginning 3))))
9677 (setq n (if n2 (max n1 n2) n1))
9678 (setq n1 (if n2 (min n1 n2)))
9679 (setq nn n)
9680 (while (and (> nn 0)
9681 (re-search-backward org-table-hline-regexp tbeg t))
9682 (push (org-current-line) hline-list)
9683 (setq nn (1- nn)))
9684 (setq hline-list (nreverse hline-list))
9685 (goto-line (nth (1- n) hline-list))
9686 (when (re-search-forward org-table-dataline-regexp)
9687 (org-table-goto-column col)
9688 (setq beg (point)))
9689 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9690 (when (re-search-backward org-table-dataline-regexp)
9691 (org-table-goto-column col)
9692 (setq end (point)))
9693 (setq l (apply 'append (org-table-copy-region beg end)))
9694 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9695 (if (equal x "") "0" x))
9696 l ",") "]"))
9697 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9698 (setq n1 (string-to-number (match-string 1 desc))
9699 n2 (string-to-number (match-string 2 desc)))
9700 (beginning-of-line 1)
9701 (save-excursion
9702 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9703 (org-table-goto-column col)
9704 (setq beg (point))))
9705 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9706 (org-table-goto-column col)
9707 (setq end (point)))
9708 (setq l (apply 'append (org-table-copy-region beg end)))
9709 (concat "[" (mapconcat
9710 (lambda (x) (setq x (org-trim x))
9711 (if (equal x "") "0" x))
9712 l ",") "]"))
9713 ((string-match "\\([0-9]+\\)" desc)
9714 (beginning-of-line 1)
9715 (when (re-search-backward org-table-dataline-regexp tbeg t
9716 (string-to-number (match-string 0 desc)))
9717 (org-table-goto-column col)
9718 (org-trim (org-table-get-field))))))))
9720 (defvar org-table-formula-history nil)
9722 (defvar org-table-column-names nil
9723 "Alist with column names, derived from the `!' line.")
9724 (defvar org-table-column-name-regexp nil
9725 "Regular expression matching the current column names.")
9726 (defvar org-table-local-parameters nil
9727 "Alist with parameter names, derived from the `$' line.")
9728 (defvar org-table-named-field-locations nil
9729 "Alist with locations of named fields.")
9731 (defun org-table-get-formula (&optional equation named)
9732 "Read a formula from the minibuffer, offer stored formula as default."
9733 (let* ((name (car (rassoc (list (org-current-line)
9734 (org-table-current-column))
9735 org-table-named-field-locations)))
9736 (scol (if named
9737 (if name name
9738 (error "Not in a named field"))
9739 (int-to-string (org-table-current-column))))
9740 (dummy (and name (not named)
9741 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9742 (error "Abort")))
9743 (org-table-may-need-update nil)
9744 (stored-list (org-table-get-stored-formulas))
9745 (stored (cdr (assoc scol stored-list)))
9746 (eq (cond
9747 ((and stored equation (string-match "^ *=? *$" equation))
9748 stored)
9749 ((stringp equation)
9750 equation)
9751 (t (read-string
9752 (format "%s formula $%s=" (if named "Field" "Column") scol)
9753 (or stored "") 'org-table-formula-history
9754 ;stored
9755 ))))
9756 mustsave)
9757 (when (not (string-match "\\S-" eq))
9758 ;; remove formula
9759 (setq stored-list (delq (assoc scol stored-list) stored-list))
9760 (org-table-store-formulas stored-list)
9761 (error "Formula removed"))
9762 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9763 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9764 (if (and name (not named))
9765 ;; We set the column equation, delete the named one.
9766 (setq stored-list (delq (assoc name stored-list) stored-list)
9767 mustsave t))
9768 (if stored
9769 (setcdr (assoc scol stored-list) eq)
9770 (setq stored-list (cons (cons scol eq) stored-list)))
9771 (if (or mustsave (not (equal stored eq)))
9772 (org-table-store-formulas stored-list))
9773 eq))
9775 (defun org-table-store-formulas (alist)
9776 "Store the list of formulas below the current table."
9777 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9778 (save-excursion
9779 (goto-char (org-table-end))
9780 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9781 (delete-region (point) (match-end 0)))
9782 (insert "#+TBLFM: "
9783 (mapconcat (lambda (x)
9784 (concat "$" (car x) "=" (cdr x)))
9785 alist "::")
9786 "\n")))
9788 (defun org-table-get-stored-formulas ()
9789 "Return an alist with the t=stored formulas directly after current table."
9790 (interactive)
9791 (let (scol eq eq-alist strings string seen)
9792 (save-excursion
9793 (goto-char (org-table-end))
9794 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9795 (setq strings (org-split-string (match-string 2) " *:: *"))
9796 (while (setq string (pop strings))
9797 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9798 (setq scol (match-string 1 string)
9799 eq (match-string 2 string)
9800 eq-alist (cons (cons scol eq) eq-alist))
9801 (if (member scol seen)
9802 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9803 (push scol seen))))))
9804 (nreverse eq-alist)))
9806 (defun org-table-modify-formulas (action &rest columns)
9807 "Modify the formulas stored below the current table.
9808 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
9809 expected, for the other actions only a single column number is needed."
9810 (let ((list (org-table-get-stored-formulas))
9811 (nmax (length (org-split-string
9812 (buffer-substring (point-at-bol) (point-at-eol))
9813 "|")))
9814 col col1 col2 scol si sc1 sc2)
9815 (cond
9816 ((null list)) ; No action needed if there are no stored formulas
9817 ((eq action 'remove)
9818 (setq col (car columns)
9819 scol (int-to-string col))
9820 (org-table-replace-in-formulas list scol "INVALID")
9821 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
9822 (loop for i from (1+ col) upto nmax by 1 do
9823 (setq si (int-to-string i))
9824 (org-table-replace-in-formulas list si (int-to-string (1- i)))
9825 (if (assoc si list) (setcar (assoc si list)
9826 (int-to-string (1- i))))))
9827 ((eq action 'insert)
9828 (setq col (car columns))
9829 (loop for i from nmax downto col by 1 do
9830 (setq si (int-to-string i))
9831 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
9832 (if (assoc si list) (setcar (assoc si list)
9833 (int-to-string (1+ i))))))
9834 ((eq action 'swap)
9835 (setq col1 (car columns) col2 (nth 1 columns)
9836 sc1 (int-to-string col1) sc2 (int-to-string col2))
9837 ;; Hopefully, ZqZtZ will never be a name in a table
9838 (org-table-replace-in-formulas list sc1 "ZqZtZ")
9839 (org-table-replace-in-formulas list sc2 sc1)
9840 (org-table-replace-in-formulas list "ZqZtZ" sc2)
9841 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
9842 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
9843 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
9844 (t (error "Invalid action in `org-table-modify-formulas'")))
9845 (if list (org-table-store-formulas list))))
9847 (defun org-table-replace-in-formulas (list s1 s2)
9848 (let (elt re s)
9849 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
9850 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
9851 re (concat (regexp-quote s1) "\\>"))
9852 (while (setq elt (pop list))
9853 (setq s (cdr elt))
9854 (while (string-match re s)
9855 (setq s (replace-match s2 t t s)))
9856 (setcdr elt s))))
9858 (defun org-table-get-specials ()
9859 "Get the column names and local parameters for this table."
9860 (save-excursion
9861 (let ((beg (org-table-begin)) (end (org-table-end))
9862 names name fields fields1 field cnt c v line col)
9863 (setq org-table-column-names nil
9864 org-table-local-parameters nil
9865 org-table-named-field-locations nil)
9866 (goto-char beg)
9867 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9868 (setq names (org-split-string (match-string 1) " *| *")
9869 cnt 1)
9870 (while (setq name (pop names))
9871 (setq cnt (1+ cnt))
9872 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9873 (push (cons name (int-to-string cnt)) org-table-column-names))))
9874 (setq org-table-column-names (nreverse org-table-column-names))
9875 (setq org-table-column-name-regexp
9876 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9877 (goto-char beg)
9878 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9879 (setq fields (org-split-string (match-string 1) " *| *"))
9880 (while (setq field (pop fields))
9881 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9882 (push (cons (match-string 1 field) (match-string 2 field))
9883 org-table-local-parameters))))
9884 (goto-char beg)
9885 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9886 (setq c (match-string 1)
9887 fields (org-split-string (match-string 2) " *| *"))
9888 (save-excursion
9889 (beginning-of-line (if (equal c "_") 2 0))
9890 (setq line (org-current-line) col 1)
9891 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9892 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9893 (while (and fields1 (setq field (pop fields)))
9894 (setq v (pop fields1) col (1+ col))
9895 (when (and (stringp field) (stringp v)
9896 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9897 (push (cons field v) org-table-local-parameters)
9898 (push (list field line col) org-table-named-field-locations)))))))
9900 (defun org-this-word ()
9901 ;; Get the current word
9902 (save-excursion
9903 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
9904 (end (progn (skip-chars-forward "^ \t\n") (point))))
9905 (buffer-substring-no-properties beg end))))
9907 (defun org-table-maybe-eval-formula ()
9908 "Check if the current field starts with \"=\" or \":=\".
9909 If yes, store the formula and apply it."
9910 ;; We already know we are in a table. Get field will only return a formula
9911 ;; when appropriate. It might return a separator line, but no problem.
9912 (when org-table-formula-evaluate-inline
9913 (let* ((field (org-trim (or (org-table-get-field) "")))
9914 named eq)
9915 (when (string-match "^:?=\\(.*\\)" field)
9916 (setq named (equal (string-to-char field) ?:)
9917 eq (match-string 1 field))
9918 (if (fboundp 'calc-eval)
9919 (org-table-eval-formula (if named '(4) nil) eq))))))
9921 (defvar org-recalc-commands nil
9922 "List of commands triggering the recalculation of a line.
9923 Will be filled automatically during use.")
9925 (defvar org-recalc-marks
9926 '((" " . "Unmarked: no special line, no automatic recalculation")
9927 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9928 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9929 ("!" . "Column name definition line. Reference in formula as $name.")
9930 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9931 ("_" . "Names for values in row below this one.")
9932 ("^" . "Names for values in row above this one.")))
9934 (defun org-table-rotate-recalc-marks (&optional newchar)
9935 "Rotate the recalculation mark in the first column.
9936 If in any row, the first field is not consistent with a mark,
9937 insert a new column for the markers.
9938 When there is an active region, change all the lines in the region,
9939 after prompting for the marking character.
9940 After each change, a message will be displayed indicating the meaning
9941 of the new mark."
9942 (interactive)
9943 (unless (org-at-table-p) (error "Not at a table"))
9944 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9945 (beg (org-table-begin))
9946 (end (org-table-end))
9947 (l (org-current-line))
9948 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9949 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9950 (have-col
9951 (save-excursion
9952 (goto-char beg)
9953 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
9954 (col (org-table-current-column))
9955 (forcenew (car (assoc newchar org-recalc-marks)))
9956 epos new)
9957 (when l1
9958 (message "Change region to what mark? Type # * ! $ or SPC: ")
9959 (setq newchar (char-to-string (read-char-exclusive))
9960 forcenew (car (assoc newchar org-recalc-marks))))
9961 (if (and newchar (not forcenew))
9962 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
9963 newchar))
9964 (if l1 (goto-line l1))
9965 (save-excursion
9966 (beginning-of-line 1)
9967 (unless (looking-at org-table-dataline-regexp)
9968 (error "Not at a table data line")))
9969 (unless have-col
9970 (org-table-goto-column 1)
9971 (org-table-insert-column)
9972 (org-table-goto-column (1+ col)))
9973 (setq epos (point-at-eol))
9974 (save-excursion
9975 (beginning-of-line 1)
9976 (org-table-get-field
9977 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
9978 (concat " "
9979 (setq new (or forcenew
9980 (cadr (member (match-string 1) marks))))
9981 " ")
9982 " # ")))
9983 (if (and l1 l2)
9984 (progn
9985 (goto-line l1)
9986 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
9987 (and (looking-at org-table-dataline-regexp)
9988 (org-table-get-field 1 (concat " " new " "))))
9989 (goto-line l1)))
9990 (if (not (= epos (point-at-eol))) (org-table-align))
9991 (goto-line l)
9992 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
9994 (defun org-table-maybe-recalculate-line ()
9995 "Recompute the current line if marked for it, and if we haven't just done it."
9996 (interactive)
9997 (and org-table-allow-automatic-line-recalculation
9998 (not (and (memq last-command org-recalc-commands)
9999 (equal org-last-recalc-line (org-current-line))))
10000 (save-excursion (beginning-of-line 1)
10001 (looking-at org-table-auto-recalculate-regexp))
10002 (fboundp 'calc-eval)
10003 (org-table-recalculate) t))
10005 (defvar org-table-formula-debug nil
10006 "Non-nil means, debug table formulas.
10007 When nil, simply write \"#ERROR\" in corrupted fields.")
10009 (defvar modes)
10010 (defsubst org-set-calc-mode (var &optional value)
10011 (if (stringp var)
10012 (setq var (assoc var '(("D" calc-angle-mode deg)
10013 ("R" calc-angle-mode rad)
10014 ("F" calc-prefer-frac t)
10015 ("S" calc-symbolic-mode t)))
10016 value (nth 2 var) var (nth 1 var)))
10017 (if (memq var modes)
10018 (setcar (cdr (memq var modes)) value)
10019 (cons var (cons value modes)))
10020 modes)
10022 (defun org-table-eval-formula (&optional arg equation
10023 suppress-align suppress-const
10024 suppress-store)
10025 "Replace the table field value at the cursor by the result of a calculation.
10027 This function makes use of Dave Gillespie's Calc package, in my view the
10028 most exciting program ever written for GNU Emacs. So you need to have Calc
10029 installed in order to use this function.
10031 In a table, this command replaces the value in the current field with the
10032 result of a formula. It also installs the formula as the \"current\" column
10033 formula, by storing it in a special line below the table. When called
10034 with a `C-u' prefix, the current field must ba a named field, and the
10035 formula is installed as valid in only this specific field.
10037 When called, the command first prompts for a formula, which is read in
10038 the minibuffer. Previously entered formulas are available through the
10039 history list, and the last used formula is offered as a default.
10040 These stored formulas are adapted correctly when moving, inserting, or
10041 deleting columns with the corresponding commands.
10043 The formula can be any algebraic expression understood by the Calc package.
10044 For details, see the Org-mode manual.
10046 This function can also be called from Lisp programs and offers
10047 additional arguments: EQUATION can be the formula to apply. If this
10048 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10049 used to speed-up recursive calls by by-passing unnecessary aligns.
10050 SUPPRESS-CONST suppresses the interpretation of constants in the
10051 formula, assuming that this has been done already outside the function.
10052 SUPPRESS-STORE means the formula should not be stored, either because
10053 it is already stored, or because it is a modified equation that should
10054 not overwrite the stored one."
10055 (interactive "P")
10056 (require 'calc)
10057 (org-table-check-inside-data-field)
10058 (org-table-get-specials)
10059 (let* (fields
10060 (ndown (if (integerp arg) arg 1))
10061 (org-table-automatic-realign nil)
10062 (case-fold-search nil)
10063 (down (> ndown 1))
10064 (formula (if (and equation suppress-store)
10065 equation
10066 (org-table-get-formula equation (equal arg '(4)))))
10067 (n0 (org-table-current-column))
10068 (modes (copy-sequence org-calc-default-modes))
10069 n form fmt x ev orig c)
10070 ;; Parse the format string. Since we have a lot of modes, this is
10071 ;; a lot of work. However, I think calc still uses most of the time.
10072 (if (string-match ";" formula)
10073 (let ((tmp (org-split-string formula ";")))
10074 (setq formula (car tmp)
10075 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10076 (nth 1 tmp)))
10077 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
10078 (setq c (string-to-char (match-string 1 fmt))
10079 n (string-to-number (or (match-string 1 fmt) "")))
10080 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
10081 (setq modes (org-set-calc-mode
10082 'calc-float-format
10083 (list (cdr (assoc c '((?n . float) (?f . fix)
10084 (?s . sci) (?e . eng))))
10085 n))))
10086 (setq fmt (replace-match "" t t fmt)))
10087 (while (string-match "[DRFS]" fmt)
10088 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10089 (setq fmt (replace-match "" t t fmt)))
10090 (unless (string-match "\\S-" fmt)
10091 (setq fmt nil))))
10092 (if (and (not suppress-const) org-table-formula-use-constants)
10093 (setq formula (org-table-formula-substitute-names formula)))
10094 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10095 (while (> ndown 0)
10096 (setq fields (org-split-string
10097 (buffer-substring
10098 (point-at-bol) (point-at-eol)) " *| *"))
10099 (if org-table-formula-numbers-only
10100 (setq fields (mapcar
10101 (lambda (x) (number-to-string (string-to-number x)))
10102 fields)))
10103 (setq ndown (1- ndown))
10104 (setq form (copy-sequence formula))
10105 ;; Insert the references to fields in same row
10106 (while (string-match "\\$\\([0-9]+\\)?" form)
10107 (setq n (if (match-beginning 1)
10108 (string-to-number (match-string 1 form))
10110 x (nth (1- n) fields))
10111 (unless x (error "Invalid field specifier \"%s\""
10112 (match-string 0 form)))
10113 (if (equal x "") (setq x "0"))
10114 (setq form (replace-match (concat "(" x ")") t t form)))
10115 ;; Insert ranges in current column
10116 (while (string-match "\\&[-I0-9]+" form)
10117 (setq form (replace-match
10118 (save-match-data
10119 (org-table-get-vertical-vector (match-string 0 form)
10120 nil n0))
10121 t t form)))
10122 (setq ev (calc-eval (cons form modes)
10123 (if org-table-formula-numbers-only 'num)))
10125 (when org-table-formula-debug
10126 (with-output-to-temp-buffer "*Help*"
10127 (princ (format "Substitution history of formula
10128 Orig: %s
10129 $xyz-> %s
10130 $1-> %s\n" orig formula form))
10131 (if (listp ev)
10132 (princ (format " %s^\nError: %s"
10133 (make-string (car ev) ?\-) (nth 1 ev)))
10134 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10135 ev (or fmt "NONE")
10136 (if fmt (format fmt (string-to-number ev)) ev)))))
10137 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
10138 (unless (and (interactive-p) (not ndown))
10139 (unless (let (inhibit-redisplay)
10140 (y-or-n-p "Debugging Formula. Continue to next? "))
10141 (org-table-align)
10142 (error "Abort"))
10143 (delete-window (get-buffer-window "*Help*"))
10144 (message "")))
10145 (if (listp ev) (setq fmt nil ev "#ERROR"))
10146 (org-table-justify-field-maybe
10147 (if fmt (format fmt (string-to-number ev)) ev))
10148 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10149 (call-interactively 'org-return)
10150 (setq ndown 0)))
10151 (and down (org-table-maybe-recalculate-line))
10152 (or suppress-align (and org-table-may-need-update
10153 (org-table-align)))))
10155 (defun org-table-recalculate (&optional all noalign)
10156 "Recalculate the current table line by applying all stored formulas."
10157 (interactive "P")
10158 (or (memq this-command org-recalc-commands)
10159 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10160 (unless (org-at-table-p) (error "Not at a table"))
10161 (org-table-get-specials)
10162 (let* ((eqlist (sort (org-table-get-stored-formulas)
10163 (lambda (a b) (string< (car a) (car b)))))
10164 (inhibit-redisplay t)
10165 (line-re org-table-dataline-regexp)
10166 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10167 (thiscol (org-table-current-column))
10168 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
10169 ;; Insert constants in all formulas
10170 (setq eqlist
10171 (mapcar (lambda (x)
10172 (setcdr x (org-table-formula-substitute-names (cdr x)))
10174 eqlist))
10175 ;; Split the equation list
10176 (while (setq eq (pop eqlist))
10177 (if (<= (string-to-char (car eq)) ?9)
10178 (push eq eqlnum)
10179 (push eq eqlname)))
10180 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10181 (if all
10182 (progn
10183 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10184 (goto-char (setq beg (org-table-begin)))
10185 (if (re-search-forward org-table-calculate-mark-regexp end t)
10186 ;; This is a table with marked lines, only compute selected lines
10187 (setq line-re org-table-recalculate-regexp)
10188 ;; Move forward to the first non-header line
10189 (if (and (re-search-forward org-table-dataline-regexp end t)
10190 (re-search-forward org-table-hline-regexp end t)
10191 (re-search-forward org-table-dataline-regexp end t))
10192 (setq beg (match-beginning 0))
10193 nil))) ;; just leave beg where it is
10194 (setq beg (point-at-bol)
10195 end (move-marker (make-marker) (1+ (point-at-eol)))))
10196 (goto-char beg)
10197 (and all (message "Re-applying formulas to full table..."))
10198 (while (re-search-forward line-re end t)
10199 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
10200 ;; Unprotected line, recalculate
10201 (and all (message "Re-applying formulas to full table...(line %d)"
10202 (setq cnt (1+ cnt))))
10203 (setq org-last-recalc-line (org-current-line))
10204 (setq eql eqlnum)
10205 (while (setq entry (pop eql))
10206 (goto-line org-last-recalc-line)
10207 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10208 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
10209 (goto-line thisline)
10210 (org-table-goto-column thiscol)
10211 (or noalign (and org-table-may-need-update (org-table-align))
10212 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10213 ;; Now do the names fields
10214 (while (setq eq (pop eqlname))
10215 (setq name (car eq)
10216 a (assoc name org-table-named-field-locations))
10217 (when a
10218 (message "Re-applying formula to named field: %s" name)
10219 (goto-line (nth 1 a))
10220 (org-table-goto-column (nth 2 a))
10221 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
10222 ;; back to initial position
10223 (goto-line thisline)
10224 (org-table-goto-column thiscol)
10225 (or noalign (and org-table-may-need-update (org-table-align))
10226 (and all (message "Re-applying formulas...done")))))
10228 (defun org-table-formula-substitute-names (f)
10229 "Replace $const with values in string F."
10230 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
10231 ;; First, check for column names
10232 (while (setq start (string-match org-table-column-name-regexp f start))
10233 (setq start (1+ start))
10234 (setq a (assoc (match-string 1 f) org-table-column-names))
10235 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10236 ;; Expand ranges to vectors
10237 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
10238 (setq n1 (string-to-number (match-string 1 f))
10239 n2 (string-to-number (match-string 2 f))
10240 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
10241 s (concat "[($" (number-to-string (1- nn1)) ")"))
10242 (loop for i from nn1 upto nn2 do
10243 (setq s (concat s ",($" (int-to-string i) ")")))
10244 (setq s (concat s "]"))
10245 (if (< n2 n1) (setq s (concat "rev(" s ")")))
10246 (setq f (replace-match s t t f)))
10247 ;; Parameters and constants
10248 (setq start 0)
10249 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
10250 (setq start (1+ start))
10251 (if (setq a (save-match-data
10252 (org-table-get-constant (match-string 1 f))))
10253 (setq f (replace-match (concat "(" a ")") t t f))))
10254 (if org-table-formula-debug
10255 (put-text-property 0 (length f) :orig-formula f1 f))
10258 (defun org-table-get-constant (const)
10259 "Find the value for a parameter or constant in a formula.
10260 Parameters get priority."
10261 (or (cdr (assoc const org-table-local-parameters))
10262 (cdr (assoc const org-table-formula-constants))
10263 (and (fboundp 'constants-get) (constants-get const))
10264 "#UNDEFINED_NAME"))
10266 (defvar org-edit-formulas-map (make-sparse-keymap))
10267 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
10268 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
10269 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
10271 (defvar org-pos)
10273 (defun org-table-edit-formulas ()
10274 "Edit the formulas of the current table in a separate buffer."
10275 (interactive)
10276 (unless (org-at-table-p)
10277 (error "Not at a table"))
10278 (org-table-get-specials)
10279 (let ((eql (org-table-get-stored-formulas))
10280 (pos (move-marker (make-marker) (point)))
10281 (wc (current-window-configuration))
10282 entry loc s)
10283 (switch-to-buffer-other-window "*Edit Formulas*")
10284 (erase-buffer)
10285 (fundamental-mode)
10286 (set (make-local-variable 'org-pos) pos)
10287 (set (make-local-variable 'org-window-configuration) wc)
10288 (use-local-map org-edit-formulas-map)
10289 (setq s "# Edit formulas and finish with `C-c C-c'.
10290 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
10291 # Use `C-c ?' to get information about $name at point.
10292 # To cancel editing, press `C-c C-q'.\n")
10293 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10294 (insert s)
10295 (while (setq entry (pop eql))
10296 (when (setq loc (assoc (car entry) org-table-named-field-locations))
10297 (setq s (format "# Named formula, referring to column %d in line %d\n"
10298 (nth 2 loc) (nth 1 loc)))
10299 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10300 (insert s))
10301 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
10302 (remove-text-properties 0 (length s) '(face nil) s)
10303 (insert s))
10304 (goto-char (point-min))
10305 (message "Edit formulas and finish with `C-c C-c'.")))
10307 (defun org-show-variable ()
10308 "Show the location/value of the $ expression at point."
10309 (interactive)
10310 (let (var (pos org-pos) (win (selected-window)) e)
10311 (save-excursion
10312 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
10313 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
10314 (setq var (match-string 1))
10315 (error "No variable at point")))
10316 (cond
10317 ((setq e (assoc var org-table-named-field-locations))
10318 (switch-to-buffer-other-window (marker-buffer pos))
10319 (goto-line (nth 1 e))
10320 (org-table-goto-column (nth 2 e))
10321 (select-window win)
10322 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10323 ((setq e (assoc var org-table-column-names))
10324 (switch-to-buffer-other-window (marker-buffer pos))
10325 (goto-char pos)
10326 (goto-char (org-table-begin))
10327 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10328 (org-table-end) t)
10329 (progn
10330 (goto-char (match-beginning 1))
10331 (message "Named column (column %s)" (cdr e)))
10332 (error "Column name not found"))
10333 (select-window win))
10334 ((string-match "^[0-9]$" var)
10335 ;; column number
10336 (switch-to-buffer-other-window (marker-buffer pos))
10337 (goto-char pos)
10338 (goto-char (org-table-begin))
10339 (recenter 1)
10340 (if (re-search-forward org-table-dataline-regexp
10341 (org-table-end) t)
10342 (progn
10343 (goto-char (match-beginning 0))
10344 (org-table-goto-column (string-to-number var))
10345 (message "Column %s" var))
10346 (error "Column name not found"))
10347 (select-window win))
10348 ((setq e (assoc var org-table-local-parameters))
10349 (switch-to-buffer-other-window (marker-buffer pos))
10350 (goto-char pos)
10351 (goto-char (org-table-begin))
10352 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10353 (progn
10354 (goto-char (match-beginning 1))
10355 (message "Local parameter."))
10356 (error "Parameter not found"))
10357 (select-window win))
10359 (cond
10360 ((setq e (assoc var org-table-formula-constants))
10361 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
10362 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10363 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
10364 (t (error "Undefined name $%s" var)))))))
10366 (defun org-finish-edit-formulas (&optional arg)
10367 "Parse the buffer for formula definitions and install them.
10368 With prefix ARG, apply the new formulas to the table."
10369 (interactive "P")
10370 (let ((pos org-pos) eql)
10371 (goto-char (point-min))
10372 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
10373 (push (cons (match-string 1) (match-string 2)) eql))
10374 (set-window-configuration org-window-configuration)
10375 (select-window (get-buffer-window (marker-buffer pos)))
10376 (goto-char pos)
10377 (unless (org-at-table-p)
10378 (error "Lost table position - cannot install formulae"))
10379 (org-table-store-formulas eql)
10380 (move-marker pos nil)
10381 (kill-buffer "*Edit Formulas*")
10382 (if arg
10383 (org-table-recalculate 'all)
10384 (message "New formulas installed - press C-u C-c C-c to apply."))))
10386 (defun org-abort-edit-formulas ()
10387 "Abort editing formulas, without installing the changes."
10388 (interactive)
10389 (let ((pos org-pos))
10390 (set-window-configuration org-window-configuration)
10391 (select-window (get-buffer-window (marker-buffer pos)))
10392 (goto-char pos)
10393 (message "Formula editing aborted without installing changes")))
10395 ;;; The orgtbl minor mode
10397 ;; Define a minor mode which can be used in other modes in order to
10398 ;; integrate the org-mode table editor.
10400 ;; This is really a hack, because the org-mode table editor uses several
10401 ;; keys which normally belong to the major mode, for example the TAB and
10402 ;; RET keys. Here is how it works: The minor mode defines all the keys
10403 ;; necessary to operate the table editor, but wraps the commands into a
10404 ;; function which tests if the cursor is currently inside a table. If that
10405 ;; is the case, the table editor command is executed. However, when any of
10406 ;; those keys is used outside a table, the function uses `key-binding' to
10407 ;; look up if the key has an associated command in another currently active
10408 ;; keymap (minor modes, major mode, global), and executes that command.
10409 ;; There might be problems if any of the keys used by the table editor is
10410 ;; otherwise used as a prefix key.
10412 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10413 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10414 ;; addresses this by checking explicitly for both bindings.
10416 ;; The optimized version (see variable `orgtbl-optimized') takes over
10417 ;; all keys which are bound to `self-insert-command' in the *global map*.
10418 ;; Some modes bind other commands to simple characters, for example
10419 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10420 ;; active, this binding is ignored inside tables and replaced with a
10421 ;; modified self-insert.
10423 (defvar orgtbl-mode nil
10424 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10425 table editor in arbitrary modes.")
10426 (make-variable-buffer-local 'orgtbl-mode)
10428 (defvar orgtbl-mode-map (make-keymap)
10429 "Keymap for `orgtbl-mode'.")
10431 ;;;###autoload
10432 (defun turn-on-orgtbl ()
10433 "Unconditionally turn on `orgtbl-mode'."
10434 (orgtbl-mode 1))
10436 ;;;###autoload
10437 (defun orgtbl-mode (&optional arg)
10438 "The `org-mode' table editor as a minor mode for use in other modes."
10439 (interactive)
10440 (if (eq major-mode 'org-mode)
10441 ;; Exit without error, in case some hook functions calls this
10442 ;; by accident in org-mode.
10443 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10444 (setq orgtbl-mode
10445 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10446 (if orgtbl-mode
10447 (progn
10448 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10449 ;; Make sure we are first in minor-mode-map-alist
10450 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10451 (and c (setq minor-mode-map-alist
10452 (cons c (delq c minor-mode-map-alist)))))
10453 (set (make-local-variable (quote org-table-may-need-update)) t)
10454 (org-add-hook 'before-change-functions 'org-before-change-function
10455 nil 'local)
10456 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
10457 auto-fill-inhibit-regexp)
10458 (set (make-local-variable 'auto-fill-inhibit-regexp)
10459 (if auto-fill-inhibit-regexp
10460 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
10461 "[ \t]*|"))
10462 (org-add-to-invisibility-spec '(org-cwidth))
10463 (easy-menu-add orgtbl-mode-menu)
10464 (run-hooks 'orgtbl-mode-hook))
10465 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10466 (org-cleanup-narrow-column-properties)
10467 (org-remove-from-invisibility-spec '(org-cwidth))
10468 (remove-hook 'before-change-functions 'org-before-change-function t)
10469 (easy-menu-remove orgtbl-mode-menu)
10470 (force-mode-line-update 'all))))
10472 (defun org-cleanup-narrow-column-properties ()
10473 "Remove all properties related to narrow-column invisibility."
10474 (let ((s 1))
10475 (while (setq s (text-property-any s (point-max)
10476 'display org-narrow-column-arrow))
10477 (remove-text-properties s (1+ s) '(display t)))
10478 (setq s 1)
10479 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10480 (remove-text-properties s (1+ s) '(org-cwidth t)))
10481 (setq s 1)
10482 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10483 (remove-text-properties s (1+ s) '(invisible t)))))
10485 ;; Install it as a minor mode.
10486 (put 'orgtbl-mode :included t)
10487 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10488 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10490 (defun orgtbl-make-binding (fun n &rest keys)
10491 "Create a function for binding in the table minor mode.
10492 FUN is the command to call inside a table. N is used to create a unique
10493 command name. KEYS are keys that should be checked in for a command
10494 to execute outside of tables."
10495 (eval
10496 (list 'defun
10497 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10498 '(arg)
10499 (concat "In tables, run `" (symbol-name fun) "'.\n"
10500 "Outside of tables, run the binding of `"
10501 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10502 "'.")
10503 '(interactive "p")
10504 (list 'if
10505 '(org-at-table-p)
10506 (list 'call-interactively (list 'quote fun))
10507 (list 'let '(orgtbl-mode)
10508 (list 'call-interactively
10509 (append '(or)
10510 (mapcar (lambda (k)
10511 (list 'key-binding k))
10512 keys)
10513 '('orgtbl-error))))))))
10515 (defun orgtbl-error ()
10516 "Error when there is no default binding for a table key."
10517 (interactive)
10518 (error "This key is has no function outside tables"))
10520 (defun orgtbl-setup ()
10521 "Setup orgtbl keymaps."
10522 (let ((nfunc 0)
10523 (bindings
10524 (list
10525 '([(meta shift left)] org-table-delete-column)
10526 '([(meta left)] org-table-move-column-left)
10527 '([(meta right)] org-table-move-column-right)
10528 '([(meta shift right)] org-table-insert-column)
10529 '([(meta shift up)] org-table-kill-row)
10530 '([(meta shift down)] org-table-insert-row)
10531 '([(meta up)] org-table-move-row-up)
10532 '([(meta down)] org-table-move-row-down)
10533 '("\C-c\C-w" org-table-cut-region)
10534 '("\C-c\M-w" org-table-copy-region)
10535 '("\C-c\C-y" org-table-paste-rectangle)
10536 '("\C-c-" org-table-insert-hline)
10537 ; '([(shift tab)] org-table-previous-field)
10538 '("\C-m" org-table-next-row)
10539 (list (org-key 'S-return) 'org-table-copy-down)
10540 '([(meta return)] org-table-wrap-region)
10541 '("\C-c\C-q" org-table-wrap-region)
10542 '("\C-c?" org-table-current-column)
10543 '("\C-c " org-table-blank-field)
10544 '("\C-c+" org-table-sum)
10545 '("\C-c=" org-table-eval-formula)
10546 '("\C-c'" org-table-edit-formulas)
10547 '("\C-c`" org-table-edit-field)
10548 '("\C-c*" org-table-recalculate)
10549 '("\C-c|" org-table-create-or-convert-from-region)
10550 '("\C-c^" org-table-sort-lines)
10551 '([(control ?#)] org-table-rotate-recalc-marks)))
10552 elt key fun cmd)
10553 (while (setq elt (pop bindings))
10554 (setq nfunc (1+ nfunc))
10555 (setq key (car elt)
10556 fun (nth 1 elt)
10557 cmd (orgtbl-make-binding fun nfunc key))
10558 (define-key orgtbl-mode-map key cmd))
10559 ;; Special treatment needed for TAB and RET
10560 (define-key orgtbl-mode-map [(return)]
10561 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10562 (define-key orgtbl-mode-map "\C-m"
10563 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10564 (define-key orgtbl-mode-map [(tab)]
10565 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10566 (define-key orgtbl-mode-map "\C-i"
10567 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
10568 (define-key orgtbl-mode-map "\C-i"
10569 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
10570 (define-key orgtbl-mode-map "\C-c\C-c"
10571 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
10572 (when orgtbl-optimized
10573 ;; If the user wants maximum table support, we need to hijack
10574 ;; some standard editing functions
10575 (org-remap orgtbl-mode-map
10576 'self-insert-command 'orgtbl-self-insert-command
10577 'delete-char 'org-delete-char
10578 'delete-backward-char 'org-delete-backward-char)
10579 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
10580 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10581 '("OrgTbl"
10582 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10583 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10584 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10585 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10586 "--"
10587 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10588 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10589 ["Copy Field from Above"
10590 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10591 "--"
10592 ("Column"
10593 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10594 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10595 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10596 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
10597 "--"
10598 ["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])
10599 ("Row"
10600 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10601 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10602 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10603 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10604 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10605 "--"
10606 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10607 ("Rectangle"
10608 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10609 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10610 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10611 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10612 "--"
10613 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10614 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10615 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10616 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10617 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10618 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10619 ["Sum Column/Rectangle" org-table-sum
10620 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10621 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10622 ["Debug Formulas"
10623 (setq org-table-formula-debug (not org-table-formula-debug))
10624 :style toggle :selected org-table-formula-debug]
10628 (defun orgtbl-tab (arg)
10629 "Justification and field motion for `orgtbl-mode'."
10630 (interactive "P")
10631 (if arg (org-table-edit-field t)
10632 (org-table-justify-field-maybe)
10633 (org-table-next-field)))
10635 (defun orgtbl-ret ()
10636 "Justification and field motion for `orgtbl-mode'."
10637 (interactive)
10638 (org-table-justify-field-maybe)
10639 (org-table-next-row))
10641 (defun orgtbl-self-insert-command (N)
10642 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10643 If the cursor is in a table looking at whitespace, the whitespace is
10644 overwritten, and the table is not marked as requiring realignment."
10645 (interactive "p")
10646 (if (and (org-at-table-p)
10648 (and org-table-auto-blank-field
10649 (member last-command
10650 '(orgtbl-hijacker-command-100
10651 orgtbl-hijacker-command-101
10652 orgtbl-hijacker-command-102
10653 orgtbl-hijacker-command-103
10654 orgtbl-hijacker-command-104
10655 orgtbl-hijacker-command-105))
10656 (org-table-blank-field))
10658 (eq N 1)
10659 (looking-at "[^|\n]* +|"))
10660 (let (org-table-may-need-update)
10661 (goto-char (1- (match-end 0)))
10662 (delete-backward-char 1)
10663 (goto-char (match-beginning 0))
10664 (self-insert-command N))
10665 (setq org-table-may-need-update t)
10666 (let (orgtbl-mode)
10667 (call-interactively (key-binding (vector last-input-event))))))
10669 (defun org-force-self-insert (N)
10670 "Needed to enforce self-insert under remapping."
10671 (interactive "p")
10672 (self-insert-command N))
10674 ;;; Exporting
10676 (defconst org-level-max 20)
10678 (defun org-export-find-first-heading-line (list)
10679 "Remove all lines from LIST which are before the first headline."
10680 (let ((orig-list list)
10681 (re (concat "^" outline-regexp)))
10682 (while (and list
10683 (not (string-match re (car list))))
10684 (pop list))
10685 (or list orig-list)))
10687 (defun org-skip-comments (lines)
10688 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10689 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10690 (re2 "^\\(\\*+\\)[ \t\n\r]")
10691 rtn line level)
10692 (while (setq line (pop lines))
10693 (cond
10694 ((and (string-match re1 line)
10695 (setq level (- (match-end 1) (match-beginning 1))))
10696 ;; Beginning of a COMMENT subtree. Skip it.
10697 (while (and (setq line (pop lines))
10698 (or (not (string-match re2 line))
10699 (> (- (match-end 1) (match-beginning 1)) level))))
10700 (setq lines (cons line lines)))
10701 ((string-match "^#" line)
10702 ;; an ordinary comment line
10704 ((and org-export-table-remove-special-lines
10705 (string-match "^[ \t]*| *[!_^] *|" line))
10706 ;; a special table line that should be removed
10708 (t (setq rtn (cons line rtn)))))
10709 (nreverse rtn)))
10711 ;; ASCII
10713 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10714 "Characters for underlining headings in ASCII export.")
10716 (defconst org-html-entities
10717 '(("nbsp")
10718 ("iexcl")
10719 ("cent")
10720 ("pound")
10721 ("curren")
10722 ("yen")
10723 ("brvbar")
10724 ("sect")
10725 ("uml")
10726 ("copy")
10727 ("ordf")
10728 ("laquo")
10729 ("not")
10730 ("shy")
10731 ("reg")
10732 ("macr")
10733 ("deg")
10734 ("plusmn")
10735 ("sup2")
10736 ("sup3")
10737 ("acute")
10738 ("micro")
10739 ("para")
10740 ("middot")
10741 ("odot"."o")
10742 ("star"."*")
10743 ("cedil")
10744 ("sup1")
10745 ("ordm")
10746 ("raquo")
10747 ("frac14")
10748 ("frac12")
10749 ("frac34")
10750 ("iquest")
10751 ("Agrave")
10752 ("Aacute")
10753 ("Acirc")
10754 ("Atilde")
10755 ("Auml")
10756 ("Aring") ("AA"."&Aring;")
10757 ("AElig")
10758 ("Ccedil")
10759 ("Egrave")
10760 ("Eacute")
10761 ("Ecirc")
10762 ("Euml")
10763 ("Igrave")
10764 ("Iacute")
10765 ("Icirc")
10766 ("Iuml")
10767 ("ETH")
10768 ("Ntilde")
10769 ("Ograve")
10770 ("Oacute")
10771 ("Ocirc")
10772 ("Otilde")
10773 ("Ouml")
10774 ("times")
10775 ("Oslash")
10776 ("Ugrave")
10777 ("Uacute")
10778 ("Ucirc")
10779 ("Uuml")
10780 ("Yacute")
10781 ("THORN")
10782 ("szlig")
10783 ("agrave")
10784 ("aacute")
10785 ("acirc")
10786 ("atilde")
10787 ("auml")
10788 ("aring")
10789 ("aelig")
10790 ("ccedil")
10791 ("egrave")
10792 ("eacute")
10793 ("ecirc")
10794 ("euml")
10795 ("igrave")
10796 ("iacute")
10797 ("icirc")
10798 ("iuml")
10799 ("eth")
10800 ("ntilde")
10801 ("ograve")
10802 ("oacute")
10803 ("ocirc")
10804 ("otilde")
10805 ("ouml")
10806 ("divide")
10807 ("oslash")
10808 ("ugrave")
10809 ("uacute")
10810 ("ucirc")
10811 ("uuml")
10812 ("yacute")
10813 ("thorn")
10814 ("yuml")
10815 ("fnof")
10816 ("Alpha")
10817 ("Beta")
10818 ("Gamma")
10819 ("Delta")
10820 ("Epsilon")
10821 ("Zeta")
10822 ("Eta")
10823 ("Theta")
10824 ("Iota")
10825 ("Kappa")
10826 ("Lambda")
10827 ("Mu")
10828 ("Nu")
10829 ("Xi")
10830 ("Omicron")
10831 ("Pi")
10832 ("Rho")
10833 ("Sigma")
10834 ("Tau")
10835 ("Upsilon")
10836 ("Phi")
10837 ("Chi")
10838 ("Psi")
10839 ("Omega")
10840 ("alpha")
10841 ("beta")
10842 ("gamma")
10843 ("delta")
10844 ("epsilon")
10845 ("varepsilon"."&epsilon;")
10846 ("zeta")
10847 ("eta")
10848 ("theta")
10849 ("iota")
10850 ("kappa")
10851 ("lambda")
10852 ("mu")
10853 ("nu")
10854 ("xi")
10855 ("omicron")
10856 ("pi")
10857 ("rho")
10858 ("sigmaf") ("varsigma"."&sigmaf;")
10859 ("sigma")
10860 ("tau")
10861 ("upsilon")
10862 ("phi")
10863 ("chi")
10864 ("psi")
10865 ("omega")
10866 ("thetasym") ("vartheta"."&thetasym;")
10867 ("upsih")
10868 ("piv")
10869 ("bull") ("bullet"."&bull;")
10870 ("hellip") ("dots"."&hellip;")
10871 ("prime")
10872 ("Prime")
10873 ("oline")
10874 ("frasl")
10875 ("weierp")
10876 ("image")
10877 ("real")
10878 ("trade")
10879 ("alefsym")
10880 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
10881 ("uarr") ("uparrow"."&uarr;")
10882 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
10883 ("darr")("downarrow"."&darr;")
10884 ("harr") ("leftrightarrow"."&harr;")
10885 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
10886 ("lArr") ("Leftarrow"."&lArr;")
10887 ("uArr") ("Uparrow"."&uArr;")
10888 ("rArr") ("Rightarrow"."&rArr;")
10889 ("dArr") ("Downarrow"."&dArr;")
10890 ("hArr") ("Leftrightarrow"."&hArr;")
10891 ("forall")
10892 ("part") ("partial"."&part;")
10893 ("exist") ("exists"."&exist;")
10894 ("empty") ("emptyset"."&empty;")
10895 ("nabla")
10896 ("isin") ("in"."&isin;")
10897 ("notin")
10898 ("ni")
10899 ("prod")
10900 ("sum")
10901 ("minus")
10902 ("lowast") ("ast"."&lowast;")
10903 ("radic")
10904 ("prop") ("proptp"."&prop;")
10905 ("infin") ("infty"."&infin;")
10906 ("ang") ("angle"."&ang;")
10907 ("and") ("vee"."&and;")
10908 ("or") ("wedge"."&or;")
10909 ("cap")
10910 ("cup")
10911 ("int")
10912 ("there4")
10913 ("sim")
10914 ("cong") ("simeq"."&cong;")
10915 ("asymp")("approx"."&asymp;")
10916 ("ne") ("neq"."&ne;")
10917 ("equiv")
10918 ("le")
10919 ("ge")
10920 ("sub") ("subset"."&sub;")
10921 ("sup") ("supset"."&sup;")
10922 ("nsub")
10923 ("sube")
10924 ("supe")
10925 ("oplus")
10926 ("otimes")
10927 ("perp")
10928 ("sdot") ("cdot"."&sdot;")
10929 ("lceil")
10930 ("rceil")
10931 ("lfloor")
10932 ("rfloor")
10933 ("lang")
10934 ("rang")
10935 ("loz") ("Diamond"."&loz;")
10936 ("spades") ("spadesuit"."&spades;")
10937 ("clubs") ("clubsuit"."&clubs;")
10938 ("hearts") ("diamondsuit"."&hearts;")
10939 ("diams") ("diamondsuit"."&diams;")
10940 ("quot")
10941 ("amp")
10942 ("lt")
10943 ("gt")
10944 ("OElig")
10945 ("oelig")
10946 ("Scaron")
10947 ("scaron")
10948 ("Yuml")
10949 ("circ")
10950 ("tilde")
10951 ("ensp")
10952 ("emsp")
10953 ("thinsp")
10954 ("zwnj")
10955 ("zwj")
10956 ("lrm")
10957 ("rlm")
10958 ("ndash")
10959 ("mdash")
10960 ("lsquo")
10961 ("rsquo")
10962 ("sbquo")
10963 ("ldquo")
10964 ("rdquo")
10965 ("bdquo")
10966 ("dagger")
10967 ("Dagger")
10968 ("permil")
10969 ("lsaquo")
10970 ("rsaquo")
10971 ("euro")
10973 ("arccos"."arccos")
10974 ("arcsin"."arcsin")
10975 ("arctan"."arctan")
10976 ("arg"."arg")
10977 ("cos"."cos")
10978 ("cosh"."cosh")
10979 ("cot"."cot")
10980 ("coth"."coth")
10981 ("csc"."csc")
10982 ("deg"."deg")
10983 ("det"."det")
10984 ("dim"."dim")
10985 ("exp"."exp")
10986 ("gcd"."gcd")
10987 ("hom"."hom")
10988 ("inf"."inf")
10989 ("ker"."ker")
10990 ("lg"."lg")
10991 ("lim"."lim")
10992 ("liminf"."liminf")
10993 ("limsup"."limsup")
10994 ("ln"."ln")
10995 ("log"."log")
10996 ("max"."max")
10997 ("min"."min")
10998 ("Pr"."Pr")
10999 ("sec"."sec")
11000 ("sin"."sin")
11001 ("sinh"."sinh")
11002 ("sup"."sup")
11003 ("tan"."tan")
11004 ("tanh"."tanh")
11006 "Entities for TeX->HTML translation.
11007 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
11008 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
11009 In that case, \"\\ent\" will be translated to \"&other;\".
11010 The list contains HTML entities for Latin-1, Greek and other symbols.
11011 It is supplemented by a number of commonly used TeX macros with appropriate
11012 translations. There is currently no way for users to extend this.")
11014 (defun org-cleaned-string-for-export (string)
11015 "Cleanup a buffer substring so that links can be created safely."
11016 (interactive)
11017 (let* ((cb (current-buffer))
11018 (re-radio (and org-target-link-regexp
11019 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
11020 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
11021 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
11022 rtn)
11023 (save-excursion
11024 (set-buffer (get-buffer-create " org-mode-tmp"))
11025 (erase-buffer)
11026 (insert string)
11027 (org-mode)
11028 ;; Find targets in comments and move them out of comments,
11029 ;; but mark them as targets that should be invisible
11030 (goto-char (point-min))
11031 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
11032 (replace-match "\\1(INVISIBLE)"))
11033 ;; Find matches for radio targets and turn them into internal links
11034 (goto-char (point-min))
11035 (when re-radio
11036 (while (re-search-forward re-radio nil t)
11037 (replace-match "\\1[[\\2]]")))
11038 ;; Find all links that contain a newline and put them into a single line
11039 (goto-char (point-min))
11040 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
11041 (replace-match "\\1 \\3")
11042 (goto-char (match-beginning 0)))
11043 ;; Normalize links: Convert angle and plain links into bracket links
11044 (goto-char (point-min))
11045 (while (re-search-forward re-plain-link nil t)
11046 (replace-match
11047 (concat
11048 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11049 t t))
11050 (goto-char (point-min))
11051 (while (re-search-forward re-angle-link nil t)
11052 (replace-match
11053 (concat
11054 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11055 t t))
11057 ;; Remove comments
11058 (goto-char (point-min))
11059 (while (re-search-forward "^#.*\n?" nil t)
11060 (replace-match ""))
11061 (setq rtn (buffer-string)))
11062 (kill-buffer " org-mode-tmp")
11063 rtn))
11065 (defun org-solidify-link-text (s &optional alist)
11066 "Take link text and make a safe target out of it."
11067 (save-match-data
11068 (let* ((rtn
11069 (mapconcat
11070 'identity
11071 (org-split-string s "[ \t\r\n]+") "--"))
11072 (a (assoc rtn alist)))
11073 (or (cdr a) rtn))))
11075 (defun org-convert-to-odd-levels ()
11076 "Convert an org-mode file with all levels allowed to one with odd levels.
11077 This will leave level 1 alone, convert level 2 to level 3, level 3 to
11078 level 5 etc."
11079 (interactive)
11080 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
11081 (let ((org-odd-levels-only nil) n)
11082 (save-excursion
11083 (goto-char (point-min))
11084 (while (re-search-forward "^\\*\\*+" nil t)
11085 (setq n (1- (length (match-string 0))))
11086 (while (>= (setq n (1- n)) 0)
11087 (org-demote))
11088 (end-of-line 1))))))
11091 (defun org-convert-to-oddeven-levels ()
11092 "Convert an org-mode file with only odd levels to one with odd and even levels.
11093 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
11094 section with an even level, conversion would destroy the structure of the file. An error
11095 is signaled in this case."
11096 (interactive)
11097 (goto-char (point-min))
11098 ;; First check if there are no even levels
11099 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
11100 (org-show-hierarchy-above)
11101 (error "Not all levels are odd in this file. Conversion not possible."))
11102 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
11103 (let ((org-odd-levels-only nil) n)
11104 (save-excursion
11105 (goto-char (point-min))
11106 (while (re-search-forward "^\\*\\*+" nil t)
11107 (setq n (/ (length (match-string 0)) 2))
11108 (while (>= (setq n (1- n)) 0)
11109 (org-promote))
11110 (end-of-line 1))))))
11112 (defun org-tr-level (n)
11113 "Make N odd if required."
11114 (if org-odd-levels-only (1+ (/ n 2)) n))
11116 (defvar org-last-level nil) ; dynamically scoped variable
11118 (defun org-export-as-ascii (arg)
11119 "Export the outline as a pretty ASCII file.
11120 If there is an active region, export only the region.
11121 The prefix ARG specifies how many levels of the outline should become
11122 underlined headlines. The default is 3."
11123 (interactive "P")
11124 (setq-default org-todo-line-regexp org-todo-line-regexp)
11125 (let* ((region
11126 (buffer-substring
11127 (if (org-region-active-p) (region-beginning) (point-min))
11128 (if (org-region-active-p) (region-end) (point-max))))
11129 (lines (org-export-find-first-heading-line
11130 (org-skip-comments
11131 (org-split-string
11132 (org-cleaned-string-for-export region)
11133 "[\r\n]"))))
11134 (org-startup-with-deadline-check nil)
11135 (level 0) line txt
11136 (umax nil)
11137 (case-fold-search nil)
11138 (filename (concat (file-name-sans-extension buffer-file-name)
11139 ".txt"))
11140 (buffer (find-file-noselect filename))
11141 (levels-open (make-vector org-level-max nil))
11142 (date (format-time-string "%Y/%m/%d" (current-time)))
11143 (time (format-time-string "%X" (org-current-time)))
11144 (author user-full-name)
11145 (title (buffer-name))
11146 (options nil)
11147 (email user-mail-address)
11148 (language org-export-default-language)
11149 (text nil)
11150 (todo nil)
11151 (lang-words nil))
11153 (setq org-last-level 1)
11154 (org-init-section-numbers)
11156 (find-file-noselect filename)
11158 ;; Search for the export key lines
11159 (org-parse-key-lines)
11161 (setq lang-words (or (assoc language org-export-language-setup)
11162 (assoc "en" org-export-language-setup)))
11163 (if org-export-ascii-show-new-buffer
11164 (switch-to-buffer-other-window buffer)
11165 (set-buffer buffer))
11166 (erase-buffer)
11167 (fundamental-mode)
11168 (if options (org-parse-export-options options))
11169 (setq umax (if arg (prefix-numeric-value arg)
11170 org-export-headline-levels))
11172 ;; File header
11173 (if title (org-insert-centered title ?=))
11174 (insert "\n")
11175 (if (or author email)
11176 (insert (concat (nth 1 lang-words) ": " (or author "")
11177 (if email (concat " <" email ">") "")
11178 "\n")))
11179 (if (and date time)
11180 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
11181 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
11183 (insert "\n\n")
11185 (if org-export-with-toc
11186 (progn
11187 (insert (nth 3 lang-words) "\n"
11188 (make-string (length (nth 3 lang-words)) ?=) "\n")
11189 (mapcar '(lambda (line)
11190 (if (string-match org-todo-line-regexp
11191 line)
11192 ;; This is a headline
11193 (progn
11194 (setq level (- (match-end 1) (match-beginning 1))
11195 level (org-tr-level level)
11196 txt (match-string 3 line)
11197 todo
11198 (or (and (match-beginning 2)
11199 (not (equal (match-string 2 line)
11200 org-done-string)))
11201 ; TODO, not DONE
11202 (and org-export-mark-todo-in-toc
11203 (= level umax)
11204 (org-search-todo-below
11205 line lines level))))
11206 (setq txt (org-html-expand-for-ascii txt))
11208 (if org-export-with-section-numbers
11209 (setq txt (concat (org-section-number level)
11210 " " txt)))
11211 (if (<= level umax)
11212 (progn
11213 (insert
11214 (make-string (* (1- level) 4) ?\ )
11215 (format (if todo "%s (*)\n" "%s\n") txt))
11216 (setq org-last-level level))
11217 ))))
11218 lines)))
11220 (org-init-section-numbers)
11221 (while (setq line (pop lines))
11222 ;; Remove the quoted HTML tags.
11223 (setq line (org-html-expand-for-ascii line))
11224 ;; Remove targets
11225 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
11226 (setq line (replace-match "" t t line)))
11227 ;; Replace internal links
11228 (while (string-match org-bracket-link-regexp line)
11229 (setq line (replace-match
11230 (if (match-end 3) "[\\3]" "[\\1]")
11231 t nil line)))
11232 (cond
11233 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11234 ;; a Headline
11235 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11236 txt (match-string 2 line))
11237 (org-ascii-level-start level txt umax))
11238 (t (insert line "\n"))))
11239 (normal-mode)
11240 (save-buffer)
11241 (goto-char (point-min))))
11243 (defun org-search-todo-below (line lines level)
11244 "Search the subtree below LINE for any TODO entries."
11245 (let ((rest (cdr (memq line lines)))
11246 (re org-todo-line-regexp)
11247 line lv todo)
11248 (catch 'exit
11249 (while (setq line (pop rest))
11250 (if (string-match re line)
11251 (progn
11252 (setq lv (- (match-end 1) (match-beginning 1))
11253 todo (and (match-beginning 2)
11254 (not (equal (match-string 2 line)
11255 org-done-string))))
11256 ; TODO, not DONE
11257 (if (<= lv level) (throw 'exit nil))
11258 (if todo (throw 'exit t))))))))
11260 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
11261 ;; We could also implement *bold*,/italic/ and _underline_ for ASCII export
11262 (defun org-html-expand-for-ascii (line)
11263 "Handle quoted HTML for ASCII export."
11264 (if org-export-html-expand
11265 (while (string-match "@<[^<>\n]*>" line)
11266 ;; We just remove the tags for now.
11267 (setq line (replace-match "" nil nil line))))
11268 line)
11270 (defun org-insert-centered (s &optional underline)
11271 "Insert the string S centered and underline it with character UNDERLINE."
11272 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
11273 (insert (make-string ind ?\ ) s "\n")
11274 (if underline
11275 (insert (make-string ind ?\ )
11276 (make-string (string-width s) underline)
11277 "\n"))))
11279 (defun org-ascii-level-start (level title umax)
11280 "Insert a new level in ASCII export."
11281 (let (char)
11282 (if (> level umax)
11283 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
11284 (if (or (not (equal (char-before) ?\n))
11285 (not (equal (char-before (1- (point))) ?\n)))
11286 (insert "\n"))
11287 (setq char (nth (- umax level) (reverse org-ascii-underline)))
11288 (if org-export-with-section-numbers
11289 (setq title (concat (org-section-number level) " " title)))
11290 (insert title "\n" (make-string (string-width title) char) "\n"))))
11292 (defun org-export-copy-visible ()
11293 "Copy the visible part of the buffer to another buffer, for printing.
11294 Also removes the first line of the buffer if it specifies a mode,
11295 and all options lines."
11296 (interactive)
11297 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
11298 ".txt"))
11299 (buffer (find-file-noselect filename))
11300 (ore (concat
11301 (org-make-options-regexp
11302 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
11303 "STARTUP" "ARCHIVE"
11304 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
11305 (if org-noutline-p "\\(\n\\|$\\)" "")))
11306 s e)
11307 (with-current-buffer buffer
11308 (erase-buffer)
11309 (text-mode))
11310 (save-excursion
11311 (setq s (goto-char (point-min)))
11312 (while (not (= (point) (point-max)))
11313 (goto-char (org-find-invisible))
11314 (append-to-buffer buffer s (point))
11315 (setq s (goto-char (org-find-visible)))))
11316 (switch-to-buffer-other-window buffer)
11317 (newline)
11318 (goto-char (point-min))
11319 (if (looking-at ".*-\\*- mode:.*\n")
11320 (replace-match ""))
11321 (while (re-search-forward ore nil t)
11322 (replace-match ""))
11323 (goto-char (point-min))))
11325 (defun org-find-visible ()
11326 (if (featurep 'noutline)
11327 (let ((s (point)))
11328 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11329 (get-char-property s 'invisible)))
11331 (skip-chars-forward "^\n")
11332 (point)))
11333 (defun org-find-invisible ()
11334 (if (featurep 'noutline)
11335 (let ((s (point)))
11336 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11337 (not (get-char-property s 'invisible))))
11339 (skip-chars-forward "^\r")
11340 (point)))
11342 ;; HTML
11344 (defun org-get-current-options ()
11345 "Return a string with current options as keyword options.
11346 Does include HTML export options as well as TODO and CATEGORY stuff."
11347 (format
11348 "#+TITLE: %s
11349 #+AUTHOR: %s
11350 #+EMAIL: %s
11351 #+LANGUAGE: %s
11352 #+TEXT: Some descriptive text to be emitted. Several lines OK.
11353 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
11354 #+CATEGORY: %s
11355 #+SEQ_TODO: %s
11356 #+TYP_TODO: %s
11357 #+STARTUP: %s %s %s %s %s
11358 #+ARCHIVE: %s
11360 (buffer-name) (user-full-name) user-mail-address org-export-default-language
11361 org-export-headline-levels
11362 org-export-with-section-numbers
11363 org-export-with-toc
11364 org-export-preserve-breaks
11365 org-export-html-expand
11366 org-export-with-fixed-width
11367 org-export-with-tables
11368 org-export-with-sub-superscripts
11369 org-export-with-emphasize
11370 org-export-with-TeX-macros
11371 (file-name-nondirectory buffer-file-name)
11372 (if (equal org-todo-interpretation 'sequence)
11373 (mapconcat 'identity org-todo-keywords " ")
11374 "TODO FEEDBACK VERIFY DONE")
11375 (if (equal org-todo-interpretation 'type)
11376 (mapconcat 'identity org-todo-keywords " ")
11377 "Me Jason Marie DONE")
11378 (cdr (assoc org-startup-folded
11379 '((nil . "nofold")(t . "fold")(content . "content"))))
11380 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
11381 (if org-odd-levels-only "odd" "oddeven")
11382 (if org-hide-leading-stars "hidestars" "showstars")
11383 (if org-startup-align-all-tables "align" "noalign")
11384 org-archive-location
11387 (defun org-insert-export-options-template ()
11388 "Insert into the buffer a template with information for exporting."
11389 (interactive)
11390 (if (not (bolp)) (newline))
11391 (let ((s (org-get-current-options)))
11392 (and (string-match "#\\+CATEGORY" s)
11393 (setq s (substring s 0 (match-beginning 0))))
11394 (insert s)))
11396 (defun org-toggle-fixed-width-section (arg)
11397 "Toggle the fixed-width export.
11398 If there is no active region, the QUOTE keyword at the current headline is
11399 inserted or removed. When present, it causes the text between this headline
11400 and the next to be exported as fixed-width text, and unmodified.
11401 If there is an active region, this command adds or removes a colon as the
11402 first character of this line. If the first character of a line is a colon,
11403 this line is also exported in fixed-width font."
11404 (interactive "P")
11405 (let* ((cc 0)
11406 (regionp (org-region-active-p))
11407 (beg (if regionp (region-beginning) (point)))
11408 (end (if regionp (region-end)))
11409 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
11410 (re "[ \t]*\\(:\\)")
11411 off)
11412 (if regionp
11413 (save-excursion
11414 (goto-char beg)
11415 (setq cc (current-column))
11416 (beginning-of-line 1)
11417 (setq off (looking-at re))
11418 (while (> nlines 0)
11419 (setq nlines (1- nlines))
11420 (beginning-of-line 1)
11421 (cond
11422 (arg
11423 (move-to-column cc t)
11424 (insert ":\n")
11425 (forward-line -1))
11426 ((and off (looking-at re))
11427 (replace-match "" t t nil 1))
11428 ((not off) (move-to-column cc t) (insert ":")))
11429 (forward-line 1)))
11430 (save-excursion
11431 (org-back-to-heading)
11432 (if (looking-at (concat outline-regexp
11433 "\\( +\\<" org-quote-string "\\>\\)"))
11434 (replace-match "" t t nil 1)
11435 (if (looking-at outline-regexp)
11436 (progn
11437 (goto-char (match-end 0))
11438 (insert " " org-quote-string))))))))
11440 (defun org-export-as-html-and-open (arg)
11441 "Export the outline as HTML and immediately open it with a browser.
11442 If there is an active region, export only the region.
11443 The prefix ARG specifies how many levels of the outline should become
11444 headlines. The default is 3. Lower levels will become bulleted lists."
11445 (interactive "P")
11446 (org-export-as-html arg 'hidden)
11447 (org-open-file buffer-file-name))
11449 (defun org-export-as-html-batch ()
11450 "Call `org-export-as-html', may be used in batch processing as
11451 emacs --batch
11452 --load=$HOME/lib/emacs/org.el
11453 --eval \"(setq org-export-headline-levels 2)\"
11454 --visit=MyFile --funcall org-export-as-html-batch"
11455 (org-export-as-html org-export-headline-levels 'hidden))
11457 (defun org-export-as-html (arg &optional hidden)
11458 "Export the outline as a pretty HTML file.
11459 If there is an active region, export only the region.
11460 The prefix ARG specifies how many levels of the outline should become
11461 headlines. The default is 3. Lower levels will become bulleted lists."
11462 (interactive "P")
11463 (setq-default org-todo-line-regexp org-todo-line-regexp)
11464 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
11465 (setq-default org-done-string org-done-string)
11466 (let* ((style org-export-html-style)
11467 (odd org-odd-levels-only)
11468 (region-p (org-region-active-p))
11469 (region
11470 (buffer-substring
11471 (if region-p (region-beginning) (point-min))
11472 (if region-p (region-end) (point-max))))
11473 (all_lines
11474 (org-skip-comments (org-split-string
11475 (org-cleaned-string-for-export region)
11476 "[\r\n]")))
11477 (lines (org-export-find-first-heading-line all_lines))
11478 (level 0) (line "") (origline "") txt todo
11479 (umax nil)
11480 (filename (concat (file-name-sans-extension buffer-file-name)
11481 ".html"))
11482 (buffer (find-file-noselect filename))
11483 (levels-open (make-vector org-level-max nil))
11484 (date (format-time-string "%Y/%m/%d" (current-time)))
11485 (time (format-time-string "%X" (org-current-time)))
11486 (author user-full-name)
11487 (title (buffer-name))
11488 (options nil)
11489 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
11490 (inquote nil)
11491 (infixed nil)
11492 (in-local-list nil)
11493 (local-list-num nil)
11494 (local-list-indent nil)
11495 (llt org-plain-list-ordered-item-terminator)
11496 (email user-mail-address)
11497 (language org-export-default-language)
11498 (text nil)
11499 (lang-words nil)
11500 (target-alist nil) tg
11501 (head-count 0) cnt
11502 (start 0)
11503 ;; FIXME: The following returns always nil under XEmacs
11504 (coding-system (and (fboundp 'coding-system-get)
11505 (boundp 'buffer-file-coding-system)
11506 buffer-file-coding-system))
11507 (coding-system-for-write (or coding-system coding-system-for-write))
11508 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
11509 (charset (and coding-system
11510 (coding-system-get coding-system 'mime-charset)))
11511 table-open type
11512 table-buffer table-orig-buffer
11513 ind start-is-num starter
11514 rpl path desc desc1 desc2 link
11516 (message "Exporting...")
11518 (setq org-last-level 1)
11519 (org-init-section-numbers)
11521 ;; Search for the export key lines
11522 (org-parse-key-lines)
11523 (setq lang-words (or (assoc language org-export-language-setup)
11524 (assoc "en" org-export-language-setup)))
11526 ;; Switch to the output buffer
11527 (if (or hidden (not org-export-html-show-new-buffer))
11528 (set-buffer buffer)
11529 (switch-to-buffer-other-window buffer))
11530 (erase-buffer)
11531 (fundamental-mode)
11532 (let ((case-fold-search nil)
11533 (org-odd-levels-only odd))
11534 (if options (org-parse-export-options options))
11535 (setq umax (if arg (prefix-numeric-value arg)
11536 org-export-headline-levels))
11538 ;; File header
11539 (insert (format
11540 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
11541 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
11542 <html lang=\"%s\"><head>
11543 <title>%s</title>
11544 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
11545 <meta name=generator content=\"Org-mode\">
11546 <meta name=generated content=\"%s %s\">
11547 <meta name=author content=\"%s\">
11549 </head><body>
11551 language (org-html-expand title) (or charset "iso-8859-1")
11552 date time author style))
11553 (if title (insert (concat "<H1 class=\"title\">"
11554 (org-html-expand title) "</H1>\n")))
11555 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
11556 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
11557 email "&gt;</a>\n")))
11558 (if (or author email) (insert "<br>\n"))
11559 (if (and date time) (insert (concat (nth 2 lang-words) ": "
11560 date " " time "<br>\n")))
11561 (if text (insert (concat "<p>\n" (org-html-expand text))))
11562 (if org-export-with-toc
11563 (progn
11564 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
11565 (insert "<ul>\n")
11566 (setq lines
11567 (mapcar '(lambda (line)
11568 (if (string-match org-todo-line-regexp line)
11569 ;; This is a headline
11570 (progn
11571 (setq level (- (match-end 1) (match-beginning 1))
11572 level (org-tr-level level)
11573 txt (save-match-data
11574 (org-html-expand
11575 (match-string 3 line)))
11576 todo
11577 (or (and (match-beginning 2)
11578 (not (equal (match-string 2 line)
11579 org-done-string)))
11580 ; TODO, not DONE
11581 (and org-export-mark-todo-in-toc
11582 (= level umax)
11583 (org-search-todo-below
11584 line lines level))))
11585 (if org-export-with-section-numbers
11586 (setq txt (concat (org-section-number level)
11587 " " txt)))
11588 (if (<= level umax)
11589 (progn
11590 (setq head-count (+ head-count 1))
11591 (if (> level org-last-level)
11592 (progn
11593 (setq cnt (- level org-last-level))
11594 (while (>= (setq cnt (1- cnt)) 0)
11595 (insert "<ul>"))
11596 (insert "\n")))
11597 (if (< level org-last-level)
11598 (progn
11599 (setq cnt (- org-last-level level))
11600 (while (>= (setq cnt (1- cnt)) 0)
11601 (insert "</ul>"))
11602 (insert "\n")))
11603 ;; Check for targets
11604 (while (string-match org-target-regexp line)
11605 (setq tg (match-string 1 line)
11606 line (replace-match
11607 (concat "@<span class=\"target\">" tg "@</span> ")
11608 t t line))
11609 (push (cons (org-solidify-link-text tg)
11610 (format "sec-%d" head-count))
11611 target-alist))
11612 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
11613 (setq txt (replace-match "" t t txt)))
11614 (insert
11615 (format
11616 (if todo
11617 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
11618 "<li><a href=\"#sec-%d\">%s</a>\n")
11619 head-count txt))
11621 (setq org-last-level level))
11623 line)
11624 lines))
11625 (while (> org-last-level 0)
11626 (setq org-last-level (1- org-last-level))
11627 (insert "</ul>\n"))
11629 (setq head-count 0)
11630 (org-init-section-numbers)
11632 (while (setq line (pop lines) origline line)
11633 (catch 'nextline
11635 ;; end of quote section?
11636 (when (and inquote (string-match "^\\*+" line))
11637 (insert "</pre>\n")
11638 (setq inquote nil))
11639 ;; inside a quote section?
11640 (when inquote
11641 (insert (org-html-protect line) "\n")
11642 (throw 'nextline nil))
11644 ;; verbatim lines
11645 (when (and org-export-with-fixed-width
11646 (string-match "^[ \t]*:\\(.*\\)" line))
11647 (when (not infixed)
11648 (setq infixed t)
11649 (insert "<pre>\n"))
11650 (insert (org-html-protect (match-string 1 line)) "\n")
11651 (when (and lines
11652 (not (string-match "^[ \t]*\\(:.*\\)"
11653 (car lines))))
11654 (setq infixed nil)
11655 (insert "</pre>\n"))
11656 (throw 'nextline nil))
11659 ;; make targets to anchors
11660 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
11661 (cond
11662 ((match-end 2)
11663 (setq line (replace-match
11664 (concat "@<a name=\""
11665 (org-solidify-link-text (match-string 1 line))
11666 "\">\\nbsp@</a>")
11667 t t line)))
11668 ((and org-export-with-toc (equal (string-to-char line) ?*))
11669 (setq line (replace-match
11670 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
11671 ; (concat "@<i>" (match-string 1 line) "@</i> ")
11672 t t line)))
11674 (setq line (replace-match
11675 (concat "@<a name=\""
11676 (org-solidify-link-text (match-string 1 line))
11677 "\" class=\"target\">" (match-string 1 line) "@</a> ")
11678 t t line)))))
11680 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
11681 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
11682 (setq line (org-html-expand line))
11684 ;; Format the links
11685 (setq start 0)
11686 (while (string-match org-bracket-link-analytic-regexp line start)
11687 (setq start (match-beginning 0))
11688 (setq type (if (match-end 2) (match-string 2 line) "internal"))
11689 (setq path (match-string 3 line))
11690 (setq desc1 (if (match-end 5) (match-string 5 line))
11691 desc2 (if (match-end 2) (concat type ":" path) path)
11692 desc (or desc1 desc2))
11693 (cond
11694 ((equal type "internal")
11695 (setq rpl
11696 (concat
11697 "<a href=\"#"
11698 (org-solidify-link-text path target-alist)
11699 "\">" desc "</a>")))
11700 ((member type '("http" "https" "ftp" "mailto" "news"))
11701 ;; standard URL
11702 (setq link (concat type ":" path))
11703 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
11704 ((string= type "file")
11705 ;; FILE link
11706 (let* ((filename path)
11707 (abs-p (file-name-absolute-p filename))
11708 (thefile (if abs-p (expand-file-name filename) filename))
11709 (thefile (save-match-data
11710 (if (string-match ":[0-9]+$" thefile)
11711 (replace-match "" t t thefile)
11712 thefile)))
11713 (file-is-image-p
11714 (save-match-data
11715 (string-match (org-image-file-name-regexp) thefile))))
11716 (setq rpl (if (and org-export-html-inline-images
11717 file-is-image-p)
11718 (concat "<img src=\"" thefile "\"/>")
11719 (concat "<a href=\"" thefile "\">" desc "</a>")))))
11720 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11721 (setq rpl (concat "<i>&lt;" type ":" path "&gt;</i>"))))
11722 ;; FIXME: We get to see the escaped links!!!!!
11723 (setq line (replace-match rpl t t line)
11724 start (+ start (length rpl))))
11725 ;; TODO items
11726 (if (and (string-match org-todo-line-regexp line)
11727 (match-beginning 2))
11728 (if (equal (match-string 2 line) org-done-string)
11729 (setq line (replace-match
11730 "<span class=\"done\">\\2</span>"
11731 nil nil line 2))
11732 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11733 nil nil line 2))))
11735 ;; DEADLINES
11736 (if (string-match org-deadline-line-regexp line)
11737 (progn
11738 (if (save-match-data
11739 (string-match "<a href"
11740 (substring line 0 (match-beginning 0))))
11741 nil ; Don't do the replacement - it is inside a link
11742 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11743 nil nil line 1)))))
11744 (cond
11745 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11746 ;; This is a headline
11747 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11748 txt (match-string 2 line))
11749 (if (<= level umax) (setq head-count (+ head-count 1)))
11750 (when in-local-list
11751 ;; Close any local lists before inserting a new header line
11752 (while local-list-num
11753 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11754 (pop local-list-num))
11755 (setq local-list-indent nil
11756 in-local-list nil))
11757 (org-html-level-start level txt umax
11758 (and org-export-with-toc (<= level umax))
11759 head-count)
11760 ;; QUOTES
11761 (when (string-match quote-re line)
11762 (insert "<pre>")
11763 (setq inquote t)))
11765 ((and org-export-with-tables
11766 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11767 (if (not table-open)
11768 ;; New table starts
11769 (setq table-open t table-buffer nil table-orig-buffer nil))
11770 ;; Accumulate lines
11771 (setq table-buffer (cons line table-buffer)
11772 table-orig-buffer (cons origline table-orig-buffer))
11773 (when (or (not lines)
11774 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11775 (car lines))))
11776 (setq table-open nil
11777 table-buffer (nreverse table-buffer)
11778 table-orig-buffer (nreverse table-orig-buffer))
11779 (insert (org-format-table-html table-buffer table-orig-buffer))))
11781 ;; Normal lines
11782 (when (and (string-match
11783 (cond
11784 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11785 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11786 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11787 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
11788 line))
11789 (setq ind (org-get-string-indentation line)
11790 start-is-num (match-beginning 4)
11791 starter (if (match-beginning 2) (match-string 2 line))
11792 line (substring line (match-beginning 5)))
11793 (unless (string-match "[^ \t]" line)
11794 ;; empty line. Pretend indentation is large.
11795 (setq ind (1+ (or (car local-list-indent) 1))))
11796 (while (and in-local-list
11797 (or (and (= ind (car local-list-indent))
11798 (not starter))
11799 (< ind (car local-list-indent))))
11800 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11801 (pop local-list-num) (pop local-list-indent)
11802 (setq in-local-list local-list-indent))
11803 (cond
11804 ((and starter
11805 (or (not in-local-list)
11806 (> ind (car local-list-indent))))
11807 ;; Start new (level of ) list
11808 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
11809 (push start-is-num local-list-num)
11810 (push ind local-list-indent)
11811 (setq in-local-list t))
11812 (starter
11813 ;; continue current list
11814 (insert "<li>\n"))))
11815 ;; Empty lines start a new paragraph. If hand-formatted lists
11816 ;; are not fully interpreted, lines starting with "-", "+", "*"
11817 ;; also start a new paragraph.
11818 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
11819 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
11821 (if org-export-html-with-timestamp
11822 (insert org-export-html-html-helper-timestamp))
11823 (insert "</body>\n</html>\n")
11824 (normal-mode)
11825 (save-buffer)
11826 (goto-char (point-min)))))
11828 (defun org-format-table-html (lines olines)
11829 "Find out which HTML converter to use and return the HTML code."
11830 (if (string-match "^[ \t]*|" (car lines))
11831 ;; A normal org table
11832 (org-format-org-table-html lines)
11833 ;; Table made by table.el - test for spanning
11834 (let* ((hlines (delq nil (mapcar
11835 (lambda (x)
11836 (if (string-match "^[ \t]*\\+-" x) x
11837 nil))
11838 lines)))
11839 (first (car hlines))
11840 (ll (and (string-match "\\S-+" first)
11841 (match-string 0 first)))
11842 (re (concat "^[ \t]*" (regexp-quote ll)))
11843 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
11844 hlines))))
11845 (if (and (not spanning)
11846 (not org-export-prefer-native-exporter-for-tables))
11847 ;; We can use my own converter with HTML conversions
11848 (org-format-table-table-html lines)
11849 ;; Need to use the code generator in table.el, with the original text.
11850 (org-format-table-table-html-using-table-generate-source olines)))))
11852 (defun org-format-org-table-html (lines)
11853 "Format a table into HTML."
11854 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11855 (setq lines (nreverse lines))
11856 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11857 (setq lines (nreverse lines))
11858 (when org-export-table-remove-special-lines
11859 ;; Check if the table has a marking column. If yes remove the
11860 ;; column and the special lines
11861 (let* ((special
11862 (not
11863 (memq nil
11864 (mapcar
11865 (lambda (x)
11866 (or (string-match "^[ \t]*|-" x)
11867 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
11868 lines)))))
11869 (if special
11870 (setq lines
11871 (delq nil
11872 (mapcar
11873 (lambda (x)
11874 (if (string-match "^[ \t]*| *[!_^] *|" x)
11875 nil ; ignore this line
11876 (and (or (string-match "^[ \t]*|-+\\+" x)
11877 (string-match "^[ \t]*|[^|]*|" x))
11878 (replace-match "|" t t x))))
11879 lines))))))
11881 (let ((head (and org-export-highlight-first-table-line
11882 (delq nil (mapcar
11883 (lambda (x) (string-match "^[ \t]*|-" x))
11884 (cdr lines)))))
11885 line fields html)
11886 (setq html (concat org-export-html-table-tag "\n"))
11887 (while (setq line (pop lines))
11888 (catch 'next-line
11889 (if (string-match "^[ \t]*|-" line)
11890 (progn
11891 (setq head nil) ;; head ends here, first time around
11892 ;; ignore this line
11893 (throw 'next-line t)))
11894 ;; Break the line into fields
11895 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11896 (setq html (concat
11897 html
11898 "<tr>"
11899 (mapconcat (lambda (x)
11900 (if head
11901 (concat "<th>" x "</th>")
11902 (concat "<td>" x "</td>")))
11903 fields "")
11904 "</tr>\n"))))
11905 (setq html (concat html "</table>\n"))
11906 html))
11908 (defun org-fake-empty-table-line (line)
11909 "Replace everything except \"|\" with spaces."
11910 (let ((i (length line))
11911 (newstr (copy-sequence line)))
11912 (while (> i 0)
11913 (setq i (1- i))
11914 (if (not (eq (aref newstr i) ?|))
11915 (aset newstr i ?\ )))
11916 newstr))
11918 (defun org-format-table-table-html (lines)
11919 "Format a table generated by table.el into HTML.
11920 This conversion does *not* use `table-generate-source' from table.el.
11921 This has the advantage that Org-mode's HTML conversions can be used.
11922 But it has the disadvantage, that no cell- or row-spanning is allowed."
11923 (let (line field-buffer
11924 (head org-export-highlight-first-table-line)
11925 fields html empty)
11926 (setq html (concat org-export-html-table-tag "\n"))
11927 (while (setq line (pop lines))
11928 (setq empty "&nbsp")
11929 (catch 'next-line
11930 (if (string-match "^[ \t]*\\+-" line)
11931 (progn
11932 (if field-buffer
11933 (progn
11934 (setq html (concat
11935 html
11936 "<tr>"
11937 (mapconcat
11938 (lambda (x)
11939 (if (equal x "") (setq x empty))
11940 (if head
11941 (concat "<th>" x "</th>\n")
11942 (concat "<td>" x "</td>\n")))
11943 field-buffer "\n")
11944 "</tr>\n"))
11945 (setq head nil)
11946 (setq field-buffer nil)))
11947 ;; Ignore this line
11948 (throw 'next-line t)))
11949 ;; Break the line into fields and store the fields
11950 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11951 (if field-buffer
11952 (setq field-buffer (mapcar
11953 (lambda (x)
11954 (concat x "<br>" (pop fields)))
11955 field-buffer))
11956 (setq field-buffer fields))))
11957 (setq html (concat html "</table>\n"))
11958 html))
11960 (defun org-format-table-table-html-using-table-generate-source (lines)
11961 "Format a table into html, using `table-generate-source' from table.el.
11962 This has the advantage that cell- or row-spanning is allowed.
11963 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
11964 (require 'table)
11965 (with-current-buffer (get-buffer-create " org-tmp1 ")
11966 (erase-buffer)
11967 (insert (mapconcat 'identity lines "\n"))
11968 (goto-char (point-min))
11969 (if (not (re-search-forward "|[^+]" nil t))
11970 (error "Error processing table"))
11971 (table-recognize-table)
11972 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
11973 (table-generate-source 'html " org-tmp2 ")
11974 (set-buffer " org-tmp2 ")
11975 (buffer-substring (point-min) (point-max))))
11977 (defun org-html-protect (s)
11978 ;; convert & to &amp;, < to &lt; and > to &gt;
11979 (let ((start 0))
11980 (while (string-match "&" s start)
11981 (setq s (replace-match "&amp;" t t s)
11982 start (1+ (match-beginning 0))))
11983 (while (string-match "<" s)
11984 (setq s (replace-match "&lt;" t t s)))
11985 (while (string-match ">" s)
11986 (setq s (replace-match "&gt;" t t s))))
11989 (defun org-html-expand (string)
11990 "Prepare STRING for HTML export. Applies all active conversions.
11991 If there are links in the string, don't modify these."
11992 (let* (m s l res)
11993 (while (setq m (string-match org-bracket-link-regexp string))
11994 (setq s (substring string 0 m)
11995 l (match-string 0 string)
11996 string (substring string (match-end 0)))
11997 (push (org-html-do-expand s) res)
11998 (push l res))
11999 (push (org-html-do-expand string) res)
12000 (apply 'concat (nreverse res))))
12002 (defun org-html-do-expand (s)
12003 "Apply all active conversions to translate special ASCII to HTML."
12004 (setq s (org-html-protect s))
12005 (if org-export-html-expand
12006 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
12007 (setq s (replace-match "<\\1>" nil nil s))))
12008 (if org-export-with-emphasize
12009 (setq s (org-export-html-convert-emphasize s)))
12010 (if org-export-with-sub-superscripts
12011 (setq s (org-export-html-convert-sub-super s)))
12012 (if org-export-with-TeX-macros
12013 (let ((start 0) wd ass)
12014 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
12015 (setq wd (match-string 1 s))
12016 (if (setq ass (assoc wd org-html-entities))
12017 (setq s (replace-match (or (cdr ass)
12018 (concat "&" (car ass) ";"))
12019 t t s))
12020 (setq start (+ start (length wd)))))))
12023 (defun org-create-multibrace-regexp (left right n)
12024 "Create a regular expression which will match a balanced sexp.
12025 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
12026 as single character strings.
12027 The regexp returned will match the entire expression including the
12028 delimiters. It will also define a single group which contains the
12029 match except for the outermost delimiters. The maximum depth of
12030 stacked delimiters is N. Escaping delimiters is not possible."
12031 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
12032 (or "\\|")
12033 (re nothing)
12034 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
12035 (while (> n 1)
12036 (setq n (1- n)
12037 re (concat re or next)
12038 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
12039 (concat left "\\(" re "\\)" right)))
12041 (defvar org-match-substring-regexp
12042 (concat
12043 "\\([^\\]\\)\\([_^]\\)\\("
12044 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
12045 "\\|"
12046 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
12047 "\\|"
12048 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
12049 "The regular expression matching a sub- or superscript.")
12051 (defun org-export-html-convert-sub-super (string)
12052 "Convert sub- and superscripts in STRING to HTML."
12053 (let (key c)
12054 (while (string-match org-match-substring-regexp string)
12055 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
12056 (setq c (or (match-string 8 string)
12057 (match-string 6 string)
12058 (match-string 5 string)))
12059 (setq string (replace-match
12060 (concat (match-string 1 string)
12061 "<" key ">" c "</" key ">")
12062 t t string)))
12063 (while (string-match "\\\\\\([_^]\\)" string)
12064 (setq string (replace-match (match-string 1 string) t t string))))
12065 string)
12067 (defun org-export-html-convert-emphasize (string)
12068 (let (c (s 0))
12069 (while (string-match "\\(\\W\\|^\\)\\([*/_]\\)\\(\\w+\\)\\2\\(\\W\\|$\\)" string s)
12070 (setq c (cdr (assoc (match-string 2 string)
12071 '(("*" . "b") ("/" . "i") ("_" . "u"))))
12072 s (+ (match-end 0) 3)
12073 string (replace-match
12074 (concat "\\1<" c ">\\3</" c ">\\4") t nil string)))
12075 string))
12077 (defun org-parse-key-lines ()
12078 "Find the special key lines with the information for exporters."
12079 (save-excursion
12080 (goto-char 0)
12081 (let ((re (org-make-options-regexp
12082 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12083 key)
12084 (while (re-search-forward re nil t)
12085 (setq key (match-string 1))
12086 (cond ((string-equal key "TITLE")
12087 (setq title (match-string 2)))
12088 ((string-equal key "AUTHOR")
12089 (setq author (match-string 2)))
12090 ((string-equal key "EMAIL")
12091 (setq email (match-string 2)))
12092 ((string-equal key "LANGUAGE")
12093 (setq language (match-string 2)))
12094 ((string-equal key "TEXT")
12095 (setq text (concat text "\n" (match-string 2))))
12096 ((string-equal key "OPTIONS")
12097 (setq options (match-string 2))))))))
12099 (defun org-parse-export-options (s)
12100 "Parse the export options line."
12101 (let ((op '(("H" . org-export-headline-levels)
12102 ("num" . org-export-with-section-numbers)
12103 ("toc" . org-export-with-toc)
12104 ("\\n" . org-export-preserve-breaks)
12105 ("@" . org-export-html-expand)
12106 (":" . org-export-with-fixed-width)
12107 ("|" . org-export-with-tables)
12108 ("^" . org-export-with-sub-superscripts)
12109 ("*" . org-export-with-emphasize)
12110 ("TeX" . org-export-with-TeX-macros)))
12112 (while (setq o (pop op))
12113 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
12115 (set (make-local-variable (cdr o))
12116 (car (read-from-string (match-string 1 s))))))))
12118 (defun org-html-level-start (level title umax with-toc head-count)
12119 "Insert a new level in HTML export."
12120 (let ((l (1+ (max level umax))))
12121 (while (<= l org-level-max)
12122 (if (aref levels-open (1- l))
12123 (progn
12124 (org-html-level-close l)
12125 (aset levels-open (1- l) nil)))
12126 (setq l (1+ l)))
12127 (if (> level umax)
12128 (progn
12129 (if (aref levels-open (1- level))
12130 (insert "<li>" title "<p>\n")
12131 (aset levels-open (1- level) t)
12132 (insert "<ul><li>" title "<p>\n")))
12133 (if org-export-with-section-numbers
12134 (setq title (concat (org-section-number level) " " title)))
12135 (setq level (+ level 1))
12136 (if with-toc
12137 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
12138 level head-count title level))
12139 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
12141 (defun org-html-level-close (&rest args)
12142 "Terminate one level in HTML export."
12143 (insert "</ul>"))
12145 ;; Variable holding the vector with section numbers
12146 (defvar org-section-numbers (make-vector org-level-max 0))
12148 (defun org-init-section-numbers ()
12149 "Initialize the vector for the section numbers."
12150 (let* ((level -1)
12151 (numbers (nreverse (org-split-string "" "\\.")))
12152 (depth (1- (length org-section-numbers)))
12153 (i depth) number-string)
12154 (while (>= i 0)
12155 (if (> i level)
12156 (aset org-section-numbers i 0)
12157 (setq number-string (or (car numbers) "0"))
12158 (if (string-match "\\`[A-Z]\\'" number-string)
12159 (aset org-section-numbers i
12160 (- (string-to-char number-string) ?A -1))
12161 (aset org-section-numbers i (string-to-number number-string)))
12162 (pop numbers))
12163 (setq i (1- i)))))
12165 (defun org-section-number (&optional level)
12166 "Return a string with the current section number.
12167 When LEVEL is non-nil, increase section numbers on that level."
12168 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
12169 (when level
12170 (when (> level -1)
12171 (aset org-section-numbers
12172 level (1+ (aref org-section-numbers level))))
12173 (setq idx (1+ level))
12174 (while (<= idx depth)
12175 (if (not (= idx 1))
12176 (aset org-section-numbers idx 0))
12177 (setq idx (1+ idx))))
12178 (setq idx 0)
12179 (while (<= idx depth)
12180 (setq n (aref org-section-numbers idx))
12181 (setq string (concat string (if (not (string= string "")) "." "")
12182 (int-to-string n)))
12183 (setq idx (1+ idx)))
12184 (save-match-data
12185 (if (string-match "\\`\\([@0]\\.\\)+" string)
12186 (setq string (replace-match "" nil nil string)))
12187 (if (string-match "\\(\\.0\\)+\\'" string)
12188 (setq string (replace-match "" nil nil string))))
12189 string))
12192 (defun org-export-icalendar-this-file ()
12193 "Export current file as an iCalendar file.
12194 The iCalendar file will be located in the same directory as the Org-mode
12195 file, but with extension `.ics'."
12196 (interactive)
12197 (org-export-icalendar nil buffer-file-name))
12199 ;;;###autoload
12200 (defun org-export-icalendar-all-agenda-files ()
12201 "Export all files in `org-agenda-files' to iCalendar .ics files.
12202 Each iCalendar file will be located in the same directory as the Org-mode
12203 file, but with extension `.ics'."
12204 (interactive)
12205 (apply 'org-export-icalendar nil (org-agenda-files t)))
12207 ;;;###autoload
12208 (defun org-export-icalendar-combine-agenda-files ()
12209 "Export all files in `org-agenda-files' to a single combined iCalendar file.
12210 The file is stored under the name `org-combined-agenda-icalendar-file'."
12211 (interactive)
12212 (apply 'org-export-icalendar t (org-agenda-files t)))
12214 (defun org-export-icalendar (combine &rest files)
12215 "Create iCalendar files for all elements of FILES.
12216 If COMBINE is non-nil, combine all calendar entries into a single large
12217 file and store it under the name `org-combined-agenda-icalendar-file'."
12218 (save-excursion
12219 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
12220 (when combine
12221 (setq ical-file org-combined-agenda-icalendar-file
12222 ical-buffer (org-get-agenda-file-buffer ical-file))
12223 (set-buffer ical-buffer) (erase-buffer))
12224 (while (setq file (pop files))
12225 (catch 'nextfile
12226 (org-check-agenda-file file)
12227 (unless combine
12228 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
12229 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
12230 (set-buffer ical-buffer) (erase-buffer))
12231 (set-buffer (org-get-agenda-file-buffer file))
12232 (setq category (or org-category
12233 (file-name-sans-extension
12234 (file-name-nondirectory buffer-file-name))))
12235 (if (symbolp category) (setq category (symbol-name category)))
12236 (let ((standard-output ical-buffer))
12237 (if combine
12238 (and (not started) (setq started t)
12239 (org-start-icalendar-file org-icalendar-combined-name))
12240 (org-start-icalendar-file category))
12241 (org-print-icalendar-entries combine category)
12242 (when (or (and combine (not files)) (not combine))
12243 (org-finish-icalendar-file)
12244 (set-buffer ical-buffer)
12245 (save-buffer)
12246 (run-hooks 'org-after-save-iCalendar-file-hook)))))
12247 (org-release-buffers org-agenda-new-buffers))))
12249 (defvar org-after-save-iCalendar-file-hook nil
12250 "Hook run after an iCalendar file has been saved.
12251 The iCalendar buffer is still current when this hook is run.
12252 A good way to use this is to tell a desktop calenndar application to re-read
12253 the iCalendar file.")
12255 (defun org-print-icalendar-entries (&optional combine category)
12256 "Print iCalendar entries for the current Org-mode file to `standard-output'.
12257 When COMBINE is non nil, add the category to each line."
12258 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
12259 (dts (org-ical-ts-to-string
12260 (format-time-string (cdr org-time-stamp-formats) (current-time))
12261 "DTSTART"))
12262 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
12263 (save-excursion
12264 (goto-char (point-min))
12265 (while (re-search-forward org-ts-regexp nil t)
12266 (setq pos (match-beginning 0)
12267 ts (match-string 0)
12268 inc t
12269 hd (org-get-heading))
12270 (if (looking-at re2)
12271 (progn
12272 (goto-char (match-end 0))
12273 (setq ts2 (match-string 1) inc nil))
12274 (setq ts2 ts
12275 tmp (buffer-substring (max (point-min)
12276 (- pos org-ds-keyword-length))
12277 pos)
12278 deadlinep (string-match org-deadline-regexp tmp)
12279 scheduledp (string-match org-scheduled-regexp tmp)
12280 ;; donep (org-entry-is-done-p)
12282 (if (or (string-match org-tr-regexp hd)
12283 (string-match org-ts-regexp hd))
12284 (setq hd (replace-match "" t t hd)))
12285 (if combine
12286 (setq hd (concat hd " (category " category ")")))
12287 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
12288 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
12289 (princ (format "BEGIN:VEVENT
12292 SUMMARY:%s
12293 END:VEVENT\n"
12294 (org-ical-ts-to-string ts "DTSTART")
12295 (org-ical-ts-to-string ts2 "DTEND" inc)
12296 hd)))
12297 (when org-icalendar-include-todo
12298 (goto-char (point-min))
12299 (while (re-search-forward org-todo-line-regexp nil t)
12300 (setq state (match-string 1))
12301 (unless (equal state org-done-string)
12302 (setq hd (match-string 3))
12303 (if (string-match org-priority-regexp hd)
12304 (setq pri (string-to-char (match-string 2 hd))
12305 hd (concat (substring hd 0 (match-beginning 1))
12306 (substring hd (- (match-end 1)))))
12307 (setq pri org-default-priority))
12308 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
12309 (- org-lowest-priority ?A))))))
12311 (princ (format "BEGIN:VTODO
12313 SUMMARY:%s
12314 SEQUENCE:1
12315 PRIORITY:%d
12316 END:VTODO\n"
12317 dts hd pri))))))))
12319 (defun org-start-icalendar-file (name)
12320 "Start an iCalendar file by inserting the header."
12321 (let ((user user-full-name)
12322 (name (or name "unknown"))
12323 (timezone (cadr (current-time-zone))))
12324 (princ
12325 (format "BEGIN:VCALENDAR
12326 VERSION:2.0
12327 X-WR-CALNAME:%s
12328 PRODID:-//%s//Emacs with Org-mode//EN
12329 X-WR-TIMEZONE:%s
12330 CALSCALE:GREGORIAN\n" name user timezone))))
12332 (defun org-finish-icalendar-file ()
12333 "Finish an iCalendar file by inserting the END statement."
12334 (princ "END:VCALENDAR\n"))
12336 (defun org-ical-ts-to-string (s keyword &optional inc)
12337 "Take a time string S and convert it to iCalendar format.
12338 KEYWORD is added in front, to make a complete line like DTSTART....
12339 When INC is non-nil, increase the hour by two (if time string contains
12340 a time), or the day by one (if it does not contain a time)."
12341 (let ((t1 (org-parse-time-string s 'nodefault))
12342 t2 fmt have-time time)
12343 (if (and (car t1) (nth 1 t1) (nth 2 t1))
12344 (setq t2 t1 have-time t)
12345 (setq t2 (org-parse-time-string s)))
12346 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
12347 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
12348 (when inc
12349 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
12350 (setq time (encode-time s mi h d m y)))
12351 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
12352 (concat keyword (format-time-string fmt time))))
12355 ;;; Key bindings
12357 ;; - Bindings in Org-mode map are currently
12358 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
12359 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
12360 ;; e (?) useful from outline-mode
12361 ;; i k @ expendable from outline-mode
12362 ;; 0123456789 % & ()_{} " ` free
12364 ;; Make `C-c C-x' a prefix key
12365 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
12367 ;; TAB key with modifiers
12368 (define-key org-mode-map "\C-i" 'org-cycle)
12369 (define-key org-mode-map [(tab)] 'org-cycle)
12370 (define-key org-mode-map [(meta tab)] 'org-complete)
12371 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
12372 ;; The following line is necessary under Suse GNU/Linux
12373 (unless (featurep 'xemacs)
12374 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
12375 (define-key org-mode-map [(shift tab)] 'org-shifttab)
12377 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
12378 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
12379 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12380 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
12381 (define-key org-mode-map [(meta return)] 'org-meta-return)
12382 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
12383 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
12385 ;; Cursor keys with modifiers
12386 (define-key org-mode-map [(meta left)] 'org-metaleft)
12387 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
12388 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
12389 (define-key org-mode-map [(meta right)] 'org-metaright)
12390 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
12391 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
12392 (define-key org-mode-map [(meta up)] 'org-metaup)
12393 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
12394 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
12395 (define-key org-mode-map [(meta down)] 'org-metadown)
12396 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
12397 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
12399 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12400 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
12401 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
12402 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
12403 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
12404 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
12405 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
12406 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
12407 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
12408 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
12409 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
12410 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
12411 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
12412 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
12413 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
12414 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
12416 ;; All the other keys
12417 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
12418 (define-key org-mode-map "\C-c\C-j" 'org-goto)
12419 (define-key org-mode-map "\C-c\C-t" 'org-todo)
12420 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
12421 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
12422 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
12423 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12424 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
12425 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
12426 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12427 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
12428 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
12429 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
12430 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
12431 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
12432 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
12433 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
12434 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12435 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12436 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12437 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12438 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
12439 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
12440 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12441 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
12442 (define-key org-mode-map "\C-c]" 'org-remove-file)
12443 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
12444 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
12445 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
12446 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12447 (define-key org-mode-map "\C-m" 'org-return)
12448 (define-key org-mode-map "\C-c?" 'org-table-current-column)
12449 (define-key org-mode-map "\C-c " 'org-table-blank-field)
12450 (define-key org-mode-map "\C-c+" 'org-table-sum)
12451 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
12452 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
12453 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
12454 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12455 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
12456 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12457 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
12458 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12459 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
12460 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
12461 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
12462 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
12463 ;; OPML support is only an option for the future
12464 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
12465 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
12466 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
12467 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
12468 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
12469 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
12470 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
12471 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12472 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
12473 (define-key org-mode-map "\C-c\C-xx" 'org-export-as-xml)
12474 (define-key org-mode-map "\C-c\C-x\C-x" 'org-export-as-xml)
12475 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
12476 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
12478 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12479 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12480 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12481 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12483 (defsubst org-table-p () (org-at-table-p))
12485 (defun org-self-insert-command (N)
12486 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12487 If the cursor is in a table looking at whitespace, the whitespace is
12488 overwritten, and the table is not marked as requiring realignment."
12489 (interactive "p")
12490 (if (and (org-table-p)
12491 (progn
12492 ;; check if we blank the field, and if that triggers align
12493 (and org-table-auto-blank-field
12494 (member last-command
12495 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12496 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12497 ;; got extra space, this field does not determine column width
12498 (let (org-table-may-need-update) (org-table-blank-field))
12499 ;; no extra space, this field may determine column width
12500 (org-table-blank-field)))
12502 (eq N 1)
12503 (looking-at "[^|\n]* |"))
12504 (let (org-table-may-need-update)
12505 (goto-char (1- (match-end 0)))
12506 (delete-backward-char 1)
12507 (goto-char (match-beginning 0))
12508 (self-insert-command N))
12509 (setq org-table-may-need-update t)
12510 (self-insert-command N)))
12512 (defun org-delete-backward-char (N)
12513 "Like `delete-backward-char', insert whitespace at field end in tables.
12514 When deleting backwards, in tables this function will insert whitespace in
12515 front of the next \"|\" separator, to keep the table aligned. The table will
12516 still be marked for re-alignment if the field did fill the entire column,
12517 because, in this case the deletion might narrow the column."
12518 (interactive "p")
12519 (if (and (org-table-p)
12520 (eq N 1)
12521 (string-match "|" (buffer-substring (point-at-bol) (point)))
12522 (looking-at ".*?|"))
12523 (let ((pos (point))
12524 (noalign (looking-at "[^|\n\r]* |"))
12525 (c org-table-may-need-update))
12526 (backward-delete-char N)
12527 (skip-chars-forward "^|")
12528 (insert " ")
12529 (goto-char (1- pos))
12530 ;; noalign: if there were two spaces at the end, this field
12531 ;; does not determine the width of the column.
12532 (if noalign (setq org-table-may-need-update c)))
12533 (backward-delete-char N)))
12535 (defun org-delete-char (N)
12536 "Like `delete-char', but insert whitespace at field end in tables.
12537 When deleting characters, in tables this function will insert whitespace in
12538 front of the next \"|\" separator, to keep the table aligned. The table will
12539 still be marked for re-alignment if the field did fill the entire column,
12540 because, in this case the deletion might narrow the column."
12541 (interactive "p")
12542 (if (and (org-table-p)
12543 (not (bolp))
12544 (not (= (char-after) ?|))
12545 (eq N 1))
12546 (if (looking-at ".*?|")
12547 (let ((pos (point))
12548 (noalign (looking-at "[^|\n\r]* |"))
12549 (c org-table-may-need-update))
12550 (replace-match (concat
12551 (substring (match-string 0) 1 -1)
12552 " |"))
12553 (goto-char pos)
12554 ;; noalign: if there were two spaces at the end, this field
12555 ;; does not determine the width of the column.
12556 (if noalign (setq org-table-may-need-update c))))
12557 (delete-char N)))
12559 ;; How to do this: Measure non-white length of current string
12560 ;; If equal to column width, we should realign.
12562 (defun org-remap (map &rest commands)
12563 "In MAP, remap the functions given in COMMANDS.
12564 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12565 (let (new old)
12566 (while commands
12567 (setq old (pop commands) new (pop commands))
12568 (if (fboundp 'command-remapping)
12569 (define-key map (vector 'remap old) new)
12570 (substitute-key-definition old new map global-map)))))
12572 (when (eq org-enable-table-editor 'optimized)
12573 ;; If the user wants maximum table support, we need to hijack
12574 ;; some standard editing functions
12575 (org-remap org-mode-map
12576 'self-insert-command 'org-self-insert-command
12577 'delete-char 'org-delete-char
12578 'delete-backward-char 'org-delete-backward-char)
12579 (define-key org-mode-map "|" 'org-force-self-insert))
12581 (defun org-shiftcursor-error ()
12582 "Throw an error because Shift-Cursor command was applied in wrong context."
12583 (error "This command is active in special context like tables, headlines or timestamps"))
12585 (defun org-shifttab ()
12586 "Global visibility cycling or move to previous table field.
12587 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
12588 See the individual commands for more information."
12589 (interactive)
12590 (cond
12591 ((org-at-table-p) (org-table-previous-field))
12592 (t (org-cycle '(4)))))
12594 (defun org-shiftmetaleft ()
12595 "Promote subtree or delete table column.
12596 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
12597 See the individual commands for more information."
12598 (interactive)
12599 (cond
12600 ((org-at-table-p) (org-table-delete-column))
12601 ((org-on-heading-p) (org-promote-subtree))
12602 ((org-at-item-p) (call-interactively 'org-outdent-item))
12603 (t (org-shiftcursor-error))))
12605 (defun org-shiftmetaright ()
12606 "Demote subtree or insert table column.
12607 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
12608 See the individual commands for more information."
12609 (interactive)
12610 (cond
12611 ((org-at-table-p) (org-table-insert-column))
12612 ((org-on-heading-p) (org-demote-subtree))
12613 ((org-at-item-p) (call-interactively 'org-indent-item))
12614 (t (org-shiftcursor-error))))
12616 (defun org-shiftmetaup (&optional arg)
12617 "Move subtree up or kill table row.
12618 Calls `org-move-subtree-up' or `org-table-kill-row' or
12619 `org-move-item-up' depending on context. See the individual commands
12620 for more information."
12621 (interactive "P")
12622 (cond
12623 ((org-at-table-p) (org-table-kill-row))
12624 ((org-on-heading-p) (org-move-subtree-up arg))
12625 ((org-at-item-p) (org-move-item-up arg))
12626 (t (org-shiftcursor-error))))
12627 (defun org-shiftmetadown (&optional arg)
12628 "Move subtree down or insert table row.
12629 Calls `org-move-subtree-down' or `org-table-insert-row' or
12630 `org-move-item-down', depending on context. See the individual
12631 commands for more information."
12632 (interactive "P")
12633 (cond
12634 ((org-at-table-p) (org-table-insert-row arg))
12635 ((org-on-heading-p) (org-move-subtree-down arg))
12636 ((org-at-item-p) (org-move-item-down arg))
12637 (t (org-shiftcursor-error))))
12639 (defun org-metaleft (&optional arg)
12640 "Promote heading or move table column to left.
12641 Calls `org-do-promote' or `org-table-move-column', depending on context.
12642 With no specific context, calls the Emacs default `backward-word'.
12643 See the individual commands for more information."
12644 (interactive "P")
12645 (cond
12646 ((org-at-table-p) (org-table-move-column 'left))
12647 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
12648 (t (backward-word (prefix-numeric-value arg)))))
12650 (defun org-metaright (&optional arg)
12651 "Demote subtree or move table column to right.
12652 Calls `org-do-demote' or `org-table-move-column', depending on context.
12653 With no specific context, calls the Emacs default `forward-word'.
12654 See the individual commands for more information."
12655 (interactive "P")
12656 (cond
12657 ((org-at-table-p) (org-table-move-column nil))
12658 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
12659 (t (forward-word (prefix-numeric-value arg)))))
12661 (defun org-metaup (&optional arg)
12662 "Move subtree up or move table row up.
12663 Calls `org-move-subtree-up' or `org-table-move-row' or
12664 `org-move-item-up', depending on context. See the individual commands
12665 for more information."
12666 (interactive "P")
12667 (cond
12668 ((org-at-table-p) (org-table-move-row 'up))
12669 ((org-on-heading-p) (org-move-subtree-up arg))
12670 ((org-at-item-p) (org-move-item-up arg))
12671 (t (org-shiftcursor-error))))
12673 (defun org-metadown (&optional arg)
12674 "Move subtree down or move table row down.
12675 Calls `org-move-subtree-down' or `org-table-move-row' or
12676 `org-move-item-down', depending on context. See the individual
12677 commands for more information."
12678 (interactive "P")
12679 (cond
12680 ((org-at-table-p) (org-table-move-row nil))
12681 ((org-on-heading-p) (org-move-subtree-down arg))
12682 ((org-at-item-p) (org-move-item-down arg))
12683 (t (org-shiftcursor-error))))
12685 (defun org-shiftup (&optional arg)
12686 "Increase item in timestamp or increase priority of current item.
12687 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12688 See the individual commands for more information."
12689 (interactive "P")
12690 (cond
12691 ((org-at-timestamp-p) (org-timestamp-up arg))
12692 (t (org-priority-up))))
12694 (defun org-shiftdown (&optional arg)
12695 "Decrease item in timestamp or decrease priority of current item.
12696 Calls `org-timestamp-down' or `org-priority-down', depending on context.
12697 See the individual commands for more information."
12698 (interactive "P")
12699 (cond
12700 ((org-at-timestamp-p) (org-timestamp-down arg))
12701 (t (org-priority-down))))
12703 (defun org-shiftright ()
12704 "Next TODO keyword or timestamp one day later, depending on context."
12705 (interactive)
12706 (cond
12707 ((org-at-timestamp-p) (org-timestamp-up-day))
12708 ((org-on-heading-p) (org-todo 'right))
12709 (t (org-shiftcursor-error))))
12711 (defun org-shiftleft ()
12712 "Previous TODO keyword or timestamp one day earlier, depending on context."
12713 (interactive)
12714 (cond
12715 ((org-at-timestamp-p) (org-timestamp-down-day))
12716 ((org-on-heading-p) (org-todo 'left))
12717 (t (org-shiftcursor-error))))
12719 (defun org-copy-special ()
12720 "Copy region in table or copy current subtree.
12721 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12722 See the individual commands for more information."
12723 (interactive)
12724 (call-interactively
12725 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12727 (defun org-cut-special ()
12728 "Cut region in table or cut current subtree.
12729 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12730 See the individual commands for more information."
12731 (interactive)
12732 (call-interactively
12733 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12735 (defun org-paste-special (arg)
12736 "Paste rectangular region into table, or past subtree relative to level.
12737 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12738 See the individual commands for more information."
12739 (interactive "P")
12740 (if (org-at-table-p)
12741 (org-table-paste-rectangle)
12742 (org-paste-subtree arg)))
12744 (defun org-ctrl-c-ctrl-c (&optional arg)
12745 "Call realign table, or recognize a table.el table, or update keywords.
12746 When the cursor is inside a table created by the table.el package,
12747 activate that table. Otherwise, if the cursor is at a normal table
12748 created with org.el, re-align that table. This command works even if
12749 the automatic table editor has been turned off.
12751 If the cursor is in a headline, prompt for tags and insert them into
12752 the current line, aligned to `org-tags-column'. When in a headline and
12753 called with prefix arg, realign all tags in the current buffer.
12755 If the cursor is in one of the special #+KEYWORD lines, this triggers
12756 scanning the buffer for these lines and updating the information.
12757 If the cursor is on a #+TBLFM line, re-apply the formulae to the table."
12758 (interactive "P")
12759 (let ((org-enable-table-editor t))
12760 (cond
12761 ((and (local-variable-p 'org-finish-function (current-buffer))
12762 (fboundp org-finish-function))
12763 (funcall org-finish-function))
12764 ((org-on-target-p) (org-update-radio-target-regexp))
12765 ((org-on-heading-p) (org-set-tags arg))
12766 ((org-at-table.el-p)
12767 (require 'table)
12768 (beginning-of-line 1)
12769 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12770 (table-recognize-table))
12771 ((org-at-table-p)
12772 (org-table-maybe-eval-formula)
12773 (if arg
12774 (org-table-recalculate t)
12775 (org-table-maybe-recalculate-line))
12776 (org-table-align))
12777 ((org-at-item-p)
12778 (org-renumber-ordered-list (prefix-numeric-value arg)))
12779 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12780 (cond
12781 ((equal (match-string 1) "TBLFM")
12782 ;; Recalculate the table before this line
12783 (save-excursion
12784 (beginning-of-line 1)
12785 (skip-chars-backward " \r\n\t")
12786 (if (org-at-table-p) (org-table-recalculate t))))
12788 (org-mode-restart))))
12789 (t (error "C-c C-c can do nothing useful at this location.")))))
12791 (defun org-mode-restart ()
12792 "Restart Org-mode, to scan again for special lines.
12793 Also updates the keyword regular expressions."
12794 (interactive)
12795 (let ((org-inhibit-startup t)) (org-mode))
12796 (message "Org-mode restarted to refresh keyword and special line setup"))
12798 (defun org-return ()
12799 "Goto next table row or insert a newline.
12800 Calls `org-table-next-row' or `newline', depending on context.
12801 See the individual commands for more information."
12802 (interactive)
12803 (cond
12804 ((org-at-table-p)
12805 (org-table-justify-field-maybe)
12806 (org-table-next-row))
12807 (t (newline))))
12809 (defun org-meta-return (&optional arg)
12810 "Insert a new heading or wrap a region in a table.
12811 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12812 See the individual commands for more information."
12813 (interactive "P")
12814 (cond
12815 ((org-at-table-p)
12816 (org-table-wrap-region arg))
12817 (t (org-insert-heading arg))))
12819 ;;; Menu entries
12821 ;; Define the Org-mode menus
12822 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12823 '("Tbl"
12824 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
12825 ["Next Field" org-cycle (org-at-table-p)]
12826 ["Previous Field" org-shifttab (org-at-table-p)]
12827 ["Next Row" org-return (org-at-table-p)]
12828 "--"
12829 ["Blank Field" org-table-blank-field (org-at-table-p)]
12830 ["Edit Field" org-table-edit-field (org-at-table-p)]
12831 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12832 "--"
12833 ("Column"
12834 ["Move Column Left" org-metaleft (org-at-table-p)]
12835 ["Move Column Right" org-metaright (org-at-table-p)]
12836 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12837 ["Insert Column" org-shiftmetaright (org-at-table-p)]
12838 "--"
12839 ["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])
12840 ("Row"
12841 ["Move Row Up" org-metaup (org-at-table-p)]
12842 ["Move Row Down" org-metadown (org-at-table-p)]
12843 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12844 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12845 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12846 "--"
12847 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
12848 ("Rectangle"
12849 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12850 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12851 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12852 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12853 "--"
12854 ("Calculate"
12855 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12856 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12857 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12858 "--"
12859 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12860 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12861 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12862 "--"
12863 ["Sum Column/Rectangle" org-table-sum
12864 (or (org-at-table-p) (org-region-active-p))]
12865 ["Which Column?" org-table-current-column (org-at-table-p)])
12866 ["Debug Formulas"
12867 (setq org-table-formula-debug (not org-table-formula-debug))
12868 :style toggle :selected org-table-formula-debug]
12869 "--"
12870 ["Create" org-table-create (and (not (org-at-table-p))
12871 org-enable-table-editor)]
12872 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12873 ["Import from File" org-table-import (not (org-at-table-p))]
12874 ["Export to File" org-table-export (org-at-table-p)]
12875 "--"
12876 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12878 (easy-menu-define org-org-menu org-mode-map "Org menu"
12879 '("Org"
12880 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
12881 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
12882 ["Sparse Tree" org-occur t]
12883 ["Show All" show-all t]
12884 "--"
12885 ["New Heading" org-insert-heading t]
12886 ("Navigate Headings"
12887 ["Up" outline-up-heading t]
12888 ["Next" outline-next-visible-heading t]
12889 ["Previous" outline-previous-visible-heading t]
12890 ["Next Same Level" outline-forward-same-level t]
12891 ["Previous Same Level" outline-backward-same-level t]
12892 "--"
12893 ["Jump" org-goto t])
12894 ("Edit Structure"
12895 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12896 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12897 "--"
12898 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12899 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12900 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12901 "--"
12902 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12903 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12904 ["Demote Heading" org-metaright (not (org-at-table-p))]
12905 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12906 "--"
12907 ["Archive Subtree" org-archive-subtree t]
12908 "--"
12909 ["Convert to odd levels" org-convert-to-odd-levels t]
12910 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12911 "--"
12912 ("TODO Lists"
12913 ["TODO/DONE/-" org-todo t]
12914 ["Show TODO Tree" org-show-todo-tree t]
12915 ["Global TODO list" org-todo-list t]
12916 "--"
12917 ["Set Priority" org-priority t]
12918 ["Priority Up" org-shiftup t]
12919 ["Priority Down" org-shiftdown t])
12920 ("Dates and Scheduling"
12921 ["Timestamp" org-time-stamp t]
12922 ["Timestamp (inactive)" org-time-stamp-inactive t]
12923 ("Change Date"
12924 ["1 Day Later" org-timestamp-up-day t]
12925 ["1 Day Earlier" org-timestamp-down-day t]
12926 ["1 ... Later" org-shiftup t]
12927 ["1 ... Earlier" org-shiftdown t])
12928 ["Compute Time Range" org-evaluate-time-range t]
12929 ["Schedule Item" org-schedule t]
12930 ["Deadline" org-deadline t]
12931 "--"
12932 ["Goto Calendar" org-goto-calendar t]
12933 ["Date from Calendar" org-date-from-calendar t])
12934 "--"
12935 ["Agenda Command" org-agenda t]
12936 ("File List for Agenda")
12937 ("Special views current file"
12938 ["TODO Tree" org-show-todo-tree t]
12939 ["Check Deadlines" org-check-deadlines t]
12940 ["Timeline" org-timeline t]
12941 ["Tags Tree" org-tags-sparse-tree t])
12942 "--"
12943 ("Hyperlinks"
12944 ["Store Link (Global)" org-store-link t]
12945 ["Insert Link" org-insert-link t]
12946 ["Follow Link" org-open-at-point t]
12947 "--"
12948 ["Descriptive Links"
12949 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12950 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
12951 ["Literal Links"
12952 (progn
12953 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12954 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
12955 "--"
12956 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
12957 (save-excursion (goto-char (point-min))
12958 (re-search-forward "<[a-z]+:" nil t))])
12959 "--"
12960 ("Export"
12961 ["ASCII" org-export-as-ascii t]
12962 ["Extract Visible Text" org-export-copy-visible t]
12963 ["HTML" org-export-as-html t]
12964 ["HTML and Open" org-export-as-html-and-open t]
12965 ["XML (XOXO)" org-export-as-xml t]
12966 "--"
12967 ["iCalendar this file" org-export-icalendar-this-file t]
12968 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
12969 :active t :keys "C-c C-x C-i"]
12970 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
12971 "--"
12972 ["Option Template" org-insert-export-options-template t]
12973 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
12974 "--"
12975 ("Documentation"
12976 ["Show Version" org-version t]
12977 ["Info Documentation" org-info t])
12978 ("Customize"
12979 ["Browse Org Group" org-customize t]
12980 "--"
12981 ["Expand This Menu" org-create-customize-menu
12982 (fboundp 'customize-menu-create)])
12983 "--"
12984 ["Refresh setup" org-mode-restart t]
12987 (defun org-info (&optional node)
12988 "Read documentation for Org-mode in the info system.
12989 With optional NODE, go directly to that node."
12990 (interactive)
12991 (require 'info)
12992 (Info-goto-node (format "(org)%s" (or node ""))))
12994 (defun org-install-agenda-files-menu ()
12995 (let ((bl (buffer-list)))
12996 (save-excursion
12997 (while bl
12998 (set-buffer (pop bl))
12999 (if (eq major-mode 'org-mode) (setq bl nil)))
13000 (when (eq major-mode 'org-mode)
13001 (easy-menu-change
13002 '("Org") "File List for Agenda"
13003 (append
13004 (list
13005 ["Edit File List" (org-edit-agenda-file-list) t]
13006 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13007 ["Remove Current File from List" org-remove-file t]
13008 ["Cycle through agenda files" org-cycle-agenda-files t]
13009 "--")
13010 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13012 ;;; Documentation
13014 (defun org-customize ()
13015 "Call the customize function with org as argument."
13016 (interactive)
13017 (customize-browse 'org))
13019 (defun org-create-customize-menu ()
13020 "Create a full customization menu for Org-mode, insert it into the menu."
13021 (interactive)
13022 (if (fboundp 'customize-menu-create)
13023 (progn
13024 (easy-menu-change
13025 '("Org") "Customize"
13026 `(["Browse Org group" org-customize t]
13027 "--"
13028 ,(customize-menu-create 'org)
13029 ["Set" Custom-set t]
13030 ["Save" Custom-save t]
13031 ["Reset to Current" Custom-reset-current t]
13032 ["Reset to Saved" Custom-reset-saved t]
13033 ["Reset to Standard Settings" Custom-reset-standard t]))
13034 (message "\"Org\"-menu now contains full customization menu"))
13035 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13037 ;;; Miscellaneous stuff
13039 (defun org-move-line-down (arg)
13040 "Move the current line down. With prefix argument, move it past ARG lines."
13041 (interactive "p")
13042 (let ((col (current-column))
13043 beg end pos)
13044 (beginning-of-line 1) (setq beg (point))
13045 (beginning-of-line 2) (setq end (point))
13046 (beginning-of-line (+ 1 arg))
13047 (setq pos (move-marker (make-marker) (point)))
13048 (insert (delete-and-extract-region beg end))
13049 (goto-char pos)
13050 (move-to-column col)))
13052 (defun org-move-line-up (arg)
13053 "Move the current line up. 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 (- 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 ;; Paragraph filling stuff.
13066 ;; We want this to be just right, so use the full arsenal.
13067 ;; FIXME: This very likely does not work correctly for XEmacs, because the
13068 ;; filladapt package works slightly differently.
13070 (defun org-set-autofill-regexps ()
13071 (interactive)
13072 ;; In the paragraph separator we include headlines, because filling
13073 ;; text in a line directly attached to a headline would otherwise
13074 ;; fill the headline as well.
13075 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
13076 ;; The paragraph starter includes hand-formatted lists.
13077 (set (make-local-variable 'paragraph-start)
13078 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13079 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13080 ;; But only if the user has not turned off tables or fixed-width regions
13081 (set (make-local-variable 'auto-fill-inhibit-regexp)
13082 (concat "\\*\\|#"
13083 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13084 (concat
13085 "\\|[ \t]*["
13086 (if org-enable-table-editor "|" "")
13087 (if org-enable-fixed-width-editor ":" "")
13088 "]"))))
13089 ;; We use our own fill-paragraph function, to make sure that tables
13090 ;; and fixed-width regions are not wrapped. That function will pass
13091 ;; through to `fill-paragraph' when appropriate.
13092 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
13093 ;; Adaptive filling: To get full control, first make sure that
13094 ;; `adaptive-fill-regexp' never matches. Then install our won matcher.
13095 (setq adaptive-fill-regexp "\000")
13096 (setq adaptive-fill-function 'org-adaptive-fill-function))
13098 (defun org-fill-paragraph (&optional justify)
13099 "Re-align a table, pass through to fill-paragraph if no table."
13100 (let ((table-p (org-at-table-p))
13101 (table.el-p (org-at-table.el-p)))
13102 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
13103 (table.el-p t) ; skip table.el tables
13104 (table-p (org-table-align) t) ; align org-mode tables
13105 (t nil)))) ; call paragraph-fill
13107 ;; For reference, this is the default value of adaptive-fill-regexp
13108 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13110 (defun org-adaptive-fill-function ()
13111 "Return a fill prefix for org-mode files.
13112 In particular, this makes sure hanging paragraphs for hand-formatted lists
13113 work correctly."
13114 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
13115 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
13117 ;; Functions needed for Emacs/XEmacs region compatibility
13119 (defun org-add-hook (hook function &optional append local)
13120 "Add-hook, compatible with both Emacsen."
13121 (if (and local (featurep 'xemacs))
13122 (add-local-hook hook function append)
13123 (add-hook hook function append local)))
13125 (defun org-region-active-p ()
13126 "Is `transient-mark-mode' on and the region active?
13127 Works on both Emacs and XEmacs."
13128 (if org-ignore-region
13130 (if (featurep 'xemacs)
13131 (and zmacs-regions (region-active-p))
13132 (and transient-mark-mode mark-active))))
13134 (defun org-add-to-invisibility-spec (arg)
13135 "Add elements to `buffer-invisibility-spec'.
13136 See documentation for `buffer-invisibility-spec' for the kind of elements
13137 that can be added."
13138 (cond
13139 ((fboundp 'add-to-invisibility-spec)
13140 (add-to-invisibility-spec arg))
13141 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
13142 (setq buffer-invisibility-spec (list arg)))
13144 (setq buffer-invisibility-spec
13145 (cons arg buffer-invisibility-spec)))))
13147 (defun org-remove-from-invisibility-spec (arg)
13148 "Remove elements from `buffer-invisibility-spec'."
13149 (if (fboundp 'remove-from-invisibility-spec)
13150 (remove-from-invisibility-spec arg)
13151 (if (consp buffer-invisibility-spec)
13152 (setq buffer-invisibility-spec
13153 (delete arg buffer-invisibility-spec)))))
13155 (defun org-in-invisibility-spec-p (arg)
13156 "Is ARG a member of `buffer-invisibility-spec'?"
13157 (if (consp buffer-invisibility-spec)
13158 (member arg buffer-invisibility-spec)
13159 nil))
13161 (defun org-image-file-name-regexp ()
13162 "Return regexp matching the file names of images."
13163 (if (fboundp 'image-file-name-regexp)
13164 (image-file-name-regexp)
13165 (let ((image-file-name-extensions
13166 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13167 "xbm" "xpm" "pbm" "pgm" "ppm")))
13168 (concat "\\."
13169 (regexp-opt (nconc (mapcar 'upcase
13170 image-file-name-extensions)
13171 image-file-name-extensions)
13173 "\\'"))))
13175 ;; Functions needed for compatibility with old outline.el.
13177 ;; Programming for the old outline.el (that uses selective display
13178 ;; instead of `invisible' text properties) is a nightmare, mostly
13179 ;; because regular expressions can no longer be anchored at
13180 ;; beginning/end of line. Therefore a number of function need special
13181 ;; treatment when the old outline.el is being used.
13183 ;; The following functions capture almost the entire compatibility code
13184 ;; between the different versions of outline-mode. The only other
13185 ;; places where this is important are the font-lock-keywords, and in
13186 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
13188 ;; C-a should go to the beginning of a *visible* line, also in the
13189 ;; new outline.el. I guess this should be patched into Emacs?
13190 (defun org-beginning-of-line ()
13191 "Go to the beginning of the current line. If that is invisible, continue
13192 to a visible line beginning. This makes the function of C-a more intuitive."
13193 (interactive)
13194 (beginning-of-line 1)
13195 (if (bobp)
13197 (backward-char 1)
13198 (if (org-invisible-p)
13199 (while (and (not (bobp)) (org-invisible-p))
13200 (backward-char 1)
13201 (beginning-of-line 1))
13202 (forward-char 1))))
13204 (when org-noutline-p
13205 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
13206 ;; FIXME: should I use substitute-key-definition to reach other bindings
13207 ;; of beginning-of-line?
13209 (defun org-invisible-p ()
13210 "Check if point is at a character currently not visible."
13211 (if org-noutline-p
13212 ;; Early versions of noutline don't have `outline-invisible-p'.
13213 (if (fboundp 'outline-invisible-p)
13214 (outline-invisible-p)
13215 (get-char-property (point) 'invisible))
13216 (save-excursion
13217 (skip-chars-backward "^\r\n")
13218 (equal (char-before) ?\r))))
13220 (defun org-invisible-p2 ()
13221 "Check if point is at a character currently not visible."
13222 (save-excursion
13223 (if org-noutline-p
13224 (progn
13225 (if (and (eolp) (not (bobp))) (backward-char 1))
13226 ;; Early versions of noutline don't have `outline-invisible-p'.
13227 (if (fboundp 'outline-invisible-p)
13228 (outline-invisible-p)
13229 (get-char-property (point) 'invisible)))
13230 (skip-chars-backward "^\r\n")
13231 (equal (char-before) ?\r))))
13233 (defun org-back-to-heading (&optional invisible-ok)
13234 "Move to previous heading line, or beg of this line if it's a heading.
13235 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
13236 (if org-noutline-p
13237 (outline-back-to-heading invisible-ok)
13238 (if (and (memq (char-before) '(?\n ?\r))
13239 (looking-at outline-regexp))
13241 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
13242 outline-regexp)
13243 nil t)
13244 (if invisible-ok
13245 (progn (goto-char (match-end 1))
13246 (looking-at outline-regexp)))
13247 (error "Before first heading")))))
13249 (defun org-on-heading-p (&optional invisible-ok)
13250 "Return t if point is on a (visible) heading line.
13251 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
13252 (if org-noutline-p
13253 (outline-on-heading-p 'invisible-ok)
13254 (save-excursion
13255 (skip-chars-backward "^\n\r")
13256 (and (looking-at outline-regexp)
13257 (or invisible-ok
13258 (bobp)
13259 (equal (char-before) ?\n))))))
13261 (defun org-on-target-p ()
13262 (let ((pos (point)))
13263 (save-excursion
13264 (skip-chars-forward "<")
13265 (and (re-search-backward "<<" nil t)
13266 (or (looking-at org-radio-target-regexp)
13267 (looking-at org-target-regexp))
13268 (<= (match-beginning 0) pos)
13269 (>= (1+ (match-end 0)) pos)))))
13271 (defun org-up-heading-all (arg)
13272 "Move to the heading line of which the present line is a subheading.
13273 This function considers both visible and invisible heading lines.
13274 With argument, move up ARG levels."
13275 (if org-noutline-p
13276 (if (fboundp 'outline-up-heading-all)
13277 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13278 (outline-up-heading arg t)) ; emacs 22 version of outline.el
13279 (org-back-to-heading t)
13280 (looking-at outline-regexp)
13281 (if (<= (- (match-end 0) (match-beginning 0)) arg)
13282 (error "Cannot move up %d levels" arg)
13283 (re-search-backward
13284 (concat "[\n\r]" (regexp-quote
13285 (make-string (- (match-end 0) (match-beginning 0) arg)
13286 ?*))
13287 "[^*]"))
13288 (forward-char 1))))
13290 (defun org-show-hidden-entry ()
13291 "Show an entry where even the heading is hidden."
13292 (save-excursion
13293 (if (not org-noutline-p)
13294 (progn
13295 (org-back-to-heading t)
13296 (org-flag-heading nil)))
13297 (org-show-entry)))
13299 (defun org-check-occur-regexp (regexp)
13300 "If REGEXP starts with \"^\", modify it to check for \\r as well.
13301 Of course, only for the old outline mode."
13302 (if org-noutline-p
13303 regexp
13304 (if (string-match "^\\^" regexp)
13305 (concat "[\n\r]" (substring regexp 1))
13306 regexp)))
13308 (defun org-flag-heading (flag &optional entry)
13309 "Flag the current heading. FLAG non-nil means make invisible.
13310 When ENTRY is non-nil, show the entire entry."
13311 (save-excursion
13312 (org-back-to-heading t)
13313 (if (not org-noutline-p)
13314 ;; Make the current headline visible
13315 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
13316 ;; Check if we should show the entire entry
13317 (if entry
13318 (progn
13319 (org-show-entry)
13320 (save-excursion ;; FIXME: Is this the fix for points in the -|
13321 ;; middle of text? |
13322 (and (outline-next-heading) ;; |
13323 (org-flag-heading nil)))) ; show the next heading _|
13324 (outline-flag-region (max 1 (1- (point)))
13325 (save-excursion (outline-end-of-heading) (point))
13326 (if org-noutline-p
13327 flag
13328 (if flag ?\r ?\n))))))
13330 (defun org-end-of-subtree (&optional invisible-OK)
13331 ;; This is an exact copy of the original function, but it uses
13332 ;; `org-back-to-heading', to make it work also in invisible
13333 ;; trees. And is uses an invisible-OK argument.
13334 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13335 (org-back-to-heading invisible-OK)
13336 (let ((first t)
13337 (level (funcall outline-level)))
13338 (while (and (not (eobp))
13339 (or first (> (funcall outline-level) level)))
13340 (setq first nil)
13341 (outline-next-heading))
13342 (if (memq (preceding-char) '(?\n ?\^M))
13343 (progn
13344 ;; Go to end of line before heading
13345 (forward-char -1)
13346 (if (memq (preceding-char) '(?\n ?\^M))
13347 ;; leave blank line before heading
13348 (forward-char -1))))))
13350 (defun org-show-subtree ()
13351 "Show everything after this heading at deeper levels."
13352 (outline-flag-region
13353 (point)
13354 (save-excursion
13355 (outline-end-of-subtree) (outline-next-heading) (point))
13356 (if org-noutline-p nil ?\n)))
13358 (defun org-show-entry ()
13359 "Show the body directly following this heading.
13360 Show the heading too, if it is currently invisible."
13361 (interactive)
13362 (save-excursion
13363 (org-back-to-heading t)
13364 (outline-flag-region
13365 (1- (point))
13366 (save-excursion
13367 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13368 (or (match-beginning 1) (point-max)))
13369 (if org-noutline-p nil ?\n))))
13372 (defun org-make-options-regexp (kwds)
13373 "Make a regular expression for keyword lines."
13374 (concat
13375 (if org-noutline-p "^" "[\n\r]")
13376 "#?[ \t]*\\+\\("
13377 (mapconcat 'regexp-quote kwds "\\|")
13378 "\\):[ \t]*"
13379 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
13381 ;; Make `bookmark-jump' show the jump location if it was hidden.
13382 (eval-after-load "bookmark"
13383 '(if (boundp 'bookmark-after-jump-hook)
13384 ;; We can use the hook
13385 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13386 ;; Hook not available, use advice
13387 (defadvice bookmark-jump (after org-make-visible activate)
13388 "Make the position visible."
13389 (org-bookmark-jump-unhide))))
13391 (defun org-bookmark-jump-unhide ()
13392 "Unhide the current position, to show the bookmark location."
13393 (and (eq major-mode 'org-mode)
13394 (or (org-invisible-p)
13395 (save-excursion (goto-char (max (point-min) (1- (point))))
13396 (org-invisible-p)))
13397 (org-show-hierarchy-above)))
13399 ;;; Finish up
13401 (provide 'org)
13403 (run-hooks 'org-load-hook)
13405 ;; Experimental code
13406 ;; FIXME: Move this code when it is ready.
13408 (defun org-upgrade-old-links (&optional query-description)
13409 "Transfer old <...> style links to new [[...]] style links.
13410 With arg query-description, ask at each match for a description text to use
13411 for this link."
13412 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
13413 (save-excursion
13414 (goto-char (point-min))
13415 (let ((re (concat "\\([^[]\\)<\\("
13416 "\\(" (mapconcat 'identity org-link-types "\\|")
13417 "\\):"
13418 "[^" org-non-link-chars "]+\\)>"))
13419 l1 l2 (cnt 0))
13420 (while (re-search-forward re nil t)
13421 (setq cnt (1+ cnt)
13422 l1 (org-match-string-no-properties 2)
13423 l2 (save-match-data (org-link-escape l1)))
13424 (when query-description (setq l1 (read-string "Desc: " l1)))
13425 (if (equal l1 l2)
13426 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
13427 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
13428 (message "%d matches have beed treated" cnt))))
13430 (defun org-export-as-xml ()
13431 "Export current buffer as XOXO XML buffer."
13432 (interactive)
13433 (cond ((eq org-export-xml-type 'xoxo)
13434 (org-export-as-xoxo (current-buffer)))))
13436 (defun org-export-as-xoxo-insert-into (buffer &rest output)
13437 (with-current-buffer buffer
13438 (apply 'insert output)))
13440 (defun org-export-as-xoxo (&optional buffer)
13441 "Export the org buffer as XOXO.
13442 The XOXO buffer is named *xoxo-<source buffer name>*"
13443 (interactive (list (current-buffer)))
13444 ;; A quickie abstraction
13446 ;; Output everything as XOXO
13447 (with-current-buffer (get-buffer buffer)
13448 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
13449 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
13450 ".xml"))
13451 (out (find-file-noselect filename))
13452 (last-level 1)
13453 (hanging-li nil))
13454 ;; Check the output buffer is empty.
13455 (with-current-buffer out (erase-buffer))
13456 ;; Kick off the output
13457 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
13458 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
13459 (let* ((hd (match-string-no-properties 1))
13460 (level (length hd))
13461 (text (concat
13462 (match-string-no-properties 2)
13463 (save-excursion
13464 (goto-char (match-end 0))
13465 (let ((str ""))
13466 (catch 'loop
13467 (while 't
13468 (forward-line)
13469 (if (looking-at "^[ \t]\\(.*\\)")
13470 (setq str (concat str (match-string-no-properties 1)))
13471 (throw 'loop str)))))))))
13473 ;; Handle level rendering
13474 (cond
13475 ((> level last-level)
13476 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
13478 ((< level last-level)
13479 (dotimes (- (- last-level level) 1)
13480 (if hanging-li
13481 (org-export-as-xoxo-insert-into out "</li>\n"))
13482 (org-export-as-xoxo-insert-into out "</ol>\n"))
13483 (when hanging-li
13484 (org-export-as-xoxo-insert-into out "</li>\n")
13485 (setq hanging-li nil)))
13487 ((equal level last-level)
13488 (if hanging-li
13489 (org-export-as-xoxo-insert-into out "</li>\n")))
13492 (setq last-level level)
13494 ;; And output the new li
13495 (setq hanging-li 't)
13496 (if (equal ?+ (elt text 0))
13497 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
13498 (org-export-as-xoxo-insert-into out "<li>" text))))
13500 ;; Finally finish off the ol
13501 (dotimes (- last-level 1)
13502 (if hanging-li
13503 (org-export-as-xoxo-insert-into out "</li>\n"))
13504 (org-export-as-xoxo-insert-into out "</ol>\n"))
13506 ;; Finish the buffer off and clean it up.
13507 (switch-to-buffer-other-window out)
13508 (indent-region (point-min) (point-max))
13509 (save-buffer)
13510 (goto-char (point-min))
13513 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13514 ;;; org.el ends here