]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
*** empty log message ***
[gnu-emacs] / lisp / textmodes / org.el
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.23
9 ;;
10 ;; This file is part of GNU Emacs.
11 ;;
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.
16
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.
21
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;
28 ;;; Commentary:
29 ;;
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.
32 ;;
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.
43 ;;
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.
50 ;;
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)
54 ;;
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:
58 ;;
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")
65 ;;
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:
68 ;;
69 ;; MY PROJECTS -*- mode: org; -*-
70 ;;
71 ;; which will select Org-mode for this buffer no matter what the file's
72 ;; name is.
73 ;;
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.
81 ;;
82 ;; Changes since version 4.00:
83 ;; ---------------------------
84 ;; Version 4.23
85 ;; - Bug fixes.
86 ;;
87 ;; Version 4.22
88 ;; - Bug fixes.
89 ;; - In agenda buffer, mouse-1 no longer follows link.
90 ;; See `org-agenda-mouse-1-follows-link' and `org-mouse-1-follows-link'.
91 ;;
92 ;; Version 4.20
93 ;; - Links use now the [[link][description]] format by default.
94 ;; When inserting links, the user is prompted for a description.
95 ;; - If a link has a description, only the description is displayed
96 ;; the link part is hidden. Use C-c C-l to edit the link part.
97 ;; - TAGS are now bold, but in the same color as the headline.
98 ;; - The width of a table column can be limited by using a field "<N>".
99 ;; - New structure for the customization tree.
100 ;; - Bug fixes.
101 ;;
102 ;; Version 4.13
103 ;; - The list of agenda files can be maintainted in an external file.
104 ;; - Bug fixes.
105 ;;
106 ;; Version 4.12
107 ;; - Templates for remember buffer. Note that the remember setup changes.
108 ;; To set up templates, see `org-remember-templates'.
109 ;; - The time in new time stamps can be rounded, see new option
110 ;; `org-time-stamp-rounding-minutes'.
111 ;; - Bug fixes (there are *always* more bugs).
112 ;;
113 ;; Version 4.10
114 ;; - Bug fixes.
115 ;;
116 ;; Version 4.09
117 ;; - Bug fixes.
118 ;; - Small improvements to font-lock support.
119 ;; - MHE support finalized.
120 ;;
121 ;; Version 4.08
122 ;; - Bug fixes.
123 ;; - Improved MHE support
124 ;;
125 ;; Version 4.07
126 ;; - Bug fixes.
127 ;; - Leading stars in headlines can be hidden, so make the outline look
128 ;; cleaner.
129 ;; - Mouse-1 can be used to follow links.
130 ;;
131 ;; Version 4.06
132 ;; - HTML exporter treats targeted internal links.
133 ;; - Bug fixes.
134 ;;
135 ;; Version 4.05
136 ;; - Changes to internal link system (thanks to David Wainberg for ideas).
137 ;; - in-file links: [[Search String]] instead of <file:::Search String>
138 ;; - automatic links to "radio targets".
139 ;; - CamelCase not longer active by default, configure org-activate-camels
140 ;; if you want to turn it back on.
141 ;; - After following a link, `C-c &' jumps back to it.
142 ;; - MH-E link support (thanks to Thomas Baumann).
143 ;; - Special table lines are no longer exported.
144 ;; - Bug fixes and minor improvements.
145 ;;
146 ;; Version 4.04
147 ;; - Cleanup tags display in agenda.
148 ;; - Bug fixes.
149 ;;
150 ;; Version 4.03
151 ;; - Table alignment fixed for use with wide characters.
152 ;; - `C-c -' leaves cursor in current table line.
153 ;; - The current TAG can be incorporated into the agenda prefix.
154 ;; See option `org-agenda-prefix-format' for details.
155 ;;
156 ;; Version 4.02
157 ;; - Minor bug fixes and improvements around tag searches.
158 ;; - XEmacs compatibility fixes.
159 ;;
160 ;; Version 4.01
161 ;; - Tags can also be set remotely from agenda buffer.
162 ;; - Boolean logic for tag searches.
163 ;; - Additional agenda commands can be configured through the variable
164 ;; `org-agenda-custom-commands'.
165 ;; - Minor bug fixes.
166 ;;
167 ;;; Code:
168
169 (eval-when-compile
170 (require 'cl)
171 (require 'calendar))
172 (require 'outline)
173 (require 'time-date)
174 (require 'easymenu)
175
176 (defvar calc-embedded-close-formula) ; defined by the calc package
177 (defvar calc-embedded-open-formula) ; defined by the calc package
178 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
179
180 ;;; Customization variables
181
182 (defvar org-version "4.23"
183 "The version number of the file org.el.")
184 (defun org-version ()
185 (interactive)
186 (message "Org-mode version %s" org-version))
187
188 ;; The following constant is for compatibility with different versions
189 ;; of outline.el.
190 (defconst org-noutline-p (featurep 'noutline)
191 "Are we using the new outline mode?")
192 (defconst org-xemacs-p (featurep 'xemacs))
193 (defconst org-format-transports-properties-p
194 (let ((x "a"))
195 (add-text-properties 0 1 '(test t) x)
196 (get-text-property 0 'test (format "%s" x)))
197 "Does format transport text properties?")
198
199 (defgroup org nil
200 "Outline-based notes management and organizer."
201 :tag "Org"
202 :group 'outlines
203 :group 'hypermedia
204 :group 'calendar)
205
206 (defgroup org-startup nil
207 "Options concerning startup of Org-mode."
208 :tag "Org Startup"
209 :group 'org)
210
211 (defcustom org-startup-folded t
212 "Non-nil means, entering Org-mode will switch to OVERVIEW.
213 This can also be configured on a per-file basis by adding one of
214 the following lines anywhere in the buffer:
215
216 #+STARTUP: fold
217 #+STARTUP: nofold
218 #+STARTUP: content"
219 :group 'org-startup
220 :type '(choice
221 (const :tag "nofold: show all" nil)
222 (const :tag "fold: overview" t)
223 (const :tag "content: all headlines" content)))
224
225 (defcustom org-startup-truncated t
226 "Non-nil means, entering Org-mode will set `truncate-lines'.
227 This is useful since some lines containing links can be very long and
228 uninteresting. Also tables look terrible when wrapped."
229 :group 'org-startup
230 :type 'boolean)
231
232 (defcustom org-startup-align-all-tables nil
233 "Non-nil means, align all tables when visiting a file.
234 This is useful when the column width in tables is forced with <N> cookies
235 in table fields. Such tables will look correct only after the first re-align."
236 :group 'org-startup
237 :type 'boolean)
238
239 (defcustom org-startup-with-deadline-check nil
240 "Non-nil means, entering Org-mode will run the deadline check.
241 This means, if you start editing an org file, you will get an
242 immediate reminder of any due deadlines.
243 This can also be configured on a per-file basis by adding one of
244 the following lines anywhere in the buffer:
245
246 #+STARTUP: dlcheck
247 #+STARTUP: nodlcheck"
248 :group 'org-startup
249 :type 'boolean)
250
251 (defcustom org-insert-mode-line-in-empty-file nil
252 "Non-nil means insert the first line setting Org-mode in empty files.
253 When the function `org-mode' is called interactively in an empty file, this
254 normally means that the file name does not automatically trigger Org-mode.
255 To ensure that the file will always be in Org-mode in the future, a
256 line enforcing Org-mode will be inserted into the buffer, if this option
257 has been set."
258 :group 'org-startup
259 :type 'boolean)
260
261 (defcustom org-CUA-compatible nil
262 "Non-nil means use alternative key bindings for S-<cursor movement>.
263 Org-mode used S-<cursor movement> for changing timestamps and priorities.
264 S-<cursor movement> is also used for example by `CUA-mode' to select text.
265 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
266 alternative bindings. Setting this variable to t will replace the following
267 keys both in Org-mode and in the Org-agenda buffer.
268
269 S-RET -> C-S-RET
270 S-up -> M-p
271 S-down -> M-n
272 S-left -> M--
273 S-right -> M-+
274
275 If you do not like the alternative keys, take a look at the variable
276 `org-disputed-keys'.
277
278 This option is only relevant at load-time of Org-mode. Changing it requires
279 a restart of Emacs to become effective."
280 :group 'org-startup
281 :type 'boolean)
282
283 (defvar org-disputed-keys
284 '((S-up [(shift up)] [(meta ?p)])
285 (S-down [(shift down)] [(meta ?n)])
286 (S-left [(shift left)] [(meta ?-)])
287 (S-right [(shift right)] [(meta ?+)])
288 (S-return [(shift return)] [(control shift return)]))
289 "Keys for which Org-mode and other modes compete.
290 This is an alist, cars are symbols for lookup, 1st element is the default key,
291 second element will be used when `org-CUA-compatible' is t.")
292
293 (defun org-key (key)
294 "Select a key according to `org-CUA-compatible'."
295 (nth (if org-CUA-compatible 2 1)
296 (or (assq key org-disputed-keys)
297 (error "Invalid Key %s in `org-key'" key))))
298
299 (defcustom org-ellipsis nil
300 "The ellipsis to use in the Org-mode outline.
301 When nil, just use the standard three dots. When a string, use that instead,
302 and just in Org-mode (which will then use its own display table).
303 Changing this requires executing `M-x org-mode' in a buffer to become
304 effective."
305 :group 'org-startup
306 :type '(choice (const :tag "Default" nil)
307 (string :tag "String" :value "...#")))
308
309 (defvar org-display-table nil
310 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
311
312 (defgroup org-keywords nil
313 "Keywords in Org-mode."
314 :tag "Org Keywords"
315 :group 'org)
316
317 (defcustom org-deadline-string "DEADLINE:"
318 "String to mark deadline entries.
319 A deadline is this string, followed by a time stamp. Should be a word,
320 terminated by a colon. You can insert a schedule keyword and
321 a timestamp with \\[org-deadline].
322 Changes become only effective after restarting Emacs."
323 :group 'org-keywords
324 :type 'string)
325
326 (defcustom org-scheduled-string "SCHEDULED:"
327 "String to mark scheduled TODO entries.
328 A schedule is this string, followed by a time stamp. Should be a word,
329 terminated by a colon. You can insert a schedule keyword and
330 a timestamp with \\[org-schedule].
331 Changes become only effective after restarting Emacs."
332 :group 'org-keywords
333 :type 'string)
334
335 (defcustom org-closed-string "CLOSED:"
336 "String used as the prefix for timestamps logging closing a TODO entry."
337 :group 'org-keywords
338 :type 'string)
339
340 (defcustom org-comment-string "COMMENT"
341 "Entries starting with this keyword will never be exported.
342 An entry can be toggled between COMMENT and normal with
343 \\[org-toggle-comment].
344 Changes become only effective after restarting Emacs."
345 :group 'org-keywords
346 :type 'string)
347
348 (defcustom org-quote-string "QUOTE"
349 "Entries starting with this keyword will be exported in fixed-width font.
350 Quoting applies only to the text in the entry following the headline, and does
351 not extend beyond the next headline, even if that is lower level.
352 An entry can be toggled between QUOTE and normal with
353 \\[org-toggle-fixed-width-section]."
354 :group 'org-keywords
355 :type 'string)
356
357 (defgroup org-structure nil
358 "Options concerning the general structure of Org-mode files."
359 :tag "Org Structure"
360 :group 'org)
361
362 (defgroup org-cycle nil
363 "Options concerning visibility cycling in Org-mode."
364 :tag "Org Cycle"
365 :group 'org-structure)
366
367 (defcustom org-cycle-emulate-tab t
368 "Where should `org-cycle' emulate TAB.
369 nil Never
370 white Only in completely white lines
371 t Everywhere except in headlines"
372 :group 'org-cycle
373 :type '(choice (const :tag "Never" nil)
374 (const :tag "Only in completely white lines" white)
375 (const :tag "Everywhere except in headlines" t)
376 ))
377
378 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
379 "Hook that is run after `org-cycle' has changed the buffer visibility.
380 The function(s) in this hook must accept a single argument which indicates
381 the new state that was set by the most recent `org-cycle' command. The
382 argument is a symbol. After a global state change, it can have the values
383 `overview', `content', or `all'. After a local state change, it can have
384 the values `folded', `children', or `subtree'."
385 :group 'org-cycle
386 :type 'hook)
387
388 (defgroup org-edit-structure nil
389 "Options concerning structure editing in Org-mode."
390 :tag "Org Edit Structure"
391 :group 'org-structure)
392
393 (defcustom org-odd-levels-only nil
394 "Non-nil means, skip even levels and only use odd levels for the outline.
395 This has the effect that two stars are being added/taken away in
396 promotion/demotion commands. It also influences how levels are
397 handled by the exporters.
398 Changing it requires restart of `font-lock-mode' to become effective
399 for fontification also in regions already fontified."
400 :group 'org-edit-structure
401 :group 'org-font-lock
402 :type 'boolean)
403
404 (defcustom org-adapt-indentation t
405 "Non-nil means, adapt indentation when promoting and demoting.
406 When this is set and the *entire* text in an entry is indented, the
407 indentation is increased by one space in a demotion command, and
408 decreased by one in a promotion command. If any line in the entry
409 body starts at column 0, indentation is not changed at all."
410 :group 'org-edit-structure
411 :type 'boolean)
412
413 (defcustom org-enable-fixed-width-editor t
414 "Non-nil means, lines starting with \":\" are treated as fixed-width.
415 This currently only means, they are never auto-wrapped.
416 When nil, such lines will be treated like ordinary lines.
417 See also the QUOTE keyword."
418 :group 'org-edit-structure
419 :type 'boolean)
420
421 (defgroup org-sparse-trees nil
422 "Options concerning sparse trees in Org-mode."
423 :tag "Org Sparse Trees"
424 :group 'org-structure)
425
426 (defcustom org-highlight-sparse-tree-matches t
427 "Non-nil means, highlight all matches that define a sparse tree.
428 The highlights will automatically disappear the next time the buffer is
429 changed by an edit command."
430 :group 'org-sparse-trees
431 :type 'boolean)
432
433 (defcustom org-show-hierarchy-above t
434 "Non-nil means, show full hierarchy when showing a spot in the tree.
435 Turning this off makes sparse trees more compact, but also less clear."
436 :group 'org-sparse-trees
437 :type 'boolean)
438
439 (defcustom org-show-following-heading t
440 "Non-nil means, show heading following match in `org-occur'.
441 When doing an `org-occur' it is useful to show the headline which
442 follows the match, even if they do not match the regexp. This makes it
443 easier to edit directly inside the sparse tree. However, if you use
444 `org-occur' mainly as an overview, the following headlines are
445 unnecessary clutter."
446 :group 'org-sparse-trees
447 :type 'boolean)
448
449 (defcustom org-occur-hook '(org-first-headline-recenter)
450 "Hook that is run after `org-occur' has constructed a sparse tree.
451 This can be used to recenter the window to show as much of the structure
452 as possible."
453 :group 'org-sparse-trees
454 :type 'hook)
455
456 (defgroup org-plain-lists nil
457 "Options concerning plain lists in Org-mode."
458 :tag "Org Plain lists"
459 :group 'org-structure)
460
461 (defcustom org-cycle-include-plain-lists nil
462 "Non-nil means, include plain lists into visibility cycling.
463 This means that during cycling, plain list items will *temporarily* be
464 interpreted as outline headlines with a level given by 1000+i where i is the
465 indentation of the bullet. In all other operations, plain list items are
466 not seen as headlines. For example, you cannot assign a TODO keyword to
467 such an item."
468 :group 'org-plain-lists
469 :type 'boolean)
470
471
472 (defcustom org-plain-list-ordered-item-terminator t
473 "The character that makes a line with leading number an ordered list item.
474 Valid values are ?. and ?\). To get both terminators, use t. While
475 ?. may look nicer, it creates the danger that a line with leading
476 number may be incorrectly interpreted as an item. ?\) therefore is
477 the safe choice."
478 :group 'org-plain-lists
479 :type '(choice (const :tag "dot like in \"2.\"" ?.)
480 (const :tag "paren like in \"2)\"" ?\))
481 (const :tab "both" t)))
482
483 (defcustom org-auto-renumber-ordered-lists t
484 "Non-nil means, automatically renumber ordered plain lists.
485 Renumbering happens when the sequence have been changed with
486 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
487 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
488 :group 'org-plain-lists
489 :type 'boolean)
490
491 (defgroup org-archive nil
492 "Options concerning archiving in Org-mode."
493 :tag "Org Archive"
494 :group 'org-structure)
495
496 (defcustom org-archive-location "%s_archive::"
497 "The location where subtrees should be archived.
498 This string consists of two parts, separated by a double-colon.
499
500 The first part is a file name - when omitted, archiving happens in the same
501 file. %s will be replaced by the current file name (without directory part).
502 Archiving to a different file is useful to keep archived entries from
503 contributing to the Org-mode Agenda.
504
505 The part after the double colon is a headline. The archived entries will be
506 filed under that headline. When omitted, the subtrees are simply filed away
507 at the end of the file, as top-level entries.
508
509 Here are a few examples:
510 \"%s_archive::\"
511 If the current file is Projects.org, archive in file
512 Projects.org_archive, as top-level trees. This is the default.
513
514 \"::* Archived Tasks\"
515 Archive in the current file, under the top-level headline
516 \"* Archived Tasks\".
517
518 \"~/org/archive.org::\"
519 Archive in file ~/org/archive.org (absolute path), as top-level trees.
520
521 \"basement::** Finished Tasks\"
522 Archive in file ./basement (relative path), as level 3 trees
523 below the level 2 heading \"** Finished Tasks\".
524
525 You may set this option on a per-file basis by adding to the buffer a
526 line like
527
528 #+ARCHIVE: basement::** Finished Tasks"
529 :group 'org-archive
530 :type 'string)
531
532 (defcustom org-archive-mark-done t
533 "Non-nil means, mark archived entries as DONE."
534 :group 'org-archive
535 :type 'boolean)
536
537 (defcustom org-archive-stamp-time t
538 "Non-nil means, add a time stamp to archived entries.
539 The time stamp will be added directly after the TODO state keyword in the
540 first line, so it is probably best to use this in combinations with
541 `org-archive-mark-done'."
542 :group 'org-archive
543 :type 'boolean)
544
545 (defgroup org-table nil
546 "Options concerning tables in Org-mode."
547 :tag "Org Table"
548 :group 'org)
549
550 (defcustom org-enable-table-editor 'optimized
551 "Non-nil means, lines starting with \"|\" are handled by the table editor.
552 When nil, such lines will be treated like ordinary lines.
553
554 When equal to the symbol `optimized', the table editor will be optimized to
555 do the following:
556 - Use automatic overwrite mode in front of whitespace in table fields.
557 This make the structure of the table stay in tact as long as the edited
558 field does not exceed the column width.
559 - Minimize the number of realigns. Normally, the table is aligned each time
560 TAB or RET are pressed to move to another field. With optimization this
561 happens only if changes to a field might have changed the column width.
562 Optimization requires replacing the functions `self-insert-command',
563 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
564 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
565 very good at guessing when a re-align will be necessary, but you can always
566 force one with \\[org-ctrl-c-ctrl-c].
567
568 If you would like to use the optimized version in Org-mode, but the
569 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
570
571 This variable can be used to turn on and off the table editor during a session,
572 but in order to toggle optimization, a restart is required.
573
574 See also the variable `org-table-auto-blank-field'."
575 :group 'org-table
576 :type '(choice
577 (const :tag "off" nil)
578 (const :tag "on" t)
579 (const :tag "on, optimized" optimized)))
580
581 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
582 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
583 In the optimized version, the table editor takes over all simple keys that
584 normally just insert a character. In tables, the characters are inserted
585 in a way to minimize disturbing the table structure (i.e. in overwrite mode
586 for empty fields). Outside tables, the correct binding of the keys is
587 restored.
588
589 The default for this option is t if the optimized version is also used in
590 Org-mode. See the variable `org-enable-table-editor' for details. Changing
591 this variable requires a restart of Emacs to become effective."
592 :group 'org-table
593 :type 'boolean)
594
595 (defgroup org-table-settings nil
596 "Settings for tables in Org-mode."
597 :tag "Org Table Settings"
598 :group 'org-table)
599
600 (defcustom org-table-default-size "5x2"
601 "The default size for newly created tables, Columns x Rows."
602 :group 'org-table-settings
603 :type 'string)
604
605 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
606 "Regular expression for recognizing numbers in table columns.
607 If a table column contains mostly numbers, it will be aligned to the
608 right. If not, it will be aligned to the left.
609
610 The default value of this option is a regular expression which allows
611 anything which looks remotely like a number as used in scientific
612 context. For example, all of the following will be considered a
613 number:
614 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
615
616 Other options offered by the customize interface are more restrictive."
617 :group 'org-table-settings
618 :type '(choice
619 (const :tag "Positive Integers"
620 "^[0-9]+$")
621 (const :tag "Integers"
622 "^[-+]?[0-9]+$")
623 (const :tag "Floating Point Numbers"
624 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
625 (const :tag "Floating Point Number or Integer"
626 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
627 (const :tag "Exponential, Floating point, Integer"
628 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
629 (const :tag "Very General Number-Like"
630 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
631 (string :tag "Regexp:")))
632
633 (defcustom org-table-number-fraction 0.5
634 "Fraction of numbers in a column required to make the column align right.
635 In a column all non-white fields are considered. If at least this
636 fraction of fields is matched by `org-table-number-fraction',
637 alignment to the right border applies."
638 :group 'org-table-settings
639 :type 'number)
640
641 (defgroup org-table-editing nil
642 "Bahavior of tables during editing in Org-mode."
643 :tag "Org Table Editing"
644 :group 'org-table)
645
646 (defcustom org-table-automatic-realign t
647 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
648 When nil, aligning is only done with \\[org-table-align], or after column
649 removal/insertion."
650 :group 'org-table-editing
651 :type 'boolean)
652
653 (defcustom org-table-limit-column-width t ;kw
654 "Non-nil means, allow to limit the width of table columns with <N> fields."
655 :group 'org-table-editing
656 :type 'boolean)
657
658 (defcustom org-table-auto-blank-field t
659 "Non-nil means, automatically blank table field when starting to type into it.
660 This only happens when typing immediately after a field motion
661 command (TAB, S-TAB or RET).
662 Only relevant when `org-enable-table-editor' is equal to `optimized'."
663 :group 'org-table-editing
664 :type 'boolean)
665
666 (defcustom org-table-tab-jumps-over-hlines t
667 "Non-nil means, tab in the last column of a table with jump over a hline.
668 If a horizontal separator line is following the current line,
669 `org-table-next-field' can either create a new row before that line, or jump
670 over the line. When this option is nil, a new line will be created before
671 this line."
672 :group 'org-table-editing
673 :type 'boolean)
674
675 (defcustom org-table-tab-recognizes-table.el t
676 "Non-nil means, TAB will automatically notice a table.el table.
677 When it sees such a table, it moves point into it and - if necessary -
678 calls `table-recognize-table'."
679 :group 'org-table-editing
680 :type 'boolean)
681
682 (defgroup org-table-calculation nil
683 "Options concerning tables in Org-mode."
684 :tag "Org Table Calculation"
685 :group 'org-table)
686
687 (defcustom org-table-copy-increment t
688 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
689 :group 'org-table-calculation
690 :type 'boolean)
691
692 (defcustom org-calc-default-modes
693 '(calc-internal-prec 12
694 calc-float-format (float 5)
695 calc-angle-mode deg
696 calc-prefer-frac nil
697 calc-symbolic-mode nil
698 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
699 calc-display-working-message t
700 )
701 "List with Calc mode settings for use in calc-eval for table formulas.
702 The list must contain alternating symbols (Calc modes variables and values).
703 Don't remove any of the default settings, just change the values. Org-mode
704 relies on the variables to be present in the list."
705 :group 'org-table-calculation
706 :type 'plist)
707
708 (defcustom org-table-formula-evaluate-inline t
709 "Non-nil means, TAB and RET evaluate a formula in current table field.
710 If the current field starts with an equal sign, it is assumed to be a formula
711 which should be evaluated as described in the manual and in the documentation
712 string of the command `org-table-eval-formula'. This feature requires the
713 Emacs calc package.
714 When this variable is nil, formula calculation is only available through
715 the command \\[org-table-eval-formula]."
716 :group 'org-table-calculation
717 :type 'boolean)
718
719
720 (defcustom org-table-formula-use-constants t
721 "Non-nil means, interpret constants in formulas in tables.
722 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
723 by the value given in `org-table-formula-constants', or by a value obtained
724 from the `constants.el' package."
725 :group 'org-table-calculation
726 :type 'boolean)
727
728 (defcustom org-table-formula-constants nil
729 "Alist with constant names and values, for use in table formulas.
730 The car of each element is a name of a constant, without the `$' before it.
731 The cdr is the value as a string. For example, if you'd like to use the
732 speed of light in a formula, you would configure
733
734 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
735
736 and then use it in an equation like `$1*$c'."
737 :group 'org-table-calculation
738 :type '(repeat
739 (cons (string :tag "name")
740 (string :tag "value"))))
741
742 (defcustom org-table-formula-numbers-only nil
743 "Non-nil means, calculate only with numbers in table formulas.
744 Then all input fields will be converted to a number, and the result
745 must also be a number. When nil, calc's full potential is available
746 in table calculations, including symbolics etc."
747 :group 'org-table-calculation
748 :type 'boolean)
749
750 (defcustom org-table-allow-automatic-line-recalculation t
751 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
752 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
753 :group 'org-table-calculation
754 :type 'boolean)
755
756 (defgroup org-link nil
757 "Options concerning links in Org-mode."
758 :tag "Org Link"
759 :group 'org)
760
761 (defcustom org-descriptive-links t
762 "Non-nil means, hide link part and only show description of bracket links.
763 Bracket links are like [[link][descritpion]]. This variable sets the initial
764 state in new org-mode buffers. The setting can then be toggled on a
765 per-buffer basis from the Org->Hyperlinks menu."
766 :group 'org-link
767 :type 'boolean)
768
769 (defcustom org-link-style 'bracket
770 "The style of links to be inserted with \\[org-insert-link].
771 Possible values are:
772 bracket [[link][description]]. This is recommended
773 plain Description \\n link. The old way, no longer recommended."
774 :group 'org-link
775 :type '(choice
776 (const :tag "Bracket (recommended)" bracket)
777 (const :tag "Plain (no longer recommended)" plain)))
778
779 (defcustom org-link-format "%s"
780 "Default format for external, URL-like linkes in the buffer.
781 This is a format string for printf, %s will be replaced by the link text.
782 The recommended value is just \"%s\", since links will be protected by
783 enclosing them in double brackets. If you prefer plain links (see variable
784 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
785 additional URL: prefix, so the format would be \"<URL:%s>\"."
786 :group 'org-link
787 :type '(choice
788 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
789 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
790 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
791 (string :tag "Other" :value "<%s>")))
792
793 (defcustom org-activate-links '(bracket angle plain radio tag date)
794 "Types of links that should be activated in Org-mode files.
795 This is a list of symbols, each leading to the activation of a certain link
796 type. In principle, it does not hurt to turn on most link types - there may
797 be a small gain when turning off unused link types. The types are:
798
799 bracket The recommended [[link][description]] or [[link]] links with hiding.
800 angular Links in angular brackes that may contain whitespace like
801 <bbdb:Carsten Dominik>.
802 plain Plain links in normal text, no whitespace, like http://google.com.
803 radio Text that is matched by a radio target, see manual for details.
804 tag Tag settings in a headline (link to tag search).
805 date Time stamps (link to calendar).
806 camel CamelCase words defining text searches.
807
808 Changing this variable requires a restart of Emacs to become effective."
809 :group 'org-link
810 :type '(set (const :tag "Double bracket links (new style)" bracket)
811 (const :tag "Angular bracket links (old style)" angular)
812 (const :tag "plain text links" plain)
813 (const :tag "Radio target matches" radio)
814 (const :tag "Tags" tag)
815 (const :tag "Timestamps" date)
816 (const :tag "CamelCase words" camel)))
817
818 (defgroup org-link-store nil
819 "Options concerning storing links in Org-mode"
820 :tag "Org Store Link"
821 :group 'org-link)
822
823 (defcustom org-context-in-file-links t
824 "Non-nil means, file links from `org-store-link' contain context.
825 A search string will be added to the file name with :: as separator and
826 used to find the context when the link is activated by the command
827 `org-open-at-point'.
828 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
829 negates this setting for the duration of the command."
830 :group 'org-link-store
831 :type 'boolean)
832
833 (defcustom org-file-link-context-use-camel-case nil
834 "Non-nil means, use CamelCase to store a search context in a file link.
835 When nil, the search string simply consists of the words of the string.
836 CamelCase is deprecated, and support for it may be dropped in the future."
837 :group 'org-link-store
838 :type 'boolean)
839
840 (defcustom org-keep-stored-link-after-insertion nil
841 "Non-nil means, keep link in list for entire session.
842
843 The command `org-store-link' adds a link pointing to the current
844 location to an internal list. These links accumulate during a session.
845 The command `org-insert-link' can be used to insert links into any
846 Org-mode file (offering completion for all stored links). When this
847 option is nil, every link which has been inserted once using \\[org-insert-link]
848 will be removed from the list, to make completing the unused links
849 more efficient."
850 :group 'org-link-store
851 :type 'boolean)
852
853 (defcustom org-usenet-links-prefer-google nil
854 "Non-nil means, `org-store-link' will create web links to Google groups.
855 When nil, Gnus will be used for such links.
856 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
857 negates this setting for the duration of the command."
858 :group 'org-link-store
859 :type 'boolean)
860
861 (defgroup org-link-follow nil
862 "Options concerning following links in Org-mode"
863 :tag "Org Follow Link"
864 :group 'org-link)
865
866 (defcustom org-tab-follows-link nil
867 "Non-nil means, on links TAB will follow the link.
868 Needs to be set before org.el is loaded."
869 :group 'org-link-follow
870 :type 'boolean)
871
872 (defcustom org-return-follows-link nil
873 "Non-nil means, on links RET will follow the link.
874 Needs to be set before org.el is loaded."
875 :group 'org-link-follow
876 :type 'boolean)
877
878 (defcustom org-mouse-1-follows-link t
879 "Non-nil means, mouse-1 on a link will follow the link.
880 A longer mouse click will still set point. Does not wortk on XEmacs.
881 Needs to be set before org.el is loaded."
882 :group 'org-link-follow
883 :type 'boolean)
884
885 (defcustom org-mark-ring-length 4
886 "Number of different positions to be recorded in the ring
887 Changing this requires a restart of Emacs to work correctly."
888 :group 'org-link-follow
889 :type 'interger)
890
891 (defcustom org-link-frame-setup
892 '((vm . vm-visit-folder-other-frame)
893 (gnus . gnus-other-frame)
894 (file . find-file-other-window))
895 "Setup the frame configuration for following links.
896 When following a link with Emacs, it may often be useful to display
897 this link in another window or frame. This variable can be used to
898 set this up for the different types of links.
899 For VM, use any of
900 `vm-visit-folder'
901 `vm-visit-folder-other-frame'
902 For Gnus, use any of
903 `gnus'
904 `gnus-other-frame'
905 For FILE, use any of
906 `find-file'
907 `find-file-other-window'
908 `find-file-other-frame'
909 For the calendar, use the variable `calendar-setup'.
910 For BBDB, it is currently only possible to display the matches in
911 another window."
912 :group 'org-link-follow
913 :type '(list
914 (cons (const vm)
915 (choice
916 (const vm-visit-folder)
917 (const vm-visit-folder-other-window)
918 (const vm-visit-folder-other-frame)))
919 (cons (const gnus)
920 (choice
921 (const gnus)
922 (const gnus-other-frame)))
923 (cons (const file)
924 (choice
925 (const find-file)
926 (const find-file-other-window)
927 (const find-file-other-frame)))))
928
929 (defcustom org-open-non-existing-files nil
930 "Non-nil means, `org-open-file' will open non-existing file.
931 When nil, an error will be generated."
932 :group 'org-link-follow
933 :type 'boolean)
934
935 (defcustom org-confirm-shell-links 'yes-or-no-p
936 "Non-nil means, ask for confirmation before executing shell links.
937 Shell links can be dangerous, just thing about a link
938
939 [[shell:rm -rf ~/*][Google Search]]
940
941 This link would show up in your Org-mode document as \"Google Search\"
942 but really it would remove your entire home directory. Dangerous indeed.
943 Therefore I *definitely* advise agains setting this varaiable to nil.
944 Just change it to `y-or-n-p' of you want to confirm with a single key press
945 rather than having to type \"yes\"."
946 :group 'org-link-follow
947 :type '(choice
948 (const :tag "with yes-or-no (safer)" yes-or-no-p)
949 (const :tag "with y-or-n (faster)" y-or-n-p)
950 (const :tag "no confirmation (dangerous)" nil)))
951
952 (defconst org-file-apps-defaults-gnu
953 '((t . mailcap))
954 "Default file applications on a UNIX or GNU/Linux system.
955 See `org-file-apps'.")
956
957 (defconst org-file-apps-defaults-macosx
958 '((t . "open %s")
959 ("ps" . "gv %s")
960 ("ps.gz" . "gv %s")
961 ("eps" . "gv %s")
962 ("eps.gz" . "gv %s")
963 ("dvi" . "xdvi %s")
964 ("fig" . "xfig %s"))
965 "Default file applications on a MacOS X system.
966 The system \"open\" is known as a default, but we use X11 applications
967 for some files for which the OS does not have a good default.
968 See `org-file-apps'.")
969
970 (defconst org-file-apps-defaults-windowsnt
971 '((t . (w32-shell-execute "open" file)))
972 "Default file applications on a Windows NT system.
973 The system \"open\" is used for most files.
974 See `org-file-apps'.")
975
976 (defcustom org-file-apps
977 '(
978 ("txt" . emacs)
979 ("tex" . emacs)
980 ("ltx" . emacs)
981 ("org" . emacs)
982 ("el" . emacs)
983 )
984 "External applications for opening `file:path' items in a document.
985 Org-mode uses system defaults for different file types, but
986 you can use this variable to set the application for a given file
987 extension. The entries in this list are cons cells with a file extension
988 and the corresponding command. Possible values for the command are:
989 `emacs' The file will be visited by the current Emacs process.
990 `default' Use the default application for this file type.
991 string A command to be executed by a shell; %s will be replaced
992 by the path to the file.
993 sexp A Lisp form which will be evaluated. The file path will
994 be available in the Lisp variable `file'.
995 For more examples, see the system specific constants
996 `org-file-apps-defaults-macosx'
997 `org-file-apps-defaults-windowsnt'
998 `org-file-apps-defaults-gnu'."
999 :group 'org-link-follow
1000 :type '(repeat
1001 (cons (choice :value ""
1002 (string :tag "Extension")
1003 (const :tag "Default for unrecognized files" t)
1004 (const :tag "Links to a directory" directory))
1005 (choice :value ""
1006 (const :tag "Visit with Emacs" emacs)
1007 (const :tag "Use system default" default)
1008 (string :tag "Command")
1009 (sexp :tag "Lisp form")))))
1010
1011 (defcustom org-mhe-search-all-folders nil
1012 "Non-nil means, that the search for the mh-message will be extended to
1013 all folders if the message cannot be found in the folder given in the link.
1014 Searching all folders is very effective with one of the search engines
1015 supported by MH-E, but will be slow with pick."
1016 :group 'org-link-follow
1017 :type 'boolean)
1018
1019 (defgroup org-remember nil
1020 "Options concerning interaction with remember.el."
1021 :tag "Org Remember"
1022 :group 'org)
1023
1024 (defcustom org-directory "~/org"
1025 "Directory with org files.
1026 This directory will be used as default to prompt for org files.
1027 Used by the hooks for remember.el."
1028 :group 'org-remember
1029 :type 'directory)
1030
1031 (defcustom org-default-notes-file "~/.notes"
1032 "Default target for storing notes.
1033 Used by the hooks for remember.el. This can be a string, or nil to mean
1034 the value of `remember-data-file'."
1035 :group 'org-remember
1036 :type '(choice
1037 (const :tag "Default from remember-data-file" nil)
1038 file))
1039
1040 (defcustom org-remember-templates nil
1041 "Templates for the creation of remember buffers.
1042 When nil, just let remember make the buffer.
1043 When not nil, this is a list of 3-element lists. In each entry, the first
1044 element is a character, a unique key to select this template.
1045 The second element is the template. The third element is optional and can
1046 specify a destination file for remember items created with this template.
1047 The default file is given by `org-default-notes-file'.
1048
1049 The template specifies the structure of the remember buffer. It should have
1050 a first line starting with a star, to act as the org-mode headline.
1051 Furthermore, the following %-escapes will be replaced with content:
1052 %t time stamp, date only
1053 %T time stamp with date and time
1054 %u inactive time stamp, date only
1055 %U inactive time stamp with date and time
1056 %n user name
1057 %a annotation, normally the link created with org-store-link
1058 %i initial content, the region when remember is called with C-u.
1059 If %i is indented, the entire inserted text will be indented as well.
1060 %? This will be removed, and the cursor placed at this position."
1061 :group 'org-remember
1062 :type '(repeat :tag "enabled"
1063 (list :value (?a "\n" nil)
1064 (character :tag "Selection Key")
1065 (string :tag "Template")
1066 (file :tag "Destination file (optional)"))))
1067
1068 (defcustom org-reverse-note-order nil
1069 "Non-nil means, store new notes at the beginning of a file or entry.
1070 When nil, new notes will be filed to the end of a file or entry."
1071 :group 'org-remember
1072 :type '(choice
1073 (const :tag "Reverse always" t)
1074 (const :tag "Reverse never" nil)
1075 (repeat :tag "By file name regexp"
1076 (cons regexp boolean))))
1077
1078 (defgroup org-todo nil
1079 "Options concerning TODO items in Org-mode."
1080 :tag "Org TODO"
1081 :group 'org)
1082
1083 (defcustom org-todo-keywords '("TODO" "DONE")
1084 "List of TODO entry keywords.
1085 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1086 considered to mean that the entry is \"done\". All the other mean that
1087 action is required, and will make the entry show up in todo lists, diaries
1088 etc.
1089 The command \\[org-todo] cycles an entry through these states, and an
1090 additional state where no keyword is present. For details about this
1091 cycling, see also the variable `org-todo-interpretation'
1092 Changes become only effective after restarting Emacs."
1093 :group 'org-todo
1094 :group 'org-keywords
1095 :type '(repeat (string :tag "Keyword")))
1096
1097 (defcustom org-todo-interpretation 'sequence
1098 "Controls how TODO keywords are interpreted.
1099 This variable is only relevant if `org-todo-keywords' contains more than two
1100 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1101
1102 When `sequence', \\[org-todo] will always switch to the next state in the
1103 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1104 to state when executed several times in direct succession. Otherwise, it
1105 switches directly to DONE from any state.
1106 See the manual for more information."
1107 :group 'org-todo
1108 :group 'org-keywords
1109 :type '(choice (const sequence)
1110 (const type)))
1111
1112 (defcustom org-after-todo-state-change-hook nil
1113 "Hook which is run after the state of a TODO item was changed.
1114 The new state (a string with a TODO keyword, or nil) is available in the
1115 Lisp variable `state'."
1116 :group 'org-todo
1117 :type 'hook)
1118
1119 (defcustom org-log-done nil
1120 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1121 When the state of an entry is changed from nothing to TODO, remove a previous
1122 closing date."
1123 :group 'org-todo
1124 :type 'boolean)
1125
1126 (defgroup org-priorities nil
1127 "Keywords in Org-mode."
1128 :tag "Org Priorities"
1129 :group 'org-todo)
1130
1131 (defcustom org-default-priority ?B
1132 "The default priority of TODO items.
1133 This is the priority an item get if no explicit priority is given."
1134 :group 'org-priorities
1135 :type 'character)
1136
1137 (defcustom org-lowest-priority ?C
1138 "The lowest priority of TODO items. A character like ?A, ?B etc."
1139 :group 'org-priorities
1140 :type 'character)
1141
1142 (defgroup org-time nil
1143 "Options concerning time stamps and deadlines in Org-mode."
1144 :tag "Org Time"
1145 :group 'org)
1146
1147 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1148 "Formats for `format-time-string' which are used for time stamps.
1149 It is not recommended to change this constant.")
1150
1151 (defcustom org-time-stamp-rounding-minutes 0
1152 "Number of minutes to round time stamps to upon insertion.
1153 When zero, insert the time unmodified. Useful rounding numbers
1154 should be factors of 60, so for example 5, 10, 15.
1155 When this is not zero, you can still force an exact time-stamp by using
1156 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1157 :group 'org-time
1158 :type 'integer)
1159
1160 (defcustom org-deadline-warning-days 30
1161 "No. of days before expiration during which a deadline becomes active.
1162 This variable governs the display in the org file."
1163 :group 'org-time
1164 :type 'number)
1165
1166 (defcustom org-popup-calendar-for-date-prompt t
1167 "Non-nil means, pop up a calendar when prompting for a date.
1168 In the calendar, the date can be selected with mouse-1. However, the
1169 minibuffer will also be active, and you can simply enter the date as well.
1170 When nil, only the minibuffer will be available."
1171 :group 'org-time
1172 :type 'boolean)
1173
1174 (defcustom org-calendar-follow-timestamp-change t
1175 "Non-nil means, make the calendar window follow timestamp changes.
1176 When a timestamp is modified and the calendar window is visible, it will be
1177 moved to the new date."
1178 :group 'org-time
1179 :type 'boolean)
1180
1181 (defgroup org-tags nil
1182 "Options concerning startup of Org-mode."
1183 :tag "Org Tags"
1184 :group 'org)
1185
1186 (defcustom org-tags-column 48
1187 "The column to which tags should be indented in a headline.
1188 If this number is positive, it specifies the column. If it is negative,
1189 it means that the tags should be flushright to that column. For example,
1190 -79 works well for a normal 80 character screen."
1191 :group 'org-tags
1192 :type 'integer)
1193
1194 (defcustom org-auto-align-tags t
1195 "Non-nil means, realign tags after pro/demotion of TODO state change.
1196 These operations change the length of a headline and therefore shift
1197 the tags around. With this options turned on, after each such operation
1198 the tags are again aligned to `org-tags-column'."
1199 :group 'org-tags
1200 :type 'boolean)
1201
1202 (defcustom org-use-tag-inheritance t
1203 "Non-nil means, tags in levels apply also for sublevels.
1204 When nil, only the tags directly given in a specific line apply there.
1205 If you turn off this option, you very likely want to turn on the
1206 companion option `org-tags-match-list-sublevels'."
1207 :group 'org-tags
1208 :type 'boolean)
1209
1210 (defcustom org-tags-match-list-sublevels nil
1211 "Non-nil means list also sublevels of headlines matching tag search.
1212 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1213 the sublevels of a headline matching a tag search often also match
1214 the same search. Listing all of them can create very long lists.
1215 Setting this variable to nil causes subtrees of a match to be skipped.
1216 This option is off by default, because inheritance in on. If you turn
1217 inheritance off, you very likely want to turn this option on.
1218
1219 As a special case, if the tag search is restricted to TODO items, the
1220 value of this variable is ignored and sublevels are always checked, to
1221 make sure all corresponding TODO items find their way into the list."
1222 :group 'org-tags
1223 :type 'boolean)
1224
1225 (defvar org-tags-history nil
1226 "History of minibuffer reads for tags.")
1227 (defvar org-last-tags-completion-table nil
1228 "The last used completion table for tags.")
1229
1230 (defgroup org-agenda nil
1231 "Options concerning agenda display Org-mode."
1232 :tag "Org Agenda"
1233 :group 'org)
1234
1235 (defvar org-category nil
1236 "Variable used by org files to set a category for agenda display.
1237 Such files should use a file variable to set it, for example
1238
1239 -*- mode: org; org-category: \"ELisp\"
1240
1241 or contain a special line
1242
1243 #+CATEGORY: ELisp
1244
1245 If the file does not specify a category, then file's base name
1246 is used instead.")
1247 (make-variable-buffer-local 'org-category)
1248
1249 (defcustom org-agenda-files nil
1250 "The files to be used for agenda display.
1251 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1252 \\[org-remove-file]. You can also use customize to edit the list.
1253
1254 If the value of the variable is not a list but a single file name, then
1255 the list of agenda files is actually stored and maintained in that file, one
1256 agenda file per line."
1257 :group 'org-agenda
1258 :type '(choice
1259 (repeat :tag "List of files" file)
1260 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1261
1262 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1263 "Custom commands for the agenda.
1264 These commands will be offered on the splash screen displayed by the
1265 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1266
1267 key The key (a single char as a string) to be associated with the command.
1268 type The command type, any of the following symbols:
1269 todo Entries with a specific TODO keyword, in all agenda files.
1270 tags Tags match in all agenda files.
1271 todo-tree Sparse tree of specific TODO keyword in *current* file.
1272 tags-tree Sparse tree with all tags matches in *current* file.
1273 occur-tree Occur sparse tree for current file.
1274 match What to search for:
1275 - a single keyword for TODO keyword searches
1276 - a tags match expression for tags searches
1277 - a regular expression for occur searches"
1278 :group 'org-agenda
1279 :type '(repeat
1280 (list (string :tag "Key")
1281 (choice :tag "Type"
1282 (const :tag "Tags search in all agenda files" tags)
1283 (const :tag "TODO keyword search in all agenda files" todo)
1284 (const :tag "Tags sparse tree in current buffer" tags-tree)
1285 (const :tag "TODO keyword tree in current buffer" todo-tree)
1286 (const :tag "Occur tree in current buffer" occur-tree))
1287 (string :tag "Match"))))
1288
1289 (defcustom org-agenda-include-all-todo t
1290 "Non-nil means, the agenda will always contain all TODO entries.
1291 When nil, date-less entries will only be shown if `org-agenda' is called
1292 with a prefix argument.
1293 When non-nil, the TODO entries will be listed at the top of the agenda, before
1294 the entries for specific days."
1295 :group 'org-agenda
1296 :type 'boolean)
1297
1298 (defcustom org-agenda-include-diary nil
1299 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1300 :group 'org-agenda
1301 :type 'boolean)
1302
1303 (defcustom org-calendar-to-agenda-key [?c]
1304 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1305 The command `org-calendar-goto-agenda' will be bound to this key. The
1306 default is the character `c' because then `c' can be used to switch back and
1307 forth between agenda and calendar."
1308 :group 'org-agenda
1309 :type 'sexp)
1310
1311 (defgroup org-agenda-window-setup nil
1312 "Options concerning setting up the Agenda window in Org Mode."
1313 :tag "Org Agenda Window Setup"
1314 :group 'org-agenda)
1315
1316 (defcustom org-agenda-mouse-1-follows-link nil
1317 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1318 A longer mouse click will still set point. Does not wortk on XEmacs.
1319 Needs to be set before org.el is loaded."
1320 :group 'org-agenda-setup
1321 :type 'boolean)
1322
1323 (defcustom org-select-timeline-window t
1324 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1325 When nil, cursor will remain in the current window."
1326 :group 'org-agenda-setup
1327 :type 'boolean)
1328
1329 (defcustom org-select-agenda-window t
1330 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1331 When nil, cursor will remain in the current window."
1332 :group 'org-agenda-setup
1333 :type 'boolean)
1334
1335 (defcustom org-fit-agenda-window t
1336 "Non-nil means, change window size of agenda to fit content."
1337 :group 'org-agenda-setup
1338 :type 'boolean)
1339
1340 (defgroup org-agenda-display nil
1341 "Options concerning what to display initially in Agenda."
1342 :tag "Org Agenda Display"
1343 :group 'org-agenda)
1344
1345 (defcustom org-agenda-show-all-dates t
1346 "Non-nil means, `org-agenda' shows every day in the selected range.
1347 When nil, only the days which actually have entries are shown."
1348 :group 'org-agenda-display
1349 :type 'boolean)
1350
1351 (defcustom org-agenda-start-on-weekday 1
1352 "Non-nil means, start the overview always on the specified weekday.
1353 0 denotes Sunday, 1 denotes Monday etc.
1354 When nil, always start on the current day."
1355 :group 'org-agenda-display
1356 :type '(choice (const :tag "Today" nil)
1357 (number :tag "Weekday No.")))
1358
1359 (defcustom org-agenda-ndays 7
1360 "Number of days to include in overview display.
1361 Should be 1 or 7."
1362 :group 'org-agenda-display
1363 :type 'number)
1364
1365 (defcustom org-agenda-use-time-grid t
1366 "Non-nil means, show a time grid in the agenda schedule.
1367 A time grid is a set of lines for specific times (like every two hours between
1368 8:00 and 20:00). The items scheduled for a day at specific times are
1369 sorted in between these lines.
1370 For details about when the grid will be shown, and what it will look like, see
1371 the variable `org-agenda-time-grid'."
1372 :group 'org-agenda-display
1373 :type 'boolean)
1374
1375 (defcustom org-agenda-time-grid
1376 '((daily today require-timed)
1377 "----------------"
1378 (800 1000 1200 1400 1600 1800 2000))
1379
1380 "The settings for time grid for agenda display.
1381 This is a list of three items. The first item is again a list. It contains
1382 symbols specifying conditions when the grid should be displayed:
1383
1384 daily if the agenda shows a single day
1385 weekly if the agenda shows an entire week
1386 today show grid on current date, independent of daily/weekly display
1387 require-timed show grid only if at least on item has a time specification
1388
1389 The second item is a string which will be places behing the grid time.
1390
1391 The third item is a list of integers, indicating the times that should have
1392 a grid line."
1393 :group 'org-agenda-display
1394 :type
1395 '(list
1396 (set :greedy t :tag "Grid Display Options"
1397 (const :tag "Show grid in single day agenda display" daily)
1398 (const :tag "Show grid in weekly agenda display" weekly)
1399 (const :tag "Always show grid for today" today)
1400 (const :tag "Show grid only if any timed entries are present"
1401 require-timed)
1402 (const :tag "Skip grid times already present in an entry"
1403 remove-match))
1404 (string :tag "Grid String")
1405 (repeat :tag "Grid Times" (integer :tag "Time"))))
1406
1407 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1408 "Sorting structure for the agenda items of a single day.
1409 This is a list of symbols which will be used in sequence to determine
1410 if an entry should be listed before another entry. The following
1411 symbols are recognized:
1412
1413 time-up Put entries with time-of-day indications first, early first
1414 time-down Put entries with time-of-day indications first, late first
1415 category-keep Keep the default order of categories, corresponding to the
1416 sequence in `org-agenda-files'.
1417 category-up Sort alphabetically by category, A-Z.
1418 category-down Sort alphabetically by category, Z-A.
1419 priority-up Sort numerically by priority, high priority last.
1420 priority-down Sort numerically by priority, high priority first.
1421
1422 The different possibilities will be tried in sequence, and testing stops
1423 if one comparison returns a \"not-equal\". For example, the default
1424 '(time-up category-keep priority-down)
1425 means: Pull out all entries having a specified time of day and sort them,
1426 in order to make a time schedule for the current day the first thing in the
1427 agenda listing for the day. Of the entries without a time indication, keep
1428 the grouped in categories, don't sort the categories, but keep them in
1429 the sequence given in `org-agenda-files'. Within each category sort by
1430 priority.
1431
1432 Leaving out `category-keep' would mean that items will be sorted across
1433 categories by priority."
1434 :group 'org-agenda-display
1435 :type '(repeat
1436 (choice
1437 (const time-up)
1438 (const time-down)
1439 (const category-keep)
1440 (const category-up)
1441 (const category-down)
1442 (const priority-up)
1443 (const priority-down))))
1444
1445 (defcustom org-sort-agenda-notime-is-late t
1446 "Non-nil means, items without time are considered late.
1447 This is only relevant for sorting. When t, items which have no explicit
1448 time like 15:30 will be considered as 24:01, i.e. later than any items which
1449 do have a time. When nil, the default time is before 0:00. You can use this
1450 option to decide if the schedule for today should come before or after timeless
1451 agenda entries."
1452 :group 'org-agenda-display
1453 :type 'boolean)
1454
1455
1456 (defgroup org-agenda-prefix nil
1457 "Options concerning the entry prefix in the Org-mode agenda display."
1458 :tag "Org Agenda Prefix"
1459 :group 'org-agenda)
1460
1461 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1462 "Format specification for the prefix of items in the agenda buffer.
1463 This format works similar to a printf format, with the following meaning:
1464
1465 %c the category of the item, \"Diary\" for entries from the diary, or
1466 as given by the CATEGORY keyword or derived from the file name.
1467 %T the first tag of the item.
1468 %t the time-of-day specification if one applies to the entry, in the
1469 format HH:MM
1470 %s Scheduling/Deadline information, a short string
1471
1472 All specifiers work basically like the standard `%s' of printf, but may
1473 contain two additional characters: A question mark just after the `%' and
1474 a whitespace/punctuation character just before the final letter.
1475
1476 If the first character after `%' is a question mark, the entire field
1477 will only be included if the corresponding value applies to the
1478 current entry. This is useful for fields which should have fixed
1479 width when present, but zero width when absent. For example,
1480 \"%?-12t\" will result in a 12 character time field if a time of the
1481 day is specified, but will completely disappear in entries which do
1482 not contain a time.
1483
1484 If there is punctuation or whitespace character just before the final
1485 format letter, this character will be appended to the field value if
1486 the value is not empty. For example, the format \"%-12:c\" leads to
1487 \"Diary: \" if the category is \"Diary\". If the category were be
1488 empty, no additional colon would be interted.
1489
1490 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1491 - Indent the line with two space characters
1492 - Give the category in a 12 chars wide field, padded with whitespace on
1493 the right (because of `-'). Append a colon if there is a category
1494 (because of `:').
1495 - If there is a time-of-day, put it into a 12 chars wide field. If no
1496 time, don't put in an empty field, just skip it (because of '?').
1497 - Finally, put the scheduling information and append a whitespace.
1498
1499 As another example, if you don't want the time-of-day of entries in
1500 the prefix, you could use:
1501
1502 (setq org-agenda-prefix-format \" %-11:c% s\")
1503
1504 See also the variables `org-agenda-remove-times-when-in-prefix' and
1505 `org-agenda-remove-tags-when-in-prefix'."
1506 :type 'string
1507 :group 'org-agenda-prefix)
1508
1509 (defcustom org-timeline-prefix-format " % s"
1510 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1511 :type 'string
1512 :group 'org-agenda-prefix)
1513
1514 (defvar org-prefix-format-compiled nil
1515 "The compiled version of the most recently used prefix format.
1516 Depending on which command was used last, this may be the compiled version
1517 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1518
1519 ;; FIXME: There seem to be situations where this does no work.
1520 (defcustom org-agenda-remove-times-when-in-prefix t
1521 "Non-nil means, remove duplicate time specifications in agenda items.
1522 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1523 time-of-day specification in a headline or diary entry is extracted and
1524 placed into the prefix. If this option is non-nil, the original specification
1525 \(a timestamp or -range, or just a plain time(range) specification like
1526 11:30-4pm) will be removed for agenda display. This makes the agenda less
1527 cluttered.
1528 The option can be t or nil. It may also be the symbol `beg', indicating
1529 that the time should only be removed what it is located at the beginning of
1530 the headline/diary entry."
1531 :group 'org-agenda-prefix
1532 :type '(choice
1533 (const :tag "Always" t)
1534 (const :tag "Never" nil)
1535 (const :tag "When at beginning of entry" beg)))
1536
1537 (defcustom org-agenda-remove-tags-when-in-prefix nil
1538 "Non-nil means, remove the tags from the headline copy in the agenda.
1539 When this is the symbol `prefix', only remove tags when
1540 `org-agenda-prefix-format' contains a `%T' specifier."
1541 :group 'org-agenda-prefix
1542 :type '(choice
1543 (const :tag "Always" t)
1544 (const :tag "Never" nil)
1545 (const :tag "When prefix format contains %T" prefix)))
1546
1547 (defgroup org-export nil
1548 "Options for exporting org-listings."
1549 :tag "Org Export"
1550 :group 'org)
1551
1552 (defgroup org-export-general nil
1553 "General options for exporting Org-mode files."
1554 :tag "Org Export General"
1555 :group 'org-export)
1556
1557 (defcustom org-export-language-setup
1558 '(("en" "Author" "Date" "Table of Contents")
1559 ("da" "Ophavsmand" "Dato" "Indhold")
1560 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1561 ("es" "Autor" "Fecha" "\xccndice")
1562 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1563 ("it" "Autore" "Data" "Indice")
1564 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1565 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1566 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1567 "Terms used in export text, translated to different languages.
1568 Use the variable `org-export-default-language' to set the language,
1569 or use the +OPTION lines for a per-file setting."
1570 :group 'org-export-general
1571 :type '(repeat
1572 (list
1573 (string :tag "HTML language tag")
1574 (string :tag "Author")
1575 (string :tag "Date")
1576 (string :tag "Table of Contents"))))
1577
1578 (defcustom org-export-default-language "en"
1579 "The default language of HTML export, as a string.
1580 This should have an association in `org-export-language-setup'."
1581 :group 'org-export-general
1582 :type 'string)
1583
1584 (defcustom org-export-headline-levels 3
1585 "The last level which is still exported as a headline.
1586 Inferior levels will produce itemize lists when exported.
1587 Note that a numeric prefix argument to an exporter function overrides
1588 this setting.
1589
1590 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1591 :group 'org-export-general
1592 :type 'number)
1593
1594 (defcustom org-export-with-section-numbers t
1595 "Non-nil means, add section numbers to headlines when exporting.
1596
1597 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1598 :group 'org-export-general
1599 :type 'boolean)
1600
1601 (defcustom org-export-with-toc t
1602 "Non-nil means, create a table of contents in exported files.
1603 The TOC contains headlines with levels up to`org-export-headline-levels'.
1604
1605 Headlines which contain any TODO items will be marked with \"(*)\" in
1606 ASCII export, and with red color in HTML output.
1607
1608 In HTML output, the TOC will be clickable.
1609
1610 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1611 :group 'org-export-general
1612 :type 'boolean)
1613
1614 (defcustom org-export-mark-todo-in-toc nil
1615 "Non-nil means, mark TOC lines that contain any open TODO items."
1616 :group 'org-export-general
1617 :type 'boolean)
1618
1619 (defcustom org-export-preserve-breaks nil
1620 "Non-nil means, preserve all line breaks when exporting.
1621 Normally, in HTML output paragraphs will be reformatted. In ASCII
1622 export, line breaks will always be preserved, regardless of this variable.
1623
1624 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1625 :group 'org-export-general
1626 :type 'boolean)
1627
1628 (defgroup org-export-translation nil
1629 "Options for translating special ascii sequences for the export backends."
1630 :tag "Org Export Translation"
1631 :group 'org-export)
1632
1633 (defcustom org-export-with-emphasize t
1634 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1635 If the export target supports emphasizing text, the word will be
1636 typeset in bold, italic, or underlined, respectively. Works only for
1637 single words, but you can say: I *really* *mean* *this*.
1638 Not all export backends support this.
1639
1640 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1641 :group 'org-export-translation
1642 :type 'boolean)
1643
1644 (defcustom org-export-with-sub-superscripts t
1645 "Non-nil means, interpret \"_\" and \"^\" for export.
1646 When this option is turned on, you can use TeX-like syntax for sub- and
1647 superscripts. Several characters after \"_\" or \"^\" will be
1648 considered as a single item - so grouping with {} is normally not
1649 needed. For example, the following things will be parsed as single
1650 sub- or superscripts.
1651
1652 10^24 or 10^tau several digits will be considered 1 item.
1653 10^-12 or 10^-tau a leading sign with digits or a word
1654 x^2-y^3 will be read as x^2 - y^3, because items are
1655 terminated by almost any nonword/nondigit char.
1656 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1657
1658 Still, ambiguity is possible - so when in doubt use {} to enclose the
1659 sub/superscript.
1660 Not all export backends support this, but HTML does.
1661
1662 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1663 :group 'org-export-translation
1664 :type 'boolean)
1665
1666 (defcustom org-export-with-TeX-macros t
1667 "Non-nil means, interpret simple TeX-like macros when exporting.
1668 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1669 No only real TeX macros will work here, but the standard HTML entities
1670 for math can be used as macro names as well. For a list of supported
1671 names in HTML export, see the constant `org-html-entities'.
1672 Not all export backends support this.
1673
1674 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1675 :group 'org-export-translation
1676 :type 'boolean)
1677
1678 (defcustom org-export-with-fixed-width t
1679 "Non-nil means, lines starting with \":\" will be in fixed width font.
1680 This can be used to have pre-formatted text, fragments of code etc. For
1681 example:
1682 : ;; Some Lisp examples
1683 : (while (defc cnt)
1684 : (ding))
1685 will be looking just like this in also HTML. See also the QUOTE keyword.
1686 Not all export backends support this.
1687
1688 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1689 :group 'org-export-translation
1690 :type 'boolean)
1691
1692 (defcustom org-match-sexp-depth 3
1693 "Number of stacked braces for sub/superscript matching.
1694 This has to be set before loading org.el to be effective."
1695 :group 'org-export-translation
1696 :type 'integer)
1697
1698 (defgroup org-export-tables nil
1699 "Options for exporting tables in Org-mode."
1700 :tag "Org Export Tables"
1701 :group 'org-export)
1702
1703 (defcustom org-export-with-tables t
1704 "If non-nil, lines starting with \"|\" define a table.
1705 For example:
1706
1707 | Name | Address | Birthday |
1708 |-------------+----------+-----------|
1709 | Arthur Dent | England | 29.2.2100 |
1710
1711 Not all export backends support this.
1712
1713 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1714 :group 'org-export-tables
1715 :type 'boolean)
1716
1717 (defcustom org-export-highlight-first-table-line t
1718 "Non-nil means, highlight the first table line.
1719 In HTML export, this means use <th> instead of <td>.
1720 In tables created with table.el, this applies to the first table line.
1721 In Org-mode tables, all lines before the first horizontal separator
1722 line will be formatted with <th> tags."
1723 :group 'org-export-tables
1724 :type 'boolean)
1725
1726 (defcustom org-export-table-remove-special-lines t
1727 "Remove special lines and marking characters in calculating tables.
1728 This removes the special marking character column from tables that are set
1729 up for spreadsheet calculations. It also removes the entire lines
1730 marked with `!', `_', or `^'. The lines with `$' are kept, because
1731 the values of constants may be useful to have."
1732 :group 'org-export-tables
1733 :type 'boolean)
1734
1735 (defcustom org-export-prefer-native-exporter-for-tables nil
1736 "Non-nil means, always export tables created with table.el natively.
1737 Natively means, use the HTML code generator in table.el.
1738 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1739 the table does not use row- or column-spanning). This has the
1740 advantage, that the automatic HTML conversions for math symbols and
1741 sub/superscripts can be applied. Org-mode's HTML generator is also
1742 much faster."
1743 :group 'org-export-tables
1744 :type 'boolean)
1745
1746 (defgroup org-export-ascii nil
1747 "Options specific for ASCII export of Org-mode files."
1748 :tag "Org Export ASCII"
1749 :group 'org-export)
1750
1751 (defcustom org-export-ascii-show-new-buffer t
1752 "Non-nil means, popup buffer containing the exported ASCII text.
1753 Otherwise the buffer will just be saved to a file and stay hidden."
1754 :group 'org-export-ascii
1755 :type 'boolean)
1756
1757 (defgroup org-export-xml nil
1758 "Options specific for XML export of Org-mode files."
1759 :tag "Org Export XML"
1760 :group 'org-export)
1761
1762 (defcustom org-export-xml-type 'xoxo ;kw, if we have only one.
1763 "The kind of XML to be produced by the XML exporter.
1764 Allowed values are:
1765 xoxo The XOXO exporter."
1766 :group 'org-export-xml
1767 :type '(choice
1768 (const :tag "XOXO" xoxo)))
1769
1770 (defgroup org-export-html nil
1771 "Options specific for HTML export of Org-mode files."
1772 :tag "Org Export HTML"
1773 :group 'org-export)
1774
1775 (defcustom org-export-html-style
1776 "<style type=\"text/css\">
1777 html {
1778 font-family: Times, serif;
1779 font-size: 12pt;
1780 }
1781 .title { text-align: center; }
1782 .todo, .deadline { color: red; }
1783 .done { color: green; }
1784 .target { background-color: lavender; }
1785 pre {
1786 border: 1pt solid #AEBDCC;
1787 background-color: #F3F5F7;
1788 padding: 5pt;
1789 font-family: courier, monospace;
1790 }
1791 table { border-collapse: collapse; }
1792 td, th {
1793 vertical-align: top;
1794 border: 1pt solid #ADB9CC;
1795 }
1796 </style>"
1797 "The default style specification for exported HTML files.
1798 Since there are different ways of setting style information, this variable
1799 needs to contain the full HTML structure to provide a style, including the
1800 surrounding HTML tags. The style specifications should include definitions
1801 for new classes todo, done, title, and deadline. For example, legal values
1802 would be:
1803
1804 <style type=\"text/css\">
1805 p { font-weight: normal; color: gray; }
1806 h1 { color: black; }
1807 .title { text-align: center; }
1808 .todo, .deadline { color: red; }
1809 .done { color: green; }
1810 </style>
1811
1812 or, if you want to keep the style in a file,
1813
1814 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1815
1816 As the value of this option simply gets inserted into the HTML <head> header,
1817 you can \"misuse\" it to add arbitrary text to the header."
1818 :group 'org-export-html
1819 :type 'string)
1820
1821 (defcustom org-export-html-inline-images t
1822 "Non-nil means, inline images into exported HTML pages.
1823 The link will still be to the original location of the image file.
1824 So if you are moving the page, lets say to your public HTML site,
1825 you will have to move the image and maybe change the link."
1826 :group 'org-export-html
1827 :type 'boolean)
1828
1829 (defcustom org-export-html-expand t
1830 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1831 When nil, these tags will be exported as plain text and therefore
1832 not be interpreted by a browser.
1833
1834 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1835 :group 'org-export-html
1836 :type 'boolean)
1837
1838 (defcustom org-export-html-table-tag
1839 "<table border=1 cellspacing=0 cellpadding=6>"
1840 "The HTML tag used to start a table.
1841 This must be a <table> tag, but you may change the options like
1842 borders and spacing."
1843 :group 'org-export-html
1844 :type 'string)
1845
1846 (defcustom org-export-html-with-timestamp nil
1847 "If non-nil, write `org-export-html-html-helper-timestamp'
1848 into the exported HTML text. Otherwise, the buffer will just be saved
1849 to a file."
1850 :group 'org-export-html
1851 :type 'boolean)
1852
1853 (defcustom org-export-html-html-helper-timestamp
1854 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1855 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1856 :group 'org-export-html
1857 :type 'string)
1858
1859 (defcustom org-export-html-show-new-buffer nil
1860 "Non-nil means, popup buffer containing the exported html text.
1861 Otherwise, the buffer will just be saved to a file and stay hidden."
1862 :group 'org-export-html
1863 :type 'boolean)
1864
1865 (defgroup org-export-icalendar nil
1866 "Options specific for iCalendar export of Org-mode files."
1867 :tag "Org Export iCalendar"
1868 :group 'org-export)
1869
1870 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1871 "The file name for the iCalendar file covering all agenda files.
1872 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1873 :group 'org-export-icalendar
1874 :type 'file)
1875
1876 (defcustom org-icalendar-include-todo nil
1877 "Non-nil means, export to iCalendar files should also cover TODO items."
1878 :group 'org-export-icalendar
1879 :type 'boolean)
1880
1881 (defcustom org-icalendar-combined-name "OrgMode"
1882 "Calendar name for the combined iCalendar representing all agenda files."
1883 :group 'org-export-icalendar
1884 :type 'string)
1885
1886 (defgroup org-font-lock nil
1887 "Font-lock settings for highlighting in Org-mode."
1888 :tag "Org Font Lock"
1889 :group 'org)
1890
1891 (defcustom org-level-color-stars-only nil
1892 "Non-nil means fontify only the stars in each headline.
1893 When nil, the entire headline is fontified.
1894 Changing it requires restart of `font-lock-mode' to become effective
1895 also in regions already fontified."
1896 :group 'org-font-lock
1897 :type 'boolean)
1898
1899 (defcustom org-hide-leading-stars nil
1900 "Non-nil means, hide the first N-1 stars in a headline.
1901 This works by using the face `org-hide' for these stars. This
1902 face is white for a light background, and black for a dark
1903 background. You may have to customize the face `org-hide' to
1904 make this work.
1905 Changing it requires restart of `font-lock-mode' to become effective
1906 also in regions already fontified."
1907 :group 'org-font-lock
1908 :type 'boolean)
1909
1910 (defcustom org-fontify-done-headline nil
1911 "Non-nil means, change the face of a headline if it is marked DONE.
1912 Normally, only the TODO/DONE keyword indicates the state of a headline.
1913 When this is non-nil, the headline after the keyword is set to the
1914 `org-headline-done' as an additional indication."
1915 :group 'org-font-lock
1916 :type 'boolean)
1917
1918 (defcustom org-fontify-emphasized-text t
1919 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
1920 Changing this variable requires a restart of Emacs to take effect."
1921 :group 'org-font-lock
1922 :type 'boolean)
1923
1924 (defgroup org-faces nil
1925 "Faces in Org-mode."
1926 :tag "Org Faces"
1927 :group 'org-font-lock)
1928
1929 (defface org-hide
1930 '(
1931 (((type tty) (class color)) (:foreground "white"))
1932 (((class color) (background light)) (:foreground "white"))
1933 (((class color) (background dark)) (:foreground "black"))
1934 (t (:inverse-video nil)))
1935 "Face used for level 1 headlines."
1936 :group 'org-faces)
1937
1938 (defface org-level-1 ;; font-lock-function-name-face
1939 '((((type tty) (class color)) (:foreground "blue" :weight bold))
1940 (((class color) (background light)) (:foreground "Blue"))
1941 (((class color) (background dark)) (:foreground "LightSkyBlue"))
1942 (t (:inverse-video t :bold t)))
1943 "Face used for level 1 headlines."
1944 :group 'org-faces)
1945
1946 (defface org-level-2 ;; font-lock-variable-name-face
1947 '((((type tty) (class color)) (:foreground "yellow" :weight light))
1948 (((class color) (background light)) (:foreground "DarkGoldenrod"))
1949 (((class color) (background dark)) (:foreground "LightGoldenrod"))
1950 (t (:bold t :italic t)))
1951 "Face used for level 2 headlines."
1952 :group 'org-faces)
1953
1954 (defface org-level-3 ;; font-lock-keyword-face
1955 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
1956 (((class color) (background light)) (:foreground "Purple"))
1957 (((class color) (background dark)) (:foreground "Cyan"))
1958 (t (:bold t)))
1959 "Face used for level 3 headlines."
1960 :group 'org-faces)
1961
1962 (defface org-level-4 ;; font-lock-comment-face
1963 '((((type tty pc) (class color) (background light)) (:foreground "red"))
1964 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
1965 (((class color) (background light)) (:foreground "Firebrick"))
1966 (((class color) (background dark)) (:foreground "chocolate1"))
1967 (t (:bold t :italic t)))
1968 "Face used for level 4 headlines."
1969 :group 'org-faces)
1970
1971 (defface org-level-5 ;; font-lock-type-face
1972 '((((type tty) (class color)) (:foreground "green"))
1973 (((class color) (background light)) (:foreground "ForestGreen"))
1974 (((class color) (background dark)) (:foreground "PaleGreen"))
1975 (t (:bold t :underline t)))
1976 "Face used for level 5 headlines."
1977 :group 'org-faces)
1978
1979 (defface org-level-6 ;; font-lock-constant-face
1980 '((((type tty) (class color)) (:foreground "magenta"))
1981 (((class color) (background light)) (:foreground "CadetBlue"))
1982 (((class color) (background dark)) (:foreground "Aquamarine"))
1983 (t (:bold t :underline t)))
1984 "Face used for level 6 headlines."
1985 :group 'org-faces)
1986
1987 (defface org-level-7 ;; font-lock-builtin-face
1988 '((((type tty) (class color)) (:foreground "blue" :weight light))
1989 (((class color) (background light)) (:foreground "Orchid"))
1990 (((class color) (background dark)) (:foreground "LightSteelBlue"))
1991 (t (:bold t)))
1992 "Face used for level 7 headlines."
1993 :group 'org-faces)
1994
1995 (defface org-level-8 ;; font-lock-string-face
1996 '((((type tty) (class color)) (:foreground "green"))
1997 (((class color) (background light)) (:foreground "RosyBrown"))
1998 (((class color) (background dark)) (:foreground "LightSalmon"))
1999 (t (:italic t)))
2000 "Face used for level 8 headlines."
2001 :group 'org-faces)
2002
2003 (defface org-special-keyword ;; font-lock-string-face
2004 '((((type tty) (class color)) (:foreground "green"))
2005 (((class color) (background light)) (:foreground "RosyBrown"))
2006 (((class color) (background dark)) (:foreground "LightSalmon"))
2007 (t (:italic t)))
2008 "Face used for special keywords."
2009 :group 'org-faces)
2010
2011 (defface org-warning ;; font-lock-warning-face
2012 '((((type tty) (class color)) (:foreground "red"))
2013 (((class color) (background light)) (:foreground "Red" :bold t))
2014 (((class color) (background dark)) (:foreground "Red1" :bold t))
2015 ; (((class color) (background dark)) (:foreground "Pink" :bold t))
2016 (t (:inverse-video t :bold t)))
2017 "Face for deadlines and TODO keywords."
2018 :group 'org-faces)
2019
2020 (defface org-headline-done ;; font-lock-string-face
2021 '((((type tty) (class color)) (:foreground "green"))
2022 (((class color) (background light)) (:foreground "RosyBrown"))
2023 (((class color) (background dark)) (:foreground "LightSalmon"))
2024 (t (:italic t)))
2025 "Face used to indicate that a headline is DONE. See also the variable
2026 `org-fontify-done-headline'."
2027 :group 'org-faces)
2028
2029 ;; Inheritance does not work for xemacs. So we just copy...
2030
2031 (defface org-deadline-announce
2032 '((((type tty) (class color)) (:foreground "blue" :weight bold))
2033 (((class color) (background light)) (:foreground "Blue"))
2034 (((class color) (background dark)) (:foreground "LightSkyBlue"))
2035 (t (:inverse-video t :bold t)))
2036 "Face for upcoming deadlines."
2037 :group 'org-faces)
2038
2039 (defface org-scheduled-today
2040 '((((type tty) (class color)) (:foreground "green"))
2041 (((class color) (background light)) (:foreground "DarkGreen"))
2042 (((class color) (background dark)) (:foreground "PaleGreen"))
2043 (t (:bold t :underline t)))
2044 "Face for items scheduled for a certain day."
2045 :group 'org-faces)
2046
2047 (defface org-scheduled-previously
2048 '((((type tty pc) (class color) (background light)) (:foreground "red"))
2049 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
2050 (((class color) (background light)) (:foreground "Firebrick"))
2051 (((class color) (background dark)) (:foreground "chocolate1"))
2052 (t (:bold t :italic t)))
2053 "Face for items scheduled previously, and not yet done."
2054 :group 'org-faces)
2055
2056 (defface org-formula
2057 '((((type tty pc) (class color) (background light)) (:foreground "red"))
2058 (((type tty pc) (class color) (background dark)) (:foreground "red1"))
2059 (((class color) (background light)) (:foreground "Firebrick"))
2060 (((class color) (background dark)) (:foreground "chocolate1"))
2061 (t (:bold t :italic t)))
2062 "Face for formulas."
2063 :group 'org-faces)
2064
2065 (defface org-link
2066 '((((type tty) (class color)) (:foreground "cyan" :weight bold))
2067 (((class color) (background light)) (:foreground "Purple" :underline t))
2068 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2069 (t (:bold t)))
2070 "Face for links."
2071 :group 'org-faces)
2072
2073 (defface org-tag
2074 '((((type tty) (class color)) (:weight bold))
2075 (((class color) (background light)) (:weight bold))
2076 (((class color) (background dark)) (:weight bold))
2077 (t (:bold t)))
2078 "Face for tags."
2079 :group 'org-faces)
2080
2081 (defface org-done ;; font-lock-type-face
2082 '((((type tty) (class color)) (:foreground "green"))
2083 (((class color) (background light)) (:foreground "ForestGreen" :bold t))
2084 (((class color) (background dark)) (:foreground "PaleGreen" :bold t))
2085 (t (:bold t :underline t)))
2086 "Face used for DONE."
2087 :group 'org-faces)
2088
2089 (defface org-table ;; font-lock-function-name-face
2090 '((((type tty) (class color)) (:foreground "blue" :weight bold))
2091 (((class color) (background light)) (:foreground "Blue"))
2092 (((class color) (background dark)) (:foreground "LightSkyBlue"))
2093 (t (:inverse-video t :bold t)))
2094 "Face used for tables."
2095 :group 'org-faces)
2096
2097 (defface org-time-grid ;; font-lock-variable-name-face
2098 '((((type tty) (class color)) (:foreground "yellow" :weight light))
2099 (((class color) (background light)) (:foreground "DarkGoldenrod"))
2100 (((class color) (background dark)) (:foreground "LightGoldenrod"))
2101 (t (:bold t :italic t)))
2102 "Face used for time grids."
2103 :group 'org-faces)
2104
2105 (defvar org-level-faces
2106 '(org-level-1 org-level-2 org-level-3 org-level-4
2107 org-level-5 org-level-6 org-level-7 org-level-8
2108 ))
2109 (defvar org-n-levels (length org-level-faces))
2110
2111
2112 ;; Variables for pre-computed regular expressions, all buffer local
2113 (defvar org-done-string nil
2114 "The last string in `org-todo-keywords', indicating an item is DONE.")
2115 (make-variable-buffer-local 'org-done-string)
2116 (defvar org-todo-regexp nil
2117 "Matches any of the TODO state keywords.")
2118 (make-variable-buffer-local 'org-todo-regexp)
2119 (defvar org-not-done-regexp nil
2120 "Matches any of the TODO state keywords except the last one.")
2121 (make-variable-buffer-local 'org-not-done-regexp)
2122 (defvar org-todo-line-regexp nil
2123 "Matches a headline and puts TODO state into group 2 if present.")
2124 (make-variable-buffer-local 'org-todo-line-regexp)
2125 (defvar org-nl-done-regexp nil
2126 "Matches newline followed by a headline with the DONE keyword.")
2127 (make-variable-buffer-local 'org-nl-done-regexp)
2128 (defvar org-looking-at-done-regexp nil
2129 "Matches the DONE keyword a point.")
2130 (make-variable-buffer-local 'org-looking-at-done-regexp)
2131 (defvar org-todo-kwd-priority-p nil
2132 "Do TODO items have priorities?")
2133 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2134 (defvar org-todo-kwd-max-priority nil
2135 "Maximum priority of TODO items.")
2136 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2137 (defvar org-ds-keyword-length 12
2138 "Maximum length of the Deadline and SCHEDULED keywords.")
2139 (make-variable-buffer-local 'org-ds-keyword-length)
2140 (defvar org-deadline-regexp nil
2141 "Matches the DEADLINE keyword.")
2142 (make-variable-buffer-local 'org-deadline-regexp)
2143 (defvar org-deadline-time-regexp nil
2144 "Matches the DEADLINE keyword together with a time stamp.")
2145 (make-variable-buffer-local 'org-deadline-time-regexp)
2146 (defvar org-deadline-line-regexp nil
2147 "Matches the DEADLINE keyword and the rest of the line.")
2148 (make-variable-buffer-local 'org-deadline-line-regexp)
2149 (defvar org-scheduled-regexp nil
2150 "Matches the SCHEDULED keyword.")
2151 (make-variable-buffer-local 'org-scheduled-regexp)
2152 (defvar org-scheduled-time-regexp nil
2153 "Matches the SCHEDULED keyword together with a time stamp.")
2154 (make-variable-buffer-local 'org-scheduled-time-regexp)
2155
2156 (defun org-set-regexps-and-options ()
2157 "Precompute regular expressions for current buffer."
2158 (when (eq major-mode 'org-mode)
2159 (let ((re (org-make-options-regexp
2160 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2161 "STARTUP" "ARCHIVE")))
2162 (splitre "[ \t]+")
2163 kwds int key value cat arch)
2164 (save-excursion
2165 (save-restriction
2166 (widen)
2167 (goto-char (point-min))
2168 (while (re-search-forward re nil t)
2169 (setq key (match-string 1) value (match-string 2))
2170 (cond
2171 ((equal key "CATEGORY")
2172 (if (string-match "[ \t]+$" value)
2173 (setq value (replace-match "" t t value)))
2174 (setq cat (intern value)))
2175 ((equal key "SEQ_TODO")
2176 (setq int 'sequence
2177 kwds (append kwds (org-split-string value splitre))))
2178 ((equal key "PRI_TODO")
2179 (setq int 'priority
2180 kwds (append kwds (org-split-string value splitre))))
2181 ((equal key "TYP_TODO")
2182 (setq int 'type
2183 kwds (append kwds (org-split-string value splitre))))
2184 ((equal key "STARTUP")
2185 (let ((opts (org-split-string value splitre))
2186 (set '(("fold" org-startup-folded t)
2187 ("overview" org-startup-folded t)
2188 ("nofold" org-startup-folded nil)
2189 ("showall" org-startup-folded nil)
2190 ("content" org-startup-folded content)
2191 ("hidestars" org-hide-leading-stars t)
2192 ("showstars" org-hide-leading-stars nil)
2193 ("odd" org-odd-levels-only t)
2194 ("oddeven" org-odd-levels-only nil)
2195 ("align" org-startup-align-all-tables t)
2196 ("noalign" org-startup-align-all-tables nil)
2197 ("dlcheck" org-startup-with-deadline-check t)
2198 ("nodlcheck" org-startup-with-deadline-check nil)))
2199 l var val)
2200 (while (setq l (assoc (pop opts) set))
2201 (setq var (nth 1 l) val (nth 2 l))
2202 (set (make-local-variable var) val))))
2203 ((equal key "ARCHIVE")
2204 (string-match " *$" value)
2205 (setq arch (replace-match "" t t value))
2206 (remove-text-properties 0 (length arch)
2207 '(face t fontified t) arch)))
2208 )))
2209 (and cat (set (make-local-variable 'org-category) cat))
2210 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2211 (and arch (set (make-local-variable 'org-archive-location) arch))
2212 (and int (set (make-local-variable 'org-todo-interpretation) int)))
2213 ;; Compute the regular expressions and other local variables
2214 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2215 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2216 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2217 (length org-scheduled-string)))
2218 org-done-string
2219 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2220 org-todo-regexp
2221 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2222 "\\|") "\\)\\>")
2223 org-not-done-regexp
2224 (concat "\\<\\("
2225 (mapconcat 'regexp-quote
2226 (nreverse (cdr (reverse org-todo-keywords)))
2227 "\\|")
2228 "\\)\\>")
2229 org-todo-line-regexp
2230 (concat "^\\(\\*+\\)[ \t]*\\("
2231 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2232 "\\)? *\\(.*\\)")
2233 org-nl-done-regexp
2234 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2235 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2236 org-deadline-regexp (concat "\\<" org-deadline-string)
2237 org-deadline-time-regexp
2238 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2239 org-deadline-line-regexp
2240 (concat "\\<\\(" org-deadline-string "\\).*")
2241 org-scheduled-regexp
2242 (concat "\\<" org-scheduled-string)
2243 org-scheduled-time-regexp
2244 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
2245 (org-set-font-lock-defaults)))
2246
2247 ;; Tell the compiler about dynamically scoped variables,
2248 ;; and variables from other packages
2249 (defvar zmacs-regions) ; XEmacs regions
2250 (defvar original-date) ; dynamically scoped in calendar
2251 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2252 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2253 (defvar org-html-entities) ; defined later in this file
2254 (defvar org-goto-start-pos) ; dynamically scoped parameter
2255 (defvar org-time-was-given) ; dynamically scoped parameter
2256 (defvar org-ts-what) ; dynamically scoped parameter
2257 (defvar mark-active) ; Emacs only, not available in XEmacs.
2258 (defvar timecnt) ; dynamically scoped parameter
2259 (defvar levels-open) ; dynamically scoped parameter
2260 (defvar title) ; dynamically scoped parameter
2261 (defvar author) ; dynamically scoped parameter
2262 (defvar email) ; dynamically scoped parameter
2263 (defvar text) ; dynamically scoped parameter
2264 (defvar entry) ; dynamically scoped parameter
2265 (defvar date) ; dynamically scoped parameter
2266 (defvar language) ; dynamically scoped parameter
2267 (defvar options) ; dynamically scoped parameter
2268 (defvar ans1) ; dynamically scoped parameter
2269 (defvar ans2) ; dynamically scoped parameter
2270 (defvar starting-day) ; local variable
2271 (defvar include-all-loc) ; local variable
2272 (defvar vm-message-pointer) ; from vm
2273 (defvar vm-folder-directory) ; from vm
2274 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2275 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2276 (defvar gnus-group-name) ; from gnus
2277 (defvar gnus-article-current) ; from gnus
2278 (defvar w3m-current-url) ; from w3m
2279 (defvar mh-progs) ; from MH-E
2280 (defvar mh-current-folder) ; from MH-E
2281 (defvar mh-show-folder-buffer) ; from MH-E
2282 (defvar mh-index-folder) ; from MH-E
2283 (defvar mh-searcher) ; from MH-E
2284 (defvar org-selected-point) ; dynamically scoped parameter
2285 (defvar calendar-mode-map) ; from calendar.el
2286 (defvar last-arg) ; local variable
2287 (defvar remember-save-after-remembering) ; from remember.el
2288 (defvar remember-data-file) ; from remember.el
2289 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2290 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2291 (defvar orgtbl-mode) ; defined later in this file
2292 ;;; Define the mode
2293
2294 (defvar org-mode-map (copy-keymap outline-mode-map)
2295 "Keymap for Org-mode.")
2296
2297 (defvar org-struct-menu) ; defined later in this file
2298 (defvar org-org-menu) ; defined later in this file
2299 (defvar org-tbl-menu) ; defined later in this file
2300
2301 ;; We use a before-change function to check if a table might need
2302 ;; an update.
2303 (defvar org-table-may-need-update t
2304 "Indicates that a table might need an update.
2305 This variable is set by `org-before-change-function'.
2306 `org-table-align' sets it back to nil.")
2307 (defvar org-mode-hook nil)
2308 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2309 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2310
2311
2312 ;;;###autoload
2313 (define-derived-mode org-mode outline-mode "Org"
2314 "Outline-based notes management and organizer, alias
2315 \"Carsten's outline-mode for keeping track of everything.\"
2316
2317 Org-mode develops organizational tasks around a NOTES file which
2318 contains information about projects as plain text. Org-mode is
2319 implemented on top of outline-mode, which is ideal to keep the content
2320 of large files well structured. It supports ToDo items, deadlines and
2321 time stamps, which magically appear in the diary listing of the Emacs
2322 calendar. Tables are easily created with a built-in table editor.
2323 Plain text URL-like links connect to websites, emails (VM), Usenet
2324 messages (Gnus), BBDB entries, and any files related to the project.
2325 For printing and sharing of notes, an Org-mode file (or a part of it)
2326 can be exported as a structured ASCII or HTML file.
2327
2328 The following commands are available:
2329
2330 \\{org-mode-map}"
2331 (easy-menu-add org-org-menu)
2332 (easy-menu-add org-tbl-menu)
2333 (org-install-agenda-files-menu)
2334 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2335 (org-add-to-invisibility-spec '(org-cwidth))
2336 (setq outline-regexp "\\*+")
2337 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2338 (setq outline-level 'org-outline-level)
2339 (when (and org-ellipsis (stringp org-ellipsis))
2340 (unless org-display-table
2341 (setq org-display-table (make-display-table)))
2342 (set-display-table-slot org-display-table
2343 4 (string-to-vector org-ellipsis))
2344 (setq buffer-display-table org-display-table))
2345 (org-set-regexps-and-options)
2346 (if org-startup-truncated (setq truncate-lines t))
2347 (set (make-local-variable 'font-lock-unfontify-region-function)
2348 'org-unfontify-region)
2349 ;; Activate before-change-function
2350 (set (make-local-variable 'org-table-may-need-update) t)
2351 (org-add-hook 'before-change-functions 'org-before-change-function nil
2352 'local)
2353 ;; Paragraphs and auto-filling
2354 (org-set-autofill-regexps)
2355 (org-update-radio-target-regexp)
2356 ;; Settings for Calc embedded mode
2357 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2358 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2359 (if (and org-insert-mode-line-in-empty-file
2360 (interactive-p)
2361 (= (point-min) (point-max)))
2362 (insert " -*- mode: org -*-\n\n"))
2363
2364 ;; Get rid of Outline menus, they are not needed
2365 ;; Need to do this here because define-derived-mode sets up
2366 ;; the keymap so late.
2367 (if (featurep 'xemacs)
2368 (progn
2369 (delete-menu-item '("Headings"))
2370 (delete-menu-item '("Show"))
2371 (delete-menu-item '("Hide"))
2372 (set-menubar-dirty-flag))
2373 (define-key org-mode-map [menu-bar headings] 'undefined)
2374 (define-key org-mode-map [menu-bar hide] 'undefined)
2375 (define-key org-mode-map [menu-bar show] 'undefined))
2376
2377 (unless org-inhibit-startup
2378 (if org-startup-align-all-tables
2379 (org-table-map-tables 'org-table-align))
2380 (if org-startup-with-deadline-check
2381 (call-interactively 'org-check-deadlines)
2382 (cond
2383 ((eq org-startup-folded t)
2384 (org-cycle '(4)))
2385 ((eq org-startup-folded 'content)
2386 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2387 (org-cycle '(4)) (org-cycle '(4))))))))
2388
2389 (defsubst org-current-line (&optional pos)
2390 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2391
2392 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2393 mouse-map t)
2394 "Properties to remove when a string without properties is wanted.")
2395
2396 (defsubst org-match-string-no-properties (num &optional string)
2397 (if (featurep 'xemacs)
2398 (let ((s (match-string num string)))
2399 (remove-text-properties 0 (length s) org-rm-props s)
2400 s)
2401 (match-string-no-properties num string)))
2402
2403 (defun org-current-time ()
2404 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2405 (if (> org-time-stamp-rounding-minutes 0)
2406 (let ((r org-time-stamp-rounding-minutes)
2407 (time (decode-time)))
2408 (apply 'encode-time
2409 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2410 (nthcdr 2 time))))
2411 (current-time)))
2412
2413 (defun org-add-props (string plist &rest props)
2414 "Add text properties to entire string, from beginning to end.
2415 PLIST may be a list of properties, PROPS are individual properties and values
2416 that will be added to PLIST. Returns the string that was modified."
2417 (add-text-properties
2418 0 (length string) (if props (append plist props) plist) string)
2419 string)
2420 (put 'org-add-props 'lisp-indent-function 2)
2421
2422
2423 ;;; Font-Lock stuff
2424
2425 (defvar org-mouse-map (make-sparse-keymap))
2426 (define-key org-mouse-map
2427 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
2428 (define-key org-mouse-map
2429 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
2430 (when org-mouse-1-follows-link
2431 (define-key org-mouse-map [follow-link] 'mouse-face))
2432 (when org-tab-follows-link
2433 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2434 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2435 (when org-return-follows-link
2436 (define-key org-mouse-map [(return)] 'org-open-at-point)
2437 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2438
2439 (require 'font-lock)
2440
2441 (defconst org-non-link-chars "]\t\n\r<>")
2442 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
2443 "wl" "mhe" "rmail" "gnus" "shell"))
2444 (defconst org-link-re-with-space
2445 (concat
2446 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2447 "\\([^" org-non-link-chars " ]"
2448 "[^" org-non-link-chars "]*"
2449 "[^" org-non-link-chars " ]\\)>?")
2450 "Matches a link with spaces, optional angular brackets around it.")
2451
2452 (defconst org-link-re-with-space2
2453 (concat
2454 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2455 "\\([^" org-non-link-chars " ]"
2456 "[^]\t\n\r]*"
2457 "[^" org-non-link-chars " ]\\)>?")
2458 "Matches a link with spaces, optional angular brackets around it.")
2459
2460 (defconst org-angle-link-re
2461 (concat
2462 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2463 "\\([^" org-non-link-chars " ]"
2464 "[^" org-non-link-chars "]*"
2465 "\\)>")
2466 "Matches link with angular brackets, spaces are allowed.")
2467 (defconst org-plain-link-re
2468 (concat
2469 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2470 "\\([^]\t\n\r<>,;() ]+\\)")
2471 "Matches plain link, without spaces.")
2472
2473 (defconst org-bracket-link-regexp
2474 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2475 "Matches a link in double brackets.")
2476
2477 (defconst org-bracket-link-analytic-regexp
2478 (concat
2479 "\\[\\["
2480 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
2481 "\\([^]]+\\)"
2482 "\\]"
2483 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
2484 "\\]"))
2485 ; 1: http:
2486 ; 2: http
2487 ; 3: path
2488 ; 4: [desc]
2489 ; 5: desc
2490
2491
2492 (defconst org-ts-lengths
2493 (cons (length (format-time-string (car org-time-stamp-formats)))
2494 (length (format-time-string (cdr org-time-stamp-formats))))
2495 "This holds the lengths of the two different time formats.")
2496 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2497 "Regular expression for fast time stamp matching.")
2498 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2499 "Regular expression for fast time stamp matching.")
2500 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2501 "Regular expression matching time strings for analysis.")
2502 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2503 "Regular expression matching time stamps, with groups.")
2504 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2505 "Regular expression matching a time stamp range.")
2506 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2507 org-ts-regexp "\\)?")
2508 "Regular expression matching a time stamp or time stamp range.")
2509
2510 (defun org-activate-plain-links (limit)
2511 "Run through the buffer and add overlays to links."
2512 (if (re-search-forward org-plain-link-re limit t)
2513 (progn
2514 (add-text-properties (match-beginning 0) (match-end 0)
2515 (list 'mouse-face 'highlight
2516 'keymap org-mouse-map
2517 ))
2518 t)))
2519
2520 (defun org-activate-angle-links (limit)
2521 "Run through the buffer and add overlays to links."
2522 (if (re-search-forward org-angle-link-re limit t)
2523 (progn
2524 (add-text-properties (match-beginning 0) (match-end 0)
2525 (list 'mouse-face 'highlight
2526 'keymap org-mouse-map
2527 ))
2528 t)))
2529
2530 (defun org-activate-bracket-links (limit)
2531 "Run through the buffer and add overlays to bracketed links."
2532 (if (re-search-forward org-bracket-link-regexp limit t)
2533 (let* ((help (concat "LINK: " (org-match-string-no-properties 1)))
2534 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
2535 'keymap org-mouse-map 'mouse-face 'highlight
2536 'help-echo help))
2537 (vp (list 'rear-nonsticky t
2538 'keymap org-mouse-map 'mouse-face 'highlight
2539 'help-echo help)))
2540 ;; We need to remove the invisible property here. Table narrowing
2541 ;; may have made some of this invisible.
2542 (remove-text-properties (match-beginning 0) (match-end 0)
2543 '(invisible nil))
2544 (if (match-end 3)
2545 (progn
2546 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
2547 (add-text-properties (match-beginning 3) (match-end 3) vp)
2548 (add-text-properties (match-end 3) (match-end 0) ip))
2549 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
2550 (add-text-properties (match-beginning 1) (match-end 1) vp)
2551 (add-text-properties (match-end 1) (match-end 0) ip))
2552 t)))
2553
2554 (defun org-activate-dates (limit)
2555 "Run through the buffer and add overlays to dates."
2556 (if (re-search-forward org-tsr-regexp limit t)
2557 (progn
2558 (add-text-properties (match-beginning 0) (match-end 0)
2559 (list 'mouse-face 'highlight
2560 'keymap org-mouse-map))
2561 t)))
2562
2563 (defvar org-target-link-regexp nil
2564 "Regular expression matching radio targets in plain text.")
2565 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2566 "Regular expression matching a link target.")
2567 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2568 "Regular expression matching a link target.")
2569
2570 (defun org-activate-target-links (limit)
2571 "Run through the buffer and add overlays to target matches."
2572 (when org-target-link-regexp
2573 (let ((case-fold-search t))
2574 (if (re-search-forward org-target-link-regexp limit t)
2575 (progn
2576 (add-text-properties (match-beginning 0) (match-end 0)
2577 (list 'mouse-face 'highlight
2578 'keymap org-mouse-map
2579 'help-echo "Radio target link"
2580 'org-linked-text t))
2581 t)))))
2582
2583 (defun org-update-radio-target-regexp ()
2584 "Find all radio targets in this file and update the regular expression."
2585 (interactive)
2586 (when (memq 'radio org-activate-links)
2587 (setq org-target-link-regexp
2588 (org-make-target-link-regexp (org-all-targets 'radio)))
2589 (org-restart-font-lock)))
2590
2591 (defun org-hide-wide-columns (limit)
2592 (let (s e)
2593 (setq s (text-property-any (point) (or limit (point-max))
2594 'org-cwidth t))
2595 (when s
2596 (setq e (next-single-property-change s 'org-cwidth))
2597 (add-text-properties s e '(invisible org-cwidth intangible t))
2598 (goto-char e)
2599 t)))
2600
2601 (defun org-restart-font-lock ()
2602 "Restart font-lock-mode, to force refontification."
2603 (when (and (boundp 'font-lock-mode) font-lock-mode)
2604 (font-lock-mode -1)
2605 (font-lock-mode 1)))
2606
2607 (defun org-all-targets (&optional radio)
2608 "Return a list of all targets in this file.
2609 With optional argument RADIO, only find radio targets."
2610 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2611 rtn)
2612 (save-excursion
2613 (goto-char (point-min))
2614 (while (re-search-forward re nil t)
2615 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
2616 rtn)))
2617
2618 (defun org-make-target-link-regexp (targets)
2619 "Make regular expression matching all strings in TARGETS.
2620 The regular expression finds the targets also if there is a line break
2621 between words."
2622 (and targets
2623 (concat
2624 "\\<\\("
2625 (mapconcat
2626 (lambda (x)
2627 (while (string-match " +" x)
2628 (setq x (replace-match "\\s-+" t t x)))
2629 x)
2630 targets
2631 "\\|")
2632 "\\)\\>")))
2633
2634 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2635 "Matches CamelCase words, possibly with a star before it.")
2636
2637 (defun org-activate-camels (limit)
2638 "Run through the buffer and add overlays to dates."
2639 (if (re-search-forward org-camel-regexp limit t)
2640 (progn
2641 (add-text-properties (match-beginning 0) (match-end 0)
2642 (list 'mouse-face 'highlight
2643 'keymap org-mouse-map))
2644 t)))
2645
2646 (defun org-activate-tags (limit)
2647 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2648 (progn
2649 (add-text-properties (match-beginning 1) (match-end 1)
2650 (list 'mouse-face 'highlight
2651 'keymap org-mouse-map))
2652 t)))
2653
2654 (defun org-font-lock-level ()
2655 (save-excursion
2656 (org-back-to-heading t)
2657 (- (match-end 0) (match-beginning 0))))
2658
2659 (defun org-outline-level ()
2660 (save-excursion
2661 (looking-at outline-regexp)
2662 (if (match-beginning 1)
2663 (+ (org-get-string-indentation (match-string 1)) 1000)
2664 (- (match-end 0) (match-beginning 0)))))
2665
2666 (defvar org-font-lock-keywords nil)
2667
2668 (defun org-set-font-lock-defaults ()
2669 (let* ((em org-fontify-emphasized-text)
2670 (lk org-activate-links)
2671 (org-font-lock-extra-keywords
2672 (list
2673 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
2674 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
2675 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2676 (1 'org-table))
2677 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
2678 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
2679 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
2680 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
2681 (if (memq 'date lk) '(org-activate-dates (0 'org-link t)))
2682 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
2683 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
2684 (if org-table-limit-column-width
2685 '(org-hide-wide-columns (0 nil append)))
2686 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2687 '(1 'org-warning t))
2688 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2689 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2690 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2691 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2692 (if em '("\\(\\W\\|^\\)\\(\\*\\w+\\*\\)\\(\\W\\|$\\)" 2 'bold prepend))
2693 (if em '("\\(\\W\\|^\\)\\(/\\w+/\\)\\(\\W\\|$\\)" 2 'italic prepend))
2694 (if em '("\\(\\W\\|^\\)\\(_\\w+_\\)\\(\\W\\|$\\)" 2 'underline prepend))
2695 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2696 "\\|" org-quote-string "\\)\\>")
2697 '(1 'org-special-keyword t))
2698 '("^#.*" (0 'font-lock-comment-face t))
2699 (if org-fontify-done-headline
2700 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2701 '(1 'org-done t) '(2 'org-headline-done t))
2702 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2703 '(1 'org-done t)))
2704 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2705 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2706 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2707 (if org-format-transports-properties-p
2708 '("| *\\(<[0-9]+>\\) *|" (1 'org-formula t)))
2709 )))
2710 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
2711 ;; Now set the full font-lock-keywords
2712 (set (make-local-variable 'org-font-lock-keywords)
2713 org-font-lock-extra-keywords)
2714 (set (make-local-variable 'font-lock-defaults)
2715 '(org-font-lock-keywords t nil nil backward-paragraph))
2716 (kill-local-variable 'font-lock-keywords) nil))
2717
2718 (defvar org-m nil)
2719 (defvar org-l nil)
2720 (defvar org-f nil)
2721 (defun org-get-level-face (n)
2722 "Get the right face for match N in font-lock matching of healdines."
2723 (setq org-l (- (match-end 2) (match-beginning 1)))
2724 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
2725 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
2726 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
2727 (cond
2728 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
2729 ((eq n 2) org-f)
2730 (t (if org-level-color-stars-only nil org-f))))
2731
2732 (defun org-unfontify-region (beg end &optional maybe_loudly)
2733 "Remove fontification and activation overlays from links."
2734 (font-lock-default-unfontify-region beg end)
2735 (let* ((buffer-undo-list t)
2736 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2737 (inhibit-modification-hooks t)
2738 deactivate-mark buffer-file-name buffer-file-truename)
2739 (remove-text-properties beg end
2740 '(mouse-face nil keymap nil org-linked-text nil
2741 invisible nil intangible nil))))
2742 ;;; Visibility cycling
2743
2744 (defvar org-cycle-global-status nil)
2745 (defvar org-cycle-subtree-status nil)
2746 (defun org-cycle (&optional arg)
2747 "Visibility cycling for Org-mode.
2748
2749 - When this function is called with a prefix argument, rotate the entire
2750 buffer through 3 states (global cycling)
2751 1. OVERVIEW: Show only top-level headlines.
2752 2. CONTENTS: Show all headlines of all levels, but no body text.
2753 3. SHOW ALL: Show everything.
2754
2755 - When point is at the beginning of a headline, rotate the subtree started
2756 by this line through 3 different states (local cycling)
2757 1. FOLDED: Only the main headline is shown.
2758 2. CHILDREN: The main headline and the direct children are shown.
2759 From this state, you can move to one of the children
2760 and zoom in further.
2761 3. SUBTREE: Show the entire subtree, including body text.
2762
2763 - When there is a numeric prefix, go up to a heading with level ARG, do
2764 a `show-subtree' and return to the previous cursor position. If ARG
2765 is negative, go up that many levels.
2766
2767 - When point is not at the beginning of a headline, execute
2768 `indent-relative', like TAB normally does. See the option
2769 `org-cycle-emulate-tab' for details.
2770
2771 - Special case: if point is the the beginning of the buffer and there is
2772 no headline in line 1, this function will act as if called with prefix arg."
2773 (interactive "P")
2774
2775 (if (or (and (bobp) (not (looking-at outline-regexp)))
2776 (equal arg '(4)))
2777 ;; special case: use global cycling
2778 (setq arg t))
2779
2780 (let ((outline-regexp
2781 (if org-cycle-include-plain-lists
2782 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2783 outline-regexp)))
2784
2785 (cond
2786
2787 ((org-at-table-p 'any)
2788 ;; Enter the table or move to the next field in the table
2789 (or (org-table-recognize-table.el)
2790 (progn
2791 (if arg (org-table-edit-field t)
2792 (org-table-justify-field-maybe)
2793 (org-table-next-field)))))
2794
2795 ((eq arg t) ;; Global cycling
2796
2797 (cond
2798 ((and (eq last-command this-command)
2799 (eq org-cycle-global-status 'overview))
2800 ;; We just created the overview - now do table of contents
2801 ;; This can be slow in very large buffers, so indicate action
2802 (message "CONTENTS...")
2803 (save-excursion
2804 ;; Visit all headings and show their offspring
2805 (goto-char (point-max))
2806 (catch 'exit
2807 (while (and (progn (condition-case nil
2808 (outline-previous-visible-heading 1)
2809 (error (goto-char (point-min))))
2810 t)
2811 (looking-at outline-regexp))
2812 (show-branches)
2813 (if (bobp) (throw 'exit nil))))
2814 (message "CONTENTS...done"))
2815 (setq org-cycle-global-status 'contents)
2816 (run-hook-with-args 'org-cycle-hook 'contents))
2817
2818 ((and (eq last-command this-command)
2819 (eq org-cycle-global-status 'contents))
2820 ;; We just showed the table of contents - now show everything
2821 (show-all)
2822 (message "SHOW ALL")
2823 (setq org-cycle-global-status 'all)
2824 (run-hook-with-args 'org-cycle-hook 'all))
2825
2826 (t
2827 ;; Default action: go to overview
2828 (hide-sublevels 1)
2829 (message "OVERVIEW")
2830 (setq org-cycle-global-status 'overview)
2831 (run-hook-with-args 'org-cycle-hook 'overview))))
2832
2833 ((integerp arg)
2834 ;; Show-subtree, ARG levels up from here.
2835 (save-excursion
2836 (org-back-to-heading)
2837 (outline-up-heading (if (< arg 0) (- arg)
2838 (- (funcall outline-level) arg)))
2839 (org-show-subtree)))
2840
2841 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2842 ;; At a heading: rotate between three different views
2843 (org-back-to-heading)
2844 (let ((goal-column 0) eoh eol eos)
2845 ;; First, some boundaries
2846 (save-excursion
2847 (org-back-to-heading)
2848 (save-excursion
2849 (beginning-of-line 2)
2850 (while (and (not (eobp)) ;; this is like `next-line'
2851 (get-char-property (1- (point)) 'invisible))
2852 (beginning-of-line 2)) (setq eol (point)))
2853 (outline-end-of-heading) (setq eoh (point))
2854 (org-end-of-subtree t) (setq eos (point))
2855 (outline-next-heading))
2856 ;; Find out what to do next and set `this-command'
2857 (cond
2858 ((= eos eoh)
2859 ;; Nothing is hidden behind this heading
2860 (message "EMPTY ENTRY")
2861 (setq org-cycle-subtree-status nil))
2862 ((>= eol eos)
2863 ;; Entire subtree is hidden in one line: open it
2864 (org-show-entry)
2865 (show-children)
2866 (message "CHILDREN")
2867 (setq org-cycle-subtree-status 'children)
2868 (run-hook-with-args 'org-cycle-hook 'children))
2869 ((and (eq last-command this-command)
2870 (eq org-cycle-subtree-status 'children))
2871 ;; We just showed the children, now show everything.
2872 (org-show-subtree)
2873 (message "SUBTREE")
2874 (setq org-cycle-subtree-status 'subtree)
2875 (run-hook-with-args 'org-cycle-hook 'subtree))
2876 (t
2877 ;; Default action: hide the subtree.
2878 (hide-subtree)
2879 (message "FOLDED")
2880 (setq org-cycle-subtree-status 'folded)
2881 (run-hook-with-args 'org-cycle-hook 'folded)))))
2882
2883 ;; TAB emulation
2884 (buffer-read-only (org-back-to-heading))
2885 ((if (and (eq org-cycle-emulate-tab 'white)
2886 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2887 t
2888 (eq org-cycle-emulate-tab t))
2889 (if (and (looking-at "[ \n\r\t]")
2890 (string-match "^[ \t]*$" (buffer-substring
2891 (point-at-bol) (point))))
2892 (progn
2893 (beginning-of-line 1)
2894 (and (looking-at "[ \t]+") (replace-match ""))))
2895 (indent-relative))
2896
2897 (t (save-excursion
2898 (org-back-to-heading)
2899 (org-cycle))))))
2900
2901 (defun org-optimize-window-after-visibility-change (state)
2902 "Adjust the window after a change in outline visibility.
2903 This function is the default value of the hook `org-cycle-hook'."
2904 (when (get-buffer-window (current-buffer))
2905 (cond
2906 ((eq state 'overview) (org-first-headline-recenter 1))
2907 ((eq state 'content) nil)
2908 ((eq state 'all) nil)
2909 ((eq state 'folded) nil)
2910 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2911 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
2912
2913 (defun org-subtree-end-visible-p ()
2914 "Is the end of the current subtree visible?"
2915 (pos-visible-in-window-p
2916 (save-excursion (org-end-of-subtree t) (point))))
2917
2918 (defun org-first-headline-recenter (&optional N)
2919 "Move cursor to the first headline and recenter the headline.
2920 Optional argument N means, put the headline into the Nth line of the window."
2921 (goto-char (point-min))
2922 (when (re-search-forward (concat "^" outline-regexp) nil t)
2923 (beginning-of-line)
2924 (recenter (prefix-numeric-value N))))
2925
2926 (defvar org-goto-window-configuration nil)
2927 (defvar org-goto-marker nil)
2928 (defvar org-goto-map (make-sparse-keymap))
2929 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2930 (while (setq cmd (pop cmds))
2931 (substitute-key-definition cmd cmd org-goto-map global-map)))
2932 (define-key org-goto-map "\C-m" 'org-goto-ret)
2933 (define-key org-goto-map [(left)] 'org-goto-left)
2934 (define-key org-goto-map [(right)] 'org-goto-right)
2935 (define-key org-goto-map [(?q)] 'org-goto-quit)
2936 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2937 (define-key org-goto-map "\C-i" 'org-cycle)
2938 (define-key org-goto-map [(tab)] 'org-cycle)
2939 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2940 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2941 (define-key org-goto-map "n" 'outline-next-visible-heading)
2942 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2943 (define-key org-goto-map "f" 'outline-forward-same-level)
2944 (define-key org-goto-map "b" 'outline-backward-same-level)
2945 (define-key org-goto-map "u" 'outline-up-heading)
2946 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
2947 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
2948 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
2949 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
2950 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
2951 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
2952 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
2953
2954 (defconst org-goto-help
2955 "Select a location to jump to, press RET
2956 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
2957
2958 (defun org-goto ()
2959 "Go to a different location of the document, keeping current visibility.
2960
2961 When you want to go to a different location in a document, the fastest way
2962 is often to fold the entire buffer and then dive into the tree. This
2963 method has the disadvantage, that the previous location will be folded,
2964 which may not be what you want.
2965
2966 This command works around this by showing a copy of the current buffer in
2967 overview mode. You can dive into the tree in that copy, to find the
2968 location you want to reach. When pressing RET, the command returns to the
2969 original buffer in which the visibility is still unchanged. It then jumps
2970 to the new location, making it and the headline hierarchy above it visible."
2971 (interactive)
2972 (let* ((org-goto-start-pos (point))
2973 (selected-point
2974 (org-get-location (current-buffer) org-goto-help)))
2975 (if selected-point
2976 (progn
2977 (org-mark-ring-push org-goto-start-pos)
2978 (goto-char selected-point)
2979 (if (or (org-invisible-p) (org-invisible-p2))
2980 (org-show-hierarchy-above)))
2981 (error "Quit"))))
2982
2983 (defun org-get-location (buf help)
2984 "Let the user select a location in the Org-mode buffer BUF.
2985 This function uses a recursive edit. It returns the selected position
2986 or nil."
2987 (let (org-selected-point)
2988 (save-excursion
2989 (save-window-excursion
2990 (delete-other-windows)
2991 (switch-to-buffer (get-buffer-create "*org-goto*"))
2992 (with-output-to-temp-buffer "*Help*"
2993 (princ help))
2994 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
2995 (setq buffer-read-only nil)
2996 (erase-buffer)
2997 (insert-buffer-substring buf)
2998 (let ((org-startup-truncated t)
2999 (org-startup-folded t)
3000 (org-startup-align-all-tables nil)
3001 (org-startup-with-deadline-check nil))
3002 (org-mode))
3003 (setq buffer-read-only t)
3004 (if (boundp 'org-goto-start-pos)
3005 (goto-char org-goto-start-pos)
3006 (goto-char (point-min)))
3007 (org-beginning-of-line)
3008 (message "Select location and press RET")
3009 ;; now we make sure that during selection, ony very few keys work
3010 ;; and that it is impossible to switch to another window.
3011 (let ((gm (current-global-map))
3012 (overriding-local-map org-goto-map))
3013 (unwind-protect
3014 (progn
3015 (use-global-map org-goto-map)
3016 (recursive-edit))
3017 (use-global-map gm)))))
3018 (kill-buffer "*org-goto*")
3019 org-selected-point))
3020
3021 ;; FIXME: It may not be a good idea to temper with the prefix argument...
3022 (defun org-goto-ret (&optional arg)
3023 "Finish `org-goto' by going to the new location."
3024 (interactive "P")
3025 (setq org-selected-point (point)
3026 current-prefix-arg arg)
3027 (throw 'exit nil))
3028
3029 (defun org-goto-left ()
3030 "Finish `org-goto' by going to the new location."
3031 (interactive)
3032 (if (org-on-heading-p)
3033 (progn
3034 (beginning-of-line 1)
3035 (setq org-selected-point (point)
3036 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3037 (throw 'exit nil))
3038 (error "Not on a heading")))
3039
3040 (defun org-goto-right ()
3041 "Finish `org-goto' by going to the new location."
3042 (interactive)
3043 (if (org-on-heading-p)
3044 (progn
3045 (outline-end-of-subtree)
3046 (or (eobp) (forward-char 1))
3047 (setq org-selected-point (point)
3048 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3049 (throw 'exit nil))
3050 (error "Not on a heading")))
3051
3052 (defun org-goto-quit ()
3053 "Finish `org-goto' without cursor motion."
3054 (interactive)
3055 (setq org-selected-point nil)
3056 (throw 'exit nil))
3057
3058 ;;; Promotion, Demotion, Inserting new headlines
3059
3060 (defvar org-ignore-region nil
3061 "To temporarily disable the active region.")
3062
3063 (defun org-insert-heading (&optional force-heading)
3064 "Insert a new heading or item with same depth at point."
3065 (interactive "P")
3066 (when (or force-heading (not (org-insert-item)))
3067 (let* ((head (save-excursion
3068 (condition-case nil
3069 (org-back-to-heading)
3070 (error (outline-next-heading)))
3071 (prog1 (match-string 0)
3072 (funcall outline-level)))))
3073 (unless (bolp) (newline))
3074 (insert head)
3075 (if (looking-at "[ \t]*")
3076 (replace-match " "))
3077 (run-hooks 'org-insert-heading-hook))))
3078
3079 (defun org-insert-item ()
3080 "Insert a new item at the current level.
3081 Return t when things worked, nil when we are not in an item."
3082 (when (save-excursion
3083 (condition-case nil
3084 (progn
3085 (org-beginning-of-item)
3086 (org-at-item-p)
3087 t)
3088 (error nil)))
3089 (unless (bolp) (newline))
3090 (insert (match-string 0))
3091 (org-maybe-renumber-ordered-list)
3092 t))
3093
3094 (defun org-insert-todo-heading (arg)
3095 "Insert a new heading with the same level and TODO state as current heading.
3096 If the heading has no TODO state, or if the state is DONE, use the first
3097 state (TODO by default). Also with prefix arg, force first state."
3098 (interactive "P")
3099 (org-insert-heading)
3100 (save-excursion
3101 (org-back-to-heading)
3102 (outline-previous-heading)
3103 (looking-at org-todo-line-regexp))
3104 (if (or arg
3105 (not (match-beginning 2))
3106 (equal (match-string 2) org-done-string))
3107 (insert (car org-todo-keywords) " ")
3108 (insert (match-string 2) " ")))
3109
3110 (defun org-promote-subtree ()
3111 "Promote the entire subtree.
3112 See also `org-promote'."
3113 (interactive)
3114 (save-excursion
3115 (org-map-tree 'org-promote)))
3116
3117 (defun org-demote-subtree ()
3118 "Demote the entire subtree. See `org-demote'.
3119 See also `org-promote'."
3120 (interactive)
3121 (save-excursion
3122 (org-map-tree 'org-demote)))
3123
3124 (defun org-do-promote ()
3125 "Promote the current heading higher up the tree.
3126 If the region is active in `transient-mark-mode', promote all headings
3127 in the region."
3128 (interactive)
3129 (save-excursion
3130 (if (org-region-active-p)
3131 (org-map-region 'org-promote (region-beginning) (region-end))
3132 (org-promote)))
3133 (org-fix-position-after-promote))
3134
3135 (defun org-do-demote ()
3136 "Demote the current heading lower down the tree.
3137 If the region is active in `transient-mark-mode', demote all headings
3138 in the region."
3139 (interactive)
3140 (save-excursion
3141 (if (org-region-active-p)
3142 (org-map-region 'org-demote (region-beginning) (region-end))
3143 (org-demote)))
3144 (org-fix-position-after-promote))
3145
3146 (defun org-fix-position-after-promote ()
3147 "Make sure that after pro/demotion cursor position is right."
3148 (and (equal (char-after) ?\ )
3149 (equal (char-before) ?*)
3150 (forward-char 1)))
3151
3152 (defun org-get-legal-level (level change)
3153 "Rectify a level change under the influence of `org-odd-levels-only'
3154 LEVEL is a current level, CHANGE is by how much the level should be
3155 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3156 even level numbers will become the next higher odd number."
3157 (if org-odd-levels-only
3158 (cond ((not change) (1+ (* 2 (/ level 2))))
3159 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3160 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3161 (max 1 (+ level change))))
3162
3163 (defun org-promote ()
3164 "Promote the current heading higher up the tree.
3165 If the region is active in `transient-mark-mode', promote all headings
3166 in the region."
3167 (org-back-to-heading t)
3168 (let* ((level (save-match-data (funcall outline-level)))
3169 (up-head (make-string (org-get-legal-level level -1) ?*))
3170 (diff (abs (- level (length up-head)))))
3171 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3172 (replace-match up-head nil t)
3173 ;; Fixup tag positioning
3174 (and org-auto-align-tags (org-set-tags nil t))
3175 (if org-adapt-indentation
3176 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
3177 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
3178
3179 (defun org-demote ()
3180 "Demote the current heading lower down the tree.
3181 If the region is active in `transient-mark-mode', demote all headings
3182 in the region."
3183 (org-back-to-heading t)
3184 (let* ((level (save-match-data (funcall outline-level)))
3185 (down-head (make-string (org-get-legal-level level 1) ?*))
3186 (diff (abs (- level (length down-head)))))
3187 (replace-match down-head nil t)
3188 ;; Fixup tag positioning
3189 (and org-auto-align-tags (org-set-tags nil t))
3190 (if org-adapt-indentation
3191 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
3192
3193 (defun org-map-tree (fun)
3194 "Call FUN for every heading underneath the current one."
3195 (org-back-to-heading)
3196 (let ((level (funcall outline-level)))
3197 (save-excursion
3198 (funcall fun)
3199 (while (and (progn
3200 (outline-next-heading)
3201 (> (funcall outline-level) level))
3202 (not (eobp)))
3203 (funcall fun)))))
3204
3205 (defun org-map-region (fun beg end)
3206 "Call FUN for every heading between BEG and END."
3207 (let ((org-ignore-region t))
3208 (save-excursion
3209 (setq end (copy-marker end))
3210 (goto-char beg)
3211 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3212 (< (point) end))
3213 (funcall fun))
3214 (while (and (progn
3215 (outline-next-heading)
3216 (< (point) end))
3217 (not (eobp)))
3218 (funcall fun)))))
3219
3220 (defun org-fixup-indentation (from to prohibit)
3221 "Change the indentation in the current entry by re-replacing FROM with TO.
3222 However, if the regexp PROHIBIT matches at all, don't do anything.
3223 This is being used to change indentation along with the length of the
3224 heading marker. But if there are any lines which are not indented, nothing
3225 is changed at all."
3226 (save-excursion
3227 (let ((end (save-excursion (outline-next-heading)
3228 (point-marker))))
3229 (unless (save-excursion (re-search-forward prohibit end t))
3230 (while (re-search-forward from end t)
3231 (replace-match to)
3232 (beginning-of-line 2)))
3233 (move-marker end nil))))
3234
3235 ;;; Vertical tree motion, cutting and pasting of subtrees
3236
3237 (defun org-move-subtree-up (&optional arg)
3238 "Move the current subtree up past ARG headlines of the same level."
3239 (interactive "p")
3240 (org-move-subtree-down (- (prefix-numeric-value arg))))
3241
3242 (defun org-move-subtree-down (&optional arg)
3243 "Move the current subtree down past ARG headlines of the same level."
3244 (interactive "p")
3245 (setq arg (prefix-numeric-value arg))
3246 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3247 'outline-get-last-sibling))
3248 (ins-point (make-marker))
3249 (cnt (abs arg))
3250 beg end txt folded)
3251 ;; Select the tree
3252 (org-back-to-heading)
3253 (setq beg (point))
3254 (save-match-data
3255 (save-excursion (outline-end-of-heading)
3256 (setq folded (org-invisible-p)))
3257 (outline-end-of-subtree))
3258 (outline-next-heading)
3259 (setq end (point))
3260 ;; Find insertion point, with error handling
3261 (goto-char beg)
3262 (while (> cnt 0)
3263 (or (and (funcall movfunc) (looking-at outline-regexp))
3264 (progn (goto-char beg)
3265 (error "Cannot move past superior level or buffer limit")))
3266 (setq cnt (1- cnt)))
3267 (if (> arg 0)
3268 ;; Moving forward - still need to move over subtree
3269 (progn (outline-end-of-subtree)
3270 (outline-next-heading)
3271 (if (not (or (looking-at (concat "^" outline-regexp))
3272 (bolp)))
3273 (newline))))
3274 (move-marker ins-point (point))
3275 (setq txt (buffer-substring beg end))
3276 (delete-region beg end)
3277 (insert txt)
3278 (goto-char ins-point)
3279 (if folded (hide-subtree))
3280 (move-marker ins-point nil)))
3281
3282 (defvar org-subtree-clip ""
3283 "Clipboard for cut and paste of subtrees.
3284 This is actually only a copy of the kill, because we use the normal kill
3285 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3286
3287 (defvar org-subtree-clip-folded nil
3288 "Was the last copied subtree folded?
3289 This is used to fold the tree back after pasting.")
3290
3291 (defun org-cut-subtree ()
3292 "Cut the current subtree into the clipboard.
3293 This is a short-hand for marking the subtree and then cutting it."
3294 (interactive)
3295 (org-copy-subtree 'cut))
3296
3297 (defun org-copy-subtree (&optional cut)
3298 "Cut the current subtree into the clipboard.
3299 This is a short-hand for marking the subtree and then copying it.
3300 If CUT is non nil, actually cut the subtree."
3301 (interactive)
3302 (let (beg end folded)
3303 (org-back-to-heading)
3304 (setq beg (point))
3305 (save-match-data
3306 (save-excursion (outline-end-of-heading)
3307 (setq folded (org-invisible-p)))
3308 (outline-end-of-subtree))
3309 (if (equal (char-after) ?\n) (forward-char 1))
3310 (setq end (point))
3311 (goto-char beg)
3312 (when (> end beg)
3313 (setq org-subtree-clip-folded folded)
3314 (if cut (kill-region beg end) (copy-region-as-kill beg end))
3315 (setq org-subtree-clip (current-kill 0))
3316 (message "%s: Subtree with %d characters"
3317 (if cut "Cut" "Copied")
3318 (length org-subtree-clip)))))
3319
3320 (defun org-paste-subtree (&optional level tree)
3321 "Paste the clipboard as a subtree, with modification of headline level.
3322 The entire subtree is promoted or demoted in order to match a new headline
3323 level. By default, the new level is derived from the visible headings
3324 before and after the insertion point, and taken to be the inferior headline
3325 level of the two. So if the previous visible heading is level 3 and the
3326 next is level 4 (or vice versa), level 4 will be used for insertion.
3327 This makes sure that the subtree remains an independent subtree and does
3328 not swallow low level entries.
3329
3330 You can also force a different level, either by using a numeric prefix
3331 argument, or by inserting the heading marker by hand. For example, if the
3332 cursor is after \"*****\", then the tree will be shifted to level 5.
3333
3334 If you want to insert the tree as is, just use \\[yank].
3335
3336 If optional TREE is given, use this text instead of the kill ring."
3337 (interactive "P")
3338 (unless (org-kill-is-subtree-p tree)
3339 (error
3340 (substitute-command-keys
3341 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
3342 (let* ((txt (or tree (current-kill 0)))
3343 (^re (concat "^\\(" outline-regexp "\\)"))
3344 (re (concat "\\(" outline-regexp "\\)"))
3345 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3346
3347 (old-level (if (string-match ^re txt)
3348 (- (match-end 0) (match-beginning 0))
3349 -1))
3350 (force-level (cond (level (prefix-numeric-value level))
3351 ((string-match
3352 ^re_ (buffer-substring (point-at-bol) (point)))
3353 (- (match-end 0) (match-beginning 0)))
3354 (t nil)))
3355 (previous-level (save-excursion
3356 (condition-case nil
3357 (progn
3358 (outline-previous-visible-heading 1)
3359 (if (looking-at re)
3360 (- (match-end 0) (match-beginning 0))
3361 1))
3362 (error 1))))
3363 (next-level (save-excursion
3364 (condition-case nil
3365 (progn
3366 (outline-next-visible-heading 1)
3367 (if (looking-at re)
3368 (- (match-end 0) (match-beginning 0))
3369 1))
3370 (error 1))))
3371 (new-level (or force-level (max previous-level next-level)))
3372 (shift (if (or (= old-level -1)
3373 (= new-level -1)
3374 (= old-level new-level))
3375 0
3376 (- new-level old-level)))
3377 (shift1 shift)
3378 (delta (if (> shift 0) -1 1))
3379 (func (if (> shift 0) 'org-demote 'org-promote))
3380 (org-odd-levels-only nil)
3381 beg end)
3382 ;; Remove the forces level indicator
3383 (if force-level
3384 (delete-region (point-at-bol) (point)))
3385 ;; Make sure we start at the beginning of an empty line
3386 (if (not (bolp)) (insert "\n"))
3387 (if (not (looking-at "[ \t]*$"))
3388 (progn (insert "\n") (backward-char 1)))
3389 ;; Paste
3390 (setq beg (point))
3391 (insert txt)
3392 (setq end (point))
3393 (goto-char beg)
3394 ;; Shift if necessary
3395 (if (= shift 0)
3396 (message "Pasted at level %d, without shift" new-level)
3397 (save-restriction
3398 (narrow-to-region beg end)
3399 (while (not (= shift 0))
3400 (org-map-region func (point-min) (point-max))
3401 (setq shift (+ delta shift)))
3402 (goto-char (point-min))
3403 (message "Pasted at level %d, with shift by %d levels"
3404 new-level shift1)))
3405 (if (and (eq org-subtree-clip (current-kill 0))
3406 org-subtree-clip-folded)
3407 ;; The tree was folded before it was killed/copied
3408 (hide-subtree))))
3409
3410 (defun org-kill-is-subtree-p (&optional txt)
3411 "Check if the current kill is an outline subtree, or a set of trees.
3412 Returns nil if kill does not start with a headline, or if the first
3413 headline level is not the largest headline level in the tree.
3414 So this will actually accept several entries of equal levels as well,
3415 which is OK for `org-paste-subtree'.
3416 If optional TXT is given, check this string instead of the current kill."
3417 (let* ((kill (or txt (current-kill 0) ""))
3418 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3419 (- (match-end 0) (match-beginning 0))))
3420 (re (concat "^" outline-regexp))
3421 (start 1))
3422 (if (not start-level)
3423 nil ;; does not even start with a heading
3424 (catch 'exit
3425 (while (setq start (string-match re kill (1+ start)))
3426 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3427 (throw 'exit nil)))
3428 t))))
3429
3430 ;;; Plain list items
3431
3432 (defun org-at-item-p ()
3433 "Is point in a line starting a hand-formatted item?"
3434 (let ((llt org-plain-list-ordered-item-terminator))
3435 (save-excursion
3436 (goto-char (point-at-bol))
3437 (looking-at
3438 (cond
3439 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3440 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3441 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3442 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3443
3444 (defun org-get-indentation ()
3445 "Get the indentation of the current line, interpreting tabs."
3446 (save-excursion
3447 (beginning-of-line 1)
3448 (skip-chars-forward " \t")
3449 (current-column)))
3450
3451 (defun org-beginning-of-item ()
3452 "Go to the beginning of the current hand-formatted item.
3453 If the cursor is not in an item, throw an error."
3454 (let ((pos (point))
3455 (limit (save-excursion (org-back-to-heading)
3456 (beginning-of-line 2) (point)))
3457 ind ind1)
3458 (if (org-at-item-p)
3459 (beginning-of-line 1)
3460 (beginning-of-line 1)
3461 (skip-chars-forward " \t")
3462 (setq ind (current-column))
3463 (if (catch 'exit
3464 (while t
3465 (beginning-of-line 0)
3466 (if (< (point) limit) (throw 'exit nil))
3467 (unless (looking-at " \t]*$")
3468 (skip-chars-forward " \t")
3469 (setq ind1 (current-column))
3470 (if (< ind1 ind)
3471 (throw 'exit (org-at-item-p))))))
3472 nil
3473 (goto-char pos)
3474 (error "Not in an item")))))
3475
3476 (defun org-end-of-item ()
3477 "Go to the end of the current hand-formatted item.
3478 If the cursor is not in an item, throw an error."
3479 (let ((pos (point))
3480 (limit (save-excursion (outline-next-heading) (point)))
3481 (ind (save-excursion
3482 (org-beginning-of-item)
3483 (skip-chars-forward " \t")
3484 (current-column)))
3485 ind1)
3486 (if (catch 'exit
3487 (while t
3488 (beginning-of-line 2)
3489 (if (>= (point) limit) (throw 'exit t))
3490 (unless (looking-at "[ \t]*$")
3491 (skip-chars-forward " \t")
3492 (setq ind1 (current-column))
3493 (if (<= ind1 ind) (throw 'exit t)))))
3494 (beginning-of-line 1)
3495 (goto-char pos)
3496 (error "Not in an item"))))
3497
3498 (defun org-move-item-down (arg)
3499 "Move the plain list item at point down, i.e. swap with following item.
3500 Subitems (items with larger indentation) are considered part of the item,
3501 so this really moves item trees."
3502 (interactive "p")
3503 (let (beg end ind ind1 (pos (point)) txt)
3504 (org-beginning-of-item)
3505 (setq beg (point))
3506 (setq ind (org-get-indentation))
3507 (org-end-of-item)
3508 (setq end (point))
3509 (setq ind1 (org-get-indentation))
3510 (if (and (org-at-item-p) (= ind ind1))
3511 (progn
3512 (org-end-of-item)
3513 (setq txt (buffer-substring beg end))
3514 (save-excursion
3515 (delete-region beg end))
3516 (setq pos (point))
3517 (insert txt)
3518 (goto-char pos)
3519 (org-maybe-renumber-ordered-list))
3520 (goto-char pos)
3521 (error "Cannot move this item further down"))))
3522
3523 (defun org-move-item-up (arg)
3524 "Move the plain list item at point up, i.e. swap with previous item.
3525 Subitems (items with larger indentation) are considered part of the item,
3526 so this really moves item trees."
3527 (interactive "p")
3528 (let (beg end ind ind1 (pos (point)) txt)
3529 (org-beginning-of-item)
3530 (setq beg (point))
3531 (setq ind (org-get-indentation))
3532 (org-end-of-item)
3533 (setq end (point))
3534 (goto-char beg)
3535 (catch 'exit
3536 (while t
3537 (beginning-of-line 0)
3538 (if (looking-at "[ \t]*$")
3539 nil
3540 (if (<= (setq ind1 (org-get-indentation)) ind)
3541 (throw 'exit t)))))
3542 (condition-case nil
3543 (org-beginning-of-item)
3544 (error (goto-char beg)
3545 (error "Cannot move this item further up")))
3546 (setq ind1 (org-get-indentation))
3547 (if (and (org-at-item-p) (= ind ind1))
3548 (progn
3549 (setq txt (buffer-substring beg end))
3550 (save-excursion
3551 (delete-region beg end))
3552 (setq pos (point))
3553 (insert txt)
3554 (goto-char pos)
3555 (org-maybe-renumber-ordered-list))
3556 (goto-char pos)
3557 (error "Cannot move this item further up"))))
3558
3559 (defun org-maybe-renumber-ordered-list ()
3560 "Renumber the ordered list at point if setup allows it.
3561 This tests the user option `org-auto-renumber-ordered-lists' before
3562 doing the renumbering."
3563 (and org-auto-renumber-ordered-lists
3564 (org-at-item-p)
3565 (match-beginning 3)
3566 (org-renumber-ordered-list 1)))
3567
3568 (defun org-get-string-indentation (s)
3569 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3570 (let ((n -1) (i 0) (w tab-width) c)
3571 (catch 'exit
3572 (while (< (setq n (1+ n)) (length s))
3573 (setq c (aref s n))
3574 (cond ((= c ?\ ) (setq i (1+ i)))
3575 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3576 (t (throw 'exit t)))))
3577 i))
3578
3579 (defun org-renumber-ordered-list (arg)
3580 "Renumber an ordered plain list.
3581 Cursor next to be in the first line of an item, the line that starts
3582 with something like \"1.\" or \"2)\"."
3583 (interactive "p")
3584 (unless (and (org-at-item-p)
3585 (match-beginning 3))
3586 (error "This is not an ordered list"))
3587 (let ((line (org-current-line))
3588 (col (current-column))
3589 (ind (org-get-string-indentation
3590 (buffer-substring (point-at-bol) (match-beginning 3))))
3591 ;; (term (substring (match-string 3) -1))
3592 ind1 (n (1- arg)))
3593 ;; find where this list begins
3594 (catch 'exit
3595 (while t
3596 (catch 'next
3597 (beginning-of-line 0)
3598 (if (looking-at "[ \t]*$") (throw 'next t))
3599 (skip-chars-forward " \t") (setq ind1 (current-column))
3600 (if (or (< ind1 ind)
3601 (and (= ind1 ind)
3602 (not (org-at-item-p))))
3603 (throw 'exit t)))))
3604 ;; Walk forward and replace these numbers
3605 (catch 'exit
3606 (while t
3607 (catch 'next
3608 (beginning-of-line 2)
3609 (if (eobp) (throw 'exit nil))
3610 (if (looking-at "[ \t]*$") (throw 'next nil))
3611 (skip-chars-forward " \t") (setq ind1 (current-column))
3612 (if (> ind1 ind) (throw 'next t))
3613 (if (< ind1 ind) (throw 'exit t))
3614 (if (not (org-at-item-p)) (throw 'exit nil))
3615 (if (not (match-beginning 3))
3616 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3617 (delete-region (match-beginning 3) (1- (match-end 3)))
3618 (goto-char (match-beginning 3))
3619 (insert (format "%d" (setq n (1+ n)))))))
3620 (goto-line line)
3621 (move-to-column col)))
3622
3623 (defvar org-last-indent-begin-marker (make-marker))
3624 (defvar org-last-indent-end-marker (make-marker))
3625
3626 (defun org-outdent-item (arg)
3627 "Outdent a local list item."
3628 (interactive "p")
3629 (org-indent-item (- arg)))
3630
3631 (defun org-indent-item (arg)
3632 "Indent a local list item."
3633 (interactive "p")
3634 (unless (org-at-item-p)
3635 (error "Not on an item"))
3636 (let (beg end ind ind1)
3637 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3638 (setq beg org-last-indent-begin-marker
3639 end org-last-indent-end-marker)
3640 (org-beginning-of-item)
3641 (setq beg (move-marker org-last-indent-begin-marker (point)))
3642 (org-end-of-item)
3643 (setq end (move-marker org-last-indent-end-marker (point))))
3644 (goto-char beg)
3645 (skip-chars-forward " \t") (setq ind (current-column))
3646 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3647 (while (< (point) end)
3648 (beginning-of-line 1)
3649 (skip-chars-forward " \t") (setq ind1 (current-column))
3650 (delete-region (point-at-bol) (point))
3651 (indent-to-column (+ ind1 arg))
3652 (beginning-of-line 2))
3653 (goto-char beg)))
3654
3655 ;;; Archiving
3656
3657 (defun org-archive-subtree ()
3658 "Move the current subtree to the archive.
3659 The archive can be a certain top-level heading in the current file, or in
3660 a different file. The tree will be moved to that location, the subtree
3661 heading be marked DONE, and the current time will be added."
3662 (interactive)
3663 ;; Save all relevant TODO keyword-relatex variables
3664 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3665 (tr-org-todo-keywords org-todo-keywords)
3666 (tr-org-todo-interpretation org-todo-interpretation)
3667 (tr-org-done-string org-done-string)
3668 (tr-org-todo-regexp org-todo-regexp)
3669 (tr-org-todo-line-regexp org-todo-line-regexp)
3670 (this-buffer (current-buffer))
3671 file heading buffer level newfile-p)
3672 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3673 (progn
3674 (setq file (format (match-string 1 org-archive-location)
3675 (file-name-nondirectory buffer-file-name))
3676 heading (match-string 2 org-archive-location)))
3677 (error "Invalid `org-archive-location'"))
3678 (if (> (length file) 0)
3679 (setq newfile-p (not (file-exists-p file))
3680 buffer (find-file-noselect file))
3681 (setq buffer (current-buffer)))
3682 (unless buffer
3683 (error "Cannot access file \"%s\"" file))
3684 (if (and (> (length heading) 0)
3685 (string-match "^\\*+" heading))
3686 (setq level (match-end 0))
3687 (setq heading nil level 0))
3688 (save-excursion
3689 ;; We first only copy, in case something goes wrong
3690 ;; we need to protect this-command, to avoid kill-region sets it,
3691 ;; which would lead to duplication of subtrees
3692 (let (this-command) (org-copy-subtree))
3693 (set-buffer buffer)
3694 ;; Enforce org-mode for the archive buffer
3695 (if (not (eq major-mode 'org-mode))
3696 ;; Force the mode for future visits.
3697 (let ((org-insert-mode-line-in-empty-file t))
3698 (call-interactively 'org-mode)))
3699 (when newfile-p
3700 (goto-char (point-max))
3701 (insert (format "\nArchived entries from file %s\n\n"
3702 (buffer-file-name this-buffer))))
3703 ;; Force the TODO keywords of the original buffer
3704 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3705 (org-todo-keywords tr-org-todo-keywords)
3706 (org-todo-interpretation tr-org-todo-interpretation)
3707 (org-done-string tr-org-done-string)
3708 (org-todo-regexp tr-org-todo-regexp)
3709 (org-todo-line-regexp tr-org-todo-line-regexp))
3710 (goto-char (point-min))
3711 (if heading
3712 (progn
3713 (if (re-search-forward
3714 (concat "\\(^\\|\r\\)"
3715 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3716 nil t)
3717 (goto-char (match-end 0))
3718 ;; Heading not found, just insert it at the end
3719 (goto-char (point-max))
3720 (or (bolp) (insert "\n"))
3721 (insert "\n" heading "\n")
3722 (end-of-line 0))
3723 ;; Make the heading visible, and the following as well
3724 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3725 (if (re-search-forward
3726 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3727 nil t)
3728 (progn (goto-char (match-beginning 0)) (insert "\n")
3729 (beginning-of-line 0))
3730 (goto-char (point-max)) (insert "\n")))
3731 (goto-char (point-max)) (insert "\n"))
3732 ;; Paste
3733 (org-paste-subtree (1+ level))
3734 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3735 (if org-archive-mark-done
3736 (org-todo (length org-todo-keywords)))
3737 ;; Move cursor to right after the TODO keyword
3738 (when org-archive-stamp-time
3739 (beginning-of-line 1)
3740 (looking-at org-todo-line-regexp)
3741 (goto-char (or (match-end 2) (match-beginning 3)))
3742 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3743 (org-current-time))
3744 ")"))
3745 ;; Save the buffer, if it is not the same buffer.
3746 (if (not (eq this-buffer buffer)) (save-buffer))))
3747 ;; Here we are back in the original buffer. Everything seems to have
3748 ;; worked. So now cut the tree and finish up.
3749 (let (this-command) (org-cut-subtree))
3750 (if (looking-at "[ \t]*$") (kill-line))
3751 (message "Subtree archived %s"
3752 (if (eq this-buffer buffer)
3753 (concat "under heading: " heading)
3754 (concat "in file: " (abbreviate-file-name file))))))
3755
3756 ;;; Completion
3757
3758 (defun org-complete (&optional arg)
3759 "Perform completion on word at point.
3760 At the beginning of a headline, this completes TODO keywords as given in
3761 `org-todo-keywords'.
3762 If the current word is preceded by a backslash, completes the TeX symbols
3763 that are supported for HTML support.
3764 If the current word is preceded by \"#+\", completes special words for
3765 setting file options.
3766 At all other locations, this simply calls `ispell-complete-word'."
3767 (interactive "P")
3768 (catch 'exit
3769 (let* ((end (point))
3770 (beg1 (save-excursion
3771 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3772 (skip-chars-backward "a-zA-Z_@0-9")
3773 (point)))
3774 (beg (save-excursion
3775 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3776 (skip-chars-backward "a-zA-Z0-9_:$")
3777 (point)))
3778 (camel (equal (char-before beg) ?*))
3779 (tag (equal (char-before beg1) ?:))
3780 (texp (equal (char-before beg) ?\\))
3781 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3782 beg)
3783 "#+"))
3784 (completion-ignore-case opt)
3785 (type nil)
3786 (tbl nil)
3787 (table (cond
3788 (opt
3789 (setq type :opt)
3790 (mapcar (lambda (x)
3791 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3792 (cons (match-string 2 x) (match-string 1 x)))
3793 (org-split-string (org-get-current-options) "\n")))
3794 (texp
3795 (setq type :tex)
3796 org-html-entities)
3797 ((string-match "\\`\\*+[ \t]*\\'"
3798 (buffer-substring (point-at-bol) beg))
3799 (setq type :todo)
3800 (mapcar 'list org-todo-keywords))
3801 (camel
3802 (setq type :camel)
3803 (save-excursion
3804 (goto-char (point-min))
3805 (while (re-search-forward org-todo-line-regexp nil t)
3806 (push (list
3807 (if org-file-link-context-use-camel-case
3808 (org-make-org-heading-camel (match-string 3) t)
3809 (org-make-org-heading-search-string
3810 (match-string 3) t)))
3811 tbl)))
3812 tbl)
3813 (tag (setq type :tag beg beg1)
3814 (org-get-buffer-tags))
3815 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3816 (pattern (buffer-substring-no-properties beg end))
3817 (completion (try-completion pattern table)))
3818 (cond ((eq completion t)
3819 (if (equal type :opt)
3820 (insert (substring (cdr (assoc (upcase pattern) table))
3821 (length pattern)))))
3822 ((null completion)
3823 (message "Can't find completion for \"%s\"" pattern)
3824 (ding))
3825 ((not (string= pattern completion))
3826 (delete-region beg end)
3827 (if (string-match " +$" completion)
3828 (setq completion (replace-match "" t t completion)))
3829 (insert completion)
3830 (if (get-buffer-window "*Completions*")
3831 (delete-window (get-buffer-window "*Completions*")))
3832 (if (assoc completion table)
3833 (if (eq type :todo) (insert " ")
3834 (if (eq type :tag) (insert ":"))))
3835 (if (and (equal type :opt) (assoc completion table))
3836 (message "%s" (substitute-command-keys
3837 "Press \\[org-complete] again to insert example settings"))))
3838 (t
3839 (message "Making completion list...")
3840 (let ((list (sort (all-completions pattern table) 'string<)))
3841 (with-output-to-temp-buffer "*Completions*"
3842 (condition-case nil
3843 ;; Protection needed for XEmacs and emacs 21
3844 (display-completion-list list pattern)
3845 (error (display-completion-list list)))))
3846 (message "Making completion list...%s" "done"))))))
3847
3848 ;;; Comments, TODO and DEADLINE
3849
3850 (defun org-toggle-comment ()
3851 "Change the COMMENT state of an entry."
3852 (interactive)
3853 (save-excursion
3854 (org-back-to-heading)
3855 (if (looking-at (concat outline-regexp
3856 "\\( +\\<" org-comment-string "\\>\\)"))
3857 (replace-match "" t t nil 1)
3858 (if (looking-at outline-regexp)
3859 (progn
3860 (goto-char (match-end 0))
3861 (insert " " org-comment-string))))))
3862
3863 (defvar org-last-todo-state-is-todo nil
3864 "This is non-nil when the last TODO state change led to a TODO state.
3865 If the last change removed the TODO tag or switched to DONE, then
3866 this is nil.")
3867
3868 (defun org-todo (&optional arg)
3869 "Change the TODO state of an item.
3870 The state of an item is given by a keyword at the start of the heading,
3871 like
3872 *** TODO Write paper
3873 *** DONE Call mom
3874
3875 The different keywords are specified in the variable `org-todo-keywords'.
3876 By default the available states are \"TODO\" and \"DONE\".
3877 So for this example: when the item starts with TODO, it is changed to DONE.
3878 When it starts with DONE, the DONE is removed. And when neither TODO nor
3879 DONE are present, add TODO at the beginning of the heading.
3880
3881 With prefix arg, use completion to determine the new state. With numeric
3882 prefix arg, switch to that state."
3883 (interactive "P")
3884 (save-excursion
3885 (org-back-to-heading)
3886 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3887 (or (looking-at (concat " +" org-todo-regexp " *"))
3888 (looking-at " *"))
3889 (let* ((this (match-string 1))
3890 (completion-ignore-case t)
3891 (member (member this org-todo-keywords))
3892 (tail (cdr member))
3893 (state (cond
3894 ((equal arg '(4))
3895 ;; Read a state with completion
3896 (completing-read "State: " (mapcar (lambda(x) (list x))
3897 org-todo-keywords)
3898 nil t))
3899 ((eq arg 'right)
3900 (if this
3901 (if tail (car tail) nil)
3902 (car org-todo-keywords)))
3903 ((eq arg 'left)
3904 (if (equal member org-todo-keywords)
3905 nil
3906 (if this
3907 (nth (- (length org-todo-keywords) (length tail) 2)
3908 org-todo-keywords)
3909 org-done-string)))
3910 (arg
3911 ;; user requests a specific state
3912 (nth (1- (prefix-numeric-value arg))
3913 org-todo-keywords))
3914 ((null member) (car org-todo-keywords))
3915 ((null tail) nil) ;; -> first entry
3916 ((eq org-todo-interpretation 'sequence)
3917 (car tail))
3918 ((memq org-todo-interpretation '(type priority))
3919 (if (eq this-command last-command)
3920 (car tail)
3921 (if (> (length tail) 0) org-done-string nil)))
3922 (t nil)))
3923 (next (if state (concat " " state " ") " ")))
3924 (replace-match next t t)
3925 (setq org-last-todo-state-is-todo
3926 (not (equal state org-done-string)))
3927 (when org-log-done
3928 (if (equal state org-done-string)
3929 (org-log-done)
3930 (if (not this)
3931 (org-log-done t))))
3932 ;; Fixup tag positioning
3933 (and org-auto-align-tags (org-set-tags nil t))
3934 (run-hooks 'org-after-todo-state-change-hook)))
3935 ;; Fixup cursor location if close to the keyword
3936 (if (and (outline-on-heading-p)
3937 (not (bolp))
3938 (save-excursion (beginning-of-line 1)
3939 (looking-at org-todo-line-regexp))
3940 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
3941 (progn
3942 (goto-char (or (match-end 2) (match-end 1)))
3943 (just-one-space))))
3944
3945 (defun org-log-done (&optional undone)
3946 "Add a time stamp logging that a TODO entry has been closed.
3947 When UNDONE is non-nil, remove such a time stamp again."
3948 (interactive)
3949 (let (beg end col)
3950 (save-excursion
3951 (org-back-to-heading t)
3952 (setq beg (point))
3953 (looking-at (concat outline-regexp " *"))
3954 (goto-char (match-end 0))
3955 (setq col (current-column))
3956 (outline-next-heading)
3957 (setq end (point))
3958 (goto-char beg)
3959 (when (re-search-forward (concat
3960 "[\r\n]\\([ \t]*"
3961 (regexp-quote org-closed-string)
3962 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
3963 (delete-region (match-beginning 1) (match-end 1)))
3964 (unless undone
3965 (org-back-to-heading t)
3966 (skip-chars-forward "^\n\r")
3967 (goto-char (min (1+ (point)) (point-max)))
3968 (when (not (member (char-before) '(?\r ?\n)))
3969 (insert "\n"))
3970 (indent-to col)
3971 (insert org-closed-string " "
3972 (format-time-string
3973 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
3974 (org-current-time))
3975 "\n")))))
3976
3977 (defun org-show-todo-tree (arg)
3978 "Make a compact tree which shows all headlines marked with TODO.
3979 The tree will show the lines where the regexp matches, and all higher
3980 headlines above the match.
3981 With \\[universal-argument] prefix, also show the DONE entries.
3982 With a numeric prefix N, construct a sparse tree for the Nth element
3983 of `org-todo-keywords'."
3984 (interactive "P")
3985 (let ((case-fold-search nil)
3986 (kwd-re
3987 (cond ((null arg) org-not-done-regexp)
3988 ((equal arg '(4)) org-todo-regexp)
3989 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
3990 (regexp-quote (nth (1- (prefix-numeric-value arg))
3991 org-todo-keywords)))
3992 (t (error "Invalid prefix argument: %s" arg)))))
3993 (message "%d TODO entries found"
3994 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
3995
3996 (defun org-deadline ()
3997 "Insert the DEADLINE: string to make a deadline.
3998 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
3999 to modify it to the correct date."
4000 (interactive)
4001 (insert
4002 org-deadline-string " "
4003 (format-time-string (car org-time-stamp-formats)
4004 (org-read-date nil 'to-time)))
4005 (message "%s" (substitute-command-keys
4006 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
4007
4008 (defun org-schedule ()
4009 "Insert the SCHEDULED: string to schedule a TODO item.
4010 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4011 to modify it to the correct date."
4012 (interactive)
4013 (insert
4014 org-scheduled-string " "
4015 (format-time-string (car org-time-stamp-formats)
4016 (org-read-date nil 'to-time)))
4017 (message "%s" (substitute-command-keys
4018 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
4019
4020
4021 (defun org-occur (regexp &optional callback)
4022 "Make a compact tree which shows all matches of REGEXP.
4023 The tree will show the lines where the regexp matches, and all higher
4024 headlines above the match. It will also show the heading after the match,
4025 to make sure editing the matching entry is easy.
4026 If CALLBACK is non-nil, it is a function which is called to confirm
4027 that the match should indeed be shown."
4028 (interactive "sRegexp: ")
4029 (org-remove-occur-highlights nil nil t)
4030 (setq regexp (org-check-occur-regexp regexp))
4031 (let ((cnt 0))
4032 (save-excursion
4033 (goto-char (point-min))
4034 (hide-sublevels 1)
4035 (while (re-search-forward regexp nil t)
4036 (when (or (not callback)
4037 (save-match-data (funcall callback)))
4038 (setq cnt (1+ cnt))
4039 (org-highlight-new-match (match-beginning 0) (match-end 0))
4040 (org-show-hierarchy-above))))
4041 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
4042 nil 'local)
4043 (run-hooks 'org-occur-hook)
4044 (if (interactive-p)
4045 (message "%d match(es) for regexp %s" cnt regexp))
4046 cnt))
4047
4048 (defun org-show-hierarchy-above ()
4049 "Make sure point and the headings hierarchy above is visible."
4050 (catch 'exit
4051 (if (org-on-heading-p t)
4052 (org-flag-heading nil) ; only show the heading
4053 (and (or (org-invisible-p) (org-invisible-p2))
4054 (org-show-hidden-entry))) ; show entire entry
4055 (save-excursion
4056 (and org-show-following-heading
4057 (outline-next-heading)
4058 (org-flag-heading nil))) ; show the next heading
4059 (when org-show-hierarchy-above
4060 (save-excursion ; show all higher headings
4061 (while (and (condition-case nil
4062 (progn (org-up-heading-all 1) t)
4063 (error nil))
4064 (not (bobp)))
4065 (org-flag-heading nil))))))
4066
4067 ;; Overlay compatibility functions
4068 (defun org-make-overlay (beg end &optional buffer)
4069 (if (featurep 'xemacs)
4070 (make-extent beg end buffer)
4071 (make-overlay beg end buffer)))
4072 (defun org-delete-overlay (ovl)
4073 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4074 (defun org-detatch-overlay (ovl)
4075 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4076 (defun org-move-overlay (ovl beg end &optional buffer)
4077 (if (featurep 'xemacs)
4078 (set-extent-endpoints ovl beg end buffer)
4079 (move-overlay ovl beg end buffer)))
4080 (defun org-overlay-put (ovl prop value)
4081 (if (featurep 'xemacs)
4082 (set-extent-property ovl prop value)
4083 (overlay-put ovl prop value)))
4084
4085 (defvar org-occur-highlights nil)
4086 (defun org-highlight-new-match (beg end)
4087 "Highlight from BEG to END and mark the highlight is an occur headline."
4088 (let ((ov (org-make-overlay beg end)))
4089 (org-overlay-put ov 'face 'secondary-selection)
4090 (push ov org-occur-highlights)))
4091
4092 (defun org-remove-occur-highlights (&optional beg end noremove)
4093 "Remove the occur highlights from the buffer.
4094 BEG and END are ignored. If NOREMOVE is nil, remove this function
4095 from the `before-change-functions' in the current buffer."
4096 (interactive)
4097 (mapc 'org-delete-overlay org-occur-highlights)
4098 (setq org-occur-highlights nil)
4099 (unless noremove
4100 (remove-hook 'before-change-functions
4101 'org-remove-occur-highlights 'local)))
4102
4103 ;;; Priorities
4104
4105 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
4106 "Regular expression matching the priority indicator.")
4107
4108 (defvar org-remove-priority-next-time nil)
4109
4110 (defun org-priority-up ()
4111 "Increase the priority of the current item."
4112 (interactive)
4113 (org-priority 'up))
4114
4115 (defun org-priority-down ()
4116 "Decrease the priority of the current item."
4117 (interactive)
4118 (org-priority 'down))
4119
4120 (defun org-priority (&optional action)
4121 "Change the priority of an item by ARG.
4122 ACTION can be set, up, or down."
4123 (interactive)
4124 (setq action (or action 'set))
4125 (let (current new news have remove)
4126 (save-excursion
4127 (org-back-to-heading)
4128 (if (looking-at org-priority-regexp)
4129 (setq current (string-to-char (match-string 2))
4130 have t)
4131 (setq current org-default-priority))
4132 (cond
4133 ((eq action 'set)
4134 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
4135 (setq new (read-char-exclusive))
4136 (cond ((equal new ?\ ) (setq remove t))
4137 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
4138 (error "Priority must be between `%c' and `%c'"
4139 ?A org-lowest-priority))))
4140 ((eq action 'up)
4141 (setq new (1- current)))
4142 ((eq action 'down)
4143 (setq new (1+ current)))
4144 (t (error "Invalid action")))
4145 (setq new (min (max ?A (upcase new)) org-lowest-priority))
4146 (setq news (format "%c" new))
4147 (if have
4148 (if remove
4149 (replace-match "" t t nil 1)
4150 (replace-match news t t nil 2))
4151 (if remove
4152 (error "No priority cookie found in line")
4153 (looking-at org-todo-line-regexp)
4154 (if (match-end 2)
4155 (progn
4156 (goto-char (match-end 2))
4157 (insert " [#" news "]"))
4158 (goto-char (match-beginning 3))
4159 (insert "[#" news "] ")))))
4160 (if remove
4161 (message "Priority removed")
4162 (message "Priority of current item set to %s" news))))
4163
4164
4165 (defun org-get-priority (s)
4166 "Find priority cookie and return priority."
4167 (save-match-data
4168 (if (not (string-match org-priority-regexp s))
4169 (* 1000 (- org-lowest-priority org-default-priority))
4170 (* 1000 (- org-lowest-priority
4171 (string-to-char (match-string 2 s)))))))
4172
4173 ;;; Timestamps
4174
4175 (defvar org-last-changed-timestamp nil)
4176
4177 (defun org-time-stamp (arg)
4178 "Prompt for a date/time and insert a time stamp.
4179 If the user specifies a time like HH:MM, or if this command is called
4180 with a prefix argument, the time stamp will contain date and time.
4181 Otherwise, only the date will be included. All parts of a date not
4182 specified by the user will be filled in from the current date/time.
4183 So if you press just return without typing anything, the time stamp
4184 will represent the current date/time. If there is already a timestamp
4185 at the cursor, it will be modified."
4186 (interactive "P")
4187 (let ((fmt (if arg (cdr org-time-stamp-formats)
4188 (car org-time-stamp-formats)))
4189 (org-time-was-given nil)
4190 time)
4191 (cond
4192 ((and (org-at-timestamp-p)
4193 (eq last-command 'org-time-stamp)
4194 (eq this-command 'org-time-stamp))
4195 (insert "--")
4196 (setq time (let ((this-command this-command))
4197 (org-read-date arg 'totime)))
4198 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4199 (insert (format-time-string fmt time)))
4200 ((org-at-timestamp-p)
4201 (setq time (let ((this-command this-command))
4202 (org-read-date arg 'totime)))
4203 (and (org-at-timestamp-p) (replace-match
4204 (setq org-last-changed-timestamp
4205 (format-time-string fmt time))
4206 t t))
4207 (message "Timestamp updated"))
4208 (t
4209 (setq time (let ((this-command this-command))
4210 (org-read-date arg 'totime)))
4211 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4212 (insert (format-time-string fmt time))))))
4213
4214 (defun org-time-stamp-inactive (&optional arg)
4215 "Insert an inactive time stamp.
4216 An inactive time stamp is enclosed in square brackets instead of angle
4217 brackets. It is inactive in the sense that it does not trigger agenda entries,
4218 does not link to the calendar and cannot be changed with the S-cursor keys.
4219 So these are more for recording a certain time/date."
4220 (interactive "P")
4221 (let ((fmt (if arg (cdr org-time-stamp-formats)
4222 (car org-time-stamp-formats)))
4223 (org-time-was-given nil)
4224 time)
4225 (setq time (org-read-date arg 'totime))
4226 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4227 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
4228 (insert (format-time-string fmt time))))
4229
4230 (defvar org-date-ovl (org-make-overlay 1 1))
4231 (org-overlay-put org-date-ovl 'face 'org-warning)
4232 (org-detatch-overlay org-date-ovl)
4233
4234 (defun org-read-date (&optional with-time to-time)
4235 "Read a date and make things smooth for the user.
4236 The prompt will suggest to enter an ISO date, but you can also enter anything
4237 which will at least partially be understood by `parse-time-string'.
4238 Unrecognized parts of the date will default to the current day, month, year,
4239 hour and minute. For example,
4240 3-2-5 --> 2003-02-05
4241 feb 15 --> currentyear-02-15
4242 sep 12 9 --> 2009-09-12
4243 12:45 --> today 12:45
4244 22 sept 0:34 --> currentyear-09-22 0:34
4245 12 --> currentyear-currentmonth-12
4246 Fri --> nearest Friday (today or later)
4247 etc.
4248 The function understands only English month and weekday abbreviations,
4249 but this can be configured with the variables `parse-time-months' and
4250 `parse-time-weekdays'.
4251
4252 While prompting, a calendar is popped up - you can also select the
4253 date with the mouse (button 1). The calendar shows a period of three
4254 months. To scroll it to other months, use the keys `>' and `<'.
4255 If you don't like the calendar, turn it off with
4256 \(setq org-popup-calendar-for-date-prompt nil)
4257
4258 With optional argument TO-TIME, the date will immediately be converted
4259 to an internal time.
4260 With an optional argument WITH-TIME, the prompt will suggest to also
4261 insert a time. Note that when WITH-TIME is not set, you can still
4262 enter a time, and this function will inform the calling routine about
4263 this change. The calling routine may then choose to change the format
4264 used to insert the time stamp into the buffer to include the time."
4265 (require 'parse-time)
4266 (let* ((org-time-stamp-rounding-minutes
4267 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
4268 (ct (org-current-time))
4269 (default-time
4270 ;; Default time is either today, or, when entering a range,
4271 ;; the range start.
4272 (if (save-excursion
4273 (re-search-backward
4274 (concat org-ts-regexp "--\\=") ; FIXME: exactly two minuses?
4275 (- (point) 20) t))
4276 (apply
4277 'encode-time
4278 (mapcar (lambda(x) (or x 0))
4279 (parse-time-string (match-string 1))))
4280 ct))
4281 (calendar-move-hook nil)
4282 (view-diary-entries-initially nil)
4283 (timestr (format-time-string
4284 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
4285 (prompt (format "YYYY-MM-DD [%s]: " timestr))
4286 ans ans1 ans2
4287 second minute hour day month year tl wday wday1)
4288
4289 (if org-popup-calendar-for-date-prompt
4290 (save-excursion
4291 (save-window-excursion
4292 (calendar)
4293 (calendar-forward-day (- (time-to-days default-time)
4294 (calendar-absolute-from-gregorian
4295 (calendar-current-date))))
4296 (org-eval-in-calendar nil)
4297 (let* ((old-map (current-local-map))
4298 (map (copy-keymap calendar-mode-map))
4299 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
4300 (define-key map (kbd "RET") 'org-calendar-select)
4301 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
4302 'org-calendar-select-mouse)
4303 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
4304 'org-calendar-select-mouse)
4305 (define-key minibuffer-local-map [(meta shift left)]
4306 (lambda () (interactive)
4307 (org-eval-in-calendar '(calendar-backward-month 1))))
4308 (define-key minibuffer-local-map [(meta shift right)]
4309 (lambda () (interactive)
4310 (org-eval-in-calendar '(calendar-forward-month 1))))
4311 (define-key minibuffer-local-map [(shift up)]
4312 (lambda () (interactive)
4313 (org-eval-in-calendar '(calendar-backward-week 1))))
4314 (define-key minibuffer-local-map [(shift down)]
4315 (lambda () (interactive)
4316 (org-eval-in-calendar '(calendar-forward-week 1))))
4317 (define-key minibuffer-local-map [(shift left)]
4318 (lambda () (interactive)
4319 (org-eval-in-calendar '(calendar-backward-day 1))))
4320 (define-key minibuffer-local-map [(shift right)]
4321 (lambda () (interactive)
4322 (org-eval-in-calendar '(calendar-forward-day 1))))
4323 (define-key minibuffer-local-map ">"
4324 (lambda () (interactive)
4325 (org-eval-in-calendar '(scroll-calendar-left 1))))
4326 (define-key minibuffer-local-map "<"
4327 (lambda () (interactive)
4328 (org-eval-in-calendar '(scroll-calendar-right 1))))
4329 (unwind-protect
4330 (progn
4331 (use-local-map map)
4332 (setq ans (read-string prompt "" nil nil))
4333 (if (not (string-match "\\S-" ans)) (setq ans nil))
4334 (setq ans (or ans1 ans ans2)))
4335 (use-local-map old-map)))))
4336 ;; Naked prompt only
4337 (setq ans (read-string prompt "" nil timestr)))
4338 (org-detatch-overlay org-date-ovl)
4339
4340 (if (string-match
4341 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
4342 (progn
4343 (setq year (if (match-end 2)
4344 (string-to-number (match-string 2 ans))
4345 (string-to-number (format-time-string "%Y")))
4346 month (string-to-number (match-string 3 ans))
4347 day (string-to-number (match-string 4 ans)))
4348 (if (< year 100) (setq year (+ 2000 year)))
4349 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
4350 t nil ans))))
4351 (setq tl (parse-time-string ans)
4352 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
4353 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
4354 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
4355 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
4356 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
4357 second (or (nth 0 tl) 0)
4358 wday (nth 6 tl))
4359 (when (and wday (not (nth 3 tl)))
4360 ;; Weekday was given, but no day, so pick that day in the week
4361 ;; on or after the derived date.
4362 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
4363 (unless (equal wday wday1)
4364 (setq day (+ day (% (- wday wday1 -7) 7)))))
4365 (if (and (boundp 'org-time-was-given)
4366 (nth 2 tl))
4367 (setq org-time-was-given t))
4368 (if (< year 100) (setq year (+ 2000 year)))
4369 (if to-time
4370 (encode-time second minute hour day month year)
4371 (if (or (nth 1 tl) (nth 2 tl))
4372 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
4373 (format "%04d-%02d-%02d" year month day)))))
4374
4375 (defun org-eval-in-calendar (form)
4376 "Eval FORM in the calendar window and return to current window.
4377 Also, store the cursor date in variable ans2."
4378 (let ((sw (selected-window)))
4379 (select-window (get-buffer-window "*Calendar*"))
4380 (eval form)
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 ans2 (format-time-string "%Y-%m-%d" time))))
4385 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4386 (select-window sw)))
4387
4388 (defun org-calendar-select ()
4389 "Return to `org-read-date' with the date currently selected.
4390 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4391 (interactive)
4392 (when (calendar-cursor-to-date)
4393 (let* ((date (calendar-cursor-to-date))
4394 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4395 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4396 (if (active-minibuffer-window) (exit-minibuffer))))
4397
4398 (defun org-calendar-select-mouse (ev)
4399 "Return to `org-read-date' with the date currently selected.
4400 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4401 (interactive "e")
4402 (mouse-set-point ev)
4403 (when (calendar-cursor-to-date)
4404 (let* ((date (calendar-cursor-to-date))
4405 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4406 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4407 (if (active-minibuffer-window) (exit-minibuffer))))
4408
4409 (defun org-check-deadlines (ndays)
4410 "Check if there are any deadlines due or past due.
4411 A deadline is considered due if it happens within `org-deadline-warning-days'
4412 days from today's date. If the deadline appears in an entry marked DONE,
4413 it is not shown. The prefix arg NDAYS can be used to test that many
4414 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4415 (interactive "P")
4416 (let* ((org-warn-days
4417 (cond
4418 ((equal ndays '(4)) 100000)
4419 (ndays (prefix-numeric-value ndays))
4420 (t org-deadline-warning-days)))
4421 (case-fold-search nil)
4422 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4423 (callback
4424 (lambda ()
4425 (and (let ((d1 (time-to-days (current-time)))
4426 (d2 (time-to-days
4427 (org-time-string-to-time (match-string 1)))))
4428 (< (- d2 d1) org-warn-days))
4429 (not (org-entry-is-done-p))))))
4430 (message "%d deadlines past-due or due within %d days"
4431 (org-occur regexp callback)
4432 org-warn-days)))
4433
4434 (defun org-evaluate-time-range (&optional to-buffer)
4435 "Evaluate a time range by computing the difference between start and end.
4436 Normally the result is just printed in the echo area, but with prefix arg
4437 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4438 If the time range is actually in a table, the result is inserted into the
4439 next column.
4440 For time difference computation, a year is assumed to be exactly 365
4441 days in order to avoid rounding problems."
4442 (interactive "P")
4443 (save-excursion
4444 (unless (org-at-date-range-p)
4445 (goto-char (point-at-bol))
4446 (re-search-forward org-tr-regexp (point-at-eol) t))
4447 (if (not (org-at-date-range-p))
4448 (error "Not at a time-stamp range, and none found in current line")))
4449 (let* ((ts1 (match-string 1))
4450 (ts2 (match-string 2))
4451 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4452 (match-end (match-end 0))
4453 (time1 (org-time-string-to-time ts1))
4454 (time2 (org-time-string-to-time ts2))
4455 (t1 (time-to-seconds time1))
4456 (t2 (time-to-seconds time2))
4457 (diff (abs (- t2 t1)))
4458 (negative (< (- t2 t1) 0))
4459 ;; (ys (floor (* 365 24 60 60)))
4460 (ds (* 24 60 60))
4461 (hs (* 60 60))
4462 (fy "%dy %dd %02d:%02d")
4463 (fy1 "%dy %dd")
4464 (fd "%dd %02d:%02d")
4465 (fd1 "%dd")
4466 (fh "%02d:%02d")
4467 y d h m align)
4468 (if havetime
4469 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4470 y 0
4471 d (floor (/ diff ds)) diff (mod diff ds)
4472 h (floor (/ diff hs)) diff (mod diff hs)
4473 m (floor (/ diff 60)))
4474 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4475 y 0
4476 d (floor (+ (/ diff ds) 0.5))
4477 h 0 m 0))
4478 (if (not to-buffer)
4479 (message (org-make-tdiff-string y d h m))
4480 (when (org-at-table-p)
4481 (goto-char match-end)
4482 (setq align t)
4483 (and (looking-at " *|") (goto-char (match-end 0))))
4484 (if (looking-at
4485 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4486 (replace-match ""))
4487 (if negative (insert " -"))
4488 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4489 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4490 (insert " " (format fh h m))))
4491 (if align (org-table-align))
4492 (message "Time difference inserted"))))
4493
4494 (defun org-make-tdiff-string (y d h m)
4495 (let ((fmt "")
4496 (l nil))
4497 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4498 l (push y l)))
4499 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4500 l (push d l)))
4501 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4502 l (push h l)))
4503 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4504 l (push m l)))
4505 (apply 'format fmt (nreverse l))))
4506
4507 (defun org-time-string-to-time (s)
4508 (apply 'encode-time (org-parse-time-string s)))
4509
4510 (defun org-parse-time-string (s &optional nodefault)
4511 "Parse the standard Org-mode time string.
4512 This should be a lot faster than the normal `parse-time-string'.
4513 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4514 hour and minute fields will be nil if not given."
4515 (if (string-match org-ts-regexp1 s)
4516 (list 0
4517 (if (or (match-beginning 8) (not nodefault))
4518 (string-to-number (or (match-string 8 s) "0")))
4519 (if (or (match-beginning 7) (not nodefault))
4520 (string-to-number (or (match-string 7 s) "0")))
4521 (string-to-number (match-string 4 s))
4522 (string-to-number (match-string 3 s))
4523 (string-to-number (match-string 2 s))
4524 nil nil nil)
4525 (make-list 9 0)))
4526
4527 (defun org-timestamp-up (&optional arg)
4528 "Increase the date item at the cursor by one.
4529 If the cursor is on the year, change the year. If it is on the month or
4530 the day, change that.
4531 With prefix ARG, change by that many units."
4532 (interactive "p")
4533 (org-timestamp-change (prefix-numeric-value arg)))
4534
4535 (defun org-timestamp-down (&optional arg)
4536 "Decrease the date item at the cursor by one.
4537 If the cursor is on the year, change the year. If it is on the month or
4538 the day, change that.
4539 With prefix ARG, change by that many units."
4540 (interactive "p")
4541 (org-timestamp-change (- (prefix-numeric-value arg))))
4542
4543 (defun org-timestamp-up-day (&optional arg)
4544 "Increase the date in the time stamp by one day.
4545 With prefix ARG, change that many days."
4546 (interactive "p")
4547 (if (and (not (org-at-timestamp-p))
4548 (org-on-heading-p))
4549 (org-todo 'up)
4550 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4551
4552 (defun org-timestamp-down-day (&optional arg)
4553 "Decrease the date in the time stamp by one day.
4554 With prefix ARG, change that many days."
4555 (interactive "p")
4556 (if (and (not (org-at-timestamp-p))
4557 (org-on-heading-p))
4558 (org-todo 'down)
4559 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4560
4561 (defsubst org-pos-in-match-range (pos n)
4562 (and (match-beginning n)
4563 (<= (match-beginning n) pos)
4564 (>= (match-end n) pos)))
4565
4566 (defun org-at-timestamp-p ()
4567 "Determine if the cursor is in or at a timestamp."
4568 (interactive)
4569 (let* ((tsr org-ts-regexp2)
4570 (pos (point))
4571 (ans (or (looking-at tsr)
4572 (save-excursion
4573 (skip-chars-backward "^<\n\r\t")
4574 (if (> (point) 1) (backward-char 1))
4575 (and (looking-at tsr)
4576 (> (- (match-end 0) pos) -1))))))
4577 (and (boundp 'org-ts-what)
4578 (setq org-ts-what
4579 (cond
4580 ((org-pos-in-match-range pos 2) 'year)
4581 ((org-pos-in-match-range pos 3) 'month)
4582 ((org-pos-in-match-range pos 7) 'hour)
4583 ((org-pos-in-match-range pos 8) 'minute)
4584 ((or (org-pos-in-match-range pos 4)
4585 (org-pos-in-match-range pos 5)) 'day)
4586 (t 'day))))
4587 ans))
4588
4589 (defun org-timestamp-change (n &optional what)
4590 "Change the date in the time stamp at point.
4591 The date will be changed by N times WHAT. WHAT can be `day', `month',
4592 `year', `minute', `second'. If WHAT is not given, the cursor position
4593 in the timestamp determines what will be changed."
4594 (let ((fmt (car org-time-stamp-formats))
4595 org-ts-what
4596 (pos (point))
4597 ts time time0)
4598 (if (not (org-at-timestamp-p))
4599 (error "Not at a timestamp"))
4600 (setq org-ts-what (or what org-ts-what))
4601 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4602 (- (match-end 0) (match-beginning 0))))
4603 1)
4604 (cdr org-time-stamp-formats)
4605 (car org-time-stamp-formats)))
4606 (setq ts (match-string 0))
4607 (replace-match "")
4608 (setq time0 (org-parse-time-string ts))
4609 (setq time
4610 (apply 'encode-time
4611 (append
4612 (list (or (car time0) 0))
4613 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4614 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4615 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4616 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4617 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4618 (nthcdr 6 time0))))
4619 (if (eq what 'calendar)
4620 (let ((cal-date
4621 (save-excursion
4622 (save-match-data
4623 (set-buffer "*Calendar*")
4624 (calendar-cursor-to-date)))))
4625 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4626 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4627 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4628 (setcar time0 (or (car time0) 0))
4629 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4630 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4631 (setq time (apply 'encode-time time0))))
4632 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4633 (goto-char pos)
4634 ;; Try to recenter the calendar window, if any
4635 (if (and org-calendar-follow-timestamp-change
4636 (get-buffer-window "*Calendar*" t)
4637 (memq org-ts-what '(day month year)))
4638 (org-recenter-calendar (time-to-days time)))))
4639
4640 (defun org-recenter-calendar (date)
4641 "If the calendar is visible, recenter it to DATE."
4642 (let* ((win (selected-window))
4643 (cwin (get-buffer-window "*Calendar*" t))
4644 (calendar-move-hook nil))
4645 (when cwin
4646 (select-window cwin)
4647 (calendar-goto-date (if (listp date) date
4648 (calendar-gregorian-from-absolute date)))
4649 (select-window win))))
4650
4651 (defun org-goto-calendar (&optional arg)
4652 "Go to the Emacs calendar at the current date.
4653 If there is a time stamp in the current line, go to that date.
4654 A prefix ARG can be used to force the current date."
4655 (interactive "P")
4656 (let ((tsr org-ts-regexp) diff
4657 (calendar-move-hook nil)
4658 (view-diary-entries-initially nil))
4659 (if (or (org-at-timestamp-p)
4660 (save-excursion
4661 (beginning-of-line 1)
4662 (looking-at (concat ".*" tsr))))
4663 (let ((d1 (time-to-days (current-time)))
4664 (d2 (time-to-days
4665 (org-time-string-to-time (match-string 1)))))
4666 (setq diff (- d2 d1))))
4667 (calendar)
4668 (calendar-goto-today)
4669 (if (and diff (not arg)) (calendar-forward-day diff))))
4670
4671 (defun org-date-from-calendar ()
4672 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4673 If there is already a time stamp at the cursor position, update it."
4674 (interactive)
4675 (org-timestamp-change 0 'calendar))
4676
4677 ;;; Agenda, and Diary Integration
4678
4679 ;;; Define the mode
4680
4681 (defvar org-agenda-mode-map (make-sparse-keymap)
4682 "Keymap for `org-agenda-mode'.")
4683
4684 (defvar org-agenda-menu) ; defined later in this file.
4685 (defvar org-agenda-follow-mode nil)
4686 (defvar org-agenda-show-log nil)
4687 (defvar org-agenda-buffer-name "*Org Agenda*")
4688 (defvar org-agenda-redo-command nil)
4689 (defvar org-agenda-mode-hook nil)
4690 (defvar org-agenda-type nil)
4691 (defvar org-agenda-force-single-file nil)
4692
4693 ;;;###autoload
4694 (defun org-agenda-mode ()
4695 "Mode for time-sorted view on action items in Org-mode files.
4696
4697 The following commands are available:
4698
4699 \\{org-agenda-mode-map}"
4700 (interactive)
4701 (kill-all-local-variables)
4702 (setq major-mode 'org-agenda-mode)
4703 (setq mode-name "Org-Agenda")
4704 (use-local-map org-agenda-mode-map)
4705 (easy-menu-add org-agenda-menu)
4706 (if org-startup-truncated (setq truncate-lines t))
4707 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4708 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4709 (unless org-agenda-keep-modes
4710 (setq org-agenda-follow-mode nil
4711 org-agenda-show-log nil))
4712 (easy-menu-change
4713 '("Agenda") "Agenda Files"
4714 (append
4715 (list
4716 (vector
4717 (if (get 'org-agenda-files 'org-restrict)
4718 "Restricted to single file"
4719 "Edit File List")
4720 '(org-edit-agenda-file-list)
4721 (not (get 'org-agenda-files 'org-restrict)))
4722 "--")
4723 (mapcar 'org-file-menu-entry (org-agenda-files))))
4724 (org-agenda-set-mode-name)
4725 (apply
4726 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4727 (list 'org-agenda-mode-hook)))
4728
4729 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4730 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
4731 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4732 (define-key org-agenda-mode-map " " 'org-agenda-show)
4733 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4734 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4735 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4736 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4737 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4738 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4739 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4740 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4741 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4742 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4743 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4744 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4745
4746 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4747 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4748 (while l (define-key org-agenda-mode-map
4749 (int-to-string (pop l)) 'digit-argument)))
4750
4751 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4752 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4753 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4754 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4755 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4756 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4757 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4758 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4759 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4760 (define-key org-agenda-mode-map "n" 'next-line)
4761 (define-key org-agenda-mode-map "p" 'previous-line)
4762 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4763 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4764 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4765 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4766 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4767 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4768 (eval-after-load "calendar"
4769 '(define-key calendar-mode-map org-calendar-to-agenda-key
4770 'org-calendar-goto-agenda))
4771 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4772 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4773 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4774 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4775 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4776 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4777 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4778 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4779 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4780 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4781 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4782 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4783 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4784 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4785 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4786 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4787 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4788 "Local keymap for agenda entries from Org-mode.")
4789
4790 (define-key org-agenda-keymap
4791 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4792 (define-key org-agenda-keymap
4793 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4794 (when org-agenda-mouse-1-follows-link
4795 (define-key org-agenda-keymap [follow-link] 'mouse-face))
4796 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4797 '("Agenda"
4798 ("Agenda Files")
4799 "--"
4800 ["Show" org-agenda-show t]
4801 ["Go To (other window)" org-agenda-goto t]
4802 ["Go To (one window)" org-agenda-switch-to t]
4803 ["Follow Mode" org-agenda-follow-mode
4804 :style toggle :selected org-agenda-follow-mode :active t]
4805 "--"
4806 ["Cycle TODO" org-agenda-todo t]
4807 ("Tags"
4808 ["Show all Tags" org-agenda-show-tags t]
4809 ["Set Tags" org-agenda-set-tags t])
4810 ("Reschedule"
4811 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4812 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4813 "--"
4814 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4815 ("Priority"
4816 ["Set Priority" org-agenda-priority t]
4817 ["Increase Priority" org-agenda-priority-up t]
4818 ["Decrease Priority" org-agenda-priority-down t]
4819 ["Show Priority" org-agenda-show-priority t])
4820 "--"
4821 ;; ["New agenda command" org-agenda t]
4822 ["Rebuild buffer" org-agenda-redo t]
4823 "--"
4824 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4825 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4826 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4827 "--"
4828 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4829 :style radio :selected (equal org-agenda-ndays 1)]
4830 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4831 :style radio :selected (equal org-agenda-ndays 7)]
4832 "--"
4833 ["Show Logbook entries" org-agenda-log-mode
4834 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4835 ["Include Diary" org-agenda-toggle-diary
4836 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4837 ["Use Time Grid" org-agenda-toggle-time-grid
4838 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4839 "--"
4840 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4841 ("Calendar Commands"
4842 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4843 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4844 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4845 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4846 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4847 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4848 "--"
4849 ["Quit" org-agenda-quit t]
4850 ["Exit and Release Buffers" org-agenda-exit t]
4851 ))
4852
4853 ;;;###autoload
4854 (defun org-agenda (arg)
4855 "Dispatch agenda commands to collect entries to the agenda buffer.
4856 Prompts for a character to select a command. Any prefix arg will be passed
4857 on to the selected command. The default selections are:
4858
4859 a Call `org-agenda' to display the agenda for the current day or week.
4860 t Call `org-todo-list' to display the global todo list.
4861 T Call `org-todo-list' to display the global todo list, select only
4862 entries with a specific TODO keyword (the user gets a prompt).
4863 m Call `org-tags-view' to display headlines with tags matching
4864 a condition (the user is prompted for the condition).
4865 M Like `m', but select only TODO entries, no ordinary headlines.
4866
4867 More commands can be added by configuring the variable
4868 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4869 searches can be pre-defined in this way.
4870
4871 If the current buffer is in Org-mode and visiting a file, you can also
4872 first press `1' to indicate that the agenda should be temporarily (until the
4873 next use of \\[org-agenda]) restricted to the current file."
4874 (interactive "P")
4875 (catch 'exit
4876 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
4877 (custom org-agenda-custom-commands)
4878 c entry key type string)
4879 (put 'org-agenda-files 'org-restrict nil)
4880 (save-window-excursion
4881 (delete-other-windows)
4882 (switch-to-buffer-other-window " *Agenda Commands*")
4883 (erase-buffer)
4884 (insert
4885 "Press key for an agenda command:
4886 --------------------------------
4887 a Agenda for current week or day
4888 t List of all TODO entries T Entries with special TODO kwd
4889 m Match a TAGS query M Like m, but only TODO entries
4890 C Configure your own agenda commands")
4891 (while (setq entry (pop custom))
4892 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4893 (insert (format "\n%-4s%-14s: %s"
4894 key
4895 (cond
4896 ((eq type 'tags) "Tags query")
4897 ((eq type 'todo) "TODO keyword")
4898 ((eq type 'tags-tree) "Tags tree")
4899 ((eq type 'todo-tree) "TODO kwd tree")
4900 ((eq type 'occur-tree) "Occur tree")
4901 (t "???"))
4902 (org-add-props string nil 'face 'org-warning))))
4903 (goto-char (point-min))
4904 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4905 (message "Press key for agenda command%s"
4906 (if restrict-ok ", or [1] to restrict to current file" ""))
4907 (setq c (read-char-exclusive))
4908 (message "")
4909 (when (equal c ?1)
4910 (if restrict-ok
4911 (put 'org-agenda-files 'org-restrict (list buffer-file-name))
4912 (error "Cannot restrict agenda to current buffer"))
4913 (message "Press key for agenda command%s"
4914 (if restrict-ok " (restricted to current file)" ""))
4915 (setq c (read-char-exclusive))
4916 (message "")))
4917 (require 'calendar) ; FIXME: can we avoid this for some commands?
4918 ;; For example the todo list should not need it (but does...)
4919 (cond
4920 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4921 ((equal c ?a) (call-interactively 'org-agenda-list))
4922 ((equal c ?t) (call-interactively 'org-todo-list))
4923 ((equal c ?T)
4924 (setq current-prefix-arg (or arg '(4)))
4925 (call-interactively 'org-todo-list))
4926 ((equal c ?m) (call-interactively 'org-tags-view))
4927 ((equal c ?M)
4928 (setq current-prefix-arg (or arg '(4)))
4929 (call-interactively 'org-tags-view))
4930 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
4931 (setq type (nth 1 entry) string (nth 2 entry))
4932 (cond
4933 ((eq type 'tags)
4934 (org-tags-view current-prefix-arg string))
4935 ((eq type 'todo)
4936 (org-todo-list string))
4937 ((eq type 'tags-tree)
4938 (org-check-for-org-mode)
4939 (org-tags-sparse-tree current-prefix-arg string))
4940 ((eq type 'todo-tree)
4941 (org-check-for-org-mode)
4942 (org-occur (concat "^" outline-regexp "[ \t]*"
4943 (regexp-quote string) "\\>")))
4944 ((eq type 'occur-tree)
4945 (org-check-for-org-mode)
4946 (org-occur string))
4947 (t (error "Invalid custom agenda command type %s" type))))
4948 (t (error "Invalid key"))))))
4949
4950 (defun org-check-for-org-mode ()
4951 "Make sure current buffer is in org-mode. Error if not."
4952 (or (eq major-mode 'org-mode)
4953 (error "Cannot execute org-mode agenda command on buffer in %s."
4954 major-mode)))
4955
4956 (defun org-fit-agenda-window ()
4957 "Fit the window to the buffer size."
4958 (and org-fit-agenda-window
4959 (fboundp 'fit-window-to-buffer)
4960 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
4961 (/ (frame-height) 2))))
4962
4963 (defun org-agenda-files (&optional unrestricted)
4964 "Get the list of agenda files.
4965 Optional UNRESTRICTED means return the full list even if a restriction
4966 is currently in place."
4967 (cond
4968 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
4969 ((stringp org-agenda-files) (org-read-agenda-file-list))
4970 ((listp org-agenda-files) org-agenda-files)
4971 (t (error "Invalid value of `org-agenda-files'"))))
4972
4973 (defvar org-window-configuration)
4974
4975 (defun org-edit-agenda-file-list ()
4976 "Edit the list of agenda files.
4977 Depending on setup, this either uses customize to edit the variable
4978 `org-agenda-files', or it visits the file that is holding the list. In the
4979 latter case, the buffer is set up in a way that saving it automatically kills
4980 the buffer and restores the previous window configuration."
4981 (interactive)
4982 (if (stringp org-agenda-files)
4983 (let ((cw (current-window-configuration)))
4984 (find-file org-agenda-files)
4985 (set (make-local-variable 'org-window-configuration) cw)
4986 (org-add-hook 'after-save-hook
4987 (lambda ()
4988 (set-window-configuration
4989 (prog1 org-window-configuration
4990 (kill-buffer (current-buffer))))
4991 (org-install-agenda-files-menu)
4992 (message "New agenda file list installed"))
4993 nil 'local)
4994 (message (substitute-command-keys
4995 "Edit list and finish with \\[save-buffer]")))
4996 (customize-variable 'org-agenda-files)))
4997
4998 (defun org-store-new-agenda-file-list (list)
4999 "Set new value for the agenda file list and save it correcly."
5000 (if (stringp org-agenda-files)
5001 (let ((f org-agenda-files) b)
5002 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
5003 (with-temp-file f
5004 (insert (mapconcat 'identity list "\n") "\n")))
5005 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5006 (setq org-agenda-files list)
5007 (customize-save-variable 'org-agenda-files org-agenda-files))))
5008
5009 (defun org-read-agenda-file-list ()
5010 "Read the list of agenda files from a file."
5011 (when (stringp org-agenda-files)
5012 (with-temp-buffer
5013 (insert-file-contents org-agenda-files)
5014 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
5015
5016 (defvar org-agenda-markers nil
5017 "List of all currently active markers created by `org-agenda'.")
5018 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
5019 "Creation time of the last agenda marker.")
5020
5021 (defun org-agenda-new-marker (&optional pos)
5022 "Return a new agenda marker.
5023 Org-mode keeps a list of these markers and resets them when they are
5024 no longer in use."
5025 (let ((m (copy-marker (or pos (point)))))
5026 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
5027 (push m org-agenda-markers)
5028 m))
5029
5030 (defun org-agenda-maybe-reset-markers (&optional force)
5031 "Reset markers created by `org-agenda'. But only if they are old enough."
5032 (if (or force
5033 (> (- (time-to-seconds (current-time))
5034 org-agenda-last-marker-time)
5035 5))
5036 (while org-agenda-markers
5037 (move-marker (pop org-agenda-markers) nil))))
5038
5039 (defvar org-agenda-new-buffers nil
5040 "Buffers created to visit agenda files.")
5041
5042 (defun org-get-agenda-file-buffer (file)
5043 "Get a buffer visiting FILE. If the buffer needs to be created, add
5044 it to the list of buffers which might be released later."
5045 (let ((buf (find-buffer-visiting file)))
5046 (if buf
5047 buf ; just return it
5048 ;; Make a new buffer and remember it
5049 (setq buf (find-file-noselect file))
5050 (if buf (push buf org-agenda-new-buffers))
5051 buf)))
5052
5053 (defun org-release-buffers (blist)
5054 "Release all buffers in list, asking the user for confirmation when needed.
5055 When a buffer is unmodified, it is just killed. When modified, it is saved
5056 \(if the user agrees) and then killed."
5057 (let (buf file)
5058 (while (setq buf (pop blist))
5059 (setq file (buffer-file-name buf))
5060 (when (and (buffer-modified-p buf)
5061 file
5062 (y-or-n-p (format "Save file %s? " file)))
5063 (with-current-buffer buf (save-buffer)))
5064 (kill-buffer buf))))
5065
5066 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
5067
5068 (defun org-timeline (&optional include-all keep-modes)
5069 "Show a time-sorted view of the entries in the current org file.
5070 Only entries with a time stamp of today or later will be listed. With
5071 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
5072 under the current date.
5073 If the buffer contains an active region, only check the region for
5074 dates."
5075 (interactive "P")
5076 (require 'calendar)
5077 (org-agenda-maybe-reset-markers 'force)
5078 (org-compile-prefix-format org-timeline-prefix-format)
5079 (let* ((dopast t)
5080 (dotodo include-all)
5081 (doclosed org-agenda-show-log)
5082 (org-agenda-keep-modes keep-modes)
5083 (entry buffer-file-name)
5084 (org-agenda-files (list buffer-file-name))
5085 (date (calendar-current-date))
5086 (win (selected-window))
5087 (pos1 (point))
5088 (beg (if (org-region-active-p) (region-beginning) (point-min)))
5089 (end (if (org-region-active-p) (region-end) (point-max)))
5090 (day-numbers (org-get-all-dates beg end 'no-ranges
5091 t doclosed)) ; always include today
5092 (today (time-to-days (current-time)))
5093 (org-respect-restriction t)
5094 (past t)
5095 args
5096 s e rtn d)
5097 (setq org-agenda-redo-command
5098 (list 'progn
5099 (list 'switch-to-buffer-other-window (current-buffer))
5100 (list 'org-timeline (list 'quote include-all) t)))
5101 (if (not dopast)
5102 ;; Remove past dates from the list of dates.
5103 (setq day-numbers (delq nil (mapcar (lambda(x)
5104 (if (>= x today) x nil))
5105 day-numbers))))
5106 (switch-to-buffer-other-window
5107 (get-buffer-create org-agenda-buffer-name))
5108 (setq buffer-read-only nil)
5109 (erase-buffer)
5110 (org-agenda-mode) (setq buffer-read-only nil)
5111 (set (make-local-variable 'org-agenda-type) 'timeline)
5112 (if doclosed (push :closed args))
5113 (push :timestamp args)
5114 (if dotodo (push :todo args))
5115 (while (setq d (pop day-numbers))
5116 (if (and (>= d today)
5117 dopast
5118 past)
5119 (progn
5120 (setq past nil)
5121 (insert (make-string 79 ?-) "\n")))
5122 (setq date (calendar-gregorian-from-absolute d))
5123 (setq s (point))
5124 (setq rtn (apply 'org-agenda-get-day-entries
5125 entry date args))
5126 (if (or rtn (equal d today))
5127 (progn
5128 (insert (calendar-day-name date) " "
5129 (number-to-string (extract-calendar-day date)) " "
5130 (calendar-month-name (extract-calendar-month date)) " "
5131 (number-to-string (extract-calendar-year date)) "\n")
5132 (put-text-property s (1- (point)) 'face
5133 'org-level-3)
5134 (if (equal d today)
5135 (put-text-property s (1- (point)) 'org-today t))
5136 (insert (org-finalize-agenda-entries rtn) "\n")
5137 (put-text-property s (1- (point)) 'day d))))
5138 (goto-char (point-min))
5139 (setq buffer-read-only t)
5140 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5141 (point-min)))
5142 (when (not org-select-timeline-window)
5143 (select-window win)
5144 (goto-char pos1))))
5145
5146 ;;;###autoload
5147 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
5148 "Produce a weekly view from all files in variable `org-agenda-files'.
5149 The view will be for the current week, but from the overview buffer you
5150 will be able to go to other weeks.
5151 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
5152 also be shown, under the current date.
5153 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
5154 on the days are also shown. See the variable `org-log-done' for how
5155 to turn on logging.
5156 START-DAY defaults to TODAY, or to the most recent match for the weekday
5157 given in `org-agenda-start-on-weekday'.
5158 NDAYS defaults to `org-agenda-ndays'."
5159 (interactive "P")
5160 (org-agenda-maybe-reset-markers 'force)
5161 (org-compile-prefix-format org-agenda-prefix-format)
5162 (require 'calendar)
5163 (let* ((org-agenda-start-on-weekday
5164 (if (or (equal ndays 1)
5165 (and (null ndays) (equal 1 org-agenda-ndays)))
5166 nil org-agenda-start-on-weekday))
5167 (org-agenda-keep-modes keep-modes)
5168 (thefiles (org-agenda-files))
5169 (files thefiles)
5170 (win (selected-window))
5171 (today (time-to-days (current-time)))
5172 (sd (or start-day today))
5173 (start (if (or (null org-agenda-start-on-weekday)
5174 (< org-agenda-ndays 7))
5175 sd
5176 (let* ((nt (calendar-day-of-week
5177 (calendar-gregorian-from-absolute sd)))
5178 (n1 org-agenda-start-on-weekday)
5179 (d (- nt n1)))
5180 (- sd (+ (if (< d 0) 7 0) d)))))
5181 (day-numbers (list start))
5182 ;FIXME (inhibit-redisplay t)
5183 s e rtn rtnall file date d start-pos end-pos todayp nd)
5184 (setq org-agenda-redo-command
5185 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
5186 ;; Make the list of days
5187 (setq ndays (or ndays org-agenda-ndays)
5188 nd ndays)
5189 (while (> ndays 1)
5190 (push (1+ (car day-numbers)) day-numbers)
5191 (setq ndays (1- ndays)))
5192 (setq day-numbers (nreverse day-numbers))
5193 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5194 (progn
5195 (delete-other-windows)
5196 (switch-to-buffer-other-window
5197 (get-buffer-create org-agenda-buffer-name))))
5198 (setq buffer-read-only nil)
5199 (erase-buffer)
5200 (org-agenda-mode) (setq buffer-read-only nil)
5201 (set (make-local-variable 'org-agenda-type) 'agenda)
5202 (set (make-local-variable 'starting-day) (car day-numbers))
5203 (set (make-local-variable 'include-all-loc) include-all)
5204 (when (and (or include-all org-agenda-include-all-todo)
5205 (member today day-numbers))
5206 (setq files thefiles
5207 rtnall nil)
5208 (while (setq file (pop files))
5209 (catch 'nextfile
5210 (org-check-agenda-file file)
5211 (setq date (calendar-gregorian-from-absolute today)
5212 rtn (org-agenda-get-day-entries
5213 file date :todo))
5214 (setq rtnall (append rtnall rtn))))
5215 (when rtnall
5216 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
5217 (add-text-properties (point-min) (1- (point))
5218 (list 'face 'org-level-3))
5219 (insert (org-finalize-agenda-entries rtnall) "\n")))
5220 (while (setq d (pop day-numbers))
5221 (setq date (calendar-gregorian-from-absolute d)
5222 s (point))
5223 (if (or (setq todayp (= d today))
5224 (and (not start-pos) (= d sd)))
5225 (setq start-pos (point))
5226 (if (and start-pos (not end-pos))
5227 (setq end-pos (point))))
5228 (setq files thefiles
5229 rtnall nil)
5230 (while (setq file (pop files))
5231 (catch 'nextfile
5232 (org-check-agenda-file file)
5233 (if org-agenda-show-log
5234 (setq rtn (org-agenda-get-day-entries
5235 file date
5236 :deadline :scheduled :timestamp :closed))
5237 (setq rtn (org-agenda-get-day-entries
5238 file date
5239 :deadline :scheduled :timestamp)))
5240 (setq rtnall (append rtnall rtn))))
5241 (if org-agenda-include-diary
5242 (progn
5243 (require 'diary-lib)
5244 (setq rtn (org-get-entries-from-diary date))
5245 (setq rtnall (append rtnall rtn))))
5246 (if (or rtnall org-agenda-show-all-dates)
5247 (progn
5248 (insert (format "%-9s %2d %s %4d\n"
5249 (calendar-day-name date)
5250 (extract-calendar-day date)
5251 (calendar-month-name (extract-calendar-month date))
5252 (extract-calendar-year date)))
5253 (put-text-property s (1- (point)) 'face
5254 'org-level-3)
5255 (if rtnall (insert
5256 (org-finalize-agenda-entries
5257 (org-agenda-add-time-grid-maybe
5258 rtnall nd todayp))
5259 "\n"))
5260 (put-text-property s (1- (point)) 'day d))))
5261 (goto-char (point-min))
5262 (setq buffer-read-only t)
5263 (org-fit-agenda-window)
5264 (unless (and (pos-visible-in-window-p (point-min))
5265 (pos-visible-in-window-p (point-max)))
5266 (goto-char (1- (point-max)))
5267 (recenter -1)
5268 (if (not (pos-visible-in-window-p (or start-pos 1)))
5269 (progn
5270 (goto-char (or start-pos 1))
5271 (recenter 1))))
5272 (goto-char (or start-pos 1))
5273 (if (not org-select-agenda-window) (select-window win))
5274 (message "")))
5275
5276 (defvar org-select-this-todo-keyword nil)
5277
5278 ;;;###autoload
5279 (defun org-todo-list (arg &optional keep-modes)
5280 "Show all TODO entries from all agenda file in a single list.
5281 The prefix arg can be used to select a specific TODO keyword and limit
5282 the list to these. When using \\[universal-argument], you will be prompted
5283 for a keyword. A numeric prefix directly selects the Nth keyword in
5284 `org-todo-keywords'."
5285 (interactive "P")
5286 (org-agenda-maybe-reset-markers 'force)
5287 (org-compile-prefix-format org-agenda-prefix-format)
5288 (let* ((org-agenda-keep-modes keep-modes)
5289 (today (time-to-days (current-time)))
5290 (date (calendar-gregorian-from-absolute today))
5291 (win (selected-window))
5292 (kwds org-todo-keywords)
5293 (completion-ignore-case t)
5294 (org-select-this-todo-keyword
5295 (if (stringp arg) arg
5296 (and arg (integerp arg) (nth (1- arg) org-todo-keywords))))
5297 rtn rtnall files file pos)
5298 (when (equal arg '(4))
5299 (setq org-select-this-todo-keyword
5300 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
5301 nil t)))
5302 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
5303 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5304 (progn
5305 (delete-other-windows)
5306 (switch-to-buffer-other-window
5307 (get-buffer-create org-agenda-buffer-name))))
5308 (setq buffer-read-only nil)
5309 (erase-buffer)
5310 (org-agenda-mode) (setq buffer-read-only nil)
5311 (set (make-local-variable 'org-agenda-type) 'todo)
5312 (set (make-local-variable 'last-arg) arg)
5313 (set (make-local-variable 'org-todo-keywords) kwds)
5314 (set (make-local-variable 'org-agenda-redo-command)
5315 '(org-todo-list (or current-prefix-arg last-arg) t))
5316 (setq files (org-agenda-files)
5317 rtnall nil)
5318 (while (setq file (pop files))
5319 (catch 'nextfile
5320 (org-check-agenda-file file)
5321 (setq rtn (org-agenda-get-day-entries file date :todo))
5322 (setq rtnall (append rtnall rtn))))
5323 (insert "Global list of TODO items of type: ")
5324 (add-text-properties (point-min) (1- (point))
5325 (list 'face 'org-level-3))
5326 (setq pos (point))
5327 (insert (or org-select-this-todo-keyword "ALL") "\n")
5328 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
5329 (setq pos (point))
5330 (insert
5331 "Available with `N r': (0)ALL "
5332 (let ((n 0))
5333 (mapconcat (lambda (x)
5334 (format "(%d)%s" (setq n (1+ n)) x))
5335 org-todo-keywords " "))
5336 "\n")
5337 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
5338 (when rtnall
5339 (insert (org-finalize-agenda-entries rtnall) "\n"))
5340 (goto-char (point-min))
5341 (setq buffer-read-only t)
5342 (org-fit-agenda-window)
5343 (if (not org-select-agenda-window) (select-window win))))
5344
5345 (defun org-check-agenda-file (file)
5346 "Make sure FILE exists. If not, ask user what to do."
5347 (when (not (file-exists-p file))
5348 (message "non-existent file %s. [R]emove from list or [A]bort?"
5349 (abbreviate-file-name file))
5350 (let ((r (downcase (read-char-exclusive))))
5351 (cond
5352 ((equal r ?r)
5353 (org-remove-file file)
5354 (throw 'nextfile t))
5355 (t (error "Abort"))))))
5356
5357 (defun org-agenda-check-type (error &rest types)
5358 "Check if agenda buffer is of allowed type.
5359 If ERROR is non-nil, throw an error, otherwise just return nil."
5360 (if (memq org-agenda-type types)
5361 t
5362 (if error
5363 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
5364 nil)))
5365
5366 (defun org-agenda-quit ()
5367 "Exit agenda by removing the window or the buffer."
5368 (interactive)
5369 (let ((buf (current-buffer)))
5370 (if (not (one-window-p)) (delete-window))
5371 (kill-buffer buf)
5372 (org-agenda-maybe-reset-markers 'force)))
5373
5374 (defun org-agenda-exit ()
5375 "Exit agenda by removing the window or the buffer.
5376 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
5377 Org-mode buffers visited directly by the user will not be touched."
5378 (interactive)
5379 (org-release-buffers org-agenda-new-buffers)
5380 (setq org-agenda-new-buffers nil)
5381 (org-agenda-quit))
5382
5383 (defun org-agenda-redo ()
5384 "Rebuild Agenda.
5385 When this is the global TODO list, a prefix argument will be interpreted."
5386 (interactive)
5387 (message "Rebuilding agenda buffer...")
5388 (eval org-agenda-redo-command)
5389 (message "Rebuilding agenda buffer...done"))
5390
5391 (defun org-agenda-goto-today ()
5392 "Go to today."
5393 (interactive)
5394 (org-agenda-check-type t 'timeline 'agenda)
5395 (if (boundp 'starting-day)
5396 (let ((cmd (car org-agenda-redo-command))
5397 (iall (nth 1 org-agenda-redo-command))
5398 (nday (nth 3 org-agenda-redo-command))
5399 (keep (nth 4 org-agenda-redo-command)))
5400 (eval (list cmd iall nil nday keep)))
5401 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5402 (point-min)))))
5403
5404 (defun org-agenda-later (arg)
5405 "Go forward in time by `org-agenda-ndays' days.
5406 With prefix ARG, go forward that many times `org-agenda-ndays'."
5407 (interactive "p")
5408 (org-agenda-check-type t 'agenda)
5409 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5410 (+ starting-day (* arg org-agenda-ndays)) nil t))
5411
5412 (defun org-agenda-earlier (arg)
5413 "Go back in time by `org-agenda-ndays' days.
5414 With prefix ARG, go back that many times `org-agenda-ndays'."
5415 (interactive "p")
5416 (org-agenda-check-type t 'agenda)
5417 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5418 (- starting-day (* arg org-agenda-ndays)) nil t))
5419
5420 (defun org-agenda-week-view ()
5421 "Switch to weekly view for agenda."
5422 (interactive)
5423 (org-agenda-check-type t 'agenda)
5424 (setq org-agenda-ndays 7)
5425 (org-agenda-list include-all-loc
5426 (or (get-text-property (point) 'day)
5427 starting-day)
5428 nil t)
5429 (org-agenda-set-mode-name)
5430 (message "Switched to week view"))
5431
5432 (defun org-agenda-day-view ()
5433 "Switch to daily view for agenda."
5434 (interactive)
5435 (org-agenda-check-type t 'agenda)
5436 (setq org-agenda-ndays 1)
5437 (org-agenda-list include-all-loc
5438 (or (get-text-property (point) 'day)
5439 starting-day)
5440 nil t)
5441 (org-agenda-set-mode-name)
5442 (message "Switched to day view"))
5443
5444 (defun org-agenda-next-date-line (&optional arg)
5445 "Jump to the next line indicating a date in agenda buffer."
5446 (interactive "p")
5447 (org-agenda-check-type t 'agenda 'timeline)
5448 (beginning-of-line 1)
5449 (if (looking-at "^\\S-") (forward-char 1))
5450 (if (not (re-search-forward "^\\S-" nil t arg))
5451 (progn
5452 (backward-char 1)
5453 (error "No next date after this line in this buffer")))
5454 (goto-char (match-beginning 0)))
5455
5456 (defun org-agenda-previous-date-line (&optional arg)
5457 "Jump to the previous line indicating a date in agenda buffer."
5458 (interactive "p")
5459 (org-agenda-check-type t 'agenda 'timeline)
5460 (beginning-of-line 1)
5461 (if (not (re-search-backward "^\\S-" nil t arg))
5462 (error "No previous date before this line in this buffer")))
5463
5464 ;; Initialize the highlight
5465 (defvar org-hl (org-make-overlay 1 1))
5466 (org-overlay-put org-hl 'face 'highlight)
5467
5468 (defun org-highlight (begin end &optional buffer)
5469 "Highlight a region with overlay."
5470 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
5471 org-hl begin end (or buffer (current-buffer))))
5472
5473 (defun org-unhighlight ()
5474 "Detach overlay INDEX."
5475 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
5476
5477
5478 (defun org-agenda-follow-mode ()
5479 "Toggle follow mode in an agenda buffer."
5480 (interactive)
5481 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5482 (org-agenda-set-mode-name)
5483 (message "Follow mode is %s"
5484 (if org-agenda-follow-mode "on" "off")))
5485
5486 (defun org-agenda-log-mode ()
5487 "Toggle log mode in an agenda buffer."
5488 (interactive)
5489 (org-agenda-check-type t 'agenda 'timeline)
5490 (setq org-agenda-show-log (not org-agenda-show-log))
5491 (org-agenda-set-mode-name)
5492 (org-agenda-redo)
5493 (message "Log mode is %s"
5494 (if org-agenda-show-log "on" "off")))
5495
5496 (defun org-agenda-toggle-diary ()
5497 "Toggle diary inclusion in an agenda buffer."
5498 (interactive)
5499 (org-agenda-check-type t 'agenda)
5500 (setq org-agenda-include-diary (not org-agenda-include-diary))
5501 (org-agenda-redo)
5502 (org-agenda-set-mode-name)
5503 (message "Diary inclusion turned %s"
5504 (if org-agenda-include-diary "on" "off")))
5505
5506 (defun org-agenda-toggle-time-grid ()
5507 "Toggle time grid in an agenda buffer."
5508 (interactive)
5509 (org-agenda-check-type t 'agenda)
5510 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5511 (org-agenda-redo)
5512 (org-agenda-set-mode-name)
5513 (message "Time-grid turned %s"
5514 (if org-agenda-use-time-grid "on" "off")))
5515
5516 (defun org-agenda-set-mode-name ()
5517 "Set the mode name to indicate all the small mode settings."
5518 (setq mode-name
5519 (concat "Org-Agenda"
5520 (if (equal org-agenda-ndays 1) " Day" "")
5521 (if (equal org-agenda-ndays 7) " Week" "")
5522 (if org-agenda-follow-mode " Follow" "")
5523 (if org-agenda-include-diary " Diary" "")
5524 (if org-agenda-use-time-grid " Grid" "")
5525 (if org-agenda-show-log " Log" "")))
5526 (force-mode-line-update))
5527
5528 (defun org-agenda-post-command-hook ()
5529 (and (eolp) (not (bolp)) (backward-char 1))
5530 (if (and org-agenda-follow-mode
5531 (get-text-property (point) 'org-marker))
5532 (org-agenda-show)))
5533
5534 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5535
5536 (defun org-get-entries-from-diary (date)
5537 "Get the (Emacs Calendar) diary entries for DATE."
5538 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5539 (diary-display-hook '(fancy-diary-display))
5540 (list-diary-entries-hook
5541 (cons 'org-diary-default-entry list-diary-entries-hook))
5542 (diary-file-name-prefix-function nil) ; turn this feature off
5543 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5544 entries
5545 (org-disable-agenda-to-diary t))
5546 (save-excursion
5547 (save-window-excursion
5548 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
5549 (if (not (get-buffer fancy-diary-buffer))
5550 (setq entries nil)
5551 (with-current-buffer fancy-diary-buffer
5552 (setq buffer-read-only nil)
5553 (if (= (point-max) 1)
5554 ;; No entries
5555 (setq entries nil)
5556 ;; Omit the date and other unnecessary stuff
5557 (org-agenda-cleanup-fancy-diary)
5558 ;; Add prefix to each line and extend the text properties
5559 (if (= (point-max) 1)
5560 (setq entries nil)
5561 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5562 (set-buffer-modified-p nil)
5563 (kill-buffer fancy-diary-buffer)))
5564 (when entries
5565 (setq entries (org-split-string entries "\n"))
5566 (setq entries
5567 (mapcar
5568 (lambda (x)
5569 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5570 ;; Extend the text properties to the beginning of the line
5571 (org-add-props x (text-properties-at (1- (length x)) x)))
5572 entries)))))
5573
5574 (defun org-agenda-cleanup-fancy-diary ()
5575 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5576 This gets rid of the date, the underline under the date, and
5577 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5578 date. It also removes lines that contain only whitespace."
5579 (goto-char (point-min))
5580 (if (looking-at ".*?:[ \t]*")
5581 (progn
5582 (replace-match "")
5583 (re-search-forward "\n=+$" nil t)
5584 (replace-match "")
5585 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5586 (re-search-forward "\n=+$" nil t)
5587 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5588 (goto-char (point-min))
5589 (while (re-search-forward "^ +\n" nil t)
5590 (replace-match ""))
5591 (goto-char (point-min))
5592 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5593 (replace-match "")))
5594
5595 ;; Make sure entries from the diary have the right text properties.
5596 (eval-after-load "diary-lib"
5597 '(if (boundp 'diary-modify-entry-list-string-function)
5598 ;; We can rely on the hook, nothing to do
5599 nil
5600 ;; Hook not avaiable, must use advice to make this work
5601 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5602 "Make the position visible."
5603 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5604 (stringp string)
5605 buffer-file-name)
5606 (setq string (org-modify-diary-entry-string string))))))
5607
5608 (defun org-modify-diary-entry-string (string)
5609 "Add text properties to string, allowing org-mode to act on it."
5610 (org-add-props string nil
5611 'mouse-face 'highlight
5612 'keymap org-agenda-keymap
5613 'help-echo (format "mouse-2 or RET jump to diary file %s"
5614 (abbreviate-file-name buffer-file-name))
5615 'org-agenda-diary-link t
5616 'org-marker (org-agenda-new-marker (point-at-bol))))
5617
5618 (defun org-diary-default-entry ()
5619 "Add a dummy entry to the diary.
5620 Needed to avoid empty dates which mess up holiday display."
5621 ;; Catch the error if dealing with the new add-to-diary-alist
5622 (when org-disable-agenda-to-diary
5623 (condition-case nil
5624 (add-to-diary-list original-date "Org-mode dummy" "")
5625 (error
5626 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5627
5628 (defun org-cycle-agenda-files ()
5629 "Cycle through the files in `org-agenda-files'.
5630 If the current buffer visits an agenda file, find the next one in the list.
5631 If the current buffer does not, find the first agenda file."
5632 (interactive)
5633 (let* ((fs (org-agenda-files t))
5634 (files (append fs (list (car fs))))
5635 (tcf (if buffer-file-name (file-truename buffer-file-name)))
5636 file)
5637 (unless files (error "No agenda files"))
5638 (catch 'exit
5639 (while (setq file (pop files))
5640 (if (equal (file-truename file) tcf)
5641 (when (car files)
5642 (find-file (car files))
5643 (throw 'exit t))))
5644 (find-file (car fs)))))
5645
5646 (defun org-agenda-file-to-end ()
5647 "Move/add the current file to the end of the agenda file list.
5648 If the file is not present in the list, it is appended to the list. If it is
5649 present, it is moved there."
5650 (interactive)
5651 (org-agenda-file-to-front 'to-end))
5652
5653 (defun org-agenda-file-to-front (&optional to-end)
5654 "Move/add the current file to the top of the agenda file list.
5655 If the file is not present in the list, it is added to the front. If it is
5656 present, it is moved there. With optional argument TO-END, add/move to the
5657 end of the list."
5658 (interactive "P")
5659 (let ((file-alist (mapcar (lambda (x)
5660 (cons (file-truename x) x))
5661 (org-agenda-files t)))
5662 (ctf (file-truename buffer-file-name))
5663 x had)
5664 (setq x (assoc ctf file-alist) had x)
5665
5666 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
5667 (if to-end
5668 (setq file-alist (append (delq x file-alist) (list x)))
5669 (setq file-alist (cons x (delq x file-alist))))
5670 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
5671 (org-install-agenda-files-menu)
5672 (message "File %s to %s of agenda file list"
5673 (if had "moved" "added") (if to-end "end" "front"))))
5674
5675 (defun org-remove-file (&optional file)
5676 "Remove current file from the list of files in variable `org-agenda-files'.
5677 These are the files which are being checked for agenda entries.
5678 Optional argument FILE means, use this file instead of the current."
5679 (interactive)
5680 (let* ((file (or file buffer-file-name))
5681 (true-file (file-truename file))
5682 (afile (abbreviate-file-name file))
5683 (files (delq nil (mapcar
5684 (lambda (x)
5685 (if (equal true-file
5686 (file-truename x))
5687 nil x))
5688 (org-agenda-files t)))))
5689 (if (not (= (length files) (length (org-agenda-files t))))
5690 (progn
5691 (org-store-new-agenda-file-list files)
5692 (org-install-agenda-files-menu)
5693 (message "Removed file: %s" afile))
5694 (message "File was not in list: %s" afile))))
5695
5696 (defun org-file-menu-entry (file)
5697 (vector file (list 'find-file file) t))
5698
5699 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5700 "Return a list of all relevant day numbers from BEG to END buffer positions.
5701 If NO-RANGES is non-nil, include only the start and end dates of a range,
5702 not every single day in the range. If FORCE-TODAY is non-nil, make
5703 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5704 inactive time stamps (those in square brackets) are included."
5705 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5706 dates date day day1 day2 ts1 ts2)
5707 (if force-today
5708 (setq dates (list (time-to-days (current-time)))))
5709 (save-excursion
5710 (goto-char beg)
5711 (while (re-search-forward re end t)
5712 (setq day (time-to-days (org-time-string-to-time
5713 (substring (match-string 1) 0 10))))
5714 (or (memq day dates) (push day dates)))
5715 (unless no-ranges
5716 (goto-char beg)
5717 (while (re-search-forward org-tr-regexp end t)
5718 (setq ts1 (substring (match-string 1) 0 10)
5719 ts2 (substring (match-string 2) 0 10)
5720 day1 (time-to-days (org-time-string-to-time ts1))
5721 day2 (time-to-days (org-time-string-to-time ts2)))
5722 (while (< (setq day1 (1+ day1)) day2)
5723 (or (memq day1 dates) (push day1 dates)))))
5724 (sort dates '<))))
5725
5726 ;;;###autoload
5727 (defun org-diary (&rest args)
5728 "Return diary information from org-files.
5729 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5730 It accesses org files and extracts information from those files to be
5731 listed in the diary. The function accepts arguments specifying what
5732 items should be listed. The following arguments are allowed:
5733
5734 :timestamp List the headlines of items containing a date stamp or
5735 date range matching the selected date. Deadlines will
5736 also be listed, on the expiration day.
5737
5738 :deadline List any deadlines past due, or due within
5739 `org-deadline-warning-days'. The listing occurs only
5740 in the diary for *today*, not at any other date. If
5741 an entry is marked DONE, it is no longer listed.
5742
5743 :scheduled List all items which are scheduled for the given date.
5744 The diary for *today* also contains items which were
5745 scheduled earlier and are not yet marked DONE.
5746
5747 :todo List all TODO items from the org-file. This may be a
5748 long list - so this is not turned on by default.
5749 Like deadlines, these entries only show up in the
5750 diary for *today*, not at any other date.
5751
5752 The call in the diary file should look like this:
5753
5754 &%%(org-diary) ~/path/to/some/orgfile.org
5755
5756 Use a separate line for each org file to check. Or, if you omit the file name,
5757 all files listed in `org-agenda-files' will be checked automatically:
5758
5759 &%%(org-diary)
5760
5761 If you don't give any arguments (as in the example above), the default
5762 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5763 also be written as
5764
5765 &%%(org-diary :deadline :timestamp :scheduled)
5766
5767 The function expects the lisp variables `entry' and `date' to be provided
5768 by the caller, because this is how the calendar works. Don't use this
5769 function from a program - use `org-agenda-get-day-entries' instead."
5770 (org-agenda-maybe-reset-markers)
5771 (org-compile-prefix-format org-agenda-prefix-format)
5772 (setq args (or args '(:deadline :scheduled :timestamp)))
5773 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5774 (list entry)
5775 (org-agenda-files t)))
5776 file rtn results)
5777 ;; If this is called during org-agenda, don't return any entries to
5778 ;; the calendar. Org Agenda will list these entries itself.
5779 (if org-disable-agenda-to-diary (setq files nil))
5780 (while (setq file (pop files))
5781 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5782 (setq results (append results rtn)))
5783 (if results
5784 (concat (org-finalize-agenda-entries results) "\n"))))
5785 (defvar org-category-table nil)
5786 (defun org-get-category-table ()
5787 "Get the table of categories and positions in current buffer."
5788 (let (tbl)
5789 (save-excursion
5790 (goto-char (point-min))
5791 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5792 (push (cons (point) (org-trim (match-string 2))) tbl)))
5793 tbl))
5794 (defun org-get-category (&optional pos)
5795 "Get the category applying to position POS."
5796 (if (not org-category-table)
5797 (cond
5798 ((null org-category)
5799 (setq org-category
5800 (if buffer-file-name
5801 (file-name-sans-extension
5802 (file-name-nondirectory buffer-file-name))
5803 "???")))
5804 ((symbolp org-category) (symbol-name org-category))
5805 (t org-category))
5806 (let ((tbl org-category-table)
5807 (pos (or pos (point))))
5808 (while (and tbl (> (caar tbl) pos))
5809 (pop tbl))
5810 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5811 org-category-table))))))
5812
5813 (defun org-agenda-get-day-entries (file date &rest args)
5814 "Does the work for `org-diary' and `org-agenda'.
5815 FILE is the path to a file to be checked for entries. DATE is date like
5816 the one returned by `calendar-current-date'. ARGS are symbols indicating
5817 which kind of entries should be extracted. For details about these, see
5818 the documentation of `org-diary'."
5819 (setq args (or args '(:deadline :scheduled :timestamp)))
5820 (let* ((org-startup-with-deadline-check nil)
5821 (org-startup-folded nil)
5822 (org-startup-align-all-tables nil)
5823 (buffer (if (file-exists-p file)
5824 (org-get-agenda-file-buffer file)
5825 (error "No such file %s" file)))
5826 arg results rtn)
5827 (if (not buffer)
5828 ;; If file does not exist, make sure an error message ends up in diary
5829 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5830 (with-current-buffer buffer
5831 (unless (eq major-mode 'org-mode)
5832 (error "Agenda file %s is not in `org-mode'" file))
5833 (setq org-category-table (org-get-category-table))
5834 (let ((case-fold-search nil))
5835 (save-excursion
5836 (save-restriction
5837 (if org-respect-restriction
5838 (if (org-region-active-p)
5839 ;; Respect a region to restrict search
5840 (narrow-to-region (region-beginning) (region-end)))
5841 ;; If we work for the calendar or many files,
5842 ;; get rid of any restriction
5843 (widen))
5844 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5845 (while (setq arg (pop args))
5846 (cond
5847 ((and (eq arg :todo)
5848 (equal date (calendar-current-date)))
5849 (setq rtn (org-agenda-get-todos))
5850 (setq results (append results rtn)))
5851 ((eq arg :timestamp)
5852 (setq rtn (org-agenda-get-blocks))
5853 (setq results (append results rtn))
5854 (setq rtn (org-agenda-get-timestamps))
5855 (setq results (append results rtn)))
5856 ((eq arg :scheduled)
5857 (setq rtn (org-agenda-get-scheduled))
5858 (setq results (append results rtn)))
5859 ((eq arg :closed)
5860 (setq rtn (org-agenda-get-closed))
5861 (setq results (append results rtn)))
5862 ((and (eq arg :deadline)
5863 (equal date (calendar-current-date)))
5864 (setq rtn (org-agenda-get-deadlines))
5865 (setq results (append results rtn))))))))
5866 results))))
5867
5868 (defun org-entry-is-done-p ()
5869 "Is the current entry marked DONE?"
5870 (save-excursion
5871 (and (re-search-backward "[\r\n]\\*" nil t)
5872 (looking-at org-nl-done-regexp))))
5873
5874 (defun org-at-date-range-p ()
5875 "Is the cursor inside a date range?"
5876 (interactive)
5877 (save-excursion
5878 (catch 'exit
5879 (let ((pos (point)))
5880 (skip-chars-backward "^<\r\n")
5881 (skip-chars-backward "<")
5882 (and (looking-at org-tr-regexp)
5883 (>= (match-end 0) pos)
5884 (throw 'exit t))
5885 (skip-chars-backward "^<\r\n")
5886 (skip-chars-backward "<")
5887 (and (looking-at org-tr-regexp)
5888 (>= (match-end 0) pos)
5889 (throw 'exit t)))
5890 nil)))
5891
5892 (defun org-agenda-get-todos ()
5893 "Return the TODO information for agenda display."
5894 (let* ((props (list 'face nil
5895 'done-face 'org-done
5896 'mouse-face 'highlight
5897 'keymap org-agenda-keymap
5898 'help-echo
5899 (format "mouse-2 or RET jump to org file %s"
5900 (abbreviate-file-name buffer-file-name))))
5901 (regexp (concat "[\n\r]\\*+ *\\("
5902 (if org-select-this-todo-keyword
5903 (concat "\\<\\(" org-select-this-todo-keyword
5904 "\\)\\>")
5905 org-not-done-regexp)
5906 "[^\n\r]*\\)"))
5907 marker priority category tags
5908 ee txt)
5909 (goto-char (point-min))
5910 (while (re-search-forward regexp nil t)
5911 (goto-char (match-beginning 1))
5912 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5913 category (org-get-category)
5914 tags (org-get-tags-at (point))
5915 txt (org-format-agenda-item "" (match-string 1) category tags)
5916 priority
5917 (+ (org-get-priority txt)
5918 (if org-todo-kwd-priority-p
5919 (- org-todo-kwd-max-priority -2
5920 (length
5921 (member (match-string 2) org-todo-keywords)))
5922 1)))
5923 (org-add-props txt props
5924 'org-marker marker 'org-hd-marker marker
5925 'priority priority 'category category)
5926 (push txt ee)
5927 (goto-char (match-end 1)))
5928 (nreverse ee)))
5929
5930 (defconst org-agenda-no-heading-message
5931 "No heading for this item in buffer or region.")
5932
5933 (defun org-agenda-get-timestamps ()
5934 "Return the date stamp information for agenda display."
5935 (let* ((props (list 'face nil
5936 'mouse-face 'highlight
5937 'keymap org-agenda-keymap
5938 'help-echo
5939 (format "mouse-2 or RET jump to org file %s"
5940 (abbreviate-file-name buffer-file-name))))
5941 (regexp (regexp-quote
5942 (substring
5943 (format-time-string
5944 (car org-time-stamp-formats)
5945 (apply 'encode-time ; DATE bound by calendar
5946 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
5947 0 11)))
5948 marker hdmarker deadlinep scheduledp donep tmp priority category
5949 ee txt timestr tags)
5950 (goto-char (point-min))
5951 (while (re-search-forward regexp nil t)
5952 (if (not (save-match-data (org-at-date-range-p)))
5953 (progn
5954 (setq marker (org-agenda-new-marker (match-beginning 0))
5955 category (org-get-category (match-beginning 0))
5956 tmp (buffer-substring (max (point-min)
5957 (- (match-beginning 0)
5958 org-ds-keyword-length))
5959 (match-beginning 0))
5960 timestr (buffer-substring (match-beginning 0) (point-at-eol))
5961 deadlinep (string-match org-deadline-regexp tmp)
5962 scheduledp (string-match org-scheduled-regexp tmp)
5963 donep (org-entry-is-done-p))
5964 (if (string-match ">" timestr)
5965 ;; substring should only run to end of time stamp
5966 (setq timestr (substring timestr 0 (match-end 0))))
5967 (save-excursion
5968 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
5969 (progn
5970 (goto-char (match-end 1))
5971 (setq hdmarker (org-agenda-new-marker)
5972 tags (org-get-tags-at))
5973 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
5974 (setq txt (org-format-agenda-item
5975 (format "%s%s"
5976 (if deadlinep "Deadline: " "")
5977 (if scheduledp "Scheduled: " ""))
5978 (match-string 1) category tags timestr)))
5979 (setq txt org-agenda-no-heading-message))
5980 (setq priority (org-get-priority txt))
5981 (org-add-props txt props
5982 'org-marker marker 'org-hd-marker hdmarker)
5983 (if deadlinep
5984 (org-add-props txt nil
5985 'face (if donep 'org-done 'org-warning)
5986 'undone-face 'org-warning 'done-face 'org-done
5987 'category category 'priority (+ 100 priority))
5988 (if scheduledp
5989 (org-add-props txt nil
5990 'face 'org-scheduled-today
5991 'undone-face 'org-scheduled-today 'done-face 'org-done
5992 'category category 'priority (+ 99 priority))
5993 (org-add-props txt nil 'priority priority 'category category)))
5994 (push txt ee))
5995 (outline-next-heading))))
5996 (nreverse ee)))
5997
5998 (defun org-agenda-get-closed ()
5999 "Return the logged TODO entries for agenda display."
6000 (let* ((props (list 'mouse-face 'highlight
6001 'keymap org-agenda-keymap
6002 'help-echo
6003 (format "mouse-2 or RET jump to org file %s"
6004 (abbreviate-file-name buffer-file-name))))
6005 (regexp (concat
6006 "\\<" org-closed-string " *\\["
6007 (regexp-quote
6008 (substring
6009 (format-time-string
6010 (car org-time-stamp-formats)
6011 (apply 'encode-time ; DATE bound by calendar
6012 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6013 1 11))))
6014 marker hdmarker priority category tags
6015 ee txt timestr)
6016 (goto-char (point-min))
6017 (while (re-search-forward regexp nil t)
6018 (if (not (save-match-data (org-at-date-range-p)))
6019 (progn
6020 (setq marker (org-agenda-new-marker (match-beginning 0))
6021 category (org-get-category (match-beginning 0))
6022 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6023 ;; donep (org-entry-is-done-p)
6024 )
6025 (if (string-match "\\]" timestr)
6026 ;; substring should only run to end of time stamp
6027 (setq timestr (substring timestr 0 (match-end 0))))
6028 (save-excursion
6029 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6030 (progn
6031 (goto-char (match-end 1))
6032 (setq hdmarker (org-agenda-new-marker)
6033 tags (org-get-tags-at))
6034 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6035 (setq txt (org-format-agenda-item
6036 "Closed: "
6037 (match-string 1) category tags timestr)))
6038 (setq txt org-agenda-no-heading-message))
6039 (setq priority 100000)
6040 (org-add-props txt props
6041 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
6042 'priority priority 'category category
6043 'undone-face 'org-warning 'done-face 'org-done)
6044 (push txt ee))
6045 (outline-next-heading))))
6046 (nreverse ee)))
6047
6048 (defun org-agenda-get-deadlines ()
6049 "Return the deadline information for agenda display."
6050 (let* ((wdays org-deadline-warning-days)
6051 (props (list 'mouse-face 'highlight
6052 'keymap org-agenda-keymap
6053 'help-echo
6054 (format "mouse-2 or RET jump to org file %s"
6055 (abbreviate-file-name buffer-file-name))))
6056 (regexp org-deadline-time-regexp)
6057 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6058 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6059 d2 diff pos pos1 category tags
6060 ee txt head)
6061 (goto-char (point-min))
6062 (while (re-search-forward regexp nil t)
6063 (setq pos (1- (match-beginning 1))
6064 d2 (time-to-days
6065 (org-time-string-to-time (match-string 1)))
6066 diff (- d2 d1))
6067 ;; When to show a deadline in the calendar:
6068 ;; If the expiration is within wdays warning time.
6069 ;; Past-due deadlines are only shown on the current date
6070 (if (and (< diff wdays) todayp (not (= diff 0)))
6071 (save-excursion
6072 (setq category (org-get-category))
6073 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6074 (progn
6075 (goto-char (match-end 0))
6076 (setq pos1 (match-end 1))
6077 (setq tags (org-get-tags-at pos1))
6078 (setq head (buffer-substring-no-properties
6079 (point)
6080 (progn (skip-chars-forward "^\r\n")
6081 (point))))
6082 (if (string-match org-looking-at-done-regexp head)
6083 (setq txt nil)
6084 (setq txt (org-format-agenda-item
6085 (format "In %3d d.: " diff) head category tags))))
6086 (setq txt org-agenda-no-heading-message))
6087 (when txt
6088 (org-add-props txt props
6089 'org-marker (org-agenda-new-marker pos)
6090 'org-hd-marker (org-agenda-new-marker pos1)
6091 'priority (+ (- 10 diff) (org-get-priority txt))
6092 'category category
6093 'face (cond ((<= diff 0) 'org-warning)
6094 ((<= diff 5) 'org-scheduled-previously)
6095 (t nil))
6096 'undone-face (cond
6097 ((<= diff 0) 'org-warning)
6098 ((<= diff 5) 'org-scheduled-previously)
6099 (t nil))
6100 'done-face 'org-done)
6101 (push txt ee)))))
6102 ee))
6103
6104 (defun org-agenda-get-scheduled ()
6105 "Return the scheduled information for agenda display."
6106 (let* ((props (list 'face 'org-scheduled-previously
6107 'undone-face 'org-scheduled-previously
6108 'done-face 'org-done
6109 'mouse-face 'highlight
6110 'keymap org-agenda-keymap
6111 'help-echo
6112 (format "mouse-2 or RET jump to org file %s"
6113 (abbreviate-file-name buffer-file-name))))
6114 (regexp org-scheduled-time-regexp)
6115 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6116 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6117 d2 diff pos pos1 category tags
6118 ee txt head)
6119 (goto-char (point-min))
6120 (while (re-search-forward regexp nil t)
6121 (setq pos (1- (match-beginning 1))
6122 d2 (time-to-days
6123 (org-time-string-to-time (match-string 1)))
6124 diff (- d2 d1))
6125 ;; When to show a scheduled item in the calendar:
6126 ;; If it is on or past the date.
6127 (if (and (< diff 0) todayp)
6128 (save-excursion
6129 (setq category (org-get-category))
6130 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6131 (progn
6132 (goto-char (match-end 0))
6133 (setq pos1 (match-end 1))
6134 (setq tags (org-get-tags-at))
6135 (setq head (buffer-substring-no-properties
6136 (point)
6137 (progn (skip-chars-forward "^\r\n") (point))))
6138 (if (string-match org-looking-at-done-regexp head)
6139 (setq txt nil)
6140 (setq txt (org-format-agenda-item
6141 (format "Sched.%2dx: " (- 1 diff)) head
6142 category tags))))
6143 (setq txt org-agenda-no-heading-message))
6144 (when txt
6145 (org-add-props txt props
6146 'org-marker (org-agenda-new-marker pos)
6147 'org-hd-marker (org-agenda-new-marker pos1)
6148 'priority (+ (- 5 diff) (org-get-priority txt))
6149 'category category)
6150 (push txt ee)))))
6151 ee))
6152
6153 (defun org-agenda-get-blocks ()
6154 "Return the date-range information for agenda display."
6155 (let* ((props (list 'face nil
6156 'mouse-face 'highlight
6157 'keymap org-agenda-keymap
6158 'help-echo
6159 (format "mouse-2 or RET jump to org file %s"
6160 (abbreviate-file-name buffer-file-name))))
6161 (regexp org-tr-regexp)
6162 (d0 (calendar-absolute-from-gregorian date))
6163 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
6164 (goto-char (point-min))
6165 (while (re-search-forward regexp nil t)
6166 (setq timestr (match-string 0)
6167 s1 (match-string 1)
6168 s2 (match-string 2)
6169 d1 (time-to-days (org-time-string-to-time s1))
6170 d2 (time-to-days (org-time-string-to-time s2)))
6171 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
6172 ;; Only allow days between the limits, because the normal
6173 ;; date stamps will catch the limits.
6174 (save-excursion
6175 (setq marker (org-agenda-new-marker (point)))
6176 (setq category (org-get-category))
6177 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6178 (progn
6179 (setq hdmarker (org-agenda-new-marker (match-end 1)))
6180 (goto-char (match-end 1))
6181 (setq tags (org-get-tags-at))
6182 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6183 (setq txt (org-format-agenda-item
6184 (format (if (= d1 d2) "" "(%d/%d): ")
6185 (1+ (- d0 d1)) (1+ (- d2 d1)))
6186 (match-string 1) category tags
6187 (if (= d0 d1) timestr))))
6188 (setq txt org-agenda-no-heading-message))
6189 (org-add-props txt props
6190 'org-marker marker 'org-hd-marker hdmarker
6191 'priority (org-get-priority txt) 'category category)
6192 (push txt ee)))
6193 (outline-next-heading))
6194 ;; Sort the entries by expiration date.
6195 (nreverse ee)))
6196
6197 (defconst org-plain-time-of-day-regexp
6198 (concat
6199 "\\(\\<[012]?[0-9]"
6200 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6201 "\\(--?"
6202 "\\(\\<[012]?[0-9]"
6203 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6204 "\\)?")
6205 "Regular expression to match a plain time or time range.
6206 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
6207 groups carry important information:
6208 0 the full match
6209 1 the first time, range or not
6210 8 the second time, if it is a range.")
6211
6212 (defconst org-stamp-time-of-day-regexp
6213 (concat
6214 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
6215 "\\([012][0-9]:[0-5][0-9]\\)>"
6216 "\\(--?"
6217 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
6218 "Regular expression to match a timestamp time or time range.
6219 After a match, the following groups carry important information:
6220 0 the full match
6221 1 date plus weekday, for backreferencing to make sure both times on same day
6222 2 the first time, range or not
6223 4 the second time, if it is a range.")
6224
6225 (defvar org-prefix-has-time nil
6226 "A flag, set by `org-compile-prefix-format'.
6227 The flag is set if the currently compiled format contains a `%t'.")
6228 (defvar org-prefix-has-tag nil
6229 "A flag, set by `org-compile-prefix-format'.
6230 The flag is set if the currently compiled format contains a `%T'.")
6231
6232 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
6233 "Format TXT to be inserted into the agenda buffer.
6234 In particular, it adds the prefix and corresponding text properties. EXTRA
6235 must be a string and replaces the `%s' specifier in the prefix format.
6236 CATEGORY (string, symbol or nil) may be used to overrule the default
6237 category taken from local variable or file name. It will replace the `%c'
6238 specifier in the format. DOTIME, when non-nil, indicates that a
6239 time-of-day should be extracted from TXT for sorting of this entry, and for
6240 the `%t' specifier in the format. When DOTIME is a string, this string is
6241 searched for a time before TXT is. NOPREFIX is a flag and indicates that
6242 only the correctly processes TXT should be returned - this is used by
6243 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
6244 (save-match-data
6245 ;; Diary entries sometimes have extra whitespace at the beginning
6246 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
6247 (let* ((category (or category
6248 org-category
6249 (if buffer-file-name
6250 (file-name-sans-extension
6251 (file-name-nondirectory buffer-file-name))
6252 "")))
6253 (tag (if tags (nth (1- (length tags)) tags) ""))
6254 ;;(tag (or (nth (1- (or (length tags) 0)) tags) "")) FIXME: rm
6255 time ;; needed for the eval of the prefix format
6256 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
6257 (time-of-day (and dotime (org-get-time-of-day ts)))
6258 stamp plain s0 s1 s2 rtn)
6259 (when (and dotime time-of-day org-prefix-has-time)
6260 ;; Extract starting and ending time and move them to prefix
6261 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
6262 (setq plain (string-match org-plain-time-of-day-regexp ts)))
6263 (setq s0 (match-string 0 ts)
6264 s1 (match-string (if plain 1 2) ts)
6265 s2 (match-string (if plain 8 4) ts))
6266
6267 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
6268 ;; them, we might want to remove them there to avoid duplication.
6269 ;; The user can turn this off with a variable.
6270 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
6271 (string-match (concat (regexp-quote s0) " *") txt)
6272 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
6273 (= (match-beginning 0) 0)
6274 t))
6275 (setq txt (replace-match "" nil nil txt))))
6276 ;; Normalize the time(s) to 24 hour
6277 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
6278 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
6279
6280 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
6281 (and org-agenda-remove-tags-when-in-prefix
6282 org-prefix-has-tag))
6283 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
6284 (setq txt (replace-match "" t t txt)))
6285
6286 ;; Create the final string
6287 (if noprefix
6288 (setq rtn txt)
6289 ;; Prepare the variables needed in the eval of the compiled format
6290 (setq time (cond (s2 (concat s1 "-" s2))
6291 (s1 (concat s1 "......"))
6292 (t ""))
6293 extra (or extra "")
6294 category (if (symbolp category) (symbol-name category) category))
6295 ;; Evaluate the compiled format
6296 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
6297
6298 ;; And finally add the text properties
6299 (org-add-props rtn nil
6300 'category (downcase category) 'tags tags
6301 'prefix-length (- (length rtn) (length txt))
6302 'time-of-day time-of-day
6303 'dotime dotime))))
6304
6305 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
6306 (catch 'exit
6307 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
6308 ((and todayp (member 'today (car org-agenda-time-grid))))
6309 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
6310 ((member 'weekly (car org-agenda-time-grid)))
6311 (t (throw 'exit list)))
6312 (let* ((have (delq nil (mapcar
6313 (lambda (x) (get-text-property 1 'time-of-day x))
6314 list)))
6315 (string (nth 1 org-agenda-time-grid))
6316 (gridtimes (nth 2 org-agenda-time-grid))
6317 (req (car org-agenda-time-grid))
6318 (remove (member 'remove-match req))
6319 new time)
6320 (if (and (member 'require-timed req) (not have))
6321 ;; don't show empty grid
6322 (throw 'exit list))
6323 (while (setq time (pop gridtimes))
6324 (unless (and remove (member time have))
6325 (setq time (int-to-string time))
6326 (push (org-format-agenda-item
6327 nil string "" nil
6328 (concat (substring time 0 -2) ":" (substring time -2)))
6329 new)
6330 (put-text-property
6331 1 (length (car new)) 'face 'org-time-grid (car new))))
6332 (if (member 'time-up org-agenda-sorting-strategy)
6333 (append new list)
6334 (append list new)))))
6335
6336 (defun org-compile-prefix-format (format)
6337 "Compile the prefix format into a Lisp form that can be evaluated.
6338 The resulting form is returned and stored in the variable
6339 `org-prefix-format-compiled'."
6340 (setq org-prefix-has-time nil org-prefix-has-tag nil)
6341 (let ((start 0) varform vars var (s format)e c f opt)
6342 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
6343 s start)
6344 (setq var (cdr (assoc (match-string 4 s)
6345 '(("c" . category) ("t" . time) ("s" . extra)
6346 ("T" . tag))))
6347 c (or (match-string 3 s) "")
6348 opt (match-beginning 1)
6349 start (1+ (match-beginning 0)))
6350 (if (equal var 'time) (setq org-prefix-has-time t))
6351 (if (equal var 'tag) (setq org-prefix-has-tag t))
6352 (setq f (concat "%" (match-string 2 s) "s"))
6353 (if opt
6354 (setq varform
6355 `(if (equal "" ,var)
6356 ""
6357 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
6358 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
6359 (setq s (replace-match "%s" t nil s))
6360 (push varform vars))
6361 (setq vars (nreverse vars))
6362 (setq org-prefix-format-compiled `(format ,s ,@vars))))
6363
6364 (defun org-get-time-of-day (s &optional string)
6365 "Check string S for a time of day.
6366 If found, return it as a military time number between 0 and 2400.
6367 If not found, return nil.
6368 The optional STRING argument forces conversion into a 5 character wide string
6369 HH:MM."
6370 (save-match-data
6371 (when
6372 (or
6373 (string-match
6374 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
6375 (string-match
6376 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
6377 (let* ((t0 (+ (* 100
6378 (+ (string-to-number (match-string 1 s))
6379 (if (and (match-beginning 4)
6380 (equal (downcase (match-string 4 s)) "pm"))
6381 12 0)))
6382 (if (match-beginning 3)
6383 (string-to-number (match-string 3 s))
6384 0)))
6385 (t1 (concat " "
6386 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6387 (int-to-string t0))))
6388 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6389
6390 (defun org-finalize-agenda-entries (list)
6391 "Sort and concatenate the agenda items."
6392 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6393
6394 (defsubst org-cmp-priority (a b)
6395 "Compare the priorities of string A and B."
6396 (let ((pa (or (get-text-property 1 'priority a) 0))
6397 (pb (or (get-text-property 1 'priority b) 0)))
6398 (cond ((> pa pb) +1)
6399 ((< pa pb) -1)
6400 (t nil))))
6401
6402 (defsubst org-cmp-category (a b)
6403 "Compare the string values of categories of strings A and B."
6404 (let ((ca (or (get-text-property 1 'category a) ""))
6405 (cb (or (get-text-property 1 'category b) "")))
6406 (cond ((string-lessp ca cb) -1)
6407 ((string-lessp cb ca) +1)
6408 (t nil))))
6409
6410 (defsubst org-cmp-time (a b)
6411 "Compare the time-of-day values of strings A and B."
6412 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6413 (ta (or (get-text-property 1 'time-of-day a) def))
6414 (tb (or (get-text-property 1 'time-of-day b) def)))
6415 (cond ((< ta tb) -1)
6416 ((< tb ta) +1)
6417 (t nil))))
6418
6419 (defun org-entries-lessp (a b)
6420 "Predicate for sorting agenda entries."
6421 ;; The following variables will be used when the form is evaluated.
6422 (let* ((time-up (org-cmp-time a b))
6423 (time-down (if time-up (- time-up) nil))
6424 (priority-up (org-cmp-priority a b))
6425 (priority-down (if priority-up (- priority-up) nil))
6426 (category-up (org-cmp-category a b))
6427 (category-down (if category-up (- category-up) nil))
6428 (category-keep (if category-up +1 nil)))
6429 (cdr (assoc
6430 (eval (cons 'or org-agenda-sorting-strategy))
6431 '((-1 . t) (1 . nil) (nil . nil))))))
6432
6433 (defun org-agenda-show-priority ()
6434 "Show the priority of the current item.
6435 This priority is composed of the main priority given with the [#A] cookies,
6436 and by additional input from the age of a schedules or deadline entry."
6437 (interactive)
6438 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6439 (message "Priority is %d" (if pri pri -1000))))
6440
6441 (defun org-agenda-show-tags ()
6442 "Show the tags applicable to the current item."
6443 (interactive)
6444 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6445 (if tags
6446 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6447 (message "No tags associated with this line"))))
6448
6449 (defun org-agenda-goto (&optional highlight)
6450 "Go to the Org-mode file which contains the item at point."
6451 (interactive)
6452 (let* ((marker (or (get-text-property (point) 'org-marker)
6453 (org-agenda-error)))
6454 (buffer (marker-buffer marker))
6455 (pos (marker-position marker)))
6456 (switch-to-buffer-other-window buffer)
6457 (widen)
6458 (goto-char pos)
6459 (when (eq major-mode 'org-mode)
6460 (org-show-hidden-entry)
6461 (save-excursion
6462 (and (outline-next-heading)
6463 (org-flag-heading nil)))) ; show the next heading
6464 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6465
6466 (defun org-agenda-switch-to ()
6467 "Go to the Org-mode file which contains the item at point."
6468 (interactive)
6469 (let* ((marker (or (get-text-property (point) 'org-marker)
6470 (org-agenda-error)))
6471 (buffer (marker-buffer marker))
6472 (pos (marker-position marker)))
6473 (switch-to-buffer buffer)
6474 (delete-other-windows)
6475 (widen)
6476 (goto-char pos)
6477 (when (eq major-mode 'org-mode)
6478 (org-show-hidden-entry)
6479 (save-excursion
6480 (and (outline-next-heading)
6481 (org-flag-heading nil)))))) ; show the next heading
6482
6483 (defun org-agenda-goto-mouse (ev)
6484 "Go to the Org-mode file which contains the item at the mouse click."
6485 (interactive "e")
6486 (mouse-set-point ev)
6487 (org-agenda-goto))
6488
6489 (defun org-agenda-show ()
6490 "Display the Org-mode file which contains the item at point."
6491 (interactive)
6492 (let ((win (selected-window)))
6493 (org-agenda-goto t)
6494 (select-window win)))
6495
6496 (defun org-agenda-recenter (arg)
6497 "Display the Org-mode file which contains the item at point and recenter."
6498 (interactive "P")
6499 (let ((win (selected-window)))
6500 (org-agenda-goto t)
6501 (recenter arg)
6502 (select-window win)))
6503
6504 (defun org-agenda-show-mouse (ev)
6505 "Display the Org-mode file which contains the item at the mouse click."
6506 (interactive "e")
6507 (mouse-set-point ev)
6508 (org-agenda-show))
6509
6510 (defun org-agenda-check-no-diary ()
6511 "Check if the entry is a diary link and abort if yes."
6512 (if (get-text-property (point) 'org-agenda-diary-link)
6513 (org-agenda-error)))
6514
6515 (defun org-agenda-error ()
6516 (error "Command not allowed in this line"))
6517
6518 (defvar org-last-heading-marker (make-marker)
6519 "Marker pointing to the headline that last changed its TODO state
6520 by a remote command from the agenda.")
6521
6522 (defun org-agenda-todo (&optional arg)
6523 "Cycle TODO state of line at point, also in Org-mode file.
6524 This changes the line at point, all other lines in the agenda referring to
6525 the same tree node, and the headline of the tree node in the Org-mode file."
6526 (interactive "P")
6527 (org-agenda-check-no-diary)
6528 (let* ((col (current-column))
6529 (marker (or (get-text-property (point) 'org-marker)
6530 (org-agenda-error)))
6531 (buffer (marker-buffer marker))
6532 (pos (marker-position marker))
6533 (hdmarker (get-text-property (point) 'org-hd-marker))
6534 (buffer-read-only nil)
6535 newhead)
6536 (with-current-buffer buffer
6537 (widen)
6538 (goto-char pos)
6539 (org-show-hidden-entry)
6540 (save-excursion
6541 (and (outline-next-heading)
6542 (org-flag-heading nil))) ; show the next heading
6543 (org-todo arg)
6544 (forward-char 1)
6545 (setq newhead (org-get-heading))
6546 (save-excursion
6547 (org-back-to-heading)
6548 (move-marker org-last-heading-marker (point))))
6549 (beginning-of-line 1)
6550 (save-excursion
6551 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6552 (move-to-column col)))
6553
6554 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6555 "Change all lines in the agenda buffer which match HDMARKER.
6556 The new content of the line will be NEWHEAD (as modified by
6557 `org-format-agenda-item'). HDMARKER is checked with
6558 `equal' against all `org-hd-marker' text properties in the file.
6559 If FIXFACE is non-nil, the face of each item is modified acording to
6560 the new TODO state."
6561 (let* (props m pl undone-face done-face finish new dotime cat tags)
6562 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6563 (save-excursion
6564 (goto-char (point-max))
6565 (beginning-of-line 1)
6566 (while (not finish)
6567 (setq finish (bobp))
6568 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6569 (equal m hdmarker))
6570 (setq props (text-properties-at (point))
6571 dotime (get-text-property (point) 'dotime)
6572 cat (get-text-property (point) 'category)
6573 tags (get-text-property (point) 'tags)
6574 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6575 pl (get-text-property (point) 'prefix-length)
6576 undone-face (get-text-property (point) 'undone-face)
6577 done-face (get-text-property (point) 'done-face))
6578 (move-to-column pl)
6579 (if (looking-at ".*")
6580 (progn
6581 (replace-match new t t)
6582 (beginning-of-line 1)
6583 (add-text-properties (point-at-bol) (point-at-eol) props)
6584 (if fixface
6585 (add-text-properties
6586 (point-at-bol) (point-at-eol)
6587 (list 'face
6588 (if org-last-todo-state-is-todo
6589 undone-face done-face))))
6590 (beginning-of-line 1))
6591 (error "Line update did not work")))
6592 (beginning-of-line 0)))))
6593
6594 (defun org-agenda-priority-up ()
6595 "Increase the priority of line at point, also in Org-mode file."
6596 (interactive)
6597 (org-agenda-priority 'up))
6598
6599 (defun org-agenda-priority-down ()
6600 "Decrease the priority of line at point, also in Org-mode file."
6601 (interactive)
6602 (org-agenda-priority 'down))
6603
6604 (defun org-agenda-priority (&optional force-direction)
6605 "Set the priority of line at point, also in Org-mode file.
6606 This changes the line at point, all other lines in the agenda referring to
6607 the same tree node, and the headline of the tree node in the Org-mode file."
6608 (interactive)
6609 (org-agenda-check-no-diary)
6610 (let* ((marker (or (get-text-property (point) 'org-marker)
6611 (org-agenda-error)))
6612 (buffer (marker-buffer marker))
6613 (pos (marker-position marker))
6614 (hdmarker (get-text-property (point) 'org-hd-marker))
6615 (buffer-read-only nil)
6616 newhead)
6617 (with-current-buffer buffer
6618 (widen)
6619 (goto-char pos)
6620 (org-show-hidden-entry)
6621 (save-excursion
6622 (and (outline-next-heading)
6623 (org-flag-heading nil))) ; show the next heading
6624 (funcall 'org-priority force-direction)
6625 (end-of-line 1)
6626 (setq newhead (org-get-heading)))
6627 (org-agenda-change-all-lines newhead hdmarker)
6628 (beginning-of-line 1)))
6629
6630 (defun org-get-tags-at (&optional pos)
6631 "Get a list of all headline targs applicable at POS.
6632 POS defaults to point. If tags are inherited, the list contains
6633 the targets in the same sequence as the headlines appear, i.e.
6634 the tags of the current headline come last."
6635 (interactive)
6636 (let (tags)
6637 (save-excursion
6638 (goto-char (or pos (point)))
6639 (save-match-data
6640 (org-back-to-heading t)
6641 (condition-case nil
6642 (while t
6643 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6644 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6645 (or org-use-tag-inheritance (error ""))
6646 (org-up-heading-all 1))
6647 (error nil))))
6648 (message "%s" tags)
6649 tags))
6650
6651 (defun org-agenda-set-tags ()
6652 "Set tags for the current headline."
6653 (interactive)
6654 (org-agenda-check-no-diary)
6655 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6656 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6657 (org-agenda-error)))
6658 (buffer (marker-buffer hdmarker))
6659 (pos (marker-position hdmarker))
6660 (buffer-read-only nil)
6661 newhead)
6662 (with-current-buffer buffer
6663 (widen)
6664 (goto-char pos)
6665 (org-show-hidden-entry)
6666 (save-excursion
6667 (and (outline-next-heading)
6668 (org-flag-heading nil))) ; show the next heading
6669 (call-interactively 'org-set-tags)
6670 (end-of-line 1)
6671 (setq newhead (org-get-heading)))
6672 (org-agenda-change-all-lines newhead hdmarker)
6673 (beginning-of-line 1)))
6674
6675 (defun org-agenda-date-later (arg &optional what)
6676 "Change the date of this item to one day later."
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-timestamp-change arg (or what 'day))
6690 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6691
6692 (defun org-agenda-date-earlier (arg &optional what)
6693 "Change the date of this item to one day earlier."
6694 (interactive "p")
6695 (org-agenda-date-later (- arg) what))
6696
6697 (defun org-agenda-date-prompt (arg)
6698 "Change the date of this item. Date is prompted for, with default today.
6699 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6700 be used to request time specification in the time stamp."
6701 (interactive "P")
6702 (org-agenda-check-type t 'agenda 'timeline)
6703 (org-agenda-check-no-diary)
6704 (let* ((marker (or (get-text-property (point) 'org-marker)
6705 (org-agenda-error)))
6706 (buffer (marker-buffer marker))
6707 (pos (marker-position marker)))
6708 (with-current-buffer buffer
6709 (widen)
6710 (goto-char pos)
6711 (if (not (org-at-timestamp-p))
6712 (error "Cannot find time stamp"))
6713 (org-time-stamp arg)
6714 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6715
6716 (defun org-get-heading ()
6717 "Return the heading of the current entry, without the stars."
6718 (save-excursion
6719 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6720 (if (and (re-search-backward "[\r\n]\\*" nil t)
6721 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6722 (match-string 1)
6723 "")))
6724
6725 (defun org-agenda-diary-entry ()
6726 "Make a diary entry, like the `i' command from the calendar.
6727 All the standard commands work: block, weekly etc."
6728 (interactive)
6729 (org-agenda-check-type t 'agenda 'timeline)
6730 (require 'diary-lib)
6731 (let* ((char (progn
6732 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6733 (read-char-exclusive)))
6734 (cmd (cdr (assoc char
6735 '((?d . insert-diary-entry)
6736 (?w . insert-weekly-diary-entry)
6737 (?m . insert-monthly-diary-entry)
6738 (?y . insert-yearly-diary-entry)
6739 (?a . insert-anniversary-diary-entry)
6740 (?b . insert-block-diary-entry)
6741 (?c . insert-cyclic-diary-entry)))))
6742 (oldf (symbol-function 'calendar-cursor-to-date))
6743 (point (point))
6744 (mark (or (mark t) (point))))
6745 (unless cmd
6746 (error "No command associated with <%c>" char))
6747 (unless (and (get-text-property point 'day)
6748 (or (not (equal ?b char))
6749 (get-text-property mark 'day)))
6750 (error "Don't know which date to use for diary entry"))
6751 ;; We implement this by hacking the `calendar-cursor-to-date' function
6752 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6753 (let ((calendar-mark-ring
6754 (list (calendar-gregorian-from-absolute
6755 (or (get-text-property mark 'day)
6756 (get-text-property point 'day))))))
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)))))
6765
6766
6767 (defun org-agenda-execute-calendar-command (cmd)
6768 "Execute a calendar command from the agenda, with the date associated to
6769 the cursor position."
6770 (org-agenda-check-type t 'agenda 'timeline)
6771 (require 'diary-lib)
6772 (unless (get-text-property (point) 'day)
6773 (error "Don't know which date to use for calendar command"))
6774 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6775 (point (point))
6776 (date (calendar-gregorian-from-absolute
6777 (get-text-property point 'day)))
6778 (displayed-day (extract-calendar-day date))
6779 (displayed-month (extract-calendar-month date))
6780 (displayed-year (extract-calendar-year date)))
6781 (unwind-protect
6782 (progn
6783 (fset 'calendar-cursor-to-date
6784 (lambda (&optional error)
6785 (calendar-gregorian-from-absolute
6786 (get-text-property point 'day))))
6787 (call-interactively cmd))
6788 (fset 'calendar-cursor-to-date oldf))))
6789
6790 (defun org-agenda-phases-of-moon ()
6791 "Display the phases of the moon for the 3 months around the cursor date."
6792 (interactive)
6793 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6794
6795 (defun org-agenda-holidays ()
6796 "Display the holidays for the 3 months around the cursor date."
6797 (interactive)
6798 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6799
6800 (defun org-agenda-sunrise-sunset (arg)
6801 "Display sunrise and sunset for the cursor date.
6802 Latitude and longitude can be specified with the variables
6803 `calendar-latitude' and `calendar-longitude'. When called with prefix
6804 argument, latitude and longitude will be prompted for."
6805 (interactive "P")
6806 (let ((calendar-longitude (if arg nil calendar-longitude))
6807 (calendar-latitude (if arg nil calendar-latitude))
6808 (calendar-location-name
6809 (if arg "the given coordinates" calendar-location-name)))
6810 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6811
6812 (defun org-agenda-goto-calendar ()
6813 "Open the Emacs calendar with the date at the cursor."
6814 (interactive)
6815 (org-agenda-check-type t 'agenda 'timeline)
6816 (let* ((day (or (get-text-property (point) 'day)
6817 (error "Don't know which date to open in calendar")))
6818 (date (calendar-gregorian-from-absolute day))
6819 (calendar-move-hook nil)
6820 (view-diary-entries-initially nil))
6821 (calendar)
6822 (calendar-goto-date date)))
6823
6824 (defun org-calendar-goto-agenda ()
6825 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6826 This is a command that has to be installed in `calendar-mode-map'."
6827 (interactive)
6828 (org-agenda-list nil (calendar-absolute-from-gregorian
6829 (calendar-cursor-to-date))
6830 nil t))
6831
6832 (defun org-agenda-convert-date ()
6833 (interactive)
6834 (org-agenda-check-type t 'agenda 'timeline)
6835 (let ((day (get-text-property (point) 'day))
6836 date s)
6837 (unless day
6838 (error "Don't know which date to convert"))
6839 (setq date (calendar-gregorian-from-absolute day))
6840 (setq s (concat
6841 "Gregorian: " (calendar-date-string date) "\n"
6842 "ISO: " (calendar-iso-date-string date) "\n"
6843 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6844 "Julian: " (calendar-julian-date-string date) "\n"
6845 "Astron. JD: " (calendar-astro-date-string date)
6846 " (Julian date number at noon UTC)\n"
6847 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6848 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6849 "French: " (calendar-french-date-string date) "\n"
6850 "Mayan: " (calendar-mayan-date-string date) "\n"
6851 "Coptic: " (calendar-coptic-date-string date) "\n"
6852 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6853 "Persian: " (calendar-persian-date-string date) "\n"
6854 "Chinese: " (calendar-chinese-date-string date) "\n"))
6855 (with-output-to-temp-buffer "*Dates*"
6856 (princ s))
6857 (if (fboundp 'fit-window-to-buffer)
6858 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6859
6860 ;;; Tags
6861
6862 (defun org-scan-tags (action matcher &optional todo-only)
6863 "Scan headline tags with inheritance and produce output ACTION.
6864 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6865 evaluated, testing if a given set of tags qualifies a headline for
6866 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
6867 are included in the output."
6868 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6869 (mapconcat 'regexp-quote
6870 (nreverse (cdr (reverse org-todo-keywords)))
6871 "\\|")
6872 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
6873 (props (list 'face nil
6874 'done-face 'org-done
6875 'undone-face nil
6876 'mouse-face 'highlight
6877 'keymap org-agenda-keymap
6878 'help-echo
6879 (format "mouse-2 or RET jump to org file %s"
6880 (abbreviate-file-name buffer-file-name))))
6881 lspos
6882 tags tags-list tags-alist (llast 0) rtn level category i txt
6883 todo marker)
6884
6885 (save-excursion
6886 (goto-char (point-min))
6887 (when (eq action 'sparse-tree) (hide-sublevels 1))
6888 (while (re-search-forward re nil t)
6889 (setq todo (if (match-end 1) (match-string 2))
6890 tags (if (match-end 4) (match-string 4)))
6891 (goto-char (setq lspos (1+ (match-beginning 0))))
6892 (setq level (funcall outline-level)
6893 category (org-get-category))
6894 (setq i llast llast level)
6895 ;; remove tag lists from same and sublevels
6896 (while (>= i level)
6897 (when (setq entry (assoc i tags-alist))
6898 (setq tags-alist (delete entry tags-alist)))
6899 (setq i (1- i)))
6900 ;; add the nex tags
6901 (when tags
6902 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6903 tags-alist
6904 (cons (cons level tags) tags-alist)))
6905 ;; compile tags for current headline
6906 (setq tags-list
6907 (if org-use-tag-inheritance
6908 (apply 'append (mapcar 'cdr tags-alist))
6909 tags))
6910 (when (and (or (not todo-only) todo)
6911 (eval matcher))
6912 ;; list this headline
6913 (if (eq action 'sparse-tree)
6914 (progn
6915 (org-show-hierarchy-above))
6916 (setq txt (org-format-agenda-item
6917 ""
6918 (concat
6919 (if org-tags-match-list-sublevels
6920 (make-string (1- level) ?.) "")
6921 (org-get-heading))
6922 category tags-list))
6923 (goto-char lspos)
6924 (setq marker (org-agenda-new-marker))
6925 (org-add-props txt props
6926 'org-marker marker 'org-hd-marker marker 'category category)
6927 (push txt rtn))
6928 ;; if we are to skip sublevels, jump to end of subtree
6929 (point)
6930 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
6931 (nreverse rtn)))
6932
6933 (defun org-tags-sparse-tree (&optional arg match)
6934 "Create a sparse tree according to tags search string MATCH.
6935 MATCH can contain positive and negative selection of tags, like
6936 \"+WORK+URGENT-WITHBOSS\"."
6937 (interactive "P")
6938 (let ((org-show-following-heading nil)
6939 (org-show-hierarchy-above nil))
6940 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
6941
6942 (defun org-make-tags-matcher (match)
6943 "Create the TAGS matcher form for the tags-selecting string MATCH."
6944 (unless match
6945 ;; Get a new match request, with completion
6946 (setq org-last-tags-completion-table
6947 (or (org-get-buffer-tags)
6948 org-last-tags-completion-table))
6949 (setq match (completing-read
6950 "Tags: " 'org-tags-completion-function nil nil nil
6951 'org-tags-history)))
6952 ;; parse the string and create a lisp form
6953 (let ((match0 match) minus tag mm matcher orterms term orlist)
6954 (setq orterms (org-split-string match "|"))
6955 (while (setq term (pop orterms))
6956 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
6957 (setq minus (and (match-end 1)
6958 (equal (match-string 1 term) "-"))
6959 tag (match-string 2 term)
6960 term (substring term (match-end 0))
6961 mm (list 'member (downcase tag) 'tags-list)
6962 mm (if minus (list 'not mm) mm))
6963 (push mm matcher))
6964 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
6965 orlist)
6966 (setq matcher nil))
6967 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
6968 ;; Return the string and lisp forms of the matcher
6969 (cons match0 matcher)))
6970
6971 ;;;###autoload
6972 (defun org-tags-view (&optional todo-only match keep-modes)
6973 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
6974 The prefix arg TODO-ONLY limits the search to TODO entries."
6975 (interactive "P")
6976 (org-agenda-maybe-reset-markers 'force)
6977 (org-compile-prefix-format org-agenda-prefix-format)
6978 (let* ((org-agenda-keep-modes keep-modes)
6979 (org-tags-match-list-sublevels
6980 (if todo-only t org-tags-match-list-sublevels))
6981 (win (selected-window))
6982 (completion-ignore-case t)
6983 rtn rtnall files file pos matcher
6984 buffer)
6985 (setq matcher (org-make-tags-matcher match)
6986 match (car matcher) matcher (cdr matcher))
6987 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6988 (progn
6989 (delete-other-windows)
6990 (switch-to-buffer-other-window
6991 (get-buffer-create org-agenda-buffer-name))))
6992 (setq buffer-read-only nil)
6993 (erase-buffer)
6994 (org-agenda-mode) (setq buffer-read-only nil)
6995 (set (make-local-variable 'org-agenda-type) 'tags)
6996 (set (make-local-variable 'org-agenda-redo-command)
6997 (list 'org-tags-view (list 'quote todo-only)
6998 (list 'if 'current-prefix-arg nil match) t))
6999 (setq files (org-agenda-files)
7000 rtnall nil)
7001 (while (setq file (pop files))
7002 (catch 'nextfile
7003 (org-check-agenda-file file)
7004 (setq buffer (if (file-exists-p file)
7005 (org-get-agenda-file-buffer file)
7006 (error "No such file %s" file)))
7007 (if (not buffer)
7008 ;; If file does not exist, merror message to agenda
7009 (setq rtn (list
7010 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7011 rtnall (append rtnall rtn))
7012 (with-current-buffer buffer
7013 (unless (eq major-mode 'org-mode)
7014 (error "Agenda file %s is not in `org-mode'" file))
7015 (save-excursion
7016 (save-restriction
7017 (if org-respect-restriction
7018 (if (org-region-active-p)
7019 ;; Respect a region to restrict search
7020 (narrow-to-region (region-beginning) (region-end)))
7021 ;; If we work for the calendar or many files,
7022 ;; get rid of any restriction
7023 (widen))
7024 (setq rtn (org-scan-tags 'agenda matcher todo-only))
7025 (setq rtnall (append rtnall rtn))))))))
7026 (insert "Headlines with TAGS match: ")
7027 (add-text-properties (point-min) (1- (point))
7028 (list 'face 'org-level-3))
7029 (setq pos (point))
7030 (insert match "\n")
7031 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7032 (setq pos (point))
7033 (insert "Press `C-u r' to search again with new search string\n")
7034 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7035 (when rtnall
7036 (insert (mapconcat 'identity rtnall "\n")))
7037 (goto-char (point-min))
7038 (setq buffer-read-only t)
7039 (org-fit-agenda-window)
7040 (if (not org-select-agenda-window) (select-window win))))
7041
7042 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
7043 (defun org-set-tags (&optional arg just-align)
7044 "Set the tags for the current headline.
7045 With prefix ARG, realign all tags in headings in the current buffer."
7046 (interactive)
7047 (let* (;(inherit (org-get-inherited-tags))
7048 (re (concat "^" outline-regexp))
7049 (col (current-column))
7050 (current (org-get-tags))
7051 tags hd empty invis)
7052 (if arg
7053 (save-excursion
7054 (goto-char (point-min))
7055 (while (re-search-forward re nil t)
7056 (org-set-tags nil t))
7057 (message "All tags realigned to column %d" org-tags-column))
7058 (if just-align
7059 (setq tags current)
7060 (setq org-last-tags-completion-table
7061 (or (org-get-buffer-tags)
7062 org-last-tags-completion-table))
7063 (setq tags
7064 (let ((org-add-colon-after-tag-completion t))
7065 (completing-read "Tags: " 'org-tags-completion-function
7066 nil nil current 'org-tags-history)))
7067 (while (string-match "[-+&]+" tags)
7068 (setq tags (replace-match ":" t t tags))))
7069 ;; FIXME: still optimize this by not checking when JUST-ALIGN?
7070 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
7071 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
7072 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
7073 (if (equal current "")
7074 (progn
7075 (end-of-line 1)
7076 (or empty (insert-before-markers " ")))
7077 (beginning-of-line 1)
7078 (setq invis (org-invisible-p))
7079 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
7080 (setq hd (match-string 1))
7081 (delete-region (match-beginning 0) (match-end 0))
7082 (insert-before-markers (org-trim hd) (if empty "" " ")))
7083 (unless (equal tags "")
7084 (move-to-column (max (current-column)
7085 (if (> org-tags-column 0)
7086 org-tags-column
7087 (- (- org-tags-column) (length tags))))
7088 t)
7089 (insert-before-markers tags)
7090 (if (and (not invis) (org-invisible-p))
7091 (outline-flag-region (point-at-bol) (point) nil)))
7092 (move-to-column col))))
7093
7094 (defun org-tags-completion-function (string predicate &optional flag)
7095 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
7096 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
7097 (setq s1 (match-string 1 string)
7098 s2 (match-string 2 string))
7099 (setq s1 "" s2 string))
7100 (cond
7101 ((eq flag nil)
7102 ;; try completion
7103 (setq rtn (try-completion s2 ctable))
7104 (if (stringp rtn)
7105 (concat s1 s2 (substring rtn (length s2))
7106 (if (and org-add-colon-after-tag-completion
7107 (assoc rtn ctable))
7108 ":" "")))
7109 )
7110 ((eq flag t)
7111 ;; all-completions
7112 (all-completions s2 ctable)
7113 )
7114 ((eq flag 'lambda)
7115 ;; exact match?
7116 (assoc s2 ctable)))
7117 ))
7118
7119 (defun org-get-tags ()
7120 "Get the TAGS string in the current headline."
7121 (unless (org-on-heading-p)
7122 (error "Not on a heading"))
7123 (save-excursion
7124 (beginning-of-line 1)
7125 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
7126 (org-match-string-no-properties 1)
7127 "")))
7128
7129 (defun org-get-buffer-tags ()
7130 "Get a table of all tags used in the buffer, for completion."
7131 (let (tags)
7132 (save-excursion
7133 (goto-char (point-min))
7134 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
7135 (mapc (lambda (x) (add-to-list 'tags x))
7136 (org-split-string (org-match-string-no-properties 1) ":"))))
7137 (mapcar 'list tags)))
7138
7139 ;;; Link Stuff
7140
7141 (defun org-find-file-at-mouse (ev)
7142 "Open file link or URL at mouse."
7143 (interactive "e")
7144 (mouse-set-point ev)
7145 (org-open-at-point 'in-emacs))
7146
7147 (defun org-open-at-mouse (ev)
7148 "Open file link or URL at mouse."
7149 (interactive "e")
7150 (mouse-set-point ev)
7151 (org-open-at-point))
7152
7153 (defun org-open-at-point (&optional in-emacs)
7154 "Open link at or after point.
7155 If there is no link at point, this function will search forward up to
7156 the end of the current subtree.
7157 Normally, files will be opened by an appropriate application. If the
7158 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7159 (interactive "P")
7160 (org-remove-occur-highlights nil nil t)
7161 (if (org-at-timestamp-p)
7162 (org-agenda-list nil (time-to-days (org-time-string-to-time
7163 (substring (match-string 1) 0 10)))
7164 1)
7165 (let (type path link line search (pos (point)))
7166 (catch 'match
7167 (save-excursion
7168 (skip-chars-forward "^]\n\r")
7169 (when (and (re-search-backward "\\[\\[" nil t)
7170 (looking-at org-bracket-link-regexp)
7171 (<= (match-beginning 0) pos)
7172 (>= (match-end 0) pos))
7173 (setq link (org-link-unescape (org-match-string-no-properties 1)))
7174 (while (string-match " *\n *" link)
7175 (setq link (replace-match " " t t link)))
7176 (if (string-match org-link-re-with-space2 link)
7177 (setq type (match-string 1 link)
7178 path (match-string 2 link))
7179 (setq type "thisfile"
7180 path link))
7181 (throw 'match t)))
7182
7183 (when (get-text-property (point) 'org-linked-text)
7184 (setq type "thisfile"
7185 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7186 (1+ (point)) (point))
7187 path (buffer-substring
7188 (previous-single-property-change pos 'org-linked-text)
7189 (next-single-property-change pos 'org-linked-text)))
7190 (throw 'match t))
7191
7192 (save-excursion
7193 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
7194 (if (equal (char-before) ?<) (backward-char 1))
7195 (when (or (looking-at org-angle-link-re)
7196 (looking-at org-plain-link-re)
7197 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
7198 (re-search-forward org-plain-link-re (point-at-eol) t))
7199 (<= (match-beginning 0) pos)
7200 (>= (match-end 0) pos)))
7201 (setq type (match-string 1)
7202 path (match-string 2))
7203 (throw 'match t)))
7204 (save-excursion
7205 (skip-chars-backward "^ \t\n\r")
7206 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
7207 (setq type "tags"
7208 path (match-string 1))
7209 (while (string-match ":" path)
7210 (setq path (replace-match "+" t t path)))
7211 (throw 'match t)))
7212 (save-excursion
7213 (skip-chars-backward "a-zA-Z_")
7214 (when (and (memq 'camel org-activate-links)
7215 (looking-at org-camel-regexp))
7216 (setq type "camel" path (match-string 0))
7217 (if (equal (char-before) ?*)
7218 (setq path (concat "*" path))))
7219 (throw 'match t)))
7220 (unless path
7221 (error "No link found"))
7222 ;; Remove any trailing spaces in path
7223 (if (string-match " +\\'" path)
7224 (setq path (replace-match "" t t path)))
7225
7226 (cond
7227
7228 ((member type '("http" "https" "ftp" "mailto" "news"))
7229 (browse-url (concat type ":" path)))
7230
7231 ((string= type "tags")
7232 (org-tags-view in-emacs path))
7233 ((or (string= type "camel")
7234 (string= type "thisfile"))
7235 (org-mark-ring-push)
7236 (org-link-search
7237 path
7238 (cond ((equal in-emacs '(4)) 'occur)
7239 ((equal in-emacs '(16)) 'org-occur)
7240 (t nil))))
7241
7242 ((string= type "file")
7243 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
7244 (setq line (string-to-number (match-string 1 path))
7245 path (substring path 0 (match-beginning 0)))
7246 (if (string-match "::\\(.+\\)\\'" path)
7247 (setq search (match-string 1 path)
7248 path (substring path 0 (match-beginning 0)))))
7249 (org-open-file path in-emacs line search))
7250
7251 ((string= type "news")
7252 (org-follow-gnus-link path))
7253
7254 ((string= type "bbdb")
7255 (org-follow-bbdb-link path))
7256
7257 ((string= type "gnus")
7258 (let (group article)
7259 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7260 (error "Error in Gnus link"))
7261 (setq group (match-string 1 path)
7262 article (match-string 3 path))
7263 (org-follow-gnus-link group article)))
7264
7265 ((string= type "vm")
7266 (let (folder article)
7267 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7268 (error "Error in VM link"))
7269 (setq folder (match-string 1 path)
7270 article (match-string 3 path))
7271 ;; in-emacs is the prefix arg, will be interpreted as read-only
7272 (org-follow-vm-link folder article in-emacs)))
7273
7274 ((string= type "wl")
7275 (let (folder article)
7276 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7277 (error "Error in Wanderlust link"))
7278 (setq folder (match-string 1 path)
7279 article (match-string 3 path))
7280 (org-follow-wl-link folder article)))
7281
7282 ((string= type "mhe")
7283 (let (folder article)
7284 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7285 (error "Error in MHE link"))
7286 (setq folder (match-string 1 path)
7287 article (match-string 3 path))
7288 (org-follow-mhe-link folder article)))
7289
7290 ((string= type "rmail")
7291 (let (folder article)
7292 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7293 (error "Error in RMAIL link"))
7294 (setq folder (match-string 1 path)
7295 article (match-string 3 path))
7296 (org-follow-rmail-link folder article)))
7297
7298 ((string= type "shell")
7299 (let ((cmd path))
7300 (while (string-match "@{" cmd)
7301 (setq cmd (replace-match "<" t t cmd)))
7302 (while (string-match "@}" cmd)
7303 (setq cmd (replace-match ">" t t cmd)))
7304 (if (or (not org-confirm-shell-links)
7305 (funcall org-confirm-shell-links
7306 (format "Execute \"%s\" in shell? "
7307 (org-add-props cmd nil
7308 'face 'org-warning))))
7309 (shell-command cmd)
7310 (error "Abort"))))
7311
7312 (t
7313 (browse-url-at-point))))))
7314
7315 (defun org-link-search (s &optional type)
7316 "Search for a link search option.
7317 When S is a CamelCaseWord, search for a target, or for a sentence containing
7318 the words. If S is surrounded by forward slashes, it is interpreted as a
7319 regular expression. In org-mode files, this will create an `org-occur'
7320 sparse tree. In ordinary files, `occur' will be used to list matches.
7321 If the current buffer is in `dired-mode', grep will be used to search
7322 in all files."
7323 (let ((case-fold-search t)
7324 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7325 (pos (point))
7326 (pre "") (post "")
7327 words re0 re1 re2 re3 re4 re5 re2a reall camel)
7328 (cond ((save-excursion
7329 (goto-char (point-min))
7330 (and
7331 (re-search-forward
7332 (concat "<<" (regexp-quote s0) ">>") nil t)
7333 (setq pos (match-beginning 0))))
7334 ;; There is an exact target for this
7335 (goto-char pos))
7336 ((string-match "^/\\(.*\\)/$" s)
7337 ;; A regular expression
7338 (cond
7339 ((eq major-mode 'org-mode)
7340 (org-occur (match-string 1 s)))
7341 ;;((eq major-mode 'dired-mode)
7342 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7343 (t (org-do-occur (match-string 1 s)))))
7344 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
7345 t)
7346 ;; A camel or a normal search string
7347 (when (equal (string-to-char s) ?*)
7348 ;; Anchor on headlines, post may include tags.
7349 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
7350 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
7351 s (substring s 1)))
7352 (remove-text-properties
7353 0 (length s)
7354 '(face nil mouse-face nil keymap nil fontified nil) s)
7355 ;; Make a series of regular expressions to find a match
7356 (setq words
7357 (if camel
7358 (org-camel-to-words s)
7359 (org-split-string s "[ \n\r\t]+"))
7360 re0 (concat "<<" (regexp-quote s0) ">>")
7361 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
7362 re2a (concat "\\<" (mapconcat 'downcase words "[ \t\r\n]+") "\\>")
7363 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
7364 re1 (concat pre re2 post)
7365 re3 (concat pre re4 post)
7366 re5 (concat pre ".*" re4)
7367 re2 (concat pre re2)
7368 re2a (concat pre re2a)
7369 re4 (concat pre re4)
7370 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7371 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7372 re5 "\\)"
7373 ))
7374 (cond
7375 ((eq type 'org-occur) (org-occur reall))
7376 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7377 (t (goto-char (point-min))
7378 (if (or (org-search-not-link re0 nil t)
7379 (org-search-not-link re1 nil t)
7380 (org-search-not-link re2 nil t)
7381 (org-search-not-link re2a nil t)
7382 (org-search-not-link re3 nil t)
7383 (org-search-not-link re4 nil t)
7384 (org-search-not-link re5 nil t)
7385 )
7386 (goto-char (match-beginning 0))
7387 (goto-char pos)
7388 (error "No match")))))
7389 (t
7390 ;; Normal string-search
7391 (goto-char (point-min))
7392 (if (search-forward s nil t)
7393 (goto-char (match-beginning 0))
7394 (error "No match"))))
7395 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
7396
7397 (defun org-search-not-link (&rest args)
7398 "Execute `re-search-forward', but only accept matches that are not a link."
7399 (catch 'exit
7400 (let ((pos (point)) p1)
7401 (while (apply 're-search-forward args)
7402 (setq p1 (point))
7403 (if (not (save-match-data
7404 (and (re-search-backward "\\[\\[" nil t)
7405 (looking-at org-bracket-link-regexp)
7406 (<= (match-beginning 0) p1)
7407 (>= (match-end 0) p1))))
7408 (progn (goto-char (match-end 0))
7409 (throw 'exit (point)))
7410 (goto-char (match-end 0)))))))
7411
7412 (defun org-do-occur (regexp &optional cleanup)
7413 "Call the Emacs command `occur'.
7414 If CLEANUP is non-nil, remove the printout of the regular expression
7415 in the *Occur* buffer. This is useful if the regex is long and not useful
7416 to read."
7417 (occur regexp)
7418 (when cleanup
7419 (let ((cwin (selected-window)) win beg end)
7420 (when (setq win (get-buffer-window "*Occur*"))
7421 (select-window win))
7422 (goto-char (point-min))
7423 (when (re-search-forward "match[a-z]+" nil t)
7424 (setq beg (match-end 0))
7425 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7426 (setq end (1- (match-beginning 0)))))
7427 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
7428 (goto-char (point-min))
7429 (select-window cwin))))
7430
7431 (defvar org-mark-ring nil
7432 "Mark ring for positions before jumps in Org-mode.")
7433 (defvar org-mark-ring-last-goto nil
7434 "Last position in the mark ring used to go back.")
7435 ;; Fill and close the ring
7436 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7437 (loop for i from 1 to org-mark-ring-length do
7438 (push (make-marker) org-mark-ring))
7439 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7440 org-mark-ring)
7441
7442 (defun org-mark-ring-push (&optional pos buffer)
7443 "Put the current position or POS into the mark ring and rotate it."
7444 (interactive)
7445 (setq pos (or pos (point)))
7446 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7447 (move-marker (car org-mark-ring)
7448 (or pos (point))
7449 (or buffer (current-buffer)))
7450 (message
7451 (substitute-command-keys
7452 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7453
7454 (defun org-mark-ring-goto (&optional n)
7455 "Jump to the previous position in the mark ring.
7456 With prefix arg N, jump back that many stored positions. When
7457 called several times in succession, walk through the entire ring.
7458 Org-mode commands jumping to a different position in the current file,
7459 or to another Org-mode file, automatically push the old position
7460 onto the ring."
7461 (interactive "p")
7462 (let (p m)
7463 (if (eq last-command this-command)
7464 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7465 (setq p org-mark-ring))
7466 (setq org-mark-ring-last-goto p)
7467 (setq m (car p))
7468 (switch-to-buffer (marker-buffer m))
7469 (goto-char m)
7470 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7471
7472 (defun org-camel-to-words (s)
7473 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7474 (let ((case-fold-search nil)
7475 words)
7476 (while (string-match "[a-z][A-Z]" s)
7477 (push (substring s 0 (1+ (match-beginning 0))) words)
7478 (setq s (substring s (1+ (match-beginning 0)))))
7479 (nreverse (cons s words))))
7480
7481 (defun org-remove-angle-brackets (s)
7482 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7483 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7484 s)
7485 (defun org-add-angle-brackets (s)
7486 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7487 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7488 s)
7489
7490 (defun org-follow-bbdb-link (name)
7491 "Follow a BBDB link to NAME."
7492 (require 'bbdb)
7493 (let ((inhibit-redisplay t)
7494 (bbdb-electric-p nil))
7495 (catch 'exit
7496 ;; Exact match on name
7497 (bbdb-name (concat "\\`" name "\\'") nil)
7498 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7499 ;; Exact match on name
7500 (bbdb-company (concat "\\`" name "\\'") nil)
7501 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7502 ;; Partial match on name
7503 (bbdb-name name nil)
7504 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7505 ;; Partial match on company
7506 (bbdb-company name nil)
7507 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7508 ;; General match including network address and notes
7509 (bbdb name nil)
7510 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7511 (delete-window (get-buffer-window "*BBDB*"))
7512 (error "No matching BBDB record")))))
7513
7514 (defun org-follow-gnus-link (&optional group article)
7515 "Follow a Gnus link to GROUP and ARTICLE."
7516 (require 'gnus)
7517 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7518 (if group (gnus-fetch-group group))
7519 (if article
7520 (or (gnus-summary-goto-article article nil 'force)
7521 (if (fboundp 'gnus-summary-insert-cached-articles)
7522 (progn
7523 (gnus-summary-insert-cached-articles)
7524 (gnus-summary-goto-article article nil 'force))
7525 (message "Message could not be found.")))))
7526
7527 (defun org-follow-vm-link (&optional folder article readonly)
7528 "Follow a VM link to FOLDER and ARTICLE."
7529 (require 'vm)
7530 (setq article (org-add-angle-brackets article))
7531 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7532 ;; ange-ftp or efs or tramp access
7533 (let ((user (or (match-string 1 folder) (user-login-name)))
7534 (host (match-string 2 folder))
7535 (file (match-string 3 folder)))
7536 (cond
7537 ((featurep 'tramp)
7538 ;; use tramp to access the file
7539 (if (featurep 'xemacs)
7540 (setq folder (format "[%s@%s]%s" user host file))
7541 (setq folder (format "/%s@%s:%s" user host file))))
7542 (t
7543 ;; use ange-ftp or efs
7544 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
7545 (setq folder (format "/%s@%s:%s" user host file))))))
7546 (when folder
7547 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7548 (sit-for 0.1)
7549 (when article
7550 (vm-select-folder-buffer)
7551 (widen)
7552 (let ((case-fold-search t))
7553 (goto-char (point-min))
7554 (if (not (re-search-forward
7555 (concat "^" "message-id: *" (regexp-quote article))))
7556 (error "Could not find the specified message in this folder"))
7557 (vm-isearch-update)
7558 (vm-isearch-narrow)
7559 (vm-beginning-of-message)
7560 (vm-summarize)))))
7561
7562 (defun org-follow-wl-link (folder article)
7563 "Follow a Wanderlust link to FOLDER and ARTICLE."
7564 (setq article (org-add-angle-brackets article))
7565 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7566 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7567 (wl-summary-redisplay))
7568
7569 (defun org-follow-rmail-link (folder article)
7570 "Follow an RMAIL link to FOLDER and ARTICLE."
7571 (setq article (org-add-angle-brackets article))
7572 (let (message-number)
7573 (save-excursion
7574 (save-window-excursion
7575 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7576 (setq message-number
7577 (save-restriction
7578 (widen)
7579 (goto-char (point-max))
7580 (if (re-search-backward
7581 (concat "^Message-ID:\\s-+" (regexp-quote
7582 (or article "")))
7583 nil t)
7584 (rmail-what-message))))))
7585 (if message-number
7586 (progn
7587 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7588 (rmail-show-message message-number)
7589 message-number)
7590 (error "Message not found"))))
7591
7592 ;; mh-e integration based on planner-mode
7593 (defun org-mhe-get-message-real-folder ()
7594 "Return the name of the current message real folder, so if you use
7595 sequences, it will now work."
7596 (save-excursion
7597 (let* ((folder
7598 (if (equal major-mode 'mh-folder-mode)
7599 mh-current-folder
7600 ;; Refer to the show buffer
7601 mh-show-folder-buffer))
7602 (end-index
7603 (if (boundp 'mh-index-folder)
7604 (min (length mh-index-folder) (length folder))))
7605 )
7606 ;; a simple test on mh-index-data does not work, because
7607 ;; mh-index-data is always nil in a show buffer.
7608 (if (and (boundp 'mh-index-folder)
7609 (string= mh-index-folder (substring folder 0 end-index)))
7610 (if (equal major-mode 'mh-show-mode)
7611 (save-window-excursion
7612 (when (buffer-live-p (get-buffer folder))
7613 (progn
7614 (pop-to-buffer folder)
7615 (org-mhe-get-message-folder-from-index)
7616 )
7617 ))
7618 (org-mhe-get-message-folder-from-index)
7619 )
7620 folder
7621 )
7622 )))
7623
7624 (defun org-mhe-get-message-folder-from-index ()
7625 "Returns the name of the message folder in a index folder buffer."
7626 (save-excursion
7627 (mh-index-previous-folder)
7628 (re-search-forward "^\\(+.*\\)$" nil t)
7629 (message (match-string 1))))
7630
7631 (defun org-mhe-get-message-folder ()
7632 "Return the name of the current message folder. Be careful if you
7633 use sequences."
7634 (save-excursion
7635 (if (equal major-mode 'mh-folder-mode)
7636 mh-current-folder
7637 ;; Refer to the show buffer
7638 mh-show-folder-buffer)))
7639
7640 (defun org-mhe-get-message-num ()
7641 "Return the number of the current message. Be careful if you
7642 use sequences."
7643 (save-excursion
7644 (if (equal major-mode 'mh-folder-mode)
7645 (mh-get-msg-num nil)
7646 ;; Refer to the show buffer
7647 (mh-show-buffer-message-number))))
7648
7649 (defun org-mhe-get-header (header)
7650 "Return a header of the message in folder mode. This will create a
7651 show buffer for the corresponding message. If you have a more clever
7652 idea..."
7653 (let* ((folder (org-mhe-get-message-folder))
7654 (num (org-mhe-get-message-num))
7655 (buffer (get-buffer-create (concat "show-" folder)))
7656 (header-field))
7657 (with-current-buffer buffer
7658 (mh-display-msg num folder)
7659 (if (equal major-mode 'mh-folder-mode)
7660 (mh-header-display)
7661 (mh-show-header-display))
7662 (set-buffer buffer)
7663 (setq header-field (mh-get-header-field header))
7664 (if (equal major-mode 'mh-folder-mode)
7665 (mh-show)
7666 (mh-show-show))
7667 header-field)))
7668
7669 (defun org-follow-mhe-link (folder article)
7670 "Follow an MHE link to FOLDER and ARTICLE.
7671 If ARTICLE is nil FOLDER is shown. If the configuration variable
7672 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
7673 ARTICLE is searched in all folders. Indexed searches (swish++,
7674 namazu, and others supported by MH-E) will always search in all
7675 folders."
7676 (require 'mh-e)
7677 (require 'mh-search)
7678 (require 'mh-utils)
7679 (mh-find-path)
7680 (if (not article)
7681 (mh-visit-folder (mh-normalize-folder-name folder))
7682 (setq article (org-add-angle-brackets article))
7683 (mh-search-choose)
7684 (if (equal mh-searcher 'pick)
7685 (progn
7686 (mh-search folder (list "--message-id" article))
7687 (when (and org-mhe-search-all-folders
7688 (not (org-mhe-get-message-real-folder)))
7689 (kill-this-buffer)
7690 (mh-search "+" (list "--message-id" article))))
7691 (mh-search "+" article))
7692 (if (org-mhe-get-message-real-folder)
7693 (mh-show-msg 1)
7694 (kill-this-buffer)
7695 (error "Message not found"))))
7696
7697 (defun org-upgrade-old-links (&optional query-description)
7698 "Transfer old <...> style links to new [[...]] style links.
7699 With arg query-description, ask at each match for a description text to use
7700 for this link."
7701 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
7702 (save-excursion
7703 (goto-char (point-min))
7704 (let ((re (concat "\\([^[]\\)<\\("
7705 "\\(" (mapconcat 'identity org-link-types "\\|")
7706 "\\):"
7707 "[^" org-non-link-chars "]+\\)>"))
7708 l1 l2 (cnt 0))
7709 (while (re-search-forward re nil t)
7710 (setq cnt (1+ cnt)
7711 l1 (org-match-string-no-properties 2)
7712 l2 (save-match-data (org-link-escape l1)))
7713 (when query-description (setq l1 (read-string "Desc: " l1)))
7714 (if (equal l1 l2)
7715 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
7716 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
7717 (message "%d matches have beed treated" cnt))))
7718
7719 (defun org-open-file (path &optional in-emacs line search)
7720 "Open the file at PATH.
7721 First, this expands any special file name abbreviations. Then the
7722 configuration variable `org-file-apps' is checked if it contains an
7723 entry for this file type, and if yes, the corresponding command is launched.
7724 If no application is found, Emacs simply visits the file.
7725 With optional argument IN-EMACS, Emacs will visit the file.
7726 Optional LINE specifies a line to go to, optional SEARCH a string to
7727 search for. If LINE or SEARCH is given, the file will always be
7728 opened in Emacs.
7729 If the file does not exist, an error is thrown."
7730 (setq in-emacs (or in-emacs line search))
7731 (let* ((file (if (equal path "")
7732 buffer-file-name
7733 (convert-standard-filename (org-expand-file-name path))))
7734 (dirp (file-directory-p file))
7735 (dfile (downcase file))
7736 (old-buffer (current-buffer))
7737 (old-pos (point))
7738 (old-mode major-mode)
7739 ext cmd apps)
7740 (if (and (not (file-exists-p file))
7741 (not org-open-non-existing-files))
7742 (error "No such file: %s" file))
7743 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7744 (setq ext (match-string 1 dfile))
7745 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7746 (setq ext (match-string 1 dfile))))
7747 (setq apps (append org-file-apps (org-default-apps)))
7748 (if in-emacs
7749 (setq cmd 'emacs)
7750 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7751 (cdr (assoc ext apps))
7752 (cdr (assoc t apps)))))
7753 (when (eq cmd 'mailcap)
7754 (require 'mailcap)
7755 (mailcap-parse-mailcaps)
7756 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7757 (command (mailcap-mime-info mime-type)))
7758 (if (stringp command)
7759 (setq cmd command)
7760 (setq cmd 'emacs))))
7761 (cond
7762 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7763 (setq cmd (format cmd (concat "\"" file "\"")))
7764 (save-window-excursion
7765 (shell-command (concat cmd " &"))))
7766 ((or (stringp cmd)
7767 (eq cmd 'emacs))
7768 (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
7769 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7770 (if line (goto-line line)
7771 (if search (org-link-search search))))
7772 ((consp cmd)
7773 (eval cmd))
7774 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7775 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7776 (or (not (equal old-buffer (current-buffer)))
7777 (not (equal old-pos (point))))
7778 (org-mark-ring-push old-pos old-buffer))))
7779
7780 (defun org-default-apps ()
7781 "Return the default applications for this operating system."
7782 (cond
7783 ((eq system-type 'darwin)
7784 org-file-apps-defaults-macosx)
7785 ((eq system-type 'windows-nt)
7786 org-file-apps-defaults-windowsnt)
7787 (t org-file-apps-defaults-gnu)))
7788
7789 (defun org-expand-file-name (path)
7790 "Replace special path abbreviations and expand the file name."
7791 (expand-file-name path))
7792
7793
7794 (defvar org-insert-link-history nil
7795 "Minibuffer history for links inserted with `org-insert-link'.")
7796
7797 (defvar org-stored-links nil
7798 "Contains the links stored with `org-store-link'.")
7799
7800 ;;;###autoload
7801 (defun org-store-link (arg)
7802 "\\<org-mode-map>Store an org-link to the current location.
7803 This link can later be inserted into an org-buffer with
7804 \\[org-insert-link].
7805 For some link types, a prefix arg is interpreted:
7806 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7807 For file links, arg negates `org-context-in-file-links'."
7808 (interactive "P")
7809 (let (link cpltxt desc txt (pos (point)))
7810 (cond
7811
7812 ((eq major-mode 'bbdb-mode)
7813 (setq cpltxt (concat
7814 "bbdb:"
7815 (or (bbdb-record-name (bbdb-current-record))
7816 (bbdb-record-company (bbdb-current-record))))
7817 link (org-make-link cpltxt)))
7818
7819 ((eq major-mode 'calendar-mode)
7820 (let ((cd (calendar-cursor-to-date)))
7821 (setq link
7822 (format-time-string
7823 (car org-time-stamp-formats)
7824 (apply 'encode-time
7825 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7826 nil nil nil))))))
7827
7828 ((or (eq major-mode 'vm-summary-mode)
7829 (eq major-mode 'vm-presentation-mode))
7830 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7831 (vm-follow-summary-cursor)
7832 (save-excursion
7833 (vm-select-folder-buffer)
7834 (let* ((message (car vm-message-pointer))
7835 (folder buffer-file-name)
7836 (subject (vm-su-subject message))
7837 (author (vm-su-full-name message))
7838 (message-id (vm-su-message-id message)))
7839 (setq message-id (org-remove-angle-brackets message-id))
7840 (setq folder (abbreviate-file-name folder))
7841 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7842 folder)
7843 (setq folder (replace-match "" t t folder)))
7844 (setq cpltxt (concat author " on: " subject))
7845 (setq link (org-make-link "vm:" folder "#" message-id)))))
7846
7847 ((eq major-mode 'wl-summary-mode)
7848 (let* ((msgnum (wl-summary-message-number))
7849 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7850 msgnum 'message-id))
7851 (wl-message-entity (elmo-msgdb-overview-get-entity
7852 msgnum (wl-summary-buffer-msgdb)))
7853 (author (wl-summary-line-from)) ; FIXME: correct?
7854 (subject "???")) ; FIXME:
7855 (setq message-id (org-remove-angle-brackets message-id))
7856 (setq cpltxt (concat author " on: " subject))
7857 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
7858 "#" message-id))))
7859
7860 ((or (equal major-mode 'mh-folder-mode)
7861 (equal major-mode 'mh-show-mode))
7862 (let ((from-header (org-mhe-get-header "From:"))
7863 (to-header (org-mhe-get-header "To:"))
7864 (subject (org-mhe-get-header "Subject:")))
7865 (setq cpltxt (concat from-header " on: " subject))
7866 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
7867 (org-remove-angle-brackets
7868 (org-mhe-get-header "Message-Id:"))))))
7869
7870 ((eq major-mode 'rmail-mode)
7871 (save-excursion
7872 (save-restriction
7873 (rmail-narrow-to-non-pruned-header)
7874 (let ((folder buffer-file-name)
7875 (message-id (mail-fetch-field "message-id"))
7876 (author (mail-fetch-field "from"))
7877 (subject (mail-fetch-field "subject")))
7878 (setq message-id (org-remove-angle-brackets message-id))
7879 (setq cpltxt (concat author " on: " subject))
7880 (setq link (org-make-link "rmail:" folder "#" message-id))))))
7881
7882 ((eq major-mode 'gnus-group-mode)
7883 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7884 (gnus-group-group-name)) ; version
7885 ((fboundp 'gnus-group-name)
7886 (gnus-group-name))
7887 (t "???"))))
7888 (setq cpltxt (concat
7889 (if (org-xor arg org-usenet-links-prefer-google)
7890 "http://groups.google.com/groups?group="
7891 "gnus:")
7892 group)
7893 link (org-make-link cpltxt))))
7894
7895 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7896 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7897 (gnus-summary-beginning-of-article)
7898 (let* ((group (car gnus-article-current))
7899 (article (cdr gnus-article-current))
7900 (header (gnus-summary-article-header article))
7901 (author (mail-header-from header))
7902 (message-id (mail-header-id header))
7903 (date (mail-header-date header))
7904 (subject (gnus-summary-subject-string)))
7905 (setq cpltxt (concat author " on: " subject))
7906 (if (org-xor arg org-usenet-links-prefer-google)
7907 (setq link
7908 (concat
7909 cpltxt "\n "
7910 (format "http://groups.google.com/groups?as_umsgid=%s"
7911 (org-fixup-message-id-for-http message-id))))
7912 (setq link (org-make-link "gnus:" group
7913 "#" (number-to-string article))))))
7914
7915 ((eq major-mode 'w3-mode)
7916 (setq cpltxt (url-view-url t)
7917 link (org-make-link cpltxt)))
7918 ((eq major-mode 'w3m-mode)
7919 (setq cpltxt w3m-current-url
7920 link (org-make-link cpltxt)))
7921
7922 ((eq major-mode 'org-mode)
7923 ;; Just link to current headline
7924 (setq cpltxt (concat "file:"
7925 (abbreviate-file-name buffer-file-name)))
7926 ;; Add a context search string
7927 (when (org-xor org-context-in-file-links arg)
7928 ;; Check if we are on a target
7929 (if (save-excursion
7930 (skip-chars-forward "^>\n\r")
7931 (and (re-search-backward "<<" nil t)
7932 (looking-at "<<\\(.*?\\)>>")
7933 (<= (match-beginning 0) pos)
7934 (>= (match-end 0) pos)))
7935 (setq cpltxt (concat cpltxt "::" (match-string 1)))
7936 (setq txt (cond
7937 ((org-on-heading-p) nil)
7938 ((org-region-active-p)
7939 (buffer-substring (region-beginning) (region-end)))
7940 (t (buffer-substring (point-at-bol) (point-at-eol)))))
7941 (setq cpltxt
7942 (concat cpltxt "::"
7943 (if org-file-link-context-use-camel-case
7944 (org-make-org-heading-camel txt)
7945 (org-make-org-heading-search-string txt)))
7946 desc "NONE")))
7947 (if (string-match "::\\'" cpltxt)
7948 (setq cpltxt (substring cpltxt 0 -2)))
7949 (setq link (org-make-link cpltxt)))
7950
7951 (buffer-file-name
7952 ;; Just link to this file here.
7953 (setq cpltxt (concat "file:"
7954 (abbreviate-file-name buffer-file-name)))
7955 ;; Add a context string
7956 (when (org-xor org-context-in-file-links arg)
7957 (setq txt (if (org-region-active-p)
7958 (buffer-substring (region-beginning) (region-end))
7959 (buffer-substring (point-at-bol) (point-at-eol))))
7960 (setq cpltxt
7961 (concat cpltxt "::"
7962 (if org-file-link-context-use-camel-case
7963 (org-make-org-heading-camel txt)
7964 (org-make-org-heading-search-string txt)))
7965 desc "NONE"))
7966 (setq link (org-make-link cpltxt)))
7967
7968 ((interactive-p)
7969 (error "Cannot link to a buffer which is not visiting a file"))
7970
7971 (t (setq link nil)))
7972
7973 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7974 (setq link (or link cpltxt)
7975 desc (or desc cpltxt))
7976 (if (equal desc "NONE") (setq desc nil))
7977
7978 (if (and (interactive-p) link)
7979 (progn
7980 (setq org-stored-links
7981 (cons (list cpltxt link desc) org-stored-links))
7982 (message "Stored: %s" (or cpltxt link)))
7983 (org-make-link-string link desc))))
7984
7985 (defun org-make-org-heading-search-string (&optional string heading)
7986 "Make search string for STRING or current headline."
7987 (interactive)
7988 (let ((s (or string (org-get-heading))))
7989 (unless (and string (not heading))
7990 ;; We are using a headline, clean up garbage in there.
7991 (if (string-match org-todo-regexp s)
7992 (setq s (replace-match "" t t s)))
7993 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
7994 (setq s (replace-match "" t t s)))
7995 (setq s (org-trim s))
7996 (if (string-match (concat "^\\(" org-quote-string "\\|"
7997 org-comment-string "\\)") s)
7998 (setq s (replace-match "" t t s)))
7999 (while (string-match org-ts-regexp s)
8000 (setq s (replace-match "" t t s))))
8001 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8002 (setq s (replace-match " " t t s)))
8003 (or string (setq s (concat "*" s))) ; Add * for headlines
8004 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8005
8006 (defun org-make-org-heading-camel (&optional string heading)
8007 "Make a CamelCase string for STRING or the current headline."
8008 (interactive)
8009 (let ((s (or string (org-get-heading))))
8010 (unless (and string (not heading))
8011 ;; We are using a headline, clean up garbage in there.
8012 (if (string-match org-todo-regexp s)
8013 (setq s (replace-match "" t t s)))
8014 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8015 (setq s (replace-match "" t t s)))
8016 (setq s (org-trim s))
8017 (if (string-match (concat "^\\(" org-quote-string "\\|"
8018 org-comment-string "\\)") s)
8019 (setq s (replace-match "" t t s)))
8020 (while (string-match org-ts-regexp s)
8021 (setq s (replace-match "" t t s))))
8022 (while (string-match "[^a-zA-Z_ \t]+" s)
8023 (setq s (replace-match " " t t s)))
8024 (or string (setq s (concat "*" s))) ; Add * for headlines
8025 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
8026
8027 (defun org-make-link (&rest strings)
8028 "Concatenate STRINGS, format resulting string with `org-link-format'."
8029 (format org-link-format (apply 'concat strings)))
8030
8031 (defun org-make-link-string (link &optional description)
8032 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8033 (if (eq org-link-style 'plain)
8034 (if (equal description link)
8035 link
8036 (concat description "\n" link))
8037 (when (stringp description)
8038 ;; Remove brackets from the description, they are fatal.
8039 (while (string-match "\\[\\|\\]" description)
8040 (setq description (replace-match "" t t description))))
8041 (when (equal (org-link-escape link) description)
8042 ;; No description needed, it is identical
8043 (setq description nil))
8044 (when (and (not description)
8045 (not (equal link (org-link-escape link))))
8046 (setq description link))
8047 (concat "[[" (org-link-escape link) "]"
8048 (if description (concat "[" description "]") "")
8049 "]")))
8050
8051 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
8052 "Association list of escapes for some characters problematic in links.")
8053
8054 (defun org-link-escape (text)
8055 "Escape charaters in TEXT that are problematic for links."
8056 (when text
8057 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
8058 org-link-escape-chars "\\|")))
8059 (while (string-match re text)
8060 (setq text
8061 (replace-match
8062 (cdr (assoc (match-string 0 text) org-link-escape-chars))
8063 t t text)))
8064 text)))
8065
8066 (defun org-link-unescape (text)
8067 "Reverse the action of `org-link-escape'."
8068 (when text
8069 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
8070 org-link-escape-chars "\\|")))
8071 (while (string-match re text)
8072 (setq text
8073 (replace-match
8074 (car (rassoc (match-string 0 text) org-link-escape-chars))
8075 t t text)))
8076 text)))
8077
8078 (defun org-xor (a b)
8079 "Exclusive or."
8080 (if a (not b) b))
8081
8082 (defun org-get-header (header)
8083 "Find a header field in the current buffer."
8084 (save-excursion
8085 (goto-char (point-min))
8086 (let ((case-fold-search t) s)
8087 (cond
8088 ((eq header 'from)
8089 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
8090 (setq s (match-string 1)))
8091 (while (string-match "\"" s)
8092 (setq s (replace-match "" t t s)))
8093 (if (string-match "[<(].*" s)
8094 (setq s (replace-match "" t t s))))
8095 ((eq header 'message-id)
8096 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
8097 (setq s (match-string 1))))
8098 ((eq header 'subject)
8099 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
8100 (setq s (match-string 1)))))
8101 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
8102 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
8103 s)))
8104
8105
8106 (defun org-fixup-message-id-for-http (s)
8107 "Replace special characters in a message id, so it can be used in an http query."
8108 (while (string-match "<" s)
8109 (setq s (replace-match "%3C" t t s)))
8110 (while (string-match ">" s)
8111 (setq s (replace-match "%3E" t t s)))
8112 (while (string-match "@" s)
8113 (setq s (replace-match "%40" t t s)))
8114 s)
8115
8116 (defun org-insert-link (&optional complete-file)
8117 "Insert a link. At the prompt, enter the link.
8118
8119 Completion can be used to select a link previously stored with
8120 `org-store-link'. When the empty string is entered (i.e. if you just
8121 press RET at the prompt), the link defaults to the most recently
8122 stored link. As SPC triggers completion in the minibuffer, you need to
8123 use M-SPC or C-q SPC to force the insertion of a space character.
8124
8125 You will also be prompted for a description, and if one is given, it will
8126 be displayed in the buffer instead of the link.
8127
8128 If there is already a link at point, this command will allow you to edit link
8129 and description parts.
8130
8131 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
8132 selected using completion. The path to the file will be relative to
8133 the current directory if the file is in the current directory or a
8134 subdirectory. Otherwise, the link will be the absolute path as
8135 completed in the minibuffer (i.e. normally ~/path/to/file).
8136
8137 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
8138 is in the current directory or below."
8139 (interactive "P")
8140 (let (link desc entry remove file (pos (point)))
8141 (cond
8142 ((save-excursion
8143 (skip-chars-forward "^]\n\r")
8144 (and (re-search-backward "\\[\\[" nil t)
8145 (looking-at org-bracket-link-regexp)
8146 (<= (match-beginning 0) pos)
8147 (>= (match-end 0) pos)))
8148 ;; We do have a link at point, and we are going to edit it.
8149 (setq remove (list (match-beginning 0) (match-end 0)))
8150 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8151 (setq link (read-string "Link: "
8152 (org-link-unescape
8153 (org-match-string-no-properties 1)))))
8154 (complete-file
8155 ;; Completing read for file names.
8156 (setq file (read-file-name "File: "))
8157 (let ((pwd (file-name-as-directory (expand-file-name "."))))
8158 (cond
8159 ((equal complete-file '(16))
8160 (setq link (org-make-link
8161 "file:"
8162 (abbreviate-file-name (expand-file-name file)))))
8163 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8164 (expand-file-name file))
8165 (setq link (org-make-link
8166 "file:" (match-string 1 (expand-file-name file)))))
8167 (t (setq link (org-make-link "file:" file))))))
8168 (t
8169 ;; Read link, with completion for stored links.
8170 (setq link (org-completing-read
8171 "Link: " org-stored-links nil nil nil
8172 org-insert-link-history
8173 (or (car (car org-stored-links)))))
8174 (setq entry (assoc link org-stored-links))
8175 (if (not org-keep-stored-link-after-insertion)
8176 (setq org-stored-links (delq (assoc link org-stored-links)
8177 org-stored-links)))
8178 (setq link (if entry (nth 1 entry) link)
8179 desc (or desc (nth 2 entry)))))
8180
8181 (if (string-match org-plain-link-re link)
8182 ;; URL-like link, normalize the use of angular brackets.
8183 (setq link (org-make-link (org-remove-angle-brackets link))))
8184
8185 ;; Check if we are linking to the current file. If yes, simplify the link.
8186 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
8187 (let* ((path (match-string 1 link))
8188 (case-fold-search nil)
8189 (search (match-string 2 link)))
8190 (when (save-match-data
8191 (equal (file-truename buffer-file-name)
8192 (file-truename path)))
8193 ;; We are linking to this same file, with a search option
8194 (setq link search))))
8195 (setq desc (read-string "Description: " desc))
8196 (unless (string-match "\\S-" desc) (setq desc nil))
8197 (if remove (apply 'delete-region remove))
8198 (insert (org-make-link-string link desc))))
8199
8200 (defun org-completing-read (&rest args)
8201 (let ((minibuffer-local-completion-map
8202 (copy-keymap minibuffer-local-completion-map)))
8203 (define-key minibuffer-local-completion-map " " 'self-insert-command)
8204 (apply 'completing-read args)))
8205
8206 ;;; Hooks for remember.el
8207
8208 (defvar org-finish-function nil)
8209
8210 ;;;###autoload
8211 (defun org-remember-annotation ()
8212 "Return a link to the current location as an annotation for remember.el.
8213 If you are using Org-mode files as target for data storage with
8214 remember.el, then the annotations should include a link compatible with the
8215 conventions in Org-mode. This function returns such a link."
8216 (org-store-link nil))
8217
8218 (defconst org-remember-help
8219 "Select a destination location for the note.
8220 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
8221 RET at beg-of-buf -> Append to file as level 2 headline
8222 RET on headline -> Store as sublevel entry to current headline
8223 <left>/<right> -> before/after current headline, same headings level")
8224
8225 ;;;###autoload
8226 (defun org-remember-apply-template ()
8227 "Initialize *remember* buffer with template, invode `org-mode'.
8228 This function should be placed into `remember-mode-hook' and in fact requires
8229 to be run from that hook to fucntion properly."
8230 (when org-remember-templates
8231 (let* ((entry (if (= (length org-remember-templates) 1)
8232 (cdar org-remember-templates)
8233 (message "Select template: %s"
8234 (mapconcat
8235 (lambda (x) (char-to-string (car x)))
8236 org-remember-templates " "))
8237 (cdr (assoc (read-char-exclusive) org-remember-templates))))
8238 (tpl (if (consp (cdr entry)) (cadr entry) (cdr entry)))
8239 (file (if (consp (cdr entry)) (nth 2 entry)))
8240 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
8241 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
8242 (v-u (concat "[" (substring v-t 1 -1) "]"))
8243 (v-U (concat "[" (substring v-T 1 -1) "]"))
8244 (v-a annotation) ; defined in `remember-mode'
8245 (v-i initial) ; defined in `remember-mode'
8246 (v-n user-full-name)
8247 )
8248 (unless tpl (setq tpl "") (message "No template") (ding))
8249 (insert tpl) (goto-char (point-min))
8250 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
8251 (when (and initial (equal (match-string 0) "%i"))
8252 (save-match-data
8253 (let* ((lead (buffer-substring
8254 (point-at-bol) (match-beginning 0))))
8255 (setq v-i (mapconcat 'identity
8256 (org-split-string initial "\n")
8257 (concat "\n" lead))))))
8258 (replace-match
8259 (or (eval (intern (concat "v-" (match-string 1)))) "")
8260 t t))
8261 (let ((org-startup-folded nil)
8262 (org-startup-with-deadline-check nil))
8263 (org-mode))
8264 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
8265 (set (make-local-variable 'org-default-notes-file) file))
8266 (goto-char (point-min))
8267 (if (re-search-forward "%\\?" nil t) (replace-match ""))
8268 (set (make-local-variable 'org-finish-function) 'remember-buffer))))
8269
8270 ;;;###autoload
8271 (defun org-remember-handler ()
8272 "Store stuff from remember.el into an org file.
8273 First prompts for an org file. If the user just presses return, the value
8274 of `org-default-notes-file' is used.
8275 Then the command offers the headings tree of the selected file in order to
8276 file the text at a specific location.
8277 You can either immediately press RET to get the note appended to the
8278 file, or you can use vertical cursor motion and visibility cycling (TAB) to
8279 find a better place. Then press RET or <left> or <right> in insert the note.
8280
8281 Key Cursor position Note gets inserted
8282 -----------------------------------------------------------------------------
8283 RET buffer-start as level 2 heading at end of file
8284 RET on headline as sublevel of the heading at cursor
8285 RET no heading at cursor position, level taken from context.
8286 Or use prefix arg to specify level manually.
8287 <left> on headline as same level, before current heading
8288 <right> on headline as same level, after current heading
8289
8290 So the fastest way to store the note is to press RET RET to append it to
8291 the default file. This way your current train of thought is not
8292 interrupted, in accordance with the principles of remember.el. But with
8293 little extra effort, you can push it directly to the correct location.
8294
8295 Before being stored away, the function ensures that the text has a
8296 headline, i.e. a first line that starts with a \"*\". If not, a headline
8297 is constructed from the current date and some additional data.
8298
8299 If the variable `org-adapt-indentation' is non-nil, the entire text is
8300 also indented so that it starts in the same column as the headline
8301 \(i.e. after the stars).
8302
8303 See also the variable `org-reverse-note-order'."
8304 (catch 'quit
8305 (let* ((txt (buffer-substring (point-min) (point-max)))
8306 (fastp current-prefix-arg)
8307 (file (if fastp org-default-notes-file (org-get-org-file)))
8308 (visiting (find-buffer-visiting file))
8309 (org-startup-with-deadline-check nil)
8310 (org-startup-folded nil)
8311 (org-startup-align-all-tables nil)
8312 spos level indent reversed)
8313 ;; Modify text so that it becomes a nice subtree which can be inserted
8314 ;; into an org tree.
8315 (let* ((lines (split-string txt "\n"))
8316 first)
8317 ;; remove empty lines at the beginning
8318 (while (and lines (string-match "^[ \t]*\n" (car lines)))
8319 (setq lines (cdr lines)))
8320 (setq first (car lines) lines (cdr lines))
8321 (if (string-match "^\\*+" first)
8322 ;; Is already a headline
8323 (setq indent nil)
8324 ;; We need to add a headline: Use time and first buffer line
8325 (setq lines (cons first lines)
8326 first (concat "* " (current-time-string)
8327 " (" (remember-buffer-desc) ")")
8328 indent " "))
8329 (if (and org-adapt-indentation indent)
8330 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
8331 (setq txt (concat first "\n"
8332 (mapconcat 'identity lines "\n"))))
8333 ;; Find the file
8334 (if (not visiting)
8335 (find-file-noselect file))
8336 (with-current-buffer (get-file-buffer file)
8337 (setq reversed (org-notes-order-reversed-p))
8338 (save-excursion
8339 (save-restriction
8340 (widen)
8341 ;; Ask the User for a location
8342 (setq spos (if fastp 1 (org-get-location
8343 (current-buffer)
8344 org-remember-help)))
8345 (if (not spos) (throw 'quit nil)) ; return nil to show we did
8346 ; not handle this note
8347 (goto-char spos)
8348 (cond ((bobp)
8349 ;; Put it at the start or end, as level 2
8350 (save-restriction
8351 (widen)
8352 (goto-char (if reversed (point-min) (point-max)))
8353 (if (not (bolp)) (newline))
8354 (org-paste-subtree 2 txt)))
8355 ((and (org-on-heading-p nil) (not current-prefix-arg))
8356 ;; Put it below this entry, at the beg/end of the subtree
8357 (org-back-to-heading)
8358 (setq level (funcall outline-level))
8359 (if reversed
8360 (outline-end-of-heading)
8361 (outline-end-of-subtree))
8362 (if (not (bolp)) (newline))
8363 (beginning-of-line 1)
8364 (org-paste-subtree (1+ level) txt))
8365 (t
8366 ;; Put it right there, with automatic level determined by
8367 ;; org-paste-subtree or from prefix arg
8368 (org-paste-subtree current-prefix-arg txt)))
8369 (when remember-save-after-remembering
8370 (save-buffer)
8371 (if (not visiting) (kill-buffer (current-buffer)))))))))
8372 t) ;; return t to indicate that we took care of this note.
8373
8374 (defun org-get-org-file ()
8375 "Read a filename, with default directory `org-directory'."
8376 (let ((default (or org-default-notes-file remember-data-file)))
8377 (read-file-name (format "File name [%s]: " default)
8378 (file-name-as-directory org-directory)
8379 default)))
8380
8381 (defun org-notes-order-reversed-p ()
8382 "Check if the current file should receive notes in reversed order."
8383 (cond
8384 ((not org-reverse-note-order) nil)
8385 ((eq t org-reverse-note-order) t)
8386 ((not (listp org-reverse-note-order)) nil)
8387 (t (catch 'exit
8388 (let ((all org-reverse-note-order)
8389 entry)
8390 (while (setq entry (pop all))
8391 (if (string-match (car entry) buffer-file-name)
8392 (throw 'exit (cdr entry))))
8393 nil)))))
8394
8395 ;;; Tables
8396
8397 ;; Watch out: Here we are talking about two different kind of tables.
8398 ;; Most of the code is for the tables created with the Org-mode table editor.
8399 ;; Sometimes, we talk about tables created and edited with the table.el
8400 ;; Emacs package. We call the former org-type tables, and the latter
8401 ;; table.el-type tables.
8402
8403
8404 (defun org-before-change-function (beg end)
8405 "Every change indicates that a table might need an update."
8406 (setq org-table-may-need-update t))
8407
8408 (defconst org-table-line-regexp "^[ \t]*|"
8409 "Detects an org-type table line.")
8410 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8411 "Detects an org-type table line.")
8412 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8413 "Detects a table line marked for automatic recalculation.")
8414 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8415 "Detects a table line marked for automatic recalculation.")
8416 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8417 "Detects a table line marked for automatic recalculation.")
8418 (defconst org-table-hline-regexp "^[ \t]*|-"
8419 "Detects an org-type table hline.")
8420 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8421 "Detects a table-type table hline.")
8422 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8423 "Detects an org-type or table-type table.")
8424 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8425 "Searching from within a table (any type) this finds the first line
8426 outside the table.")
8427 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8428 "Searching from within a table (any type) this finds the first line
8429 outside the table.")
8430
8431 (defun org-table-create-with-table.el ()
8432 "Use the table.el package to insert a new table.
8433 If there is already a table at point, convert between Org-mode tables
8434 and table.el tables."
8435 (interactive)
8436 (require 'table)
8437 (cond
8438 ((org-at-table.el-p)
8439 (if (y-or-n-p "Convert table to Org-mode table? ")
8440 (org-table-convert)))
8441 ((org-at-table-p)
8442 (if (y-or-n-p "Convert table to table.el table? ")
8443 (org-table-convert)))
8444 (t (call-interactively 'table-insert))))
8445
8446 (defun org-table-create-or-convert-from-region (arg)
8447 "Convert region to table, or create an empty table.
8448 If there is an active region, convert it to a table. If there is no such
8449 region, create an empty table."
8450 (interactive "P")
8451 (if (org-region-active-p)
8452 (org-table-convert-region (region-beginning) (region-end) arg)
8453 (org-table-create arg)))
8454
8455 (defun org-table-create (&optional size)
8456 "Query for a size and insert a table skeleton.
8457 SIZE is a string Columns x Rows like for example \"3x2\"."
8458 (interactive "P")
8459 (unless size
8460 (setq size (read-string
8461 (concat "Table size Columns x Rows [e.g. "
8462 org-table-default-size "]: ")
8463 "" nil org-table-default-size)))
8464
8465 (let* ((pos (point))
8466 (indent (make-string (current-column) ?\ ))
8467 (split (org-split-string size " *x *"))
8468 (rows (string-to-number (nth 1 split)))
8469 (columns (string-to-number (car split)))
8470 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8471 "\n")))
8472 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8473 (point-at-bol) (point)))
8474 (beginning-of-line 1)
8475 (newline))
8476 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8477 (dotimes (i rows) (insert line))
8478 (goto-char pos)
8479 (if (> rows 1)
8480 ;; Insert a hline after the first row.
8481 (progn
8482 (end-of-line 1)
8483 (insert "\n|-")
8484 (goto-char pos)))
8485 (org-table-align)))
8486
8487 (defun org-table-convert-region (beg0 end0 &optional nspace)
8488 "Convert region to a table.
8489 The region goes from BEG0 to END0, but these borders will be moved
8490 slightly, to make sure a beginning of line in the first line is included.
8491 When NSPACE is non-nil, it indicates the minimum number of spaces that
8492 separate columns (default: just one space)."
8493 (interactive "rP")
8494 (let* ((beg (min beg0 end0))
8495 (end (max beg0 end0))
8496 (tabsep t)
8497 re)
8498 (goto-char beg)
8499 (beginning-of-line 1)
8500 (setq beg (move-marker (make-marker) (point)))
8501 (goto-char end)
8502 (if (bolp) (backward-char 1) (end-of-line 1))
8503 (setq end (move-marker (make-marker) (point)))
8504 ;; Lets see if this is tab-separated material. If every nonempty line
8505 ;; contains a tab, we will assume that it is tab-separated material
8506 (if nspace
8507 (setq tabsep nil)
8508 (goto-char beg)
8509 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
8510 (if nspace (setq tabsep nil))
8511 (if tabsep
8512 (setq re "^\\|\t")
8513 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
8514 (max 1 (prefix-numeric-value nspace)))))
8515 (goto-char beg)
8516 (while (re-search-forward re end t)
8517 (replace-match "|" t t))
8518 (goto-char beg)
8519 (insert " ")
8520 (org-table-align)))
8521
8522 (defun org-table-import (file arg)
8523 "Import FILE as a table.
8524 The file is assumed to be tab-separated. Such files can be produced by most
8525 spreadsheet and database applications. If no tabs (at least one per line)
8526 are found, lines will be split on whitespace into fields."
8527 (interactive "f\nP")
8528 (or (bolp) (newline))
8529 (let ((beg (point))
8530 (pm (point-max)))
8531 (insert-file-contents file)
8532 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8533
8534 (defun org-table-export ()
8535 "Export table as a tab-separated file.
8536 Such a file can be imported into a spreadsheet program like Excel."
8537 (interactive)
8538 (let* ((beg (org-table-begin))
8539 (end (org-table-end))
8540 (table (buffer-substring beg end))
8541 (file (read-file-name "Export table to: "))
8542 buf)
8543 (unless (or (not (file-exists-p file))
8544 (y-or-n-p (format "Overwrite file %s? " file)))
8545 (error "Abort"))
8546 (with-current-buffer (find-file-noselect file)
8547 (setq buf (current-buffer))
8548 (erase-buffer)
8549 (fundamental-mode)
8550 (insert table)
8551 (goto-char (point-min))
8552 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8553 (replace-match "" t t)
8554 (end-of-line 1))
8555 (goto-char (point-min))
8556 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8557 (replace-match "" t t)
8558 (goto-char (min (1+ (point)) (point-max))))
8559 (goto-char (point-min))
8560 (while (re-search-forward "^-[-+]*$" nil t)
8561 (replace-match "")
8562 (if (looking-at "\n")
8563 (delete-char 1)))
8564 (goto-char (point-min))
8565 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8566 (replace-match "\t" t t))
8567 (save-buffer))
8568 (kill-buffer buf)))
8569
8570 (defvar org-table-aligned-begin-marker (make-marker)
8571 "Marker at the beginning of the table last aligned.
8572 Used to check if cursor still is in that table, to minimize realignment.")
8573 (defvar org-table-aligned-end-marker (make-marker)
8574 "Marker at the end of the table last aligned.
8575 Used to check if cursor still is in that table, to minimize realignment.")
8576 (defvar org-table-last-alignment nil
8577 "List of flags for flushright alignment, from the last re-alignment.
8578 This is being used to correctly align a single field after TAB or RET.")
8579 (defvar org-table-last-column-widths nil
8580 "List of max width of fields in each column.
8581 This is being used to correctly align a single field after TAB or RET.")
8582
8583 (defvar org-last-recalc-line nil)
8584 (defconst org-narrow-column-arrow "=>"
8585 "Used as display property in narrowed table columns.")
8586
8587 (defun org-table-align ()
8588 "Align the table at point by aligning all vertical bars."
8589 (interactive)
8590 (let* (
8591 ;; Limits of table
8592 (beg (org-table-begin))
8593 (end (org-table-end))
8594 ;; Current cursor position
8595 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8596 (colpos (org-table-current-column))
8597 (winstart (window-start))
8598 text lines (new "") lengths l typenums ty fields maxfields i
8599 column
8600 (indent "") cnt frac
8601 rfmt hfmt
8602 (spaces '(1 . 1))
8603 (sp1 (car spaces))
8604 (sp2 (cdr spaces))
8605 (rfmt1 (concat
8606 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8607 (hfmt1 (concat
8608 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8609 emptystrings xx links narrow fmax fmin f1 len c e)
8610 (untabify beg end)
8611 (remove-text-properties beg end '(org-cwidth t display t))
8612 ;; Check if we have links
8613 (goto-char beg)
8614 (setq links (re-search-forward org-bracket-link-regexp end t))
8615 ;; Make sure the link properties are right FIXME: Can this be optimized????
8616 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8617 ;; Check if we are narrowing any columns
8618 (goto-char beg)
8619 (setq narrow (and org-format-transports-properties-p
8620 (re-search-forward "<[0-9]+>" end t)))
8621 ;; Get the rows
8622 (setq lines (org-split-string
8623 (buffer-substring beg end) "\n"))
8624 ;; Store the indentation of the first line
8625 (if (string-match "^ *" (car lines))
8626 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8627 ;; Mark the hlines by setting the corresponding element to nil
8628 ;; At the same time, we remove trailing space.
8629 (setq lines (mapcar (lambda (l)
8630 (if (string-match "^ *|-" l)
8631 nil
8632 (if (string-match "[ \t]+$" l)
8633 (substring l 0 (match-beginning 0))
8634 l)))
8635 lines))
8636 ;; Get the data fields by splitting the lines.
8637 (setq fields (mapcar
8638 (lambda (l)
8639 (org-split-string l " *| *"))
8640 (delq nil (copy-sequence lines))))
8641 ;; How many fields in the longest line?
8642 (condition-case nil
8643 (setq maxfields (apply 'max (mapcar 'length fields)))
8644 (error
8645 (kill-region beg end)
8646 (org-table-create org-table-default-size)
8647 (error "Empty table - created default table")))
8648 ;; A list of empty string to fill any short rows on output
8649 (setq emptystrings (make-list maxfields ""))
8650 ;; Check for special formatting.
8651 (setq i -1)
8652 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8653 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8654 ;; Check if there is an explicit width specified
8655 (when (and org-table-limit-column-width narrow)
8656 (setq c column fmax nil)
8657 (while c
8658 (setq e (pop c))
8659 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8660 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8661 ;; Find fields that are wider than fmax, and shorten them
8662 (when fmax
8663 (loop for xx in column do
8664 (when (and (stringp xx)
8665 (> (org-string-width xx) fmax))
8666 (org-add-props xx nil
8667 'help-echo
8668 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (copy-sequence xx)))
8669 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8670 (unless (> f1 1)
8671 (error "Cannot narrow field starting with wide link \"%s\""
8672 (match-string 0 xx)))
8673 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8674 (add-text-properties (- f1 2) f1
8675 (list 'display org-narrow-column-arrow)
8676 xx)))))
8677 ;; Get the maximum width for each column
8678 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8679 ;; Get the fraction of numbers, to decide about alignment of the column
8680 (setq cnt 0 frac 0.0)
8681 (loop for x in column do
8682 (if (equal x "")
8683 nil
8684 (setq frac ( / (+ (* frac cnt)
8685 (if (string-match org-table-number-regexp x) 1 0))
8686 (setq cnt (1+ cnt))))))
8687 (push (>= frac org-table-number-fraction) typenums))
8688 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8689
8690 ;; Store the alignment of this table, for later editing of single fields
8691 (setq org-table-last-alignment typenums
8692 org-table-last-column-widths lengths)
8693
8694 ;; With invisible characters, `format' does not get the field width right
8695 ;; So we need to make these fields wide by hand.
8696 (when links
8697 (loop for i from 0 upto (1- maxfields) do
8698 (setq len (nth i lengths))
8699 (loop for j from 0 upto (1- (length fields)) do
8700 (setq c (nthcdr i (car (nthcdr j fields))))
8701 (if (and (stringp (car c))
8702 (string-match org-bracket-link-regexp (car c))
8703 (< (org-string-width (car c)) len))
8704 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8705
8706 ;; Compute the formats needed for output of the table
8707 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8708 (while (setq l (pop lengths))
8709 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8710 (setq rfmt (concat rfmt (format rfmt1 ty l))
8711 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8712 (setq rfmt (concat rfmt "\n")
8713 hfmt (concat (substring hfmt 0 -1) "|\n"))
8714
8715 (setq new (mapconcat
8716 (lambda (l)
8717 (if l (apply 'format rfmt
8718 (append (pop fields) emptystrings))
8719 hfmt))
8720 lines ""))
8721 ;; Replace the old one
8722 (delete-region beg end)
8723 (move-marker end nil)
8724 (move-marker org-table-aligned-begin-marker (point))
8725 (insert new)
8726 (move-marker org-table-aligned-end-marker (point))
8727 (when (and orgtbl-mode (not (eq major-mode 'org-mode)))
8728 (goto-char org-table-aligned-begin-marker)
8729 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8730 ;; Try to move to the old location (approximately)
8731 (goto-line linepos)
8732 (set-window-start (selected-window) winstart 'noforce)
8733 (org-table-goto-column colpos)
8734 (setq org-table-may-need-update nil)
8735 ))
8736
8737 (defun org-string-width (s)
8738 "Compute width of string, ignoring invisible characters.
8739 This ignores character with invisibility property `org-link', and also
8740 characters with property `org-cwidth', because these will become invisible
8741 upon the next fontification round."
8742 (let (b)
8743 (when (or (eq t buffer-invisibility-spec)
8744 (assq 'org-link buffer-invisibility-spec))
8745 (while (setq b (text-property-any 0 (length s)
8746 'invisible 'org-link s))
8747 (setq s (concat (substring s 0 b)
8748 (substring s (or (next-single-property-change
8749 b 'invisible s) (length s)))))))
8750 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8751 (setq s (concat (substring s 0 b)
8752 (substring s (or (next-single-property-change
8753 b 'org-cwidth s) (length s))))))
8754 (string-width s)))
8755
8756 (defun org-table-begin (&optional table-type)
8757 "Find the beginning of the table and return its position.
8758 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8759 (save-excursion
8760 (if (not (re-search-backward
8761 (if table-type org-table-any-border-regexp
8762 org-table-border-regexp)
8763 nil t))
8764 (error "Can't find beginning of table")
8765 (goto-char (match-beginning 0))
8766 (beginning-of-line 2)
8767 (point))))
8768
8769 (defun org-table-end (&optional table-type)
8770 "Find the end of the table and return its position.
8771 With argument TABLE-TYPE, go to the end of a table.el-type table."
8772 (save-excursion
8773 (if (not (re-search-forward
8774 (if table-type org-table-any-border-regexp
8775 org-table-border-regexp)
8776 nil t))
8777 (goto-char (point-max))
8778 (goto-char (match-beginning 0)))
8779 (point-marker)))
8780
8781 (defun org-table-justify-field-maybe (&optional new)
8782 "Justify the current field, text to left, number to right.
8783 Optional argument NEW may specify text to replace the current field content."
8784 (cond
8785 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8786 ((org-at-table-hline-p))
8787 ((and (not new)
8788 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8789 (current-buffer)))
8790 (< (point) org-table-aligned-begin-marker)
8791 (>= (point) org-table-aligned-end-marker)))
8792 ;; This is not the same table, force a full re-align
8793 (setq org-table-may-need-update t))
8794 (t ;; realign the current field, based on previous full realign
8795 (let* ((pos (point)) s
8796 (col (org-table-current-column))
8797 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8798 l f n o e)
8799 (when (> col 0)
8800 (skip-chars-backward "^|\n")
8801 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8802 (progn
8803 (setq s (match-string 1)
8804 o (match-string 0)
8805 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8806 e (not (= (match-beginning 2) (match-end 2))))
8807 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8808 l (if e "|" (setq org-table-may-need-update t) ""))
8809 n (format f s t t))
8810 (if new
8811 (if (<= (length new) l)
8812 (setq n (format f new t t)) ;; FIXME: why t t?????
8813 (setq n (concat new "|") org-table-may-need-update t)))
8814 (or (equal n o)
8815 (let (org-table-may-need-update)
8816 (replace-match n))))
8817 (setq org-table-may-need-update t))
8818 (goto-char pos))))))
8819
8820 (defun org-table-next-field ()
8821 "Go to the next field in the current table, creating new lines as needed.
8822 Before doing so, re-align the table if necessary."
8823 (interactive)
8824 (org-table-maybe-eval-formula)
8825 (org-table-maybe-recalculate-line)
8826 (if (and org-table-automatic-realign
8827 org-table-may-need-update)
8828 (org-table-align))
8829 (let ((end (org-table-end)))
8830 (if (org-at-table-hline-p)
8831 (end-of-line 1))
8832 (condition-case nil
8833 (progn
8834 (re-search-forward "|" end)
8835 (if (looking-at "[ \t]*$")
8836 (re-search-forward "|" end))
8837 (if (and (looking-at "-")
8838 org-table-tab-jumps-over-hlines
8839 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8840 (goto-char (match-beginning 1)))
8841 (if (looking-at "-")
8842 (progn
8843 (beginning-of-line 0)
8844 (org-table-insert-row 'below))
8845 (if (looking-at " ") (forward-char 1))))
8846 (error
8847 (org-table-insert-row 'below)))))
8848
8849 (defun org-table-previous-field ()
8850 "Go to the previous field in the table.
8851 Before doing so, re-align the table if necessary."
8852 (interactive)
8853 (org-table-justify-field-maybe)
8854 (org-table-maybe-recalculate-line)
8855 (if (and org-table-automatic-realign
8856 org-table-may-need-update)
8857 (org-table-align))
8858 (if (org-at-table-hline-p)
8859 (end-of-line 1))
8860 (re-search-backward "|" (org-table-begin))
8861 (re-search-backward "|" (org-table-begin))
8862 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8863 (re-search-backward "|" (org-table-begin)))
8864 (if (looking-at "| ?")
8865 (goto-char (match-end 0))))
8866
8867 (defun org-table-next-row ()
8868 "Go to the next row (same column) in the current table.
8869 Before doing so, re-align the table if necessary."
8870 (interactive)
8871 (org-table-maybe-eval-formula)
8872 (org-table-maybe-recalculate-line)
8873 (if (or (looking-at "[ \t]*$")
8874 (save-excursion (skip-chars-backward " \t") (bolp)))
8875 (newline)
8876 (if (and org-table-automatic-realign
8877 org-table-may-need-update)
8878 (org-table-align))
8879 (let ((col (org-table-current-column)))
8880 (beginning-of-line 2)
8881 (if (or (not (org-at-table-p))
8882 (org-at-table-hline-p))
8883 (progn
8884 (beginning-of-line 0)
8885 (org-table-insert-row 'below)))
8886 (org-table-goto-column col)
8887 (skip-chars-backward "^|\n\r")
8888 (if (looking-at " ") (forward-char 1)))))
8889
8890 (defun org-table-copy-down (n)
8891 "Copy a field down in the current column.
8892 If the field at the cursor is empty, copy into it the content of the nearest
8893 non-empty field above. With argument N, use the Nth non-empty field.
8894 If the current field is not empty, it is copied down to the next row, and
8895 the cursor is moved with it. Therefore, repeating this command causes the
8896 column to be filled row-by-row.
8897 If the variable `org-table-copy-increment' is non-nil and the field is an
8898 integer, it will be incremented while copying."
8899 (interactive "p")
8900 (let* ((colpos (org-table-current-column))
8901 (field (org-table-get-field))
8902 (non-empty (string-match "[^ \t]" field))
8903 (beg (org-table-begin))
8904 txt)
8905 (org-table-check-inside-data-field)
8906 (if non-empty
8907 (progn
8908 (setq txt (org-trim field))
8909 (org-table-next-row)
8910 (org-table-blank-field))
8911 (save-excursion
8912 (setq txt
8913 (catch 'exit
8914 (while (progn (beginning-of-line 1)
8915 (re-search-backward org-table-dataline-regexp
8916 beg t))
8917 (org-table-goto-column colpos t)
8918 (if (and (looking-at
8919 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
8920 (= (setq n (1- n)) 0))
8921 (throw 'exit (match-string 1))))))))
8922 (if txt
8923 (progn
8924 (if (and org-table-copy-increment
8925 (string-match "^[0-9]+$" txt))
8926 (setq txt (format "%d" (+ (string-to-number txt) 1))))
8927 (insert txt)
8928 (org-table-maybe-recalculate-line)
8929 (org-table-align))
8930 (error "No non-empty field found"))))
8931
8932 (defun org-table-check-inside-data-field ()
8933 "Is point inside a table data field?
8934 I.e. not on a hline or before the first or after the last column?
8935 This actually throws an error, so it aborts the current command."
8936 (if (or (not (org-at-table-p))
8937 (= (org-table-current-column) 0)
8938 (org-at-table-hline-p)
8939 (looking-at "[ \t]*$"))
8940 (error "Not in table data field")))
8941
8942 (defvar org-table-clip nil
8943 "Clipboard for table regions.")
8944
8945 (defun org-table-blank-field ()
8946 "Blank the current table field or active region."
8947 (interactive)
8948 (org-table-check-inside-data-field)
8949 (if (and (interactive-p) (org-region-active-p))
8950 (let (org-table-clip)
8951 (org-table-cut-region (region-beginning) (region-end)))
8952 (skip-chars-backward "^|")
8953 (backward-char 1)
8954 (if (looking-at "|[^|\n]+")
8955 (let* ((pos (match-beginning 0))
8956 (match (match-string 0))
8957 (len (org-string-width match)))
8958 (replace-match (concat "|" (make-string (1- len) ?\ )))
8959 (goto-char (+ 2 pos))
8960 (substring match 1)))))
8961
8962 (defun org-table-get-field (&optional n replace)
8963 "Return the value of the field in column N of current row.
8964 N defaults to current field.
8965 If REPLACE is a string, replace field with this value. The return value
8966 is always the old value."
8967 (and n (org-table-goto-column n))
8968 (skip-chars-backward "^|\n")
8969 (backward-char 1)
8970 (if (looking-at "|[^|\r\n]*")
8971 (let* ((pos (match-beginning 0))
8972 (val (buffer-substring (1+ pos) (match-end 0))))
8973 (if replace
8974 (replace-match (concat "|" replace)))
8975 (goto-char (min (point-at-eol) (+ 2 pos)))
8976 val)
8977 (forward-char 1) ""))
8978
8979 (defun org-table-current-column ()
8980 "Find out which column we are in.
8981 When called interactively, column is also displayed in echo area."
8982 (interactive)
8983 (if (interactive-p) (org-table-check-inside-data-field))
8984 (save-excursion
8985 (let ((cnt 0) (pos (point)))
8986 (beginning-of-line 1)
8987 (while (search-forward "|" pos t)
8988 (setq cnt (1+ cnt)))
8989 (if (interactive-p) (message "This is table column %d" cnt))
8990 cnt)))
8991
8992 (defun org-table-goto-column (n &optional on-delim force)
8993 "Move the cursor to the Nth column in the current table line.
8994 With optional argument ON-DELIM, stop with point before the left delimiter
8995 of the field.
8996 If there are less than N fields, just go to after the last delimiter.
8997 However, when FORCE is non-nil, create new columns if necessary."
8998 (interactive "p")
8999 (let ((pos (point-at-eol)))
9000 (beginning-of-line 1)
9001 (when (> n 0)
9002 (while (and (> (setq n (1- n)) -1)
9003 (or (search-forward "|" pos t)
9004 (and force
9005 (progn (end-of-line 1)
9006 (skip-chars-backward "^|")
9007 (insert " | "))))))
9008 ; (backward-char 2) t)))))
9009 (when (and force (not (looking-at ".*|")))
9010 (save-excursion (end-of-line 1) (insert " | ")))
9011 (if on-delim
9012 (backward-char 1)
9013 (if (looking-at " ") (forward-char 1))))))
9014
9015 (defun org-at-table-p (&optional table-type)
9016 "Return t if the cursor is inside an org-type table.
9017 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9018 (if org-enable-table-editor
9019 (save-excursion
9020 (beginning-of-line 1)
9021 (looking-at (if table-type org-table-any-line-regexp
9022 org-table-line-regexp)))
9023 nil))
9024
9025 (defun org-at-table.el-p ()
9026 "Return t if and only if we are at a table.el table."
9027 (and (org-at-table-p 'any)
9028 (save-excursion
9029 (goto-char (org-table-begin 'any))
9030 (looking-at org-table1-hline-regexp))))
9031
9032 (defun org-table-recognize-table.el ()
9033 "If there is a table.el table nearby, recognize it and move into it."
9034 (if org-table-tab-recognizes-table.el
9035 (if (org-at-table.el-p)
9036 (progn
9037 (beginning-of-line 1)
9038 (if (looking-at org-table-dataline-regexp)
9039 nil
9040 (if (looking-at org-table1-hline-regexp)
9041 (progn
9042 (beginning-of-line 2)
9043 (if (looking-at org-table-any-border-regexp)
9044 (beginning-of-line -1)))))
9045 (if (re-search-forward "|" (org-table-end t) t)
9046 (progn
9047 (require 'table)
9048 (if (table--at-cell-p (point))
9049 t
9050 (message "recognizing table.el table...")
9051 (table-recognize-table)
9052 (message "recognizing table.el table...done")))
9053 (error "This should not happen..."))
9054 t)
9055 nil)
9056 nil))
9057
9058 (defun org-at-table-hline-p ()
9059 "Return t if the cursor is inside a hline in a table."
9060 (if org-enable-table-editor
9061 (save-excursion
9062 (beginning-of-line 1)
9063 (looking-at org-table-hline-regexp))
9064 nil))
9065
9066 (defun org-table-insert-column ()
9067 "Insert a new column into the table."
9068 (interactive)
9069 (if (not (org-at-table-p))
9070 (error "Not at a table"))
9071 (org-table-find-dataline)
9072 (let* ((col (max 1 (org-table-current-column)))
9073 (beg (org-table-begin))
9074 (end (org-table-end))
9075 ;; Current cursor position
9076 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9077 (colpos col))
9078 (goto-char beg)
9079 (while (< (point) end)
9080 (if (org-at-table-hline-p)
9081 nil
9082 (org-table-goto-column col t)
9083 (insert "| "))
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 'insert col)))
9090
9091 (defun org-table-find-dataline ()
9092 "Find a dataline in the current table, which is needed for column commands."
9093 (if (and (org-at-table-p)
9094 (not (org-at-table-hline-p)))
9095 t
9096 (let ((col (current-column))
9097 (end (org-table-end)))
9098 (move-to-column col)
9099 (while (and (< (point) end)
9100 (or (not (= (current-column) col))
9101 (org-at-table-hline-p)))
9102 (beginning-of-line 2)
9103 (move-to-column col))
9104 (if (and (org-at-table-p)
9105 (not (org-at-table-hline-p)))
9106 t
9107 (error
9108 "Please position cursor in a data line for column operations")))))
9109
9110 (defun org-table-delete-column ()
9111 "Delete a column into the table."
9112 (interactive)
9113 (if (not (org-at-table-p))
9114 (error "Not at a table"))
9115 (org-table-find-dataline)
9116 (org-table-check-inside-data-field)
9117 (let* ((col (org-table-current-column))
9118 (beg (org-table-begin))
9119 (end (org-table-end))
9120 ;; Current cursor position
9121 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9122 (colpos col))
9123 (goto-char beg)
9124 (while (< (point) end)
9125 (if (org-at-table-hline-p)
9126 nil
9127 (org-table-goto-column col t)
9128 (and (looking-at "|[^|\n]+|")
9129 (replace-match "|")))
9130 (beginning-of-line 2))
9131 (move-marker end nil)
9132 (goto-line linepos)
9133 (org-table-goto-column colpos)
9134 (org-table-align)
9135 (org-table-modify-formulas 'remove col)))
9136
9137 (defun org-table-move-column-right ()
9138 "Move column to the right."
9139 (interactive)
9140 (org-table-move-column nil))
9141 (defun org-table-move-column-left ()
9142 "Move column to the left."
9143 (interactive)
9144 (org-table-move-column 'left))
9145
9146 (defun org-table-move-column (&optional left)
9147 "Move the current column to the right. With arg LEFT, move to the left."
9148 (interactive "P")
9149 (if (not (org-at-table-p))
9150 (error "Not at a table"))
9151 (org-table-find-dataline)
9152 (org-table-check-inside-data-field)
9153 (let* ((col (org-table-current-column))
9154 (col1 (if left (1- col) col))
9155 (beg (org-table-begin))
9156 (end (org-table-end))
9157 ;; Current cursor position
9158 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9159 (colpos (if left (1- col) (1+ col))))
9160 (if (and left (= col 1))
9161 (error "Cannot move column further left"))
9162 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9163 (error "Cannot move column further right"))
9164 (goto-char beg)
9165 (while (< (point) end)
9166 (if (org-at-table-hline-p)
9167 nil
9168 (org-table-goto-column col1 t)
9169 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9170 (replace-match "|\\2|\\1|")))
9171 (beginning-of-line 2))
9172 (move-marker end nil)
9173 (goto-line linepos)
9174 (org-table-goto-column colpos)
9175 (org-table-align)
9176 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
9177
9178 (defun org-table-move-row-down ()
9179 "Move table row down."
9180 (interactive)
9181 (org-table-move-row nil))
9182 (defun org-table-move-row-up ()
9183 "Move table row up."
9184 (interactive)
9185 (org-table-move-row 'up))
9186
9187 (defun org-table-move-row (&optional up)
9188 "Move the current table line down. With arg UP, move it up."
9189 (interactive "P")
9190 (let ((col (current-column))
9191 (pos (point))
9192 (tonew (if up 0 2))
9193 txt)
9194 (beginning-of-line tonew)
9195 (if (not (org-at-table-p))
9196 (progn
9197 (goto-char pos)
9198 (error "Cannot move row further")))
9199 (goto-char pos)
9200 (beginning-of-line 1)
9201 (setq pos (point))
9202 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9203 (delete-region (point) (1+ (point-at-eol)))
9204 (beginning-of-line tonew)
9205 (insert txt)
9206 (beginning-of-line 0)
9207 (move-to-column col)))
9208
9209 (defun org-table-insert-row (&optional arg)
9210 "Insert a new row above the current line into the table.
9211 With prefix ARG, insert below the current line."
9212 (interactive "P")
9213 (if (not (org-at-table-p))
9214 (error "Not at a table"))
9215 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9216 (new (org-table-clean-line line)))
9217 ;; Fix the first field if necessary
9218 (if (string-match "^[ \t]*| *[#$] *|" line)
9219 (setq new (replace-match (match-string 0 line) t t new)))
9220 (beginning-of-line (if arg 2 1))
9221 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9222 (beginning-of-line 0)
9223 (re-search-forward "| ?" (point-at-eol) t)
9224 (and org-table-may-need-update (org-table-align))))
9225
9226 (defun org-table-insert-hline (&optional arg)
9227 "Insert a horizontal-line below the current line into the table.
9228 With prefix ARG, insert above the current line."
9229 (interactive "P")
9230 (if (not (org-at-table-p))
9231 (error "Not at a table"))
9232 (let ((line (org-table-clean-line
9233 (buffer-substring (point-at-bol) (point-at-eol))))
9234 (col (current-column)))
9235 (while (string-match "|\\( +\\)|" line)
9236 (setq line (replace-match
9237 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9238 ?-) "|") t t line)))
9239 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9240 (beginning-of-line (if arg 1 2))
9241 (insert line "\n")
9242 (beginning-of-line (if arg 1 -1))
9243 (move-to-column col)))
9244
9245 (defun org-table-clean-line (s)
9246 "Convert a table line S into a string with only \"|\" and space.
9247 In particular, this does handle wide and invisible characters."
9248 (if (string-match "^[ \t]*|-" s)
9249 ;; It's a hline, just map the characters
9250 (setq s (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) s))
9251 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9252 (setq s (replace-match
9253 (concat "|" (make-string (org-string-width (match-string 1 s))
9254 ?\ ) "|")
9255 t t s)))
9256 s))
9257
9258 (defun org-table-kill-row ()
9259 "Delete the current row or horizontal line from the table."
9260 (interactive)
9261 (if (not (org-at-table-p))
9262 (error "Not at a table"))
9263 (let ((col (current-column)))
9264 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9265 (if (not (org-at-table-p)) (beginning-of-line 0))
9266 (move-to-column col)))
9267
9268 (defun org-table-sort-lines (beg end numericp)
9269 "Sort table lines in region.
9270 Point and mark define the first and last line to include. Both point and
9271 mark should be in the column that is used for sorting. For example, to
9272 sort according to column 3, put the mark in the first line to sort, in
9273 table column 3. Put point into the last line to be included in the sorting,
9274 also in table column 3. The command will prompt for the sorting method
9275 \(n for numerical, a for alphanumeric)."
9276 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
9277 (setq numericp (string-match "[nN]" numericp))
9278 (org-table-align) ;; Just to be safe
9279 (let* (bcol ecol cmp column lns)
9280 (goto-char beg)
9281 (org-table-check-inside-data-field)
9282 (setq column (org-table-current-column)
9283 beg (move-marker (make-marker) (point-at-bol)))
9284 (goto-char end)
9285 (org-table-check-inside-data-field)
9286 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
9287 (untabify beg end)
9288 (goto-char beg)
9289 (org-table-goto-column column)
9290 (skip-chars-backward "^|")
9291 (setq bcol (current-column))
9292 (org-table-goto-column (1+ column))
9293 (skip-chars-backward "^|")
9294 (setq ecol (1- (current-column)))
9295 (setq cmp (if numericp
9296 (lambda (a b) (< (car a) (car b)))
9297 (lambda (a b) (string< (car a) (car b)))))
9298 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
9299 (split-string (buffer-substring beg end) "\n")))
9300 (if numericp
9301 (setq lns (mapcar (lambda(x)
9302 (cons (string-to-number (car x)) (cdr x)))
9303 lns)))
9304 (delete-region beg end)
9305 (move-marker beg nil)
9306 (move-marker end nil)
9307 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
9308 (message "%d lines sorted %s based on column %d"
9309 (length lns)
9310 (if numericp "numerically" "alphabetically") column)))
9311
9312 (defun org-table-cut-region (beg end)
9313 "Copy region in table to the clipboard and blank all relevant fields."
9314 (interactive "r")
9315 (org-table-copy-region beg end 'cut))
9316
9317 (defun org-table-copy-region (beg end &optional cut)
9318 "Copy rectangular region in table to clipboard.
9319 A special clipboard is used which can only be accessed
9320 with `org-table-paste-rectangle'."
9321 (interactive "rP")
9322 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9323 region cols
9324 (rpl (if cut " " nil)))
9325 (goto-char beg)
9326 (org-table-check-inside-data-field)
9327 (setq l01 (count-lines (point-min) (point))
9328 c01 (org-table-current-column))
9329 (goto-char end)
9330 (org-table-check-inside-data-field)
9331 (setq l02 (count-lines (point-min) (point))
9332 c02 (org-table-current-column))
9333 (setq l1 (min l01 l02) l2 (max l01 l02)
9334 c1 (min c01 c02) c2 (max c01 c02))
9335 (catch 'exit
9336 (while t
9337 (catch 'nextline
9338 (if (> l1 l2) (throw 'exit t))
9339 (goto-line l1)
9340 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9341 (setq cols nil ic1 c1 ic2 c2)
9342 (while (< ic1 (1+ ic2))
9343 (push (org-table-get-field ic1 rpl) cols)
9344 (setq ic1 (1+ ic1)))
9345 (push (nreverse cols) region)
9346 (setq l1 (1+ l1)))))
9347 (setq org-table-clip (nreverse region))
9348 (if cut (org-table-align))
9349 org-table-clip))
9350
9351 (defun org-table-paste-rectangle ()
9352 "Paste a rectangular region into a table.
9353 The upper right corner ends up in the current field. All involved fields
9354 will be overwritten. If the rectangle does not fit into the present table,
9355 the table is enlarged as needed. The process ignores horizontal separator
9356 lines."
9357 (interactive)
9358 (unless (and org-table-clip (listp org-table-clip))
9359 (error "First cut/copy a region to paste!"))
9360 (org-table-check-inside-data-field)
9361 (let* ((clip org-table-clip)
9362 (line (count-lines (point-min) (point)))
9363 (col (org-table-current-column))
9364 (org-enable-table-editor t)
9365 (org-table-automatic-realign nil)
9366 c cols field)
9367 (while (setq cols (pop clip))
9368 (while (org-at-table-hline-p) (beginning-of-line 2))
9369 (if (not (org-at-table-p))
9370 (progn (end-of-line 0) (org-table-next-field)))
9371 (setq c col)
9372 (while (setq field (pop cols))
9373 (org-table-goto-column c nil 'force)
9374 (org-table-get-field nil field)
9375 (setq c (1+ c)))
9376 (beginning-of-line 2))
9377 (goto-line line)
9378 (org-table-goto-column col)
9379 (org-table-align)))
9380
9381 (defun org-table-convert ()
9382 "Convert from `org-mode' table to table.el and back.
9383 Obviously, this only works within limits. When an Org-mode table is
9384 converted to table.el, all horizontal separator lines get lost, because
9385 table.el uses these as cell boundaries and has no notion of horizontal lines.
9386 A table.el table can be converted to an Org-mode table only if it does not
9387 do row or column spanning. Multiline cells will become multiple cells.
9388 Beware, Org-mode does not test if the table can be successfully converted - it
9389 blindly applies a recipe that works for simple tables."
9390 (interactive)
9391 (require 'table)
9392 (if (org-at-table.el-p)
9393 ;; convert to Org-mode table
9394 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9395 (end (move-marker (make-marker) (org-table-end t))))
9396 (table-unrecognize-region beg end)
9397 (goto-char beg)
9398 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9399 (replace-match ""))
9400 (goto-char beg))
9401 (if (org-at-table-p)
9402 ;; convert to table.el table
9403 (let ((beg (move-marker (make-marker) (org-table-begin)))
9404 (end (move-marker (make-marker) (org-table-end))))
9405 ;; first, get rid of all horizontal lines
9406 (goto-char beg)
9407 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9408 (replace-match ""))
9409 ;; insert a hline before first
9410 (goto-char beg)
9411 (org-table-insert-hline 'above)
9412 (beginning-of-line -1)
9413 ;; insert a hline after each line
9414 (while (progn (beginning-of-line 3) (< (point) end))
9415 (org-table-insert-hline))
9416 (goto-char beg)
9417 (setq end (move-marker end (org-table-end)))
9418 ;; replace "+" at beginning and ending of hlines
9419 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9420 (replace-match "\\1+-"))
9421 (goto-char beg)
9422 (while (re-search-forward "-|[ \t]*$" end t)
9423 (replace-match "-+"))
9424 (goto-char beg)))))
9425
9426 (defun org-table-wrap-region (arg)
9427 "Wrap several fields in a column like a paragraph.
9428 This is useful if you'd like to spread the contents of a field over several
9429 lines, in order to keep the table compact.
9430
9431 If there is an active region, and both point and mark are in the same column,
9432 the text in the column is wrapped to minimum width for the given number of
9433 lines. Generally, this makes the table more compact. A prefix ARG may be
9434 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9435 formats the selected text to two lines. If the region was longer than two
9436 lines, the remaining lines remain empty. A negative prefix argument reduces
9437 the current number of lines by that amount. The wrapped text is pasted back
9438 into the table. If you formatted it to more lines than it was before, fields
9439 further down in the table get overwritten - so you might need to make space in
9440 the table first.
9441
9442 If there is no region, the current field is split at the cursor position and
9443 the text fragment to the right of the cursor is prepended to the field one
9444 line down.
9445
9446 If there is no region, but you specify a prefix ARG, the current field gets
9447 blank, and the content is appended to the field above."
9448 (interactive "P")
9449 (org-table-check-inside-data-field)
9450 (if (org-region-active-p)
9451 ;; There is a region: fill as a paragraph
9452 (let ((beg (region-beginning))
9453 nlines)
9454 (org-table-cut-region (region-beginning) (region-end))
9455 (if (> (length (car org-table-clip)) 1)
9456 (error "Region must be limited to single column"))
9457 (setq nlines (if arg
9458 (if (< arg 1)
9459 (+ (length org-table-clip) arg)
9460 arg)
9461 (length org-table-clip)))
9462 (setq org-table-clip
9463 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9464 nil nlines)))
9465 (goto-char beg)
9466 (org-table-paste-rectangle))
9467 ;; No region, split the current field at point
9468 (if arg
9469 ;; combine with field above
9470 (let ((s (org-table-blank-field))
9471 (col (org-table-current-column)))
9472 (beginning-of-line 0)
9473 (while (org-at-table-hline-p) (beginning-of-line 0))
9474 (org-table-goto-column col)
9475 (skip-chars-forward "^|")
9476 (skip-chars-backward " ")
9477 (insert " " (org-trim s))
9478 (org-table-align))
9479 ;; split field
9480 (when (looking-at "\\([^|]+\\)+|")
9481 (let ((s (match-string 1)))
9482 (replace-match " |")
9483 (goto-char (match-beginning 0))
9484 (org-table-next-row)
9485 (insert (org-trim s) " ")
9486 (org-table-align))))))
9487
9488 (defvar org-field-marker nil)
9489
9490 (defun org-table-edit-field (arg)
9491 "Edit table field in a different window.
9492 This is mainly useful for fields that contain hidden parts.
9493 When called with a \\[universal-argument] prefix, just make the full field visible so that
9494 it can be edited in place."
9495 (interactive "P")
9496 (if arg
9497 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9498 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9499 (remove-text-properties b e '(org-cwidth t invisible t
9500 display t intangible t))
9501 (if (and (boundp 'font-lock-mode) font-lock-mode)
9502 (font-lock-fontify-block)))
9503 (let ((pos (move-marker (make-marker) (point)))
9504 (field (org-table-get-field))
9505 (cw (current-window-configuration))
9506 p)
9507 (switch-to-buffer-other-window "*Org tmp*")
9508 (erase-buffer)
9509 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9510 (org-mode)
9511 (goto-char (setq p (point-max)))
9512 (insert (org-trim field))
9513 (remove-text-properties p (point-max)
9514 '(invisible t org-cwidth t display t
9515 intangible t))
9516 (goto-char p)
9517 (set (make-local-variable 'org-finish-function)
9518 'org-table-finish-edit-field)
9519 (set (make-local-variable 'org-window-configuration) cw)
9520 (set (make-local-variable 'org-field-marker) pos)
9521 (message "Edit and finish with C-c C-c"))))
9522
9523 (defun org-table-finish-edit-field ()
9524 "Finish editing a table data field.
9525 Remove all newline characters, insert the result into the table, realign
9526 the table and kill the editing buffer."
9527 (let ((pos org-field-marker)
9528 (cw org-window-configuration)
9529 (cb (current-buffer))
9530 text)
9531 (goto-char (point-min))
9532 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9533 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9534 (replace-match " "))
9535 (setq text (org-trim (buffer-string)))
9536 (set-window-configuration cw)
9537 (kill-buffer cb)
9538 (select-window (get-buffer-window (marker-buffer pos)))
9539 (goto-char pos)
9540 (move-marker pos nil)
9541 (org-table-check-inside-data-field)
9542 (org-table-get-field nil text)
9543 (org-table-align)
9544 (message "New field value inserted")))
9545
9546 (defun org-trim (s)
9547 "Remove whitespace at beginning and end of string."
9548 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
9549 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
9550 s)
9551
9552 (defun org-wrap (string &optional width lines)
9553 "Wrap string to either a number of lines, or a width in characters.
9554 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9555 that costs. If there is a word longer than WIDTH, the text is actually
9556 wrapped to the length of that word.
9557 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9558 many lines, whatever width that takes.
9559 The return value is a list of lines, without newlines at the end."
9560 (let* ((words (org-split-string string "[ \t\n]+"))
9561 (maxword (apply 'max (mapcar 'org-string-width words)))
9562 w ll)
9563 (cond (width
9564 (org-do-wrap words (max maxword width)))
9565 (lines
9566 (setq w maxword)
9567 (setq ll (org-do-wrap words maxword))
9568 (if (<= (length ll) lines)
9569 ll
9570 (setq ll words)
9571 (while (> (length ll) lines)
9572 (setq w (1+ w))
9573 (setq ll (org-do-wrap words w)))
9574 ll))
9575 (t (error "Cannot wrap this")))))
9576
9577
9578 (defun org-do-wrap (words width)
9579 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9580 (let (lines line)
9581 (while words
9582 (setq line (pop words))
9583 (while (and words (< (+ (length line) (length (car words))) width))
9584 (setq line (concat line " " (pop words))))
9585 (setq lines (push line lines)))
9586 (nreverse lines)))
9587
9588 (defun org-split-string (string &optional separators)
9589 "Splits STRING into substrings at SEPARATORS.
9590 No empty strings are returned if there are matches at the beginning
9591 and end of string."
9592 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9593 (start 0)
9594 notfirst
9595 (list nil))
9596 (while (and (string-match rexp string
9597 (if (and notfirst
9598 (= start (match-beginning 0))
9599 (< start (length string)))
9600 (1+ start) start))
9601 (< (match-beginning 0) (length string)))
9602 (setq notfirst t)
9603 (or (eq (match-beginning 0) 0)
9604 (and (eq (match-beginning 0) (match-end 0))
9605 (eq (match-beginning 0) start))
9606 (setq list
9607 (cons (substring string start (match-beginning 0))
9608 list)))
9609 (setq start (match-end 0)))
9610 (or (eq start (length string))
9611 (setq list
9612 (cons (substring string start)
9613 list)))
9614 (nreverse list)))
9615
9616 (defun org-table-map-tables (function)
9617 "Apply FUNCTION to the start of all tables in the buffer."
9618 (save-excursion
9619 (save-restriction
9620 (widen)
9621 (goto-char (point-min))
9622 (while (re-search-forward org-table-any-line-regexp nil t)
9623 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9624 (beginning-of-line 1)
9625 (if (looking-at org-table-line-regexp)
9626 (save-excursion (funcall function)))
9627 (re-search-forward org-table-any-border-regexp nil 1))))
9628 (message "Mapping tables: done"))
9629
9630 (defun org-table-sum (&optional beg end nlast)
9631 "Sum numbers in region of current table column.
9632 The result will be displayed in the echo area, and will be available
9633 as kill to be inserted with \\[yank].
9634
9635 If there is an active region, it is interpreted as a rectangle and all
9636 numbers in that rectangle will be summed. If there is no active
9637 region and point is located in a table column, sum all numbers in that
9638 column.
9639
9640 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9641 numbers are assumed to be times as well (in decimal hours) and the
9642 numbers are added as such.
9643
9644 If NLAST is a number, only the NLAST fields will actually be summed."
9645 (interactive)
9646 (save-excursion
9647 (let (col (timecnt 0) diff h m s org-table-clip)
9648 (cond
9649 ((and beg end)) ; beg and end given explicitly
9650 ((org-region-active-p)
9651 (setq beg (region-beginning) end (region-end)))
9652 (t
9653 (setq col (org-table-current-column))
9654 (goto-char (org-table-begin))
9655 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9656 (error "No table data"))
9657 (org-table-goto-column col)
9658 ;not needed? (skip-chars-backward "^|")
9659 (setq beg (point))
9660 (goto-char (org-table-end))
9661 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9662 (error "No table data"))
9663 (org-table-goto-column col)
9664 ;not needed? (skip-chars-forward "^|")
9665 (setq end (point))))
9666 (let* ((items (apply 'append (org-table-copy-region beg end)))
9667 (items1 (cond ((not nlast) items)
9668 ((>= nlast (length items)) items)
9669 (t (setq items (reverse items))
9670 (setcdr (nthcdr (1- nlast) items) nil)
9671 (nreverse items))))
9672 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9673 items1)))
9674 (res (apply '+ numbers))
9675 (sres (if (= timecnt 0)
9676 (format "%g" res)
9677 (setq diff (* 3600 res)
9678 h (floor (/ diff 3600)) diff (mod diff 3600)
9679 m (floor (/ diff 60)) diff (mod diff 60)
9680 s diff)
9681 (format "%d:%02d:%02d" h m s))))
9682 (kill-new sres)
9683 (if (interactive-p)
9684 (message "%s"
9685 (substitute-command-keys
9686 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9687 (length numbers) sres))))
9688 sres))))
9689
9690 (defun org-table-get-number-for-summing (s)
9691 (let (n)
9692 (if (string-match "^ *|? *" s)
9693 (setq s (replace-match "" nil nil s)))
9694 (if (string-match " *|? *$" s)
9695 (setq s (replace-match "" nil nil s)))
9696 (setq n (string-to-number s))
9697 (cond
9698 ((and (string-match "0" s)
9699 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9700 ((string-match "\\`[ \t]+\\'" s) nil)
9701 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9702 (let ((h (string-to-number (or (match-string 1 s) "0")))
9703 (m (string-to-number (or (match-string 2 s) "0")))
9704 (s (string-to-number (or (match-string 4 s) "0"))))
9705 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9706 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9707 ((equal n 0) nil)
9708 (t n))))
9709
9710 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9711 "Get a calc vector from a column, accorting to descriptor DESC.
9712 Optional arguments TBEG and COL can give the beginning of the table and
9713 the current column, to avoid unnecessary parsing."
9714 (save-excursion
9715 (or tbeg (setq tbeg (org-table-begin)))
9716 (or col (setq col (org-table-current-column)))
9717 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9718 (cond
9719 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9720 (setq n1 (- (match-end 1) (match-beginning 1)))
9721 (if (match-beginning 3)
9722 (setq n2 (- (match-end 2) (match-beginning 3))))
9723 (setq n (if n2 (max n1 n2) n1))
9724 (setq n1 (if n2 (min n1 n2)))
9725 (setq nn n)
9726 (while (and (> nn 0)
9727 (re-search-backward org-table-hline-regexp tbeg t))
9728 (push (org-current-line) hline-list)
9729 (setq nn (1- nn)))
9730 (setq hline-list (nreverse hline-list))
9731 (goto-line (nth (1- n) hline-list))
9732 (when (re-search-forward org-table-dataline-regexp)
9733 (org-table-goto-column col)
9734 (setq beg (point)))
9735 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9736 (when (re-search-backward org-table-dataline-regexp)
9737 (org-table-goto-column col)
9738 (setq end (point)))
9739 (setq l (apply 'append (org-table-copy-region beg end)))
9740 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9741 (if (equal x "") "0" x))
9742 l ",") "]"))
9743 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9744 (setq n1 (string-to-number (match-string 1 desc))
9745 n2 (string-to-number (match-string 2 desc)))
9746 (beginning-of-line 1)
9747 (save-excursion
9748 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9749 (org-table-goto-column col)
9750 (setq beg (point))))
9751 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9752 (org-table-goto-column col)
9753 (setq end (point)))
9754 (setq l (apply 'append (org-table-copy-region beg end)))
9755 (concat "[" (mapconcat
9756 (lambda (x) (setq x (org-trim x))
9757 (if (equal x "") "0" x))
9758 l ",") "]"))
9759 ((string-match "\\([0-9]+\\)" desc)
9760 (beginning-of-line 1)
9761 (when (re-search-backward org-table-dataline-regexp tbeg t
9762 (string-to-number (match-string 0 desc)))
9763 (org-table-goto-column col)
9764 (org-trim (org-table-get-field))))))))
9765
9766 (defvar org-table-formula-history nil)
9767
9768 (defvar org-table-column-names nil
9769 "Alist with column names, derived from the `!' line.")
9770 (defvar org-table-column-name-regexp nil
9771 "Regular expression matching the current column names.")
9772 (defvar org-table-local-parameters nil
9773 "Alist with parameter names, derived from the `$' line.")
9774 (defvar org-table-named-field-locations nil
9775 "Alist with locations of named fields.")
9776
9777 (defun org-table-get-formula (&optional equation named)
9778 "Read a formula from the minibuffer, offer stored formula as default."
9779 (let* ((name (car (rassoc (list (org-current-line)
9780 (org-table-current-column))
9781 org-table-named-field-locations)))
9782 (scol (if named
9783 (if name name
9784 (error "Not in a named field"))
9785 (int-to-string (org-table-current-column))))
9786 (dummy (and name (not named)
9787 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9788 (error "Abort")))
9789 (org-table-may-need-update nil)
9790 (stored-list (org-table-get-stored-formulas))
9791 (stored (cdr (assoc scol stored-list)))
9792 (eq (cond
9793 ((and stored equation (string-match "^ *=? *$" equation))
9794 stored)
9795 ((stringp equation)
9796 equation)
9797 (t (read-string
9798 (format "%s formula $%s=" (if named "Field" "Column") scol)
9799 (or stored "") 'org-table-formula-history
9800 ;stored
9801 ))))
9802 mustsave)
9803 (when (not (string-match "\\S-" eq))
9804 ;; remove formula
9805 (setq stored-list (delq (assoc scol stored-list) stored-list))
9806 (org-table-store-formulas stored-list)
9807 (error "Formula removed"))
9808 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9809 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9810 (if (and name (not named))
9811 ;; We set the column equation, delete the named one.
9812 (setq stored-list (delq (assoc name stored-list) stored-list)
9813 mustsave t))
9814 (if stored
9815 (setcdr (assoc scol stored-list) eq)
9816 (setq stored-list (cons (cons scol eq) stored-list)))
9817 (if (or mustsave (not (equal stored eq)))
9818 (org-table-store-formulas stored-list))
9819 eq))
9820
9821 (defun org-table-store-formulas (alist)
9822 "Store the list of formulas below the current table."
9823 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9824 (save-excursion
9825 (goto-char (org-table-end))
9826 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9827 (delete-region (point) (match-end 0)))
9828 (insert "#+TBLFM: "
9829 (mapconcat (lambda (x)
9830 (concat "$" (car x) "=" (cdr x)))
9831 alist "::")
9832 "\n")))
9833
9834 (defun org-table-get-stored-formulas ()
9835 "Return an alist with the t=stored formulas directly after current table."
9836 (interactive)
9837 (let (scol eq eq-alist strings string seen)
9838 (save-excursion
9839 (goto-char (org-table-end))
9840 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9841 (setq strings (org-split-string (match-string 2) " *:: *"))
9842 (while (setq string (pop strings))
9843 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9844 (setq scol (match-string 1 string)
9845 eq (match-string 2 string)
9846 eq-alist (cons (cons scol eq) eq-alist))
9847 (if (member scol seen)
9848 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9849 (push scol seen))))))
9850 (nreverse eq-alist)))
9851
9852 (defun org-table-modify-formulas (action &rest columns)
9853 "Modify the formulas stored below the current table.
9854 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
9855 expected, for the other actions only a single column number is needed."
9856 (let ((list (org-table-get-stored-formulas))
9857 (nmax (length (org-split-string
9858 (buffer-substring (point-at-bol) (point-at-eol))
9859 "|")))
9860 col col1 col2 scol si sc1 sc2)
9861 (cond
9862 ((null list)) ; No action needed if there are no stored formulas
9863 ((eq action 'remove)
9864 (setq col (car columns)
9865 scol (int-to-string col))
9866 (org-table-replace-in-formulas list scol "INVALID")
9867 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
9868 (loop for i from (1+ col) upto nmax by 1 do
9869 (setq si (int-to-string i))
9870 (org-table-replace-in-formulas list si (int-to-string (1- i)))
9871 (if (assoc si list) (setcar (assoc si list)
9872 (int-to-string (1- i))))))
9873 ((eq action 'insert)
9874 (setq col (car columns))
9875 (loop for i from nmax downto col by 1 do
9876 (setq si (int-to-string i))
9877 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
9878 (if (assoc si list) (setcar (assoc si list)
9879 (int-to-string (1+ i))))))
9880 ((eq action 'swap)
9881 (setq col1 (car columns) col2 (nth 1 columns)
9882 sc1 (int-to-string col1) sc2 (int-to-string col2))
9883 ;; Hopefully, ZqZtZ will never be a name in a table
9884 (org-table-replace-in-formulas list sc1 "ZqZtZ")
9885 (org-table-replace-in-formulas list sc2 sc1)
9886 (org-table-replace-in-formulas list "ZqZtZ" sc2)
9887 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
9888 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
9889 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
9890 (t (error "Invalid action in `org-table-modify-formulas'")))
9891 (if list (org-table-store-formulas list))))
9892
9893 (defun org-table-replace-in-formulas (list s1 s2)
9894 (let (elt re s)
9895 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
9896 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
9897 re (concat (regexp-quote s1) "\\>"))
9898 (while (setq elt (pop list))
9899 (setq s (cdr elt))
9900 (while (string-match re s)
9901 (setq s (replace-match s2 t t s)))
9902 (setcdr elt s))))
9903
9904 (defun org-table-get-specials ()
9905 "Get the column names and local parameters for this table."
9906 (save-excursion
9907 (let ((beg (org-table-begin)) (end (org-table-end))
9908 names name fields fields1 field cnt c v line col)
9909 (setq org-table-column-names nil
9910 org-table-local-parameters nil
9911 org-table-named-field-locations nil)
9912 (goto-char beg)
9913 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
9914 (setq names (org-split-string (match-string 1) " *| *")
9915 cnt 1)
9916 (while (setq name (pop names))
9917 (setq cnt (1+ cnt))
9918 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
9919 (push (cons name (int-to-string cnt)) org-table-column-names))))
9920 (setq org-table-column-names (nreverse org-table-column-names))
9921 (setq org-table-column-name-regexp
9922 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
9923 (goto-char beg)
9924 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
9925 (setq fields (org-split-string (match-string 1) " *| *"))
9926 (while (setq field (pop fields))
9927 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
9928 (push (cons (match-string 1 field) (match-string 2 field))
9929 org-table-local-parameters))))
9930 (goto-char beg)
9931 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
9932 (setq c (match-string 1)
9933 fields (org-split-string (match-string 2) " *| *"))
9934 (save-excursion
9935 (beginning-of-line (if (equal c "_") 2 0))
9936 (setq line (org-current-line) col 1)
9937 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
9938 (setq fields1 (org-split-string (match-string 1) " *| *"))))
9939 (while (and fields1 (setq field (pop fields)))
9940 (setq v (pop fields1) col (1+ col))
9941 (when (and (stringp field) (stringp v)
9942 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
9943 (push (cons field v) org-table-local-parameters)
9944 (push (list field line col) org-table-named-field-locations)))))))
9945
9946 (defun org-this-word ()
9947 ;; Get the current word
9948 (save-excursion
9949 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
9950 (end (progn (skip-chars-forward "^ \t\n") (point))))
9951 (buffer-substring-no-properties beg end))))
9952
9953 (defun org-table-maybe-eval-formula ()
9954 "Check if the current field starts with \"=\" or \":=\".
9955 If yes, store the formula and apply it."
9956 ;; We already know we are in a table. Get field will only return a formula
9957 ;; when appropriate. It might return a separator line, but no problem.
9958 (when org-table-formula-evaluate-inline
9959 (let* ((field (org-trim (or (org-table-get-field) "")))
9960 named eq)
9961 (when (string-match "^:?=\\(.*\\)" field)
9962 (setq named (equal (string-to-char field) ?:)
9963 eq (match-string 1 field))
9964 (if (fboundp 'calc-eval)
9965 (org-table-eval-formula (if named '(4) nil) eq))))))
9966
9967 (defvar org-recalc-commands nil
9968 "List of commands triggering the recalculation of a line.
9969 Will be filled automatically during use.")
9970
9971 (defvar org-recalc-marks
9972 '((" " . "Unmarked: no special line, no automatic recalculation")
9973 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
9974 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
9975 ("!" . "Column name definition line. Reference in formula as $name.")
9976 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
9977 ("_" . "Names for values in row below this one.")
9978 ("^" . "Names for values in row above this one.")))
9979
9980 (defun org-table-rotate-recalc-marks (&optional newchar)
9981 "Rotate the recalculation mark in the first column.
9982 If in any row, the first field is not consistent with a mark,
9983 insert a new column for the markers.
9984 When there is an active region, change all the lines in the region,
9985 after prompting for the marking character.
9986 After each change, a message will be displayed indicating the meaning
9987 of the new mark."
9988 (interactive)
9989 (unless (org-at-table-p) (error "Not at a table"))
9990 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
9991 (beg (org-table-begin))
9992 (end (org-table-end))
9993 (l (org-current-line))
9994 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
9995 (l2 (if (org-region-active-p) (org-current-line (region-end))))
9996 (have-col
9997 (save-excursion
9998 (goto-char beg)
9999 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10000 (col (org-table-current-column))
10001 (forcenew (car (assoc newchar org-recalc-marks)))
10002 epos new)
10003 (when l1
10004 (message "Change region to what mark? Type # * ! $ or SPC: ")
10005 (setq newchar (char-to-string (read-char-exclusive))
10006 forcenew (car (assoc newchar org-recalc-marks))))
10007 (if (and newchar (not forcenew))
10008 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10009 newchar))
10010 (if l1 (goto-line l1))
10011 (save-excursion
10012 (beginning-of-line 1)
10013 (unless (looking-at org-table-dataline-regexp)
10014 (error "Not at a table data line")))
10015 (unless have-col
10016 (org-table-goto-column 1)
10017 (org-table-insert-column)
10018 (org-table-goto-column (1+ col)))
10019 (setq epos (point-at-eol))
10020 (save-excursion
10021 (beginning-of-line 1)
10022 (org-table-get-field
10023 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10024 (concat " "
10025 (setq new (or forcenew
10026 (cadr (member (match-string 1) marks))))
10027 " ")
10028 " # ")))
10029 (if (and l1 l2)
10030 (progn
10031 (goto-line l1)
10032 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10033 (and (looking-at org-table-dataline-regexp)
10034 (org-table-get-field 1 (concat " " new " "))))
10035 (goto-line l1)))
10036 (if (not (= epos (point-at-eol))) (org-table-align))
10037 (goto-line l)
10038 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
10039
10040 (defun org-table-maybe-recalculate-line ()
10041 "Recompute the current line if marked for it, and if we haven't just done it."
10042 (interactive)
10043 (and org-table-allow-automatic-line-recalculation
10044 (not (and (memq last-command org-recalc-commands)
10045 (equal org-last-recalc-line (org-current-line))))
10046 (save-excursion (beginning-of-line 1)
10047 (looking-at org-table-auto-recalculate-regexp))
10048 (fboundp 'calc-eval)
10049 (org-table-recalculate) t))
10050
10051 (defvar org-table-formula-debug nil
10052 "Non-nil means, debug table formulas.
10053 When nil, simply write \"#ERROR\" in corrupted fields.")
10054
10055 (defvar modes)
10056 (defsubst org-set-calc-mode (var &optional value)
10057 (if (stringp var)
10058 (setq var (assoc var '(("D" calc-angle-mode deg)
10059 ("R" calc-angle-mode rad)
10060 ("F" calc-prefer-frac t)
10061 ("S" calc-symbolic-mode t)))
10062 value (nth 2 var) var (nth 1 var)))
10063 (if (memq var modes)
10064 (setcar (cdr (memq var modes)) value)
10065 (cons var (cons value modes)))
10066 modes)
10067
10068 (defun org-table-eval-formula (&optional arg equation
10069 suppress-align suppress-const
10070 suppress-store)
10071 "Replace the table field value at the cursor by the result of a calculation.
10072
10073 This function makes use of Dave Gillespie's Calc package, in my view the
10074 most exciting program ever written for GNU Emacs. So you need to have Calc
10075 installed in order to use this function.
10076
10077 In a table, this command replaces the value in the current field with the
10078 result of a formula. It also installs the formula as the \"current\" column
10079 formula, by storing it in a special line below the table. When called
10080 with a `C-u' prefix, the current field must ba a named field, and the
10081 formula is installed as valid in only this specific field.
10082
10083 When called, the command first prompts for a formula, which is read in
10084 the minibuffer. Previously entered formulas are available through the
10085 history list, and the last used formula is offered as a default.
10086 These stored formulas are adapted correctly when moving, inserting, or
10087 deleting columns with the corresponding commands.
10088
10089 The formula can be any algebraic expression understood by the Calc package.
10090 For details, see the Org-mode manual.
10091
10092 This function can also be called from Lisp programs and offers
10093 additional arguments: EQUATION can be the formula to apply. If this
10094 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10095 used to speed-up recursive calls by by-passing unnecessary aligns.
10096 SUPPRESS-CONST suppresses the interpretation of constants in the
10097 formula, assuming that this has been done already outside the function.
10098 SUPPRESS-STORE means the formula should not be stored, either because
10099 it is already stored, or because it is a modified equation that should
10100 not overwrite the stored one."
10101 (interactive "P")
10102 (require 'calc)
10103 (org-table-check-inside-data-field)
10104 (org-table-get-specials)
10105 (let* (fields
10106 (ndown (if (integerp arg) arg 1))
10107 (org-table-automatic-realign nil)
10108 (case-fold-search nil)
10109 (down (> ndown 1))
10110 (formula (if (and equation suppress-store)
10111 equation
10112 (org-table-get-formula equation (equal arg '(4)))))
10113 (n0 (org-table-current-column))
10114 (modes (copy-sequence org-calc-default-modes))
10115 n form fmt x ev orig c)
10116 ;; Parse the format string. Since we have a lot of modes, this is
10117 ;; a lot of work. However, I think calc still uses most of the time.
10118 (if (string-match ";" formula)
10119 (let ((tmp (org-split-string formula ";")))
10120 (setq formula (car tmp)
10121 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10122 (nth 1 tmp)))
10123 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
10124 (setq c (string-to-char (match-string 1 fmt))
10125 n (string-to-number (or (match-string 1 fmt) "")))
10126 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
10127 (setq modes (org-set-calc-mode
10128 'calc-float-format
10129 (list (cdr (assoc c '((?n . float) (?f . fix)
10130 (?s . sci) (?e . eng))))
10131 n))))
10132 (setq fmt (replace-match "" t t fmt)))
10133 (while (string-match "[DRFS]" fmt)
10134 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10135 (setq fmt (replace-match "" t t fmt)))
10136 (unless (string-match "\\S-" fmt)
10137 (setq fmt nil))))
10138 (if (and (not suppress-const) org-table-formula-use-constants)
10139 (setq formula (org-table-formula-substitute-names formula)))
10140 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10141 (while (> ndown 0)
10142 (setq fields (org-split-string
10143 (buffer-substring
10144 (point-at-bol) (point-at-eol)) " *| *"))
10145 (if org-table-formula-numbers-only
10146 (setq fields (mapcar
10147 (lambda (x) (number-to-string (string-to-number x)))
10148 fields)))
10149 (setq ndown (1- ndown))
10150 (setq form (copy-sequence formula))
10151 ;; Insert the references to fields in same row
10152 (while (string-match "\\$\\([0-9]+\\)?" form)
10153 (setq n (if (match-beginning 1)
10154 (string-to-number (match-string 1 form))
10155 n0)
10156 x (nth (1- n) fields))
10157 (unless x (error "Invalid field specifier \"%s\""
10158 (match-string 0 form)))
10159 (if (equal x "") (setq x "0"))
10160 (setq form (replace-match (concat "(" x ")") t t form)))
10161 ;; Insert ranges in current column
10162 (while (string-match "\\&[-I0-9]+" form)
10163 (setq form (replace-match
10164 (save-match-data
10165 (org-table-get-vertical-vector (match-string 0 form)
10166 nil n0))
10167 t t form)))
10168 (setq ev (calc-eval (cons form modes)
10169 (if org-table-formula-numbers-only 'num)))
10170
10171 (when org-table-formula-debug
10172 (with-output-to-temp-buffer "*Help*"
10173 (princ (format "Substitution history of formula
10174 Orig: %s
10175 $xyz-> %s
10176 $1-> %s\n" orig formula form))
10177 (if (listp ev)
10178 (princ (format " %s^\nError: %s"
10179 (make-string (car ev) ?\-) (nth 1 ev)))
10180 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10181 ev (or fmt "NONE")
10182 (if fmt (format fmt (string-to-number ev)) ev)))))
10183 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
10184 (unless (and (interactive-p) (not ndown))
10185 (unless (let (inhibit-redisplay)
10186 (y-or-n-p "Debugging Formula. Continue to next? "))
10187 (org-table-align)
10188 (error "Abort"))
10189 (delete-window (get-buffer-window "*Help*"))
10190 (message "")))
10191 (if (listp ev) (setq fmt nil ev "#ERROR"))
10192 (org-table-justify-field-maybe
10193 (if fmt (format fmt (string-to-number ev)) ev))
10194 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10195 (call-interactively 'org-return)
10196 (setq ndown 0)))
10197 (and down (org-table-maybe-recalculate-line))
10198 (or suppress-align (and org-table-may-need-update
10199 (org-table-align)))))
10200
10201 (defun org-table-recalculate (&optional all noalign)
10202 "Recalculate the current table line by applying all stored formulas.
10203 With prefix arg ALL, do this for all lines in the table."
10204 (interactive "P")
10205 (or (memq this-command org-recalc-commands)
10206 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10207 (unless (org-at-table-p) (error "Not at a table"))
10208 (org-table-get-specials)
10209 (let* ((eqlist (sort (org-table-get-stored-formulas)
10210 (lambda (a b) (string< (car a) (car b)))))
10211 (inhibit-redisplay t)
10212 (line-re org-table-dataline-regexp)
10213 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10214 (thiscol (org-table-current-column))
10215 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
10216 ;; Insert constants in all formulas
10217 (setq eqlist
10218 (mapcar (lambda (x)
10219 (setcdr x (org-table-formula-substitute-names (cdr x)))
10220 x)
10221 eqlist))
10222 ;; Split the equation list
10223 (while (setq eq (pop eqlist))
10224 (if (<= (string-to-char (car eq)) ?9)
10225 (push eq eqlnum)
10226 (push eq eqlname)))
10227 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10228 (if all
10229 (progn
10230 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10231 (goto-char (setq beg (org-table-begin)))
10232 (if (re-search-forward org-table-calculate-mark-regexp end t)
10233 ;; This is a table with marked lines, only compute selected lines
10234 (setq line-re org-table-recalculate-regexp)
10235 ;; Move forward to the first non-header line
10236 (if (and (re-search-forward org-table-dataline-regexp end t)
10237 (re-search-forward org-table-hline-regexp end t)
10238 (re-search-forward org-table-dataline-regexp end t))
10239 (setq beg (match-beginning 0))
10240 nil))) ;; just leave beg where it is
10241 (setq beg (point-at-bol)
10242 end (move-marker (make-marker) (1+ (point-at-eol)))))
10243 (goto-char beg)
10244 (and all (message "Re-applying formulas to full table..."))
10245 (while (re-search-forward line-re end t)
10246 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
10247 ;; Unprotected line, recalculate
10248 (and all (message "Re-applying formulas to full table...(line %d)"
10249 (setq cnt (1+ cnt))))
10250 (setq org-last-recalc-line (org-current-line))
10251 (setq eql eqlnum)
10252 (while (setq entry (pop eql))
10253 (goto-line org-last-recalc-line)
10254 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10255 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
10256 (goto-line thisline)
10257 (org-table-goto-column thiscol)
10258 (or noalign (and org-table-may-need-update (org-table-align))
10259 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10260 ;; Now do the names fields
10261 (while (setq eq (pop eqlname))
10262 (setq name (car eq)
10263 a (assoc name org-table-named-field-locations))
10264 (when a
10265 (message "Re-applying formula to named field: %s" name)
10266 (goto-line (nth 1 a))
10267 (org-table-goto-column (nth 2 a))
10268 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
10269 ;; back to initial position
10270 (goto-line thisline)
10271 (org-table-goto-column thiscol)
10272 (or noalign (and org-table-may-need-update (org-table-align))
10273 (and all (message "Re-applying formulas...done")))))
10274
10275 (defun org-table-formula-substitute-names (f)
10276 "Replace $const with values in string F."
10277 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
10278 ;; First, check for column names
10279 (while (setq start (string-match org-table-column-name-regexp f start))
10280 (setq start (1+ start))
10281 (setq a (assoc (match-string 1 f) org-table-column-names))
10282 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10283 ;; Expand ranges to vectors
10284 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
10285 (setq n1 (string-to-number (match-string 1 f))
10286 n2 (string-to-number (match-string 2 f))
10287 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
10288 s (concat "[($" (number-to-string (1- nn1)) ")"))
10289 (loop for i from nn1 upto nn2 do
10290 (setq s (concat s ",($" (int-to-string i) ")")))
10291 (setq s (concat s "]"))
10292 (if (< n2 n1) (setq s (concat "rev(" s ")")))
10293 (setq f (replace-match s t t f)))
10294 ;; Parameters and constants
10295 (setq start 0)
10296 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
10297 (setq start (1+ start))
10298 (if (setq a (save-match-data
10299 (org-table-get-constant (match-string 1 f))))
10300 (setq f (replace-match (concat "(" a ")") t t f))))
10301 (if org-table-formula-debug
10302 (put-text-property 0 (length f) :orig-formula f1 f))
10303 f))
10304
10305 (defun org-table-get-constant (const)
10306 "Find the value for a parameter or constant in a formula.
10307 Parameters get priority."
10308 (or (cdr (assoc const org-table-local-parameters))
10309 (cdr (assoc const org-table-formula-constants))
10310 (and (fboundp 'constants-get) (constants-get const))
10311 "#UNDEFINED_NAME"))
10312
10313 (defvar org-edit-formulas-map (make-sparse-keymap))
10314 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
10315 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
10316 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
10317
10318 (defvar org-pos)
10319
10320 (defun org-table-edit-formulas ()
10321 "Edit the formulas of the current table in a separate buffer."
10322 (interactive)
10323 (unless (org-at-table-p)
10324 (error "Not at a table"))
10325 (org-table-get-specials)
10326 (let ((eql (org-table-get-stored-formulas))
10327 (pos (move-marker (make-marker) (point)))
10328 (wc (current-window-configuration))
10329 entry loc s)
10330 (switch-to-buffer-other-window "*Edit Formulas*")
10331 (erase-buffer)
10332 (fundamental-mode)
10333 (set (make-local-variable 'org-pos) pos)
10334 (set (make-local-variable 'org-window-configuration) wc)
10335 (use-local-map org-edit-formulas-map)
10336 (setq s "# Edit formulas and finish with `C-c C-c'.
10337 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
10338 # Use `C-c ?' to get information about $name at point.
10339 # To cancel editing, press `C-c C-q'.\n")
10340 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10341 (insert s)
10342 (while (setq entry (pop eql))
10343 (when (setq loc (assoc (car entry) org-table-named-field-locations))
10344 (setq s (format "# Named formula, referring to column %d in line %d\n"
10345 (nth 2 loc) (nth 1 loc)))
10346 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10347 (insert s))
10348 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
10349 (remove-text-properties 0 (length s) '(face nil) s)
10350 (insert s))
10351 (goto-char (point-min))
10352 (message "Edit formulas and finish with `C-c C-c'.")))
10353
10354 (defun org-show-variable ()
10355 "Show the location/value of the $ expression at point."
10356 (interactive)
10357 (let (var (pos org-pos) (win (selected-window)) e)
10358 (save-excursion
10359 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
10360 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
10361 (setq var (match-string 1))
10362 (error "No variable at point")))
10363 (cond
10364 ((setq e (assoc var org-table-named-field-locations))
10365 (switch-to-buffer-other-window (marker-buffer pos))
10366 (goto-line (nth 1 e))
10367 (org-table-goto-column (nth 2 e))
10368 (select-window win)
10369 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10370 ((setq e (assoc var org-table-column-names))
10371 (switch-to-buffer-other-window (marker-buffer pos))
10372 (goto-char pos)
10373 (goto-char (org-table-begin))
10374 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10375 (org-table-end) t)
10376 (progn
10377 (goto-char (match-beginning 1))
10378 (message "Named column (column %s)" (cdr e)))
10379 (error "Column name not found"))
10380 (select-window win))
10381 ((string-match "^[0-9]$" var)
10382 ;; column number
10383 (switch-to-buffer-other-window (marker-buffer pos))
10384 (goto-char pos)
10385 (goto-char (org-table-begin))
10386 (recenter 1)
10387 (if (re-search-forward org-table-dataline-regexp
10388 (org-table-end) t)
10389 (progn
10390 (goto-char (match-beginning 0))
10391 (org-table-goto-column (string-to-number var))
10392 (message "Column %s" var))
10393 (error "Column name not found"))
10394 (select-window win))
10395 ((setq e (assoc var org-table-local-parameters))
10396 (switch-to-buffer-other-window (marker-buffer pos))
10397 (goto-char pos)
10398 (goto-char (org-table-begin))
10399 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10400 (progn
10401 (goto-char (match-beginning 1))
10402 (message "Local parameter."))
10403 (error "Parameter not found"))
10404 (select-window win))
10405 (t
10406 (cond
10407 ((setq e (assoc var org-table-formula-constants))
10408 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
10409 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10410 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
10411 (t (error "Undefined name $%s" var)))))))
10412
10413 (defun org-finish-edit-formulas (&optional arg)
10414 "Parse the buffer for formula definitions and install them.
10415 With prefix ARG, apply the new formulas to the table."
10416 (interactive "P")
10417 (let ((pos org-pos) eql)
10418 (goto-char (point-min))
10419 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
10420 (push (cons (match-string 1) (match-string 2)) eql))
10421 (set-window-configuration org-window-configuration)
10422 (select-window (get-buffer-window (marker-buffer pos)))
10423 (goto-char pos)
10424 (unless (org-at-table-p)
10425 (error "Lost table position - cannot install formulae"))
10426 (org-table-store-formulas eql)
10427 (move-marker pos nil)
10428 (kill-buffer "*Edit Formulas*")
10429 (if arg
10430 (org-table-recalculate 'all)
10431 (message "New formulas installed - press C-u C-c C-c to apply."))))
10432
10433 (defun org-abort-edit-formulas ()
10434 "Abort editing formulas, without installing the changes."
10435 (interactive)
10436 (let ((pos org-pos))
10437 (set-window-configuration org-window-configuration)
10438 (select-window (get-buffer-window (marker-buffer pos)))
10439 (goto-char pos)
10440 (message "Formula editing aborted without installing changes")))
10441
10442 ;;; The orgtbl minor mode
10443
10444 ;; Define a minor mode which can be used in other modes in order to
10445 ;; integrate the org-mode table editor.
10446
10447 ;; This is really a hack, because the org-mode table editor uses several
10448 ;; keys which normally belong to the major mode, for example the TAB and
10449 ;; RET keys. Here is how it works: The minor mode defines all the keys
10450 ;; necessary to operate the table editor, but wraps the commands into a
10451 ;; function which tests if the cursor is currently inside a table. If that
10452 ;; is the case, the table editor command is executed. However, when any of
10453 ;; those keys is used outside a table, the function uses `key-binding' to
10454 ;; look up if the key has an associated command in another currently active
10455 ;; keymap (minor modes, major mode, global), and executes that command.
10456 ;; There might be problems if any of the keys used by the table editor is
10457 ;; otherwise used as a prefix key.
10458
10459 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10460 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10461 ;; addresses this by checking explicitly for both bindings.
10462
10463 ;; The optimized version (see variable `orgtbl-optimized') takes over
10464 ;; all keys which are bound to `self-insert-command' in the *global map*.
10465 ;; Some modes bind other commands to simple characters, for example
10466 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10467 ;; active, this binding is ignored inside tables and replaced with a
10468 ;; modified self-insert.
10469
10470 (defvar orgtbl-mode nil
10471 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10472 table editor in arbitrary modes.")
10473 (make-variable-buffer-local 'orgtbl-mode)
10474
10475 (defvar orgtbl-mode-map (make-keymap)
10476 "Keymap for `orgtbl-mode'.")
10477
10478 ;;;###autoload
10479 (defun turn-on-orgtbl ()
10480 "Unconditionally turn on `orgtbl-mode'."
10481 (orgtbl-mode 1))
10482
10483 ;;;###autoload
10484 (defun orgtbl-mode (&optional arg)
10485 "The `org-mode' table editor as a minor mode for use in other modes."
10486 (interactive)
10487 (if (eq major-mode 'org-mode)
10488 ;; Exit without error, in case some hook functions calls this
10489 ;; by accident in org-mode.
10490 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10491 (setq orgtbl-mode
10492 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10493 (if orgtbl-mode
10494 (progn
10495 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10496 ;; Make sure we are first in minor-mode-map-alist
10497 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10498 (and c (setq minor-mode-map-alist
10499 (cons c (delq c minor-mode-map-alist)))))
10500 (set (make-local-variable (quote org-table-may-need-update)) t)
10501 (org-add-hook 'before-change-functions 'org-before-change-function
10502 nil 'local)
10503 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
10504 auto-fill-inhibit-regexp)
10505 (set (make-local-variable 'auto-fill-inhibit-regexp)
10506 (if auto-fill-inhibit-regexp
10507 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
10508 "[ \t]*|"))
10509 (org-add-to-invisibility-spec '(org-cwidth))
10510 (easy-menu-add orgtbl-mode-menu)
10511 (run-hooks 'orgtbl-mode-hook))
10512 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10513 (org-cleanup-narrow-column-properties)
10514 (org-remove-from-invisibility-spec '(org-cwidth))
10515 (remove-hook 'before-change-functions 'org-before-change-function t)
10516 (easy-menu-remove orgtbl-mode-menu)
10517 (force-mode-line-update 'all))))
10518
10519 (defun org-cleanup-narrow-column-properties ()
10520 "Remove all properties related to narrow-column invisibility."
10521 (let ((s 1))
10522 (while (setq s (text-property-any s (point-max)
10523 'display org-narrow-column-arrow))
10524 (remove-text-properties s (1+ s) '(display t)))
10525 (setq s 1)
10526 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10527 (remove-text-properties s (1+ s) '(org-cwidth t)))
10528 (setq s 1)
10529 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10530 (remove-text-properties s (1+ s) '(invisible t)))))
10531
10532 ;; Install it as a minor mode.
10533 (put 'orgtbl-mode :included t)
10534 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10535 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10536
10537 (defun orgtbl-make-binding (fun n &rest keys)
10538 "Create a function for binding in the table minor mode.
10539 FUN is the command to call inside a table. N is used to create a unique
10540 command name. KEYS are keys that should be checked in for a command
10541 to execute outside of tables."
10542 (eval
10543 (list 'defun
10544 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10545 '(arg)
10546 (concat "In tables, run `" (symbol-name fun) "'.\n"
10547 "Outside of tables, run the binding of `"
10548 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10549 "'.")
10550 '(interactive "p")
10551 (list 'if
10552 '(org-at-table-p)
10553 (list 'call-interactively (list 'quote fun))
10554 (list 'let '(orgtbl-mode)
10555 (list 'call-interactively
10556 (append '(or)
10557 (mapcar (lambda (k)
10558 (list 'key-binding k))
10559 keys)
10560 '('orgtbl-error))))))))
10561
10562 (defun orgtbl-error ()
10563 "Error when there is no default binding for a table key."
10564 (interactive)
10565 (error "This key is has no function outside tables"))
10566
10567 (defun orgtbl-setup ()
10568 "Setup orgtbl keymaps."
10569 (let ((nfunc 0)
10570 (bindings
10571 (list
10572 '([(meta shift left)] org-table-delete-column)
10573 '([(meta left)] org-table-move-column-left)
10574 '([(meta right)] org-table-move-column-right)
10575 '([(meta shift right)] org-table-insert-column)
10576 '([(meta shift up)] org-table-kill-row)
10577 '([(meta shift down)] org-table-insert-row)
10578 '([(meta up)] org-table-move-row-up)
10579 '([(meta down)] org-table-move-row-down)
10580 '("\C-c\C-w" org-table-cut-region)
10581 '("\C-c\M-w" org-table-copy-region)
10582 '("\C-c\C-y" org-table-paste-rectangle)
10583 '("\C-c-" org-table-insert-hline)
10584 ; '([(shift tab)] org-table-previous-field)
10585 '("\C-m" org-table-next-row)
10586 (list (org-key 'S-return) 'org-table-copy-down)
10587 '([(meta return)] org-table-wrap-region)
10588 '("\C-c\C-q" org-table-wrap-region)
10589 '("\C-c?" org-table-current-column)
10590 '("\C-c " org-table-blank-field)
10591 '("\C-c+" org-table-sum)
10592 '("\C-c=" org-table-eval-formula)
10593 '("\C-c'" org-table-edit-formulas)
10594 '("\C-c`" org-table-edit-field)
10595 '("\C-c*" org-table-recalculate)
10596 '("\C-c|" org-table-create-or-convert-from-region)
10597 '("\C-c^" org-table-sort-lines)
10598 '([(control ?#)] org-table-rotate-recalc-marks)))
10599 elt key fun cmd)
10600 (while (setq elt (pop bindings))
10601 (setq nfunc (1+ nfunc))
10602 (setq key (car elt)
10603 fun (nth 1 elt)
10604 cmd (orgtbl-make-binding fun nfunc key))
10605 (define-key orgtbl-mode-map key cmd))
10606 ;; Special treatment needed for TAB and RET
10607 (define-key orgtbl-mode-map [(return)]
10608 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10609 (define-key orgtbl-mode-map "\C-m"
10610 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10611 (define-key orgtbl-mode-map [(tab)]
10612 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10613 (define-key orgtbl-mode-map "\C-i"
10614 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
10615 (define-key orgtbl-mode-map "\C-i"
10616 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
10617 (define-key orgtbl-mode-map "\C-c\C-c"
10618 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
10619 (when orgtbl-optimized
10620 ;; If the user wants maximum table support, we need to hijack
10621 ;; some standard editing functions
10622 (org-remap orgtbl-mode-map
10623 'self-insert-command 'orgtbl-self-insert-command
10624 'delete-char 'org-delete-char
10625 'delete-backward-char 'org-delete-backward-char)
10626 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
10627 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10628 '("OrgTbl"
10629 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10630 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10631 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10632 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10633 "--"
10634 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10635 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10636 ["Copy Field from Above"
10637 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10638 "--"
10639 ("Column"
10640 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10641 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10642 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10643 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
10644 "--"
10645 ["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])
10646 ("Row"
10647 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10648 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10649 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10650 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10651 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10652 "--"
10653 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10654 ("Rectangle"
10655 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10656 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10657 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10658 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10659 "--"
10660 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10661 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10662 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10663 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10664 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10665 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10666 ["Sum Column/Rectangle" org-table-sum
10667 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10668 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10669 ["Debug Formulas"
10670 (setq org-table-formula-debug (not org-table-formula-debug))
10671 :style toggle :selected org-table-formula-debug]
10672 ))
10673 t)
10674
10675 (defun orgtbl-tab (arg)
10676 "Justification and field motion for `orgtbl-mode'."
10677 (interactive "P")
10678 (if arg (org-table-edit-field t)
10679 (org-table-justify-field-maybe)
10680 (org-table-next-field)))
10681
10682 (defun orgtbl-ret ()
10683 "Justification and field motion for `orgtbl-mode'."
10684 (interactive)
10685 (org-table-justify-field-maybe)
10686 (org-table-next-row))
10687
10688 (defun orgtbl-self-insert-command (N)
10689 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10690 If the cursor is in a table looking at whitespace, the whitespace is
10691 overwritten, and the table is not marked as requiring realignment."
10692 (interactive "p")
10693 (if (and (org-at-table-p)
10694 (or
10695 (and org-table-auto-blank-field
10696 (member last-command
10697 '(orgtbl-hijacker-command-100
10698 orgtbl-hijacker-command-101
10699 orgtbl-hijacker-command-102
10700 orgtbl-hijacker-command-103
10701 orgtbl-hijacker-command-104
10702 orgtbl-hijacker-command-105))
10703 (org-table-blank-field))
10704 t)
10705 (eq N 1)
10706 (looking-at "[^|\n]* +|"))
10707 (let (org-table-may-need-update)
10708 (goto-char (1- (match-end 0)))
10709 (delete-backward-char 1)
10710 (goto-char (match-beginning 0))
10711 (self-insert-command N))
10712 (setq org-table-may-need-update t)
10713 (let (orgtbl-mode)
10714 (call-interactively (key-binding (vector last-input-event))))))
10715
10716 (defun org-force-self-insert (N)
10717 "Needed to enforce self-insert under remapping."
10718 (interactive "p")
10719 (self-insert-command N))
10720
10721 ;;; Exporting
10722
10723 (defconst org-level-max 20)
10724
10725 (defun org-export-find-first-heading-line (list)
10726 "Remove all lines from LIST which are before the first headline."
10727 (let ((orig-list list)
10728 (re (concat "^" outline-regexp)))
10729 (while (and list
10730 (not (string-match re (car list))))
10731 (pop list))
10732 (or list orig-list)))
10733
10734 (defun org-skip-comments (lines)
10735 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10736 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10737 (re2 "^\\(\\*+\\)[ \t\n\r]")
10738 rtn line level)
10739 (while (setq line (pop lines))
10740 (cond
10741 ((and (string-match re1 line)
10742 (setq level (- (match-end 1) (match-beginning 1))))
10743 ;; Beginning of a COMMENT subtree. Skip it.
10744 (while (and (setq line (pop lines))
10745 (or (not (string-match re2 line))
10746 (> (- (match-end 1) (match-beginning 1)) level))))
10747 (setq lines (cons line lines)))
10748 ((string-match "^#" line)
10749 ;; an ordinary comment line
10750 )
10751 ((and org-export-table-remove-special-lines
10752 (string-match "^[ \t]*| *[!_^] *|" line))
10753 ;; a special table line that should be removed
10754 )
10755 (t (setq rtn (cons line rtn)))))
10756 (nreverse rtn)))
10757
10758 ;; ASCII
10759
10760 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10761 "Characters for underlining headings in ASCII export.")
10762
10763 (defconst org-html-entities
10764 '(("nbsp")
10765 ("iexcl")
10766 ("cent")
10767 ("pound")
10768 ("curren")
10769 ("yen")
10770 ("brvbar")
10771 ("sect")
10772 ("uml")
10773 ("copy")
10774 ("ordf")
10775 ("laquo")
10776 ("not")
10777 ("shy")
10778 ("reg")
10779 ("macr")
10780 ("deg")
10781 ("plusmn")
10782 ("sup2")
10783 ("sup3")
10784 ("acute")
10785 ("micro")
10786 ("para")
10787 ("middot")
10788 ("odot"."o")
10789 ("star"."*")
10790 ("cedil")
10791 ("sup1")
10792 ("ordm")
10793 ("raquo")
10794 ("frac14")
10795 ("frac12")
10796 ("frac34")
10797 ("iquest")
10798 ("Agrave")
10799 ("Aacute")
10800 ("Acirc")
10801 ("Atilde")
10802 ("Auml")
10803 ("Aring") ("AA"."&Aring;")
10804 ("AElig")
10805 ("Ccedil")
10806 ("Egrave")
10807 ("Eacute")
10808 ("Ecirc")
10809 ("Euml")
10810 ("Igrave")
10811 ("Iacute")
10812 ("Icirc")
10813 ("Iuml")
10814 ("ETH")
10815 ("Ntilde")
10816 ("Ograve")
10817 ("Oacute")
10818 ("Ocirc")
10819 ("Otilde")
10820 ("Ouml")
10821 ("times")
10822 ("Oslash")
10823 ("Ugrave")
10824 ("Uacute")
10825 ("Ucirc")
10826 ("Uuml")
10827 ("Yacute")
10828 ("THORN")
10829 ("szlig")
10830 ("agrave")
10831 ("aacute")
10832 ("acirc")
10833 ("atilde")
10834 ("auml")
10835 ("aring")
10836 ("aelig")
10837 ("ccedil")
10838 ("egrave")
10839 ("eacute")
10840 ("ecirc")
10841 ("euml")
10842 ("igrave")
10843 ("iacute")
10844 ("icirc")
10845 ("iuml")
10846 ("eth")
10847 ("ntilde")
10848 ("ograve")
10849 ("oacute")
10850 ("ocirc")
10851 ("otilde")
10852 ("ouml")
10853 ("divide")
10854 ("oslash")
10855 ("ugrave")
10856 ("uacute")
10857 ("ucirc")
10858 ("uuml")
10859 ("yacute")
10860 ("thorn")
10861 ("yuml")
10862 ("fnof")
10863 ("Alpha")
10864 ("Beta")
10865 ("Gamma")
10866 ("Delta")
10867 ("Epsilon")
10868 ("Zeta")
10869 ("Eta")
10870 ("Theta")
10871 ("Iota")
10872 ("Kappa")
10873 ("Lambda")
10874 ("Mu")
10875 ("Nu")
10876 ("Xi")
10877 ("Omicron")
10878 ("Pi")
10879 ("Rho")
10880 ("Sigma")
10881 ("Tau")
10882 ("Upsilon")
10883 ("Phi")
10884 ("Chi")
10885 ("Psi")
10886 ("Omega")
10887 ("alpha")
10888 ("beta")
10889 ("gamma")
10890 ("delta")
10891 ("epsilon")
10892 ("varepsilon"."&epsilon;")
10893 ("zeta")
10894 ("eta")
10895 ("theta")
10896 ("iota")
10897 ("kappa")
10898 ("lambda")
10899 ("mu")
10900 ("nu")
10901 ("xi")
10902 ("omicron")
10903 ("pi")
10904 ("rho")
10905 ("sigmaf") ("varsigma"."&sigmaf;")
10906 ("sigma")
10907 ("tau")
10908 ("upsilon")
10909 ("phi")
10910 ("chi")
10911 ("psi")
10912 ("omega")
10913 ("thetasym") ("vartheta"."&thetasym;")
10914 ("upsih")
10915 ("piv")
10916 ("bull") ("bullet"."&bull;")
10917 ("hellip") ("dots"."&hellip;")
10918 ("prime")
10919 ("Prime")
10920 ("oline")
10921 ("frasl")
10922 ("weierp")
10923 ("image")
10924 ("real")
10925 ("trade")
10926 ("alefsym")
10927 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
10928 ("uarr") ("uparrow"."&uarr;")
10929 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
10930 ("darr")("downarrow"."&darr;")
10931 ("harr") ("leftrightarrow"."&harr;")
10932 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
10933 ("lArr") ("Leftarrow"."&lArr;")
10934 ("uArr") ("Uparrow"."&uArr;")
10935 ("rArr") ("Rightarrow"."&rArr;")
10936 ("dArr") ("Downarrow"."&dArr;")
10937 ("hArr") ("Leftrightarrow"."&hArr;")
10938 ("forall")
10939 ("part") ("partial"."&part;")
10940 ("exist") ("exists"."&exist;")
10941 ("empty") ("emptyset"."&empty;")
10942 ("nabla")
10943 ("isin") ("in"."&isin;")
10944 ("notin")
10945 ("ni")
10946 ("prod")
10947 ("sum")
10948 ("minus")
10949 ("lowast") ("ast"."&lowast;")
10950 ("radic")
10951 ("prop") ("proptp"."&prop;")
10952 ("infin") ("infty"."&infin;")
10953 ("ang") ("angle"."&ang;")
10954 ("and") ("vee"."&and;")
10955 ("or") ("wedge"."&or;")
10956 ("cap")
10957 ("cup")
10958 ("int")
10959 ("there4")
10960 ("sim")
10961 ("cong") ("simeq"."&cong;")
10962 ("asymp")("approx"."&asymp;")
10963 ("ne") ("neq"."&ne;")
10964 ("equiv")
10965 ("le")
10966 ("ge")
10967 ("sub") ("subset"."&sub;")
10968 ("sup") ("supset"."&sup;")
10969 ("nsub")
10970 ("sube")
10971 ("supe")
10972 ("oplus")
10973 ("otimes")
10974 ("perp")
10975 ("sdot") ("cdot"."&sdot;")
10976 ("lceil")
10977 ("rceil")
10978 ("lfloor")
10979 ("rfloor")
10980 ("lang")
10981 ("rang")
10982 ("loz") ("Diamond"."&loz;")
10983 ("spades") ("spadesuit"."&spades;")
10984 ("clubs") ("clubsuit"."&clubs;")
10985 ("hearts") ("diamondsuit"."&hearts;")
10986 ("diams") ("diamondsuit"."&diams;")
10987 ("quot")
10988 ("amp")
10989 ("lt")
10990 ("gt")
10991 ("OElig")
10992 ("oelig")
10993 ("Scaron")
10994 ("scaron")
10995 ("Yuml")
10996 ("circ")
10997 ("tilde")
10998 ("ensp")
10999 ("emsp")
11000 ("thinsp")
11001 ("zwnj")
11002 ("zwj")
11003 ("lrm")
11004 ("rlm")
11005 ("ndash")
11006 ("mdash")
11007 ("lsquo")
11008 ("rsquo")
11009 ("sbquo")
11010 ("ldquo")
11011 ("rdquo")
11012 ("bdquo")
11013 ("dagger")
11014 ("Dagger")
11015 ("permil")
11016 ("lsaquo")
11017 ("rsaquo")
11018 ("euro")
11019
11020 ("arccos"."arccos")
11021 ("arcsin"."arcsin")
11022 ("arctan"."arctan")
11023 ("arg"."arg")
11024 ("cos"."cos")
11025 ("cosh"."cosh")
11026 ("cot"."cot")
11027 ("coth"."coth")
11028 ("csc"."csc")
11029 ("deg"."deg")
11030 ("det"."det")
11031 ("dim"."dim")
11032 ("exp"."exp")
11033 ("gcd"."gcd")
11034 ("hom"."hom")
11035 ("inf"."inf")
11036 ("ker"."ker")
11037 ("lg"."lg")
11038 ("lim"."lim")
11039 ("liminf"."liminf")
11040 ("limsup"."limsup")
11041 ("ln"."ln")
11042 ("log"."log")
11043 ("max"."max")
11044 ("min"."min")
11045 ("Pr"."Pr")
11046 ("sec"."sec")
11047 ("sin"."sin")
11048 ("sinh"."sinh")
11049 ("sup"."sup")
11050 ("tan"."tan")
11051 ("tanh"."tanh")
11052 )
11053 "Entities for TeX->HTML translation.
11054 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
11055 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
11056 In that case, \"\\ent\" will be translated to \"&other;\".
11057 The list contains HTML entities for Latin-1, Greek and other symbols.
11058 It is supplemented by a number of commonly used TeX macros with appropriate
11059 translations. There is currently no way for users to extend this.")
11060
11061 (defun org-cleaned-string-for-export (string)
11062 "Cleanup a buffer substring so that links can be created safely."
11063 (interactive)
11064 (let* ((cb (current-buffer))
11065 (re-radio (and org-target-link-regexp
11066 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
11067 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
11068 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
11069 rtn)
11070 (save-excursion
11071 (set-buffer (get-buffer-create " org-mode-tmp"))
11072 (erase-buffer)
11073 (insert string)
11074 (org-mode)
11075 ;; Find targets in comments and move them out of comments,
11076 ;; but mark them as targets that should be invisible
11077 (goto-char (point-min))
11078 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
11079 (replace-match "\\1(INVISIBLE)"))
11080 ;; Find matches for radio targets and turn them into internal links
11081 (goto-char (point-min))
11082 (when re-radio
11083 (while (re-search-forward re-radio nil t)
11084 (replace-match "\\1[[\\2]]")))
11085 ;; Find all links that contain a newline and put them into a single line
11086 (goto-char (point-min))
11087 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
11088 (replace-match "\\1 \\3")
11089 (goto-char (match-beginning 0)))
11090 ;; Normalize links: Convert angle and plain links into bracket links
11091 (goto-char (point-min))
11092 (while (re-search-forward re-plain-link nil t)
11093 (replace-match
11094 (concat
11095 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11096 t t))
11097 (goto-char (point-min))
11098 (while (re-search-forward re-angle-link nil t)
11099 (replace-match
11100 (concat
11101 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11102 t t))
11103
11104 ;; Remove comments
11105 (goto-char (point-min))
11106 (while (re-search-forward "^#.*\n?" nil t)
11107 (replace-match ""))
11108 (setq rtn (buffer-string)))
11109 (kill-buffer " org-mode-tmp")
11110 rtn))
11111
11112 (defun org-solidify-link-text (s &optional alist)
11113 "Take link text and make a safe target out of it."
11114 (save-match-data
11115 (let* ((rtn
11116 (mapconcat
11117 'identity
11118 (org-split-string s "[ \t\r\n]+") "--"))
11119 (a (assoc rtn alist)))
11120 (or (cdr a) rtn))))
11121
11122 (defun org-convert-to-odd-levels ()
11123 "Convert an org-mode file with all levels allowed to one with odd levels.
11124 This will leave level 1 alone, convert level 2 to level 3, level 3 to
11125 level 5 etc."
11126 (interactive)
11127 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
11128 (let ((org-odd-levels-only nil) n)
11129 (save-excursion
11130 (goto-char (point-min))
11131 (while (re-search-forward "^\\*\\*+" nil t)
11132 (setq n (1- (length (match-string 0))))
11133 (while (>= (setq n (1- n)) 0)
11134 (org-demote))
11135 (end-of-line 1))))))
11136
11137
11138 (defun org-convert-to-oddeven-levels ()
11139 "Convert an org-mode file with only odd levels to one with odd and even levels.
11140 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
11141 section with an even level, conversion would destroy the structure of the file. An error
11142 is signaled in this case."
11143 (interactive)
11144 (goto-char (point-min))
11145 ;; First check if there are no even levels
11146 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
11147 (org-show-hierarchy-above)
11148 (error "Not all levels are odd in this file. Conversion not possible."))
11149 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
11150 (let ((org-odd-levels-only nil) n)
11151 (save-excursion
11152 (goto-char (point-min))
11153 (while (re-search-forward "^\\*\\*+" nil t)
11154 (setq n (/ (length (match-string 0)) 2))
11155 (while (>= (setq n (1- n)) 0)
11156 (org-promote))
11157 (end-of-line 1))))))
11158
11159 (defun org-tr-level (n)
11160 "Make N odd if required."
11161 (if org-odd-levels-only (1+ (/ n 2)) n))
11162
11163 (defvar org-last-level nil) ; dynamically scoped variable
11164
11165 (defun org-export-as-ascii (arg)
11166 "Export the outline as a pretty ASCII file.
11167 If there is an active region, export only the region.
11168 The prefix ARG specifies how many levels of the outline should become
11169 underlined headlines. The default is 3."
11170 (interactive "P")
11171 (setq-default org-todo-line-regexp org-todo-line-regexp)
11172 (let* ((region
11173 (buffer-substring
11174 (if (org-region-active-p) (region-beginning) (point-min))
11175 (if (org-region-active-p) (region-end) (point-max))))
11176 (lines (org-export-find-first-heading-line
11177 (org-skip-comments
11178 (org-split-string
11179 (org-cleaned-string-for-export region)
11180 "[\r\n]"))))
11181 (org-startup-with-deadline-check nil)
11182 (level 0) line txt
11183 (umax nil)
11184 (case-fold-search nil)
11185 (filename (concat (file-name-sans-extension buffer-file-name)
11186 ".txt"))
11187 (buffer (find-file-noselect filename))
11188 (levels-open (make-vector org-level-max nil))
11189 (date (format-time-string "%Y/%m/%d" (current-time)))
11190 (time (format-time-string "%X" (org-current-time)))
11191 (author user-full-name)
11192 (title (buffer-name))
11193 (options nil)
11194 (email user-mail-address)
11195 (language org-export-default-language)
11196 (text nil)
11197 (todo nil)
11198 (lang-words nil))
11199
11200 (setq org-last-level 1)
11201 (org-init-section-numbers)
11202
11203 (find-file-noselect filename)
11204
11205 ;; Search for the export key lines
11206 (org-parse-key-lines)
11207
11208 (setq lang-words (or (assoc language org-export-language-setup)
11209 (assoc "en" org-export-language-setup)))
11210 (if org-export-ascii-show-new-buffer
11211 (switch-to-buffer-other-window buffer)
11212 (set-buffer buffer))
11213 (erase-buffer)
11214 (fundamental-mode)
11215 (if options (org-parse-export-options options))
11216 (setq umax (if arg (prefix-numeric-value arg)
11217 org-export-headline-levels))
11218
11219 ;; File header
11220 (if title (org-insert-centered title ?=))
11221 (insert "\n")
11222 (if (or author email)
11223 (insert (concat (nth 1 lang-words) ": " (or author "")
11224 (if email (concat " <" email ">") "")
11225 "\n")))
11226 (if (and date time)
11227 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
11228 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
11229
11230 (insert "\n\n")
11231
11232 (if org-export-with-toc
11233 (progn
11234 (insert (nth 3 lang-words) "\n"
11235 (make-string (length (nth 3 lang-words)) ?=) "\n")
11236 (mapcar '(lambda (line)
11237 (if (string-match org-todo-line-regexp
11238 line)
11239 ;; This is a headline
11240 (progn
11241 (setq level (- (match-end 1) (match-beginning 1))
11242 level (org-tr-level level)
11243 txt (match-string 3 line)
11244 todo
11245 (or (and (match-beginning 2)
11246 (not (equal (match-string 2 line)
11247 org-done-string)))
11248 ; TODO, not DONE
11249 (and org-export-mark-todo-in-toc
11250 (= level umax)
11251 (org-search-todo-below
11252 line lines level))))
11253 (setq txt (org-html-expand-for-ascii txt))
11254
11255 (if org-export-with-section-numbers
11256 (setq txt (concat (org-section-number level)
11257 " " txt)))
11258 (if (<= level umax)
11259 (progn
11260 (insert
11261 (make-string (* (1- level) 4) ?\ )
11262 (format (if todo "%s (*)\n" "%s\n") txt))
11263 (setq org-last-level level))
11264 ))))
11265 lines)))
11266
11267 (org-init-section-numbers)
11268 (while (setq line (pop lines))
11269 ;; Remove the quoted HTML tags.
11270 (setq line (org-html-expand-for-ascii line))
11271 ;; Remove targets
11272 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
11273 (setq line (replace-match "" t t line)))
11274 ;; Replace internal links
11275 (while (string-match org-bracket-link-regexp line)
11276 (setq line (replace-match
11277 (if (match-end 3) "[\\3]" "[\\1]")
11278 t nil line)))
11279 (cond
11280 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11281 ;; a Headline
11282 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11283 txt (match-string 2 line))
11284 (org-ascii-level-start level txt umax))
11285 (t (insert line "\n"))))
11286 (normal-mode)
11287 (save-buffer)
11288 (goto-char (point-min))))
11289
11290 (defun org-search-todo-below (line lines level)
11291 "Search the subtree below LINE for any TODO entries."
11292 (let ((rest (cdr (memq line lines)))
11293 (re org-todo-line-regexp)
11294 line lv todo)
11295 (catch 'exit
11296 (while (setq line (pop rest))
11297 (if (string-match re line)
11298 (progn
11299 (setq lv (- (match-end 1) (match-beginning 1))
11300 todo (and (match-beginning 2)
11301 (not (equal (match-string 2 line)
11302 org-done-string))))
11303 ; TODO, not DONE
11304 (if (<= lv level) (throw 'exit nil))
11305 (if todo (throw 'exit t))))))))
11306
11307 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
11308 ;; We could also implement *bold*,/italic/ and _underline_ for ASCII export
11309 (defun org-html-expand-for-ascii (line)
11310 "Handle quoted HTML for ASCII export."
11311 (if org-export-html-expand
11312 (while (string-match "@<[^<>\n]*>" line)
11313 ;; We just remove the tags for now.
11314 (setq line (replace-match "" nil nil line))))
11315 line)
11316
11317 (defun org-insert-centered (s &optional underline)
11318 "Insert the string S centered and underline it with character UNDERLINE."
11319 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
11320 (insert (make-string ind ?\ ) s "\n")
11321 (if underline
11322 (insert (make-string ind ?\ )
11323 (make-string (string-width s) underline)
11324 "\n"))))
11325
11326 (defun org-ascii-level-start (level title umax)
11327 "Insert a new level in ASCII export."
11328 (let (char)
11329 (if (> level umax)
11330 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
11331 (if (or (not (equal (char-before) ?\n))
11332 (not (equal (char-before (1- (point))) ?\n)))
11333 (insert "\n"))
11334 (setq char (nth (- umax level) (reverse org-ascii-underline)))
11335 (if org-export-with-section-numbers
11336 (setq title (concat (org-section-number level) " " title)))
11337 (insert title "\n" (make-string (string-width title) char) "\n"))))
11338
11339 (defun org-export-copy-visible ()
11340 "Copy the visible part of the buffer to another buffer, for printing.
11341 Also removes the first line of the buffer if it specifies a mode,
11342 and all options lines."
11343 (interactive)
11344 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
11345 ".txt"))
11346 (buffer (find-file-noselect filename))
11347 (ore (concat
11348 (org-make-options-regexp
11349 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
11350 "STARTUP" "ARCHIVE"
11351 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
11352 (if org-noutline-p "\\(\n\\|$\\)" "")))
11353 s e)
11354 (with-current-buffer buffer
11355 (erase-buffer)
11356 (text-mode))
11357 (save-excursion
11358 (setq s (goto-char (point-min)))
11359 (while (not (= (point) (point-max)))
11360 (goto-char (org-find-invisible))
11361 (append-to-buffer buffer s (point))
11362 (setq s (goto-char (org-find-visible)))))
11363 (switch-to-buffer-other-window buffer)
11364 (newline)
11365 (goto-char (point-min))
11366 (if (looking-at ".*-\\*- mode:.*\n")
11367 (replace-match ""))
11368 (while (re-search-forward ore nil t)
11369 (replace-match ""))
11370 (goto-char (point-min))))
11371
11372 (defun org-find-visible ()
11373 (if (featurep 'noutline)
11374 (let ((s (point)))
11375 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11376 (get-char-property s 'invisible)))
11377 s)
11378 (skip-chars-forward "^\n")
11379 (point)))
11380 (defun org-find-invisible ()
11381 (if (featurep 'noutline)
11382 (let ((s (point)))
11383 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11384 (not (get-char-property s 'invisible))))
11385 s)
11386 (skip-chars-forward "^\r")
11387 (point)))
11388
11389 ;; HTML
11390
11391 (defun org-get-current-options ()
11392 "Return a string with current options as keyword options.
11393 Does include HTML export options as well as TODO and CATEGORY stuff."
11394 (format
11395 "#+TITLE: %s
11396 #+AUTHOR: %s
11397 #+EMAIL: %s
11398 #+LANGUAGE: %s
11399 #+TEXT: Some descriptive text to be emitted. Several lines OK.
11400 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
11401 #+CATEGORY: %s
11402 #+SEQ_TODO: %s
11403 #+TYP_TODO: %s
11404 #+STARTUP: %s %s %s %s %s
11405 #+ARCHIVE: %s
11406 "
11407 (buffer-name) (user-full-name) user-mail-address org-export-default-language
11408 org-export-headline-levels
11409 org-export-with-section-numbers
11410 org-export-with-toc
11411 org-export-preserve-breaks
11412 org-export-html-expand
11413 org-export-with-fixed-width
11414 org-export-with-tables
11415 org-export-with-sub-superscripts
11416 org-export-with-emphasize
11417 org-export-with-TeX-macros
11418 (file-name-nondirectory buffer-file-name)
11419 (if (equal org-todo-interpretation 'sequence)
11420 (mapconcat 'identity org-todo-keywords " ")
11421 "TODO FEEDBACK VERIFY DONE")
11422 (if (equal org-todo-interpretation 'type)
11423 (mapconcat 'identity org-todo-keywords " ")
11424 "Me Jason Marie DONE")
11425 (cdr (assoc org-startup-folded
11426 '((nil . "showall") (t . "overview") (content . "content"))))
11427 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
11428 (if org-odd-levels-only "odd" "oddeven")
11429 (if org-hide-leading-stars "hidestars" "showstars")
11430 (if org-startup-align-all-tables "align" "noalign")
11431 org-archive-location
11432 ))
11433
11434 (defun org-insert-export-options-template ()
11435 "Insert into the buffer a template with information for exporting."
11436 (interactive)
11437 (if (not (bolp)) (newline))
11438 (let ((s (org-get-current-options)))
11439 (and (string-match "#\\+CATEGORY" s)
11440 (setq s (substring s 0 (match-beginning 0))))
11441 (insert s)))
11442
11443 (defun org-toggle-fixed-width-section (arg)
11444 "Toggle the fixed-width export.
11445 If there is no active region, the QUOTE keyword at the current headline is
11446 inserted or removed. When present, it causes the text between this headline
11447 and the next to be exported as fixed-width text, and unmodified.
11448 If there is an active region, this command adds or removes a colon as the
11449 first character of this line. If the first character of a line is a colon,
11450 this line is also exported in fixed-width font."
11451 (interactive "P")
11452 (let* ((cc 0)
11453 (regionp (org-region-active-p))
11454 (beg (if regionp (region-beginning) (point)))
11455 (end (if regionp (region-end)))
11456 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
11457 (re "[ \t]*\\(:\\)")
11458 off)
11459 (if regionp
11460 (save-excursion
11461 (goto-char beg)
11462 (setq cc (current-column))
11463 (beginning-of-line 1)
11464 (setq off (looking-at re))
11465 (while (> nlines 0)
11466 (setq nlines (1- nlines))
11467 (beginning-of-line 1)
11468 (cond
11469 (arg
11470 (move-to-column cc t)
11471 (insert ":\n")
11472 (forward-line -1))
11473 ((and off (looking-at re))
11474 (replace-match "" t t nil 1))
11475 ((not off) (move-to-column cc t) (insert ":")))
11476 (forward-line 1)))
11477 (save-excursion
11478 (org-back-to-heading)
11479 (if (looking-at (concat outline-regexp
11480 "\\( +\\<" org-quote-string "\\>\\)"))
11481 (replace-match "" t t nil 1)
11482 (if (looking-at outline-regexp)
11483 (progn
11484 (goto-char (match-end 0))
11485 (insert " " org-quote-string))))))))
11486
11487 (defun org-export-as-html-and-open (arg)
11488 "Export the outline as HTML and immediately open it with a browser.
11489 If there is an active region, export only the region.
11490 The prefix ARG specifies how many levels of the outline should become
11491 headlines. The default is 3. Lower levels will become bulleted lists."
11492 (interactive "P")
11493 (org-export-as-html arg 'hidden)
11494 (org-open-file buffer-file-name))
11495
11496 (defun org-export-as-html-batch ()
11497 "Call `org-export-as-html', may be used in batch processing as
11498 emacs --batch
11499 --load=$HOME/lib/emacs/org.el
11500 --eval \"(setq org-export-headline-levels 2)\"
11501 --visit=MyFile --funcall org-export-as-html-batch"
11502 (org-export-as-html org-export-headline-levels 'hidden))
11503
11504 (defun org-export-as-html (arg &optional hidden)
11505 "Export the outline as a pretty HTML file.
11506 If there is an active region, export only the region.
11507 The prefix ARG specifies how many levels of the outline should become
11508 headlines. The default is 3. Lower levels will become bulleted lists."
11509 (interactive "P")
11510 (setq-default org-todo-line-regexp org-todo-line-regexp)
11511 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
11512 (setq-default org-done-string org-done-string)
11513 (let* ((style org-export-html-style)
11514 (odd org-odd-levels-only)
11515 (region-p (org-region-active-p))
11516 (region
11517 (buffer-substring
11518 (if region-p (region-beginning) (point-min))
11519 (if region-p (region-end) (point-max))))
11520 (all_lines
11521 (org-skip-comments (org-split-string
11522 (org-cleaned-string-for-export region)
11523 "[\r\n]")))
11524 (lines (org-export-find-first-heading-line all_lines))
11525 (level 0) (line "") (origline "") txt todo
11526 (umax nil)
11527 (filename (concat (file-name-sans-extension buffer-file-name)
11528 ".html"))
11529 (buffer (find-file-noselect filename))
11530 (levels-open (make-vector org-level-max nil))
11531 (date (format-time-string "%Y/%m/%d" (current-time)))
11532 (time (format-time-string "%X" (org-current-time)))
11533 (author user-full-name)
11534 (title (buffer-name))
11535 (options nil)
11536 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
11537 (inquote nil)
11538 (infixed nil)
11539 (in-local-list nil)
11540 (local-list-num nil)
11541 (local-list-indent nil)
11542 (llt org-plain-list-ordered-item-terminator)
11543 (email user-mail-address)
11544 (language org-export-default-language)
11545 (text nil)
11546 (lang-words nil)
11547 (target-alist nil) tg
11548 (head-count 0) cnt
11549 (start 0)
11550 ;; FIXME: The following returns always nil under XEmacs
11551 (coding-system (and (fboundp 'coding-system-get)
11552 (boundp 'buffer-file-coding-system)
11553 buffer-file-coding-system))
11554 (coding-system-for-write (or coding-system coding-system-for-write))
11555 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
11556 (charset (and coding-system
11557 (coding-system-get coding-system 'mime-charset)))
11558 table-open type
11559 table-buffer table-orig-buffer
11560 ind start-is-num starter
11561 rpl path desc desc1 desc2 link
11562 )
11563 (message "Exporting...")
11564
11565 (setq org-last-level 1)
11566 (org-init-section-numbers)
11567
11568 ;; Search for the export key lines
11569 (org-parse-key-lines)
11570 (setq lang-words (or (assoc language org-export-language-setup)
11571 (assoc "en" org-export-language-setup)))
11572
11573 ;; Switch to the output buffer
11574 (if (or hidden (not org-export-html-show-new-buffer))
11575 (set-buffer buffer)
11576 (switch-to-buffer-other-window buffer))
11577 (erase-buffer)
11578 (fundamental-mode)
11579 (let ((case-fold-search nil)
11580 (org-odd-levels-only odd))
11581 (if options (org-parse-export-options options))
11582 (setq umax (if arg (prefix-numeric-value arg)
11583 org-export-headline-levels))
11584
11585 ;; File header
11586 (insert (format
11587 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
11588 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
11589 <html lang=\"%s\"><head>
11590 <title>%s</title>
11591 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
11592 <meta name=generator content=\"Org-mode\">
11593 <meta name=generated content=\"%s %s\">
11594 <meta name=author content=\"%s\">
11595 %s
11596 </head><body>
11597 "
11598 language (org-html-expand title) (or charset "iso-8859-1")
11599 date time author style))
11600 (if title (insert (concat "<H1 class=\"title\">"
11601 (org-html-expand title) "</H1>\n")))
11602 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
11603 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
11604 email "&gt;</a>\n")))
11605 (if (or author email) (insert "<br>\n"))
11606 (if (and date time) (insert (concat (nth 2 lang-words) ": "
11607 date " " time "<br>\n")))
11608 (if text (insert (concat "<p>\n" (org-html-expand text))))
11609 (if org-export-with-toc
11610 (progn
11611 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
11612 (insert "<ul>\n")
11613 (setq lines
11614 (mapcar '(lambda (line)
11615 (if (string-match org-todo-line-regexp line)
11616 ;; This is a headline
11617 (progn
11618 (setq level (- (match-end 1) (match-beginning 1))
11619 level (org-tr-level level)
11620 txt (save-match-data
11621 (org-html-expand
11622 (match-string 3 line)))
11623 todo
11624 (or (and (match-beginning 2)
11625 (not (equal (match-string 2 line)
11626 org-done-string)))
11627 ; TODO, not DONE
11628 (and org-export-mark-todo-in-toc
11629 (= level umax)
11630 (org-search-todo-below
11631 line lines level))))
11632 (if org-export-with-section-numbers
11633 (setq txt (concat (org-section-number level)
11634 " " txt)))
11635 (if (<= level umax)
11636 (progn
11637 (setq head-count (+ head-count 1))
11638 (if (> level org-last-level)
11639 (progn
11640 (setq cnt (- level org-last-level))
11641 (while (>= (setq cnt (1- cnt)) 0)
11642 (insert "<ul>"))
11643 (insert "\n")))
11644 (if (< level org-last-level)
11645 (progn
11646 (setq cnt (- org-last-level level))
11647 (while (>= (setq cnt (1- cnt)) 0)
11648 (insert "</ul>"))
11649 (insert "\n")))
11650 ;; Check for targets
11651 (while (string-match org-target-regexp line)
11652 (setq tg (match-string 1 line)
11653 line (replace-match
11654 (concat "@<span class=\"target\">" tg "@</span> ")
11655 t t line))
11656 (push (cons (org-solidify-link-text tg)
11657 (format "sec-%d" head-count))
11658 target-alist))
11659 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
11660 (setq txt (replace-match "" t t txt)))
11661 (insert
11662 (format
11663 (if todo
11664 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
11665 "<li><a href=\"#sec-%d\">%s</a>\n")
11666 head-count txt))
11667
11668 (setq org-last-level level))
11669 )))
11670 line)
11671 lines))
11672 (while (> org-last-level 0)
11673 (setq org-last-level (1- org-last-level))
11674 (insert "</ul>\n"))
11675 ))
11676 (setq head-count 0)
11677 (org-init-section-numbers)
11678
11679 (while (setq line (pop lines) origline line)
11680 (catch 'nextline
11681
11682 ;; end of quote section?
11683 (when (and inquote (string-match "^\\*+" line))
11684 (insert "</pre>\n")
11685 (setq inquote nil))
11686 ;; inside a quote section?
11687 (when inquote
11688 (insert (org-html-protect line) "\n")
11689 (throw 'nextline nil))
11690
11691 ;; verbatim lines
11692 (when (and org-export-with-fixed-width
11693 (string-match "^[ \t]*:\\(.*\\)" line))
11694 (when (not infixed)
11695 (setq infixed t)
11696 (insert "<pre>\n"))
11697 (insert (org-html-protect (match-string 1 line)) "\n")
11698 (when (and lines
11699 (not (string-match "^[ \t]*\\(:.*\\)"
11700 (car lines))))
11701 (setq infixed nil)
11702 (insert "</pre>\n"))
11703 (throw 'nextline nil))
11704
11705
11706 ;; make targets to anchors
11707 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
11708 (cond
11709 ((match-end 2)
11710 (setq line (replace-match
11711 (concat "@<a name=\""
11712 (org-solidify-link-text (match-string 1 line))
11713 "\">\\nbsp@</a>")
11714 t t line)))
11715 ((and org-export-with-toc (equal (string-to-char line) ?*))
11716 (setq line (replace-match
11717 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
11718 ; (concat "@<i>" (match-string 1 line) "@</i> ")
11719 t t line)))
11720 (t
11721 (setq line (replace-match
11722 (concat "@<a name=\""
11723 (org-solidify-link-text (match-string 1 line))
11724 "\" class=\"target\">" (match-string 1 line) "@</a> ")
11725 t t line)))))
11726
11727 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
11728 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
11729 (setq line (org-html-expand line))
11730
11731 ;; Format the links
11732 (setq start 0)
11733 (while (string-match org-bracket-link-analytic-regexp line start)
11734 (setq start (match-beginning 0))
11735 (setq type (if (match-end 2) (match-string 2 line) "internal"))
11736 (setq path (match-string 3 line))
11737 (setq desc1 (if (match-end 5) (match-string 5 line))
11738 desc2 (if (match-end 2) (concat type ":" path) path)
11739 desc (or desc1 desc2))
11740 (cond
11741 ((equal type "internal")
11742 (setq rpl
11743 (concat
11744 "<a href=\"#"
11745 (org-solidify-link-text path target-alist)
11746 "\">" desc "</a>")))
11747 ((member type '("http" "https" "ftp" "mailto" "news"))
11748 ;; standard URL
11749 (setq link (concat type ":" path))
11750 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
11751 ((string= type "file")
11752 ;; FILE link
11753 (let* ((filename path)
11754 (abs-p (file-name-absolute-p filename))
11755 (thefile (if abs-p (expand-file-name filename) filename))
11756 (thefile (save-match-data
11757 (if (string-match ":[0-9]+$" thefile)
11758 (replace-match "" t t thefile)
11759 thefile)))
11760 (file-is-image-p
11761 (save-match-data
11762 (string-match (org-image-file-name-regexp) thefile))))
11763 (setq rpl (if (and org-export-html-inline-images
11764 file-is-image-p)
11765 (concat "<img src=\"" thefile "\"/>")
11766 (concat "<a href=\"" thefile "\">" desc "</a>")))))
11767 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11768 (setq rpl (concat "<i>&lt;" type ":" path "&gt;</i>"))))
11769 ;; FIXME: We get to see the escaped links!!!!!
11770 (setq line (replace-match rpl t t line)
11771 start (+ start (length rpl))))
11772 ;; TODO items
11773 (if (and (string-match org-todo-line-regexp line)
11774 (match-beginning 2))
11775 (if (equal (match-string 2 line) org-done-string)
11776 (setq line (replace-match
11777 "<span class=\"done\">\\2</span>"
11778 nil nil line 2))
11779 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11780 nil nil line 2))))
11781
11782 ;; DEADLINES
11783 (if (string-match org-deadline-line-regexp line)
11784 (progn
11785 (if (save-match-data
11786 (string-match "<a href"
11787 (substring line 0 (match-beginning 0))))
11788 nil ; Don't do the replacement - it is inside a link
11789 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11790 nil nil line 1)))))
11791 (cond
11792 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11793 ;; This is a headline
11794 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11795 txt (match-string 2 line))
11796 (if (<= level umax) (setq head-count (+ head-count 1)))
11797 (when in-local-list
11798 ;; Close any local lists before inserting a new header line
11799 (while local-list-num
11800 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11801 (pop local-list-num))
11802 (setq local-list-indent nil
11803 in-local-list nil))
11804 (org-html-level-start level txt umax
11805 (and org-export-with-toc (<= level umax))
11806 head-count)
11807 ;; QUOTES
11808 (when (string-match quote-re line)
11809 (insert "<pre>")
11810 (setq inquote t)))
11811
11812 ((and org-export-with-tables
11813 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11814 (if (not table-open)
11815 ;; New table starts
11816 (setq table-open t table-buffer nil table-orig-buffer nil))
11817 ;; Accumulate lines
11818 (setq table-buffer (cons line table-buffer)
11819 table-orig-buffer (cons origline table-orig-buffer))
11820 (when (or (not lines)
11821 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11822 (car lines))))
11823 (setq table-open nil
11824 table-buffer (nreverse table-buffer)
11825 table-orig-buffer (nreverse table-orig-buffer))
11826 (insert (org-format-table-html table-buffer table-orig-buffer))))
11827 (t
11828 ;; Normal lines
11829 (when (and (string-match
11830 (cond
11831 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11832 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11833 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11834 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
11835 line))
11836 (setq ind (org-get-string-indentation line)
11837 start-is-num (match-beginning 4)
11838 starter (if (match-beginning 2) (match-string 2 line))
11839 line (substring line (match-beginning 5)))
11840 (unless (string-match "[^ \t]" line)
11841 ;; empty line. Pretend indentation is large.
11842 (setq ind (1+ (or (car local-list-indent) 1))))
11843 (while (and in-local-list
11844 (or (and (= ind (car local-list-indent))
11845 (not starter))
11846 (< ind (car local-list-indent))))
11847 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11848 (pop local-list-num) (pop local-list-indent)
11849 (setq in-local-list local-list-indent))
11850 (cond
11851 ((and starter
11852 (or (not in-local-list)
11853 (> ind (car local-list-indent))))
11854 ;; Start new (level of ) list
11855 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
11856 (push start-is-num local-list-num)
11857 (push ind local-list-indent)
11858 (setq in-local-list t))
11859 (starter
11860 ;; continue current list
11861 (insert "<li>\n"))))
11862 ;; Empty lines start a new paragraph. If hand-formatted lists
11863 ;; are not fully interpreted, lines starting with "-", "+", "*"
11864 ;; also start a new paragraph.
11865 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
11866 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
11867 ))
11868 (if org-export-html-with-timestamp
11869 (insert org-export-html-html-helper-timestamp))
11870 (insert "</body>\n</html>\n")
11871 (normal-mode)
11872 (save-buffer)
11873 (goto-char (point-min)))))
11874
11875 (defun org-format-table-html (lines olines)
11876 "Find out which HTML converter to use and return the HTML code."
11877 (if (string-match "^[ \t]*|" (car lines))
11878 ;; A normal org table
11879 (org-format-org-table-html lines)
11880 ;; Table made by table.el - test for spanning
11881 (let* ((hlines (delq nil (mapcar
11882 (lambda (x)
11883 (if (string-match "^[ \t]*\\+-" x) x
11884 nil))
11885 lines)))
11886 (first (car hlines))
11887 (ll (and (string-match "\\S-+" first)
11888 (match-string 0 first)))
11889 (re (concat "^[ \t]*" (regexp-quote ll)))
11890 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
11891 hlines))))
11892 (if (and (not spanning)
11893 (not org-export-prefer-native-exporter-for-tables))
11894 ;; We can use my own converter with HTML conversions
11895 (org-format-table-table-html lines)
11896 ;; Need to use the code generator in table.el, with the original text.
11897 (org-format-table-table-html-using-table-generate-source olines)))))
11898
11899 (defun org-format-org-table-html (lines)
11900 "Format a table into HTML."
11901 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11902 (setq lines (nreverse lines))
11903 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
11904 (setq lines (nreverse lines))
11905 (when org-export-table-remove-special-lines
11906 ;; Check if the table has a marking column. If yes remove the
11907 ;; column and the special lines
11908 (let* ((special
11909 (not
11910 (memq nil
11911 (mapcar
11912 (lambda (x)
11913 (or (string-match "^[ \t]*|-" x)
11914 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
11915 lines)))))
11916 (if special
11917 (setq lines
11918 (delq nil
11919 (mapcar
11920 (lambda (x)
11921 (if (string-match "^[ \t]*| *[!_^] *|" x)
11922 nil ; ignore this line
11923 (and (or (string-match "^[ \t]*|-+\\+" x)
11924 (string-match "^[ \t]*|[^|]*|" x))
11925 (replace-match "|" t t x))))
11926 lines))))))
11927
11928 (let ((head (and org-export-highlight-first-table-line
11929 (delq nil (mapcar
11930 (lambda (x) (string-match "^[ \t]*|-" x))
11931 (cdr lines)))))
11932 line fields html)
11933 (setq html (concat org-export-html-table-tag "\n"))
11934 (while (setq line (pop lines))
11935 (catch 'next-line
11936 (if (string-match "^[ \t]*|-" line)
11937 (progn
11938 (setq head nil) ;; head ends here, first time around
11939 ;; ignore this line
11940 (throw 'next-line t)))
11941 ;; Break the line into fields
11942 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11943 (setq html (concat
11944 html
11945 "<tr>"
11946 (mapconcat (lambda (x)
11947 (if head
11948 (concat "<th>" x "</th>")
11949 (concat "<td>" x "</td>")))
11950 fields "")
11951 "</tr>\n"))))
11952 (setq html (concat html "</table>\n"))
11953 html))
11954
11955 (defun org-fake-empty-table-line (line)
11956 "Replace everything except \"|\" with spaces."
11957 (let ((i (length line))
11958 (newstr (copy-sequence line)))
11959 (while (> i 0)
11960 (setq i (1- i))
11961 (if (not (eq (aref newstr i) ?|))
11962 (aset newstr i ?\ )))
11963 newstr))
11964
11965 (defun org-format-table-table-html (lines)
11966 "Format a table generated by table.el into HTML.
11967 This conversion does *not* use `table-generate-source' from table.el.
11968 This has the advantage that Org-mode's HTML conversions can be used.
11969 But it has the disadvantage, that no cell- or row-spanning is allowed."
11970 (let (line field-buffer
11971 (head org-export-highlight-first-table-line)
11972 fields html empty)
11973 (setq html (concat org-export-html-table-tag "\n"))
11974 (while (setq line (pop lines))
11975 (setq empty "&nbsp")
11976 (catch 'next-line
11977 (if (string-match "^[ \t]*\\+-" line)
11978 (progn
11979 (if field-buffer
11980 (progn
11981 (setq html (concat
11982 html
11983 "<tr>"
11984 (mapconcat
11985 (lambda (x)
11986 (if (equal x "") (setq x empty))
11987 (if head
11988 (concat "<th>" x "</th>\n")
11989 (concat "<td>" x "</td>\n")))
11990 field-buffer "\n")
11991 "</tr>\n"))
11992 (setq head nil)
11993 (setq field-buffer nil)))
11994 ;; Ignore this line
11995 (throw 'next-line t)))
11996 ;; Break the line into fields and store the fields
11997 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
11998 (if field-buffer
11999 (setq field-buffer (mapcar
12000 (lambda (x)
12001 (concat x "<br>" (pop fields)))
12002 field-buffer))
12003 (setq field-buffer fields))))
12004 (setq html (concat html "</table>\n"))
12005 html))
12006
12007 (defun org-format-table-table-html-using-table-generate-source (lines)
12008 "Format a table into html, using `table-generate-source' from table.el.
12009 This has the advantage that cell- or row-spanning is allowed.
12010 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
12011 (require 'table)
12012 (with-current-buffer (get-buffer-create " org-tmp1 ")
12013 (erase-buffer)
12014 (insert (mapconcat 'identity lines "\n"))
12015 (goto-char (point-min))
12016 (if (not (re-search-forward "|[^+]" nil t))
12017 (error "Error processing table"))
12018 (table-recognize-table)
12019 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
12020 (table-generate-source 'html " org-tmp2 ")
12021 (set-buffer " org-tmp2 ")
12022 (buffer-substring (point-min) (point-max))))
12023
12024 (defun org-html-protect (s)
12025 ;; convert & to &amp;, < to &lt; and > to &gt;
12026 (let ((start 0))
12027 (while (string-match "&" s start)
12028 (setq s (replace-match "&amp;" t t s)
12029 start (1+ (match-beginning 0))))
12030 (while (string-match "<" s)
12031 (setq s (replace-match "&lt;" t t s)))
12032 (while (string-match ">" s)
12033 (setq s (replace-match "&gt;" t t s))))
12034 s)
12035
12036 (defun org-html-expand (string)
12037 "Prepare STRING for HTML export. Applies all active conversions.
12038 If there are links in the string, don't modify these."
12039 (let* (m s l res)
12040 (while (setq m (string-match org-bracket-link-regexp string))
12041 (setq s (substring string 0 m)
12042 l (match-string 0 string)
12043 string (substring string (match-end 0)))
12044 (push (org-html-do-expand s) res)
12045 (push l res))
12046 (push (org-html-do-expand string) res)
12047 (apply 'concat (nreverse res))))
12048
12049 (defun org-html-do-expand (s)
12050 "Apply all active conversions to translate special ASCII to HTML."
12051 (setq s (org-html-protect s))
12052 (if org-export-html-expand
12053 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
12054 (setq s (replace-match "<\\1>" nil nil s))))
12055 (if org-export-with-emphasize
12056 (setq s (org-export-html-convert-emphasize s)))
12057 (if org-export-with-sub-superscripts
12058 (setq s (org-export-html-convert-sub-super s)))
12059 (if org-export-with-TeX-macros
12060 (let ((start 0) wd ass)
12061 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
12062 (setq wd (match-string 1 s))
12063 (if (setq ass (assoc wd org-html-entities))
12064 (setq s (replace-match (or (cdr ass)
12065 (concat "&" (car ass) ";"))
12066 t t s))
12067 (setq start (+ start (length wd)))))))
12068 s)
12069
12070 (defun org-create-multibrace-regexp (left right n)
12071 "Create a regular expression which will match a balanced sexp.
12072 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
12073 as single character strings.
12074 The regexp returned will match the entire expression including the
12075 delimiters. It will also define a single group which contains the
12076 match except for the outermost delimiters. The maximum depth of
12077 stacked delimiters is N. Escaping delimiters is not possible."
12078 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
12079 (or "\\|")
12080 (re nothing)
12081 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
12082 (while (> n 1)
12083 (setq n (1- n)
12084 re (concat re or next)
12085 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
12086 (concat left "\\(" re "\\)" right)))
12087
12088 (defvar org-match-substring-regexp
12089 (concat
12090 "\\([^\\]\\)\\([_^]\\)\\("
12091 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
12092 "\\|"
12093 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
12094 "\\|"
12095 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
12096 "The regular expression matching a sub- or superscript.")
12097
12098 (defun org-export-html-convert-sub-super (string)
12099 "Convert sub- and superscripts in STRING to HTML."
12100 (let (key c)
12101 (while (string-match org-match-substring-regexp string)
12102 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
12103 (setq c (or (match-string 8 string)
12104 (match-string 6 string)
12105 (match-string 5 string)))
12106 (setq string (replace-match
12107 (concat (match-string 1 string)
12108 "<" key ">" c "</" key ">")
12109 t t string)))
12110 (while (string-match "\\\\\\([_^]\\)" string)
12111 (setq string (replace-match (match-string 1 string) t t string))))
12112 string)
12113
12114 (defun org-export-html-convert-emphasize (string)
12115 (let (c (s 0))
12116 (while (string-match "\\(\\W\\|^\\)\\([*/_]\\)\\(\\w+\\)\\2\\(\\W\\|$\\)" string s)
12117 (setq c (cdr (assoc (match-string 2 string)
12118 '(("*" . "b") ("/" . "i") ("_" . "u"))))
12119 s (+ (match-end 0) 3)
12120 string (replace-match
12121 (concat "\\1<" c ">\\3</" c ">\\4") t nil string)))
12122 string))
12123
12124 (defun org-parse-key-lines ()
12125 "Find the special key lines with the information for exporters."
12126 (save-excursion
12127 (goto-char 0)
12128 (let ((re (org-make-options-regexp
12129 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12130 key)
12131 (while (re-search-forward re nil t)
12132 (setq key (match-string 1))
12133 (cond ((string-equal key "TITLE")
12134 (setq title (match-string 2)))
12135 ((string-equal key "AUTHOR")
12136 (setq author (match-string 2)))
12137 ((string-equal key "EMAIL")
12138 (setq email (match-string 2)))
12139 ((string-equal key "LANGUAGE")
12140 (setq language (match-string 2)))
12141 ((string-equal key "TEXT")
12142 (setq text (concat text "\n" (match-string 2))))
12143 ((string-equal key "OPTIONS")
12144 (setq options (match-string 2))))))))
12145
12146 (defun org-parse-export-options (s)
12147 "Parse the export options line."
12148 (let ((op '(("H" . org-export-headline-levels)
12149 ("num" . org-export-with-section-numbers)
12150 ("toc" . org-export-with-toc)
12151 ("\\n" . org-export-preserve-breaks)
12152 ("@" . org-export-html-expand)
12153 (":" . org-export-with-fixed-width)
12154 ("|" . org-export-with-tables)
12155 ("^" . org-export-with-sub-superscripts)
12156 ("*" . org-export-with-emphasize)
12157 ("TeX" . org-export-with-TeX-macros)))
12158 o)
12159 (while (setq o (pop op))
12160 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
12161 s)
12162 (set (make-local-variable (cdr o))
12163 (car (read-from-string (match-string 1 s))))))))
12164
12165 (defun org-html-level-start (level title umax with-toc head-count)
12166 "Insert a new level in HTML export."
12167 (let ((l (1+ (max level umax))))
12168 (while (<= l org-level-max)
12169 (if (aref levels-open (1- l))
12170 (progn
12171 (org-html-level-close l)
12172 (aset levels-open (1- l) nil)))
12173 (setq l (1+ l)))
12174 (if (> level umax)
12175 (progn
12176 (if (aref levels-open (1- level))
12177 (insert "<li>" title "<p>\n")
12178 (aset levels-open (1- level) t)
12179 (insert "<ul><li>" title "<p>\n")))
12180 (if org-export-with-section-numbers
12181 (setq title (concat (org-section-number level) " " title)))
12182 (setq level (+ level 1))
12183 (if with-toc
12184 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
12185 level head-count title level))
12186 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
12187
12188 (defun org-html-level-close (&rest args)
12189 "Terminate one level in HTML export."
12190 (insert "</ul>"))
12191
12192 ;; Variable holding the vector with section numbers
12193 (defvar org-section-numbers (make-vector org-level-max 0))
12194
12195 (defun org-init-section-numbers ()
12196 "Initialize the vector for the section numbers."
12197 (let* ((level -1)
12198 (numbers (nreverse (org-split-string "" "\\.")))
12199 (depth (1- (length org-section-numbers)))
12200 (i depth) number-string)
12201 (while (>= i 0)
12202 (if (> i level)
12203 (aset org-section-numbers i 0)
12204 (setq number-string (or (car numbers) "0"))
12205 (if (string-match "\\`[A-Z]\\'" number-string)
12206 (aset org-section-numbers i
12207 (- (string-to-char number-string) ?A -1))
12208 (aset org-section-numbers i (string-to-number number-string)))
12209 (pop numbers))
12210 (setq i (1- i)))))
12211
12212 (defun org-section-number (&optional level)
12213 "Return a string with the current section number.
12214 When LEVEL is non-nil, increase section numbers on that level."
12215 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
12216 (when level
12217 (when (> level -1)
12218 (aset org-section-numbers
12219 level (1+ (aref org-section-numbers level))))
12220 (setq idx (1+ level))
12221 (while (<= idx depth)
12222 (if (not (= idx 1))
12223 (aset org-section-numbers idx 0))
12224 (setq idx (1+ idx))))
12225 (setq idx 0)
12226 (while (<= idx depth)
12227 (setq n (aref org-section-numbers idx))
12228 (setq string (concat string (if (not (string= string "")) "." "")
12229 (int-to-string n)))
12230 (setq idx (1+ idx)))
12231 (save-match-data
12232 (if (string-match "\\`\\([@0]\\.\\)+" string)
12233 (setq string (replace-match "" nil nil string)))
12234 (if (string-match "\\(\\.0\\)+\\'" string)
12235 (setq string (replace-match "" nil nil string))))
12236 string))
12237
12238
12239 (defun org-export-icalendar-this-file ()
12240 "Export current file as an iCalendar file.
12241 The iCalendar file will be located in the same directory as the Org-mode
12242 file, but with extension `.ics'."
12243 (interactive)
12244 (org-export-icalendar nil buffer-file-name))
12245
12246 (defun org-export-as-xml ()
12247 "Export current buffer as XOXO XML buffer."
12248 (interactive)
12249 (cond ((eq org-export-xml-type 'xoxo)
12250 (org-export-as-xoxo (current-buffer)))))
12251
12252 (defun org-export-as-xoxo-insert-into (buffer &rest output)
12253 (with-current-buffer buffer
12254 (apply 'insert output)))
12255
12256 (defun org-export-as-xoxo (&optional buffer)
12257 "Export the org buffer as XOXO.
12258 The XOXO buffer is named *xoxo-<source buffer name>*"
12259 (interactive (list (current-buffer)))
12260 ;; A quickie abstraction
12261
12262 ;; Output everything as XOXO
12263 (with-current-buffer (get-buffer buffer)
12264 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
12265 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
12266 ".xml"))
12267 (out (find-file-noselect filename))
12268 (last-level 1)
12269 (hanging-li nil))
12270 ;; Check the output buffer is empty.
12271 (with-current-buffer out (erase-buffer))
12272 ;; Kick off the output
12273 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
12274 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
12275 (let* ((hd (match-string-no-properties 1))
12276 (level (length hd))
12277 (text (concat
12278 (match-string-no-properties 2)
12279 (save-excursion
12280 (goto-char (match-end 0))
12281 (let ((str ""))
12282 (catch 'loop
12283 (while 't
12284 (forward-line)
12285 (if (looking-at "^[ \t]\\(.*\\)")
12286 (setq str (concat str (match-string-no-properties 1)))
12287 (throw 'loop str)))))))))
12288
12289 ;; Handle level rendering
12290 (cond
12291 ((> level last-level)
12292 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
12293
12294 ((< level last-level)
12295 (dotimes (- (- last-level level) 1)
12296 (if hanging-li
12297 (org-export-as-xoxo-insert-into out "</li>\n"))
12298 (org-export-as-xoxo-insert-into out "</ol>\n"))
12299 (when hanging-li
12300 (org-export-as-xoxo-insert-into out "</li>\n")
12301 (setq hanging-li nil)))
12302
12303 ((equal level last-level)
12304 (if hanging-li
12305 (org-export-as-xoxo-insert-into out "</li>\n")))
12306 )
12307
12308 (setq last-level level)
12309
12310 ;; And output the new li
12311 (setq hanging-li 't)
12312 (if (equal ?+ (elt text 0))
12313 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
12314 (org-export-as-xoxo-insert-into out "<li>" text))))
12315
12316 ;; Finally finish off the ol
12317 (dotimes (- last-level 1)
12318 (if hanging-li
12319 (org-export-as-xoxo-insert-into out "</li>\n"))
12320 (org-export-as-xoxo-insert-into out "</ol>\n"))
12321
12322 ;; Finish the buffer off and clean it up.
12323 (switch-to-buffer-other-window out)
12324 (indent-region (point-min) (point-max))
12325 (save-buffer)
12326 (goto-char (point-min))
12327 )))
12328
12329 ;;;###autoload
12330 (defun org-export-icalendar-all-agenda-files ()
12331 "Export all files in `org-agenda-files' to iCalendar .ics files.
12332 Each iCalendar file will be located in the same directory as the Org-mode
12333 file, but with extension `.ics'."
12334 (interactive)
12335 (apply 'org-export-icalendar nil (org-agenda-files t)))
12336
12337 ;;;###autoload
12338 (defun org-export-icalendar-combine-agenda-files ()
12339 "Export all files in `org-agenda-files' to a single combined iCalendar file.
12340 The file is stored under the name `org-combined-agenda-icalendar-file'."
12341 (interactive)
12342 (apply 'org-export-icalendar t (org-agenda-files t)))
12343
12344 (defun org-export-icalendar (combine &rest files)
12345 "Create iCalendar files for all elements of FILES.
12346 If COMBINE is non-nil, combine all calendar entries into a single large
12347 file and store it under the name `org-combined-agenda-icalendar-file'."
12348 (save-excursion
12349 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
12350 (when combine
12351 (setq ical-file org-combined-agenda-icalendar-file
12352 ical-buffer (org-get-agenda-file-buffer ical-file))
12353 (set-buffer ical-buffer) (erase-buffer))
12354 (while (setq file (pop files))
12355 (catch 'nextfile
12356 (org-check-agenda-file file)
12357 (unless combine
12358 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
12359 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
12360 (set-buffer ical-buffer) (erase-buffer))
12361 (set-buffer (org-get-agenda-file-buffer file))
12362 (setq category (or org-category
12363 (file-name-sans-extension
12364 (file-name-nondirectory buffer-file-name))))
12365 (if (symbolp category) (setq category (symbol-name category)))
12366 (let ((standard-output ical-buffer))
12367 (if combine
12368 (and (not started) (setq started t)
12369 (org-start-icalendar-file org-icalendar-combined-name))
12370 (org-start-icalendar-file category))
12371 (org-print-icalendar-entries combine category)
12372 (when (or (and combine (not files)) (not combine))
12373 (org-finish-icalendar-file)
12374 (set-buffer ical-buffer)
12375 (save-buffer)
12376 (run-hooks 'org-after-save-iCalendar-file-hook)))))
12377 (org-release-buffers org-agenda-new-buffers))))
12378
12379 (defvar org-after-save-iCalendar-file-hook nil
12380 "Hook run after an iCalendar file has been saved.
12381 The iCalendar buffer is still current when this hook is run.
12382 A good way to use this is to tell a desktop calenndar application to re-read
12383 the iCalendar file.")
12384
12385 (defun org-print-icalendar-entries (&optional combine category)
12386 "Print iCalendar entries for the current Org-mode file to `standard-output'.
12387 When COMBINE is non nil, add the category to each line."
12388 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
12389 (dts (org-ical-ts-to-string
12390 (format-time-string (cdr org-time-stamp-formats) (current-time))
12391 "DTSTART"))
12392 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
12393 (save-excursion
12394 (goto-char (point-min))
12395 (while (re-search-forward org-ts-regexp nil t)
12396 (setq pos (match-beginning 0)
12397 ts (match-string 0)
12398 inc t
12399 hd (org-get-heading))
12400 (if (looking-at re2)
12401 (progn
12402 (goto-char (match-end 0))
12403 (setq ts2 (match-string 1) inc nil))
12404 (setq ts2 ts
12405 tmp (buffer-substring (max (point-min)
12406 (- pos org-ds-keyword-length))
12407 pos)
12408 deadlinep (string-match org-deadline-regexp tmp)
12409 scheduledp (string-match org-scheduled-regexp tmp)
12410 ;; donep (org-entry-is-done-p)
12411 ))
12412 (if (or (string-match org-tr-regexp hd)
12413 (string-match org-ts-regexp hd))
12414 (setq hd (replace-match "" t t hd)))
12415 (if combine
12416 (setq hd (concat hd " (category " category ")")))
12417 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
12418 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
12419 (princ (format "BEGIN:VEVENT
12420 %s
12421 %s
12422 SUMMARY:%s
12423 END:VEVENT\n"
12424 (org-ical-ts-to-string ts "DTSTART")
12425 (org-ical-ts-to-string ts2 "DTEND" inc)
12426 hd)))
12427 (when org-icalendar-include-todo
12428 (goto-char (point-min))
12429 (while (re-search-forward org-todo-line-regexp nil t)
12430 (setq state (match-string 1))
12431 (unless (equal state org-done-string)
12432 (setq hd (match-string 3))
12433 (if (string-match org-priority-regexp hd)
12434 (setq pri (string-to-char (match-string 2 hd))
12435 hd (concat (substring hd 0 (match-beginning 1))
12436 (substring hd (- (match-end 1)))))
12437 (setq pri org-default-priority))
12438 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
12439 (- org-lowest-priority ?A))))))
12440
12441 (princ (format "BEGIN:VTODO
12442 %s
12443 SUMMARY:%s
12444 SEQUENCE:1
12445 PRIORITY:%d
12446 END:VTODO\n"
12447 dts hd pri))))))))
12448
12449 (defun org-start-icalendar-file (name)
12450 "Start an iCalendar file by inserting the header."
12451 (let ((user user-full-name)
12452 (name (or name "unknown"))
12453 (timezone (cadr (current-time-zone))))
12454 (princ
12455 (format "BEGIN:VCALENDAR
12456 VERSION:2.0
12457 X-WR-CALNAME:%s
12458 PRODID:-//%s//Emacs with Org-mode//EN
12459 X-WR-TIMEZONE:%s
12460 CALSCALE:GREGORIAN\n" name user timezone))))
12461
12462 (defun org-finish-icalendar-file ()
12463 "Finish an iCalendar file by inserting the END statement."
12464 (princ "END:VCALENDAR\n"))
12465
12466 (defun org-ical-ts-to-string (s keyword &optional inc)
12467 "Take a time string S and convert it to iCalendar format.
12468 KEYWORD is added in front, to make a complete line like DTSTART....
12469 When INC is non-nil, increase the hour by two (if time string contains
12470 a time), or the day by one (if it does not contain a time)."
12471 (let ((t1 (org-parse-time-string s 'nodefault))
12472 t2 fmt have-time time)
12473 (if (and (car t1) (nth 1 t1) (nth 2 t1))
12474 (setq t2 t1 have-time t)
12475 (setq t2 (org-parse-time-string s)))
12476 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
12477 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
12478 (when inc
12479 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
12480 (setq time (encode-time s mi h d m y)))
12481 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
12482 (concat keyword (format-time-string fmt time))))
12483
12484
12485 ;;; Key bindings
12486
12487 ;; - Bindings in Org-mode map are currently
12488 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
12489 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
12490 ;; e (?) useful from outline-mode
12491 ;; i k @ expendable from outline-mode
12492 ;; 0123456789 % & ()_{} " ` free
12493
12494 ;; Make `C-c C-x' a prefix key
12495 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
12496
12497 ;; TAB key with modifiers
12498 (define-key org-mode-map "\C-i" 'org-cycle)
12499 (define-key org-mode-map [(tab)] 'org-cycle)
12500 (define-key org-mode-map [(meta tab)] 'org-complete)
12501 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
12502 ;; The following line is necessary under Suse GNU/Linux
12503 (unless (featurep 'xemacs)
12504 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
12505 (define-key org-mode-map [(shift tab)] 'org-shifttab)
12506
12507 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
12508 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
12509 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12510 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
12511 (define-key org-mode-map [(meta return)] 'org-meta-return)
12512 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
12513 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
12514
12515 ;; Cursor keys with modifiers
12516 (define-key org-mode-map [(meta left)] 'org-metaleft)
12517 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
12518 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
12519 (define-key org-mode-map [(meta right)] 'org-metaright)
12520 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
12521 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
12522 (define-key org-mode-map [(meta up)] 'org-metaup)
12523 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
12524 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
12525 (define-key org-mode-map [(meta down)] 'org-metadown)
12526 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
12527 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
12528
12529 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12530 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
12531 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
12532 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
12533 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
12534 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
12535 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
12536 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
12537 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
12538 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
12539 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
12540 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
12541 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
12542 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
12543 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
12544 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
12545
12546 ;; All the other keys
12547 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
12548 (define-key org-mode-map "\C-c\C-j" 'org-goto)
12549 (define-key org-mode-map "\C-c\C-t" 'org-todo)
12550 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
12551 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
12552 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
12553 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12554 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
12555 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
12556 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12557 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
12558 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
12559 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
12560 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
12561 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
12562 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
12563 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
12564 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12565 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12566 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12567 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12568 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
12569 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
12570 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12571 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
12572 (define-key org-mode-map "\C-c]" 'org-remove-file)
12573 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
12574 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
12575 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
12576 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12577 (define-key org-mode-map "\C-m" 'org-return)
12578 (define-key org-mode-map "\C-c?" 'org-table-current-column)
12579 (define-key org-mode-map "\C-c " 'org-table-blank-field)
12580 (define-key org-mode-map "\C-c+" 'org-table-sum)
12581 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
12582 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
12583 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
12584 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12585 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
12586 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12587 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
12588 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12589 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
12590 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
12591 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
12592 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
12593 ;; OPML support is only an option for the future
12594 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
12595 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
12596 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
12597 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
12598 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
12599 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
12600 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
12601 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12602 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
12603 (define-key org-mode-map "\C-c\C-xx" 'org-export-as-xml)
12604 (define-key org-mode-map "\C-c\C-x\C-x" 'org-export-as-xml)
12605 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
12606 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
12607
12608 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12609 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12610 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12611 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12612
12613 (defsubst org-table-p () (org-at-table-p))
12614
12615 (defun org-self-insert-command (N)
12616 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12617 If the cursor is in a table looking at whitespace, the whitespace is
12618 overwritten, and the table is not marked as requiring realignment."
12619 (interactive "p")
12620 (if (and (org-table-p)
12621 (progn
12622 ;; check if we blank the field, and if that triggers align
12623 (and org-table-auto-blank-field
12624 (member last-command
12625 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12626 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12627 ;; got extra space, this field does not determine column width
12628 (let (org-table-may-need-update) (org-table-blank-field))
12629 ;; no extra space, this field may determine column width
12630 (org-table-blank-field)))
12631 t)
12632 (eq N 1)
12633 (looking-at "[^|\n]* |"))
12634 (let (org-table-may-need-update)
12635 (goto-char (1- (match-end 0)))
12636 (delete-backward-char 1)
12637 (goto-char (match-beginning 0))
12638 (self-insert-command N))
12639 (setq org-table-may-need-update t)
12640 (self-insert-command N)))
12641
12642 (defun org-delete-backward-char (N)
12643 "Like `delete-backward-char', insert whitespace at field end in tables.
12644 When deleting backwards, in tables this function will insert whitespace in
12645 front of the next \"|\" separator, to keep the table aligned. The table will
12646 still be marked for re-alignment if the field did fill the entire column,
12647 because, in this case the deletion might narrow the column."
12648 (interactive "p")
12649 (if (and (org-table-p)
12650 (eq N 1)
12651 (string-match "|" (buffer-substring (point-at-bol) (point)))
12652 (looking-at ".*?|"))
12653 (let ((pos (point))
12654 (noalign (looking-at "[^|\n\r]* |"))
12655 (c org-table-may-need-update))
12656 (backward-delete-char N)
12657 (skip-chars-forward "^|")
12658 (insert " ")
12659 (goto-char (1- pos))
12660 ;; noalign: if there were two spaces at the end, this field
12661 ;; does not determine the width of the column.
12662 (if noalign (setq org-table-may-need-update c)))
12663 (backward-delete-char N)))
12664
12665 (defun org-delete-char (N)
12666 "Like `delete-char', but insert whitespace at field end in tables.
12667 When deleting characters, in tables this function will insert whitespace in
12668 front of the next \"|\" separator, to keep the table aligned. The table will
12669 still be marked for re-alignment if the field did fill the entire column,
12670 because, in this case the deletion might narrow the column."
12671 (interactive "p")
12672 (if (and (org-table-p)
12673 (not (bolp))
12674 (not (= (char-after) ?|))
12675 (eq N 1))
12676 (if (looking-at ".*?|")
12677 (let ((pos (point))
12678 (noalign (looking-at "[^|\n\r]* |"))
12679 (c org-table-may-need-update))
12680 (replace-match (concat
12681 (substring (match-string 0) 1 -1)
12682 " |"))
12683 (goto-char pos)
12684 ;; noalign: if there were two spaces at the end, this field
12685 ;; does not determine the width of the column.
12686 (if noalign (setq org-table-may-need-update c))))
12687 (delete-char N)))
12688
12689 ;; How to do this: Measure non-white length of current string
12690 ;; If equal to column width, we should realign.
12691
12692 (defun org-remap (map &rest commands)
12693 "In MAP, remap the functions given in COMMANDS.
12694 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12695 (let (new old)
12696 (while commands
12697 (setq old (pop commands) new (pop commands))
12698 (if (fboundp 'command-remapping)
12699 (define-key map (vector 'remap old) new)
12700 (substitute-key-definition old new map global-map)))))
12701
12702 (when (eq org-enable-table-editor 'optimized)
12703 ;; If the user wants maximum table support, we need to hijack
12704 ;; some standard editing functions
12705 (org-remap org-mode-map
12706 'self-insert-command 'org-self-insert-command
12707 'delete-char 'org-delete-char
12708 'delete-backward-char 'org-delete-backward-char)
12709 (define-key org-mode-map "|" 'org-force-self-insert))
12710
12711 (defun org-shiftcursor-error ()
12712 "Throw an error because Shift-Cursor command was applied in wrong context."
12713 (error "This command is active in special context like tables, headlines or timestamps"))
12714
12715 (defun org-shifttab ()
12716 "Global visibility cycling or move to previous table field.
12717 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
12718 See the individual commands for more information."
12719 (interactive)
12720 (cond
12721 ((org-at-table-p) (org-table-previous-field))
12722 (t (org-cycle '(4)))))
12723
12724 (defun org-shiftmetaleft ()
12725 "Promote subtree or delete table column.
12726 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
12727 See the individual commands for more information."
12728 (interactive)
12729 (cond
12730 ((org-at-table-p) (org-table-delete-column))
12731 ((org-on-heading-p) (org-promote-subtree))
12732 ((org-at-item-p) (call-interactively 'org-outdent-item))
12733 (t (org-shiftcursor-error))))
12734
12735 (defun org-shiftmetaright ()
12736 "Demote subtree or insert table column.
12737 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
12738 See the individual commands for more information."
12739 (interactive)
12740 (cond
12741 ((org-at-table-p) (org-table-insert-column))
12742 ((org-on-heading-p) (org-demote-subtree))
12743 ((org-at-item-p) (call-interactively 'org-indent-item))
12744 (t (org-shiftcursor-error))))
12745
12746 (defun org-shiftmetaup (&optional arg)
12747 "Move subtree up or kill table row.
12748 Calls `org-move-subtree-up' or `org-table-kill-row' or
12749 `org-move-item-up' depending on context. See the individual commands
12750 for more information."
12751 (interactive "P")
12752 (cond
12753 ((org-at-table-p) (org-table-kill-row))
12754 ((org-on-heading-p) (org-move-subtree-up arg))
12755 ((org-at-item-p) (org-move-item-up arg))
12756 (t (org-shiftcursor-error))))
12757 (defun org-shiftmetadown (&optional arg)
12758 "Move subtree down or insert table row.
12759 Calls `org-move-subtree-down' or `org-table-insert-row' or
12760 `org-move-item-down', depending on context. See the individual
12761 commands for more information."
12762 (interactive "P")
12763 (cond
12764 ((org-at-table-p) (org-table-insert-row arg))
12765 ((org-on-heading-p) (org-move-subtree-down arg))
12766 ((org-at-item-p) (org-move-item-down arg))
12767 (t (org-shiftcursor-error))))
12768
12769 (defun org-metaleft (&optional arg)
12770 "Promote heading or move table column to left.
12771 Calls `org-do-promote' or `org-table-move-column', depending on context.
12772 With no specific context, calls the Emacs default `backward-word'.
12773 See the individual commands for more information."
12774 (interactive "P")
12775 (cond
12776 ((org-at-table-p) (org-table-move-column 'left))
12777 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
12778 (t (backward-word (prefix-numeric-value arg)))))
12779
12780 (defun org-metaright (&optional arg)
12781 "Demote subtree or move table column to right.
12782 Calls `org-do-demote' or `org-table-move-column', depending on context.
12783 With no specific context, calls the Emacs default `forward-word'.
12784 See the individual commands for more information."
12785 (interactive "P")
12786 (cond
12787 ((org-at-table-p) (org-table-move-column nil))
12788 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
12789 (t (forward-word (prefix-numeric-value arg)))))
12790
12791 (defun org-metaup (&optional arg)
12792 "Move subtree up or move table row up.
12793 Calls `org-move-subtree-up' or `org-table-move-row' or
12794 `org-move-item-up', depending on context. See the individual commands
12795 for more information."
12796 (interactive "P")
12797 (cond
12798 ((org-at-table-p) (org-table-move-row 'up))
12799 ((org-on-heading-p) (org-move-subtree-up arg))
12800 ((org-at-item-p) (org-move-item-up arg))
12801 (t (org-shiftcursor-error))))
12802
12803 (defun org-metadown (&optional arg)
12804 "Move subtree down or move table row down.
12805 Calls `org-move-subtree-down' or `org-table-move-row' or
12806 `org-move-item-down', depending on context. See the individual
12807 commands for more information."
12808 (interactive "P")
12809 (cond
12810 ((org-at-table-p) (org-table-move-row nil))
12811 ((org-on-heading-p) (org-move-subtree-down arg))
12812 ((org-at-item-p) (org-move-item-down arg))
12813 (t (org-shiftcursor-error))))
12814
12815 (defun org-shiftup (&optional arg)
12816 "Increase item in timestamp or increase priority of current item.
12817 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12818 See the individual commands for more information."
12819 (interactive "P")
12820 (cond
12821 ((org-at-timestamp-p) (org-timestamp-up arg))
12822 (t (org-priority-up))))
12823
12824 (defun org-shiftdown (&optional arg)
12825 "Decrease item in timestamp or decrease priority of current item.
12826 Calls `org-timestamp-down' or `org-priority-down', depending on context.
12827 See the individual commands for more information."
12828 (interactive "P")
12829 (cond
12830 ((org-at-timestamp-p) (org-timestamp-down arg))
12831 (t (org-priority-down))))
12832
12833 (defun org-shiftright ()
12834 "Next TODO keyword or timestamp one day later, depending on context."
12835 (interactive)
12836 (cond
12837 ((org-at-timestamp-p) (org-timestamp-up-day))
12838 ((org-on-heading-p) (org-todo 'right))
12839 (t (org-shiftcursor-error))))
12840
12841 (defun org-shiftleft ()
12842 "Previous TODO keyword or timestamp one day earlier, depending on context."
12843 (interactive)
12844 (cond
12845 ((org-at-timestamp-p) (org-timestamp-down-day))
12846 ((org-on-heading-p) (org-todo 'left))
12847 (t (org-shiftcursor-error))))
12848
12849 (defun org-copy-special ()
12850 "Copy region in table or copy current subtree.
12851 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12852 See the individual commands for more information."
12853 (interactive)
12854 (call-interactively
12855 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12856
12857 (defun org-cut-special ()
12858 "Cut region in table or cut current subtree.
12859 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12860 See the individual commands for more information."
12861 (interactive)
12862 (call-interactively
12863 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12864
12865 (defun org-paste-special (arg)
12866 "Paste rectangular region into table, or past subtree relative to level.
12867 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12868 See the individual commands for more information."
12869 (interactive "P")
12870 (if (org-at-table-p)
12871 (org-table-paste-rectangle)
12872 (org-paste-subtree arg)))
12873
12874 (defun org-ctrl-c-ctrl-c (&optional arg)
12875 "Set tags in headline, or update according to changed information at point.
12876
12877 This command does many different things, depending on context:
12878
12879 - If the cursor is in a headline, prompt for tags and insert them
12880 into the current line, aligned to `org-tags-column'. When called
12881 with prefix arg, realign all tags in the current buffer.
12882
12883 - If the cursor is in one of the special #+KEYWORD lines, this
12884 triggers scanning the buffer for these lines and updating the
12885 information.
12886
12887 - If the cursor is inside a table, realign the table. This command
12888 works even if the automatic table editor has been turned off.
12889
12890 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12891 the entire table.
12892
12893 - If the cursor is inside a table created by the table.el package,
12894 activate that table.
12895
12896 - If the current buffer is a remember buffer, close note and file it.
12897 with a prefix argument, file it without further interaction to the default
12898 location.
12899
12900 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12901 links in this buffer.
12902
12903 - If the cursor is on a numbered item in a plain list, renumber the
12904 ordered list."
12905 (interactive "P")
12906 (let ((org-enable-table-editor t))
12907 (cond
12908 ((and (local-variable-p 'org-finish-function (current-buffer))
12909 (fboundp org-finish-function))
12910 (funcall org-finish-function))
12911 ((org-on-target-p) (org-update-radio-target-regexp))
12912 ((org-on-heading-p) (org-set-tags arg))
12913 ((org-at-table.el-p)
12914 (require 'table)
12915 (beginning-of-line 1)
12916 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12917 (table-recognize-table))
12918 ((org-at-table-p)
12919 (org-table-maybe-eval-formula)
12920 (if arg
12921 (org-table-recalculate t)
12922 (org-table-maybe-recalculate-line))
12923 (org-table-align))
12924 ((org-at-item-p)
12925 (org-renumber-ordered-list (prefix-numeric-value arg)))
12926 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12927 (cond
12928 ((equal (match-string 1) "TBLFM")
12929 ;; Recalculate the table before this line
12930 (save-excursion
12931 (beginning-of-line 1)
12932 (skip-chars-backward " \r\n\t")
12933 (if (org-at-table-p) (org-table-recalculate t))))
12934 (t
12935 (org-mode-restart))))
12936 (t (error "C-c C-c can do nothing useful at this location.")))))
12937
12938 (defun org-mode-restart ()
12939 "Restart Org-mode, to scan again for special lines.
12940 Also updates the keyword regular expressions."
12941 (interactive)
12942 (let ((org-inhibit-startup t)) (org-mode))
12943 (message "Org-mode restarted to refresh keyword and special line setup"))
12944
12945 (defun org-return ()
12946 "Goto next table row or insert a newline.
12947 Calls `org-table-next-row' or `newline', depending on context.
12948 See the individual commands for more information."
12949 (interactive)
12950 (cond
12951 ((org-at-table-p)
12952 (org-table-justify-field-maybe)
12953 (org-table-next-row))
12954 (t (newline))))
12955
12956 (defun org-meta-return (&optional arg)
12957 "Insert a new heading or wrap a region in a table.
12958 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12959 See the individual commands for more information."
12960 (interactive "P")
12961 (cond
12962 ((org-at-table-p)
12963 (org-table-wrap-region arg))
12964 (t (org-insert-heading arg))))
12965
12966 ;;; Menu entries
12967
12968 ;; Define the Org-mode menus
12969 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12970 '("Tbl"
12971 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
12972 ["Next Field" org-cycle (org-at-table-p)]
12973 ["Previous Field" org-shifttab (org-at-table-p)]
12974 ["Next Row" org-return (org-at-table-p)]
12975 "--"
12976 ["Blank Field" org-table-blank-field (org-at-table-p)]
12977 ["Edit Field" org-table-edit-field (org-at-table-p)]
12978 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12979 "--"
12980 ("Column"
12981 ["Move Column Left" org-metaleft (org-at-table-p)]
12982 ["Move Column Right" org-metaright (org-at-table-p)]
12983 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12984 ["Insert Column" org-shiftmetaright (org-at-table-p)]
12985 "--"
12986 ["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])
12987 ("Row"
12988 ["Move Row Up" org-metaup (org-at-table-p)]
12989 ["Move Row Down" org-metadown (org-at-table-p)]
12990 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12991 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12992 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12993 "--"
12994 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
12995 ("Rectangle"
12996 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12997 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12998 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12999 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13000 "--"
13001 ("Calculate"
13002 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13003 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13004 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
13005 "--"
13006 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13007 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13008 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13009 "--"
13010 ["Sum Column/Rectangle" org-table-sum
13011 (or (org-at-table-p) (org-region-active-p))]
13012 ["Which Column?" org-table-current-column (org-at-table-p)])
13013 ["Debug Formulas"
13014 (setq org-table-formula-debug (not org-table-formula-debug))
13015 :style toggle :selected org-table-formula-debug]
13016 "--"
13017 ["Create" org-table-create (and (not (org-at-table-p))
13018 org-enable-table-editor)]
13019 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13020 ["Import from File" org-table-import (not (org-at-table-p))]
13021 ["Export to File" org-table-export (org-at-table-p)]
13022 "--"
13023 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13024
13025 (easy-menu-define org-org-menu org-mode-map "Org menu"
13026 '("Org"
13027 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
13028 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
13029 ["Sparse Tree" org-occur t]
13030 ["Show All" show-all t]
13031 "--"
13032 ["New Heading" org-insert-heading t]
13033 ("Navigate Headings"
13034 ["Up" outline-up-heading t]
13035 ["Next" outline-next-visible-heading t]
13036 ["Previous" outline-previous-visible-heading t]
13037 ["Next Same Level" outline-forward-same-level t]
13038 ["Previous Same Level" outline-backward-same-level t]
13039 "--"
13040 ["Jump" org-goto t])
13041 ("Edit Structure"
13042 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13043 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13044 "--"
13045 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13046 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13047 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13048 "--"
13049 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13050 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13051 ["Demote Heading" org-metaright (not (org-at-table-p))]
13052 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13053 "--"
13054 ["Archive Subtree" org-archive-subtree t]
13055 "--"
13056 ["Convert to odd levels" org-convert-to-odd-levels t]
13057 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13058 "--"
13059 ("TODO Lists"
13060 ["TODO/DONE/-" org-todo t]
13061 ["Show TODO Tree" org-show-todo-tree t]
13062 ["Global TODO list" org-todo-list t]
13063 "--"
13064 ["Set Priority" org-priority t]
13065 ["Priority Up" org-shiftup t]
13066 ["Priority Down" org-shiftdown t])
13067 ("Dates and Scheduling"
13068 ["Timestamp" org-time-stamp t]
13069 ["Timestamp (inactive)" org-time-stamp-inactive t]
13070 ("Change Date"
13071 ["1 Day Later" org-timestamp-up-day t]
13072 ["1 Day Earlier" org-timestamp-down-day t]
13073 ["1 ... Later" org-shiftup t]
13074 ["1 ... Earlier" org-shiftdown t])
13075 ["Compute Time Range" org-evaluate-time-range t]
13076 ["Schedule Item" org-schedule t]
13077 ["Deadline" org-deadline t]
13078 "--"
13079 ["Goto Calendar" org-goto-calendar t]
13080 ["Date from Calendar" org-date-from-calendar t])
13081 "--"
13082 ["Agenda Command" org-agenda t]
13083 ("File List for Agenda")
13084 ("Special views current file"
13085 ["TODO Tree" org-show-todo-tree t]
13086 ["Check Deadlines" org-check-deadlines t]
13087 ["Timeline" org-timeline t]
13088 ["Tags Tree" org-tags-sparse-tree t])
13089 "--"
13090 ("Hyperlinks"
13091 ["Store Link (Global)" org-store-link t]
13092 ["Insert Link" org-insert-link t]
13093 ["Follow Link" org-open-at-point t]
13094 "--"
13095 ["Descriptive Links"
13096 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13097 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
13098 ["Literal Links"
13099 (progn
13100 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13101 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
13102 "--"
13103 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
13104 (save-excursion (goto-char (point-min))
13105 (re-search-forward "<[a-z]+:" nil t))])
13106 "--"
13107 ("Export"
13108 ["ASCII" org-export-as-ascii t]
13109 ["Extract Visible Text" org-export-copy-visible t]
13110 ["HTML" org-export-as-html t]
13111 ["HTML and Open" org-export-as-html-and-open t]
13112 ["XML (XOXO)" org-export-as-xml t]
13113 "--"
13114 ["iCalendar this file" org-export-icalendar-this-file t]
13115 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
13116 :active t :keys "C-c C-x C-i"]
13117 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
13118 "--"
13119 ["Option Template" org-insert-export-options-template t]
13120 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
13121 "--"
13122 ("Documentation"
13123 ["Show Version" org-version t]
13124 ["Info Documentation" org-info t])
13125 ("Customize"
13126 ["Browse Org Group" org-customize t]
13127 "--"
13128 ["Expand This Menu" org-create-customize-menu
13129 (fboundp 'customize-menu-create)])
13130 "--"
13131 ["Refresh setup" org-mode-restart t]
13132 ))
13133
13134 (defun org-info (&optional node)
13135 "Read documentation for Org-mode in the info system.
13136 With optional NODE, go directly to that node."
13137 (interactive)
13138 (require 'info)
13139 (Info-goto-node (format "(org)%s" (or node ""))))
13140
13141 (defun org-install-agenda-files-menu ()
13142 (let ((bl (buffer-list)))
13143 (save-excursion
13144 (while bl
13145 (set-buffer (pop bl))
13146 (if (eq major-mode 'org-mode) (setq bl nil)))
13147 (when (eq major-mode 'org-mode)
13148 (easy-menu-change
13149 '("Org") "File List for Agenda"
13150 (append
13151 (list
13152 ["Edit File List" (org-edit-agenda-file-list) t]
13153 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13154 ["Remove Current File from List" org-remove-file t]
13155 ["Cycle through agenda files" org-cycle-agenda-files t]
13156 "--")
13157 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13158
13159 ;;; Documentation
13160
13161 (defun org-customize ()
13162 "Call the customize function with org as argument."
13163 (interactive)
13164 (customize-browse 'org))
13165
13166 (defun org-create-customize-menu ()
13167 "Create a full customization menu for Org-mode, insert it into the menu."
13168 (interactive)
13169 (if (fboundp 'customize-menu-create)
13170 (progn
13171 (easy-menu-change
13172 '("Org") "Customize"
13173 `(["Browse Org group" org-customize t]
13174 "--"
13175 ,(customize-menu-create 'org)
13176 ["Set" Custom-set t]
13177 ["Save" Custom-save t]
13178 ["Reset to Current" Custom-reset-current t]
13179 ["Reset to Saved" Custom-reset-saved t]
13180 ["Reset to Standard Settings" Custom-reset-standard t]))
13181 (message "\"Org\"-menu now contains full customization menu"))
13182 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13183
13184 ;;; Miscellaneous stuff
13185
13186 (defun org-move-line-down (arg)
13187 "Move the current line down. With prefix argument, move it past ARG lines."
13188 (interactive "p")
13189 (let ((col (current-column))
13190 beg end pos)
13191 (beginning-of-line 1) (setq beg (point))
13192 (beginning-of-line 2) (setq end (point))
13193 (beginning-of-line (+ 1 arg))
13194 (setq pos (move-marker (make-marker) (point)))
13195 (insert (delete-and-extract-region beg end))
13196 (goto-char pos)
13197 (move-to-column col)))
13198
13199 (defun org-move-line-up (arg)
13200 "Move the current line up. With prefix argument, move it past ARG lines."
13201 (interactive "p")
13202 (let ((col (current-column))
13203 beg end pos)
13204 (beginning-of-line 1) (setq beg (point))
13205 (beginning-of-line 2) (setq end (point))
13206 (beginning-of-line (- arg))
13207 (setq pos (move-marker (make-marker) (point)))
13208 (insert (delete-and-extract-region beg end))
13209 (goto-char pos)
13210 (move-to-column col)))
13211
13212 ;; Paragraph filling stuff.
13213 ;; We want this to be just right, so use the full arsenal.
13214 ;; FIXME: This very likely does not work correctly for XEmacs, because the
13215 ;; filladapt package works slightly differently.
13216
13217 (defun org-set-autofill-regexps ()
13218 (interactive)
13219 ;; In the paragraph separator we include headlines, because filling
13220 ;; text in a line directly attached to a headline would otherwise
13221 ;; fill the headline as well.
13222 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
13223 ;; The paragraph starter includes hand-formatted lists.
13224 (set (make-local-variable 'paragraph-start)
13225 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13226 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13227 ;; But only if the user has not turned off tables or fixed-width regions
13228 (set (make-local-variable 'auto-fill-inhibit-regexp)
13229 (concat "\\*\\|#"
13230 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13231 (concat
13232 "\\|[ \t]*["
13233 (if org-enable-table-editor "|" "")
13234 (if org-enable-fixed-width-editor ":" "")
13235 "]"))))
13236 ;; We use our own fill-paragraph function, to make sure that tables
13237 ;; and fixed-width regions are not wrapped. That function will pass
13238 ;; through to `fill-paragraph' when appropriate.
13239 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
13240 ;; Adaptive filling: To get full control, first make sure that
13241 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13242 (set (make-local-variable 'adaptive-fill-regexp) "\000")
13243 (set (make-local-variable 'adaptive-fill-function)
13244 'org-adaptive-fill-function))
13245
13246 (defun org-fill-paragraph (&optional justify)
13247 "Re-align a table, pass through to fill-paragraph if no table."
13248 (let ((table-p (org-at-table-p))
13249 (table.el-p (org-at-table.el-p)))
13250 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
13251 (table.el-p t) ; skip table.el tables
13252 (table-p (org-table-align) t) ; align org-mode tables
13253 (t nil)))) ; call paragraph-fill
13254
13255 ;; For reference, this is the default value of adaptive-fill-regexp
13256 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13257
13258 (defun org-adaptive-fill-function ()
13259 "Return a fill prefix for org-mode files.
13260 In particular, this makes sure hanging paragraphs for hand-formatted lists
13261 work correctly."
13262 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
13263 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
13264
13265 ;; Functions needed for Emacs/XEmacs region compatibility
13266
13267 (defun org-add-hook (hook function &optional append local)
13268 "Add-hook, compatible with both Emacsen."
13269 (if (and local (featurep 'xemacs))
13270 (add-local-hook hook function append)
13271 (add-hook hook function append local)))
13272
13273 (defun org-region-active-p ()
13274 "Is `transient-mark-mode' on and the region active?
13275 Works on both Emacs and XEmacs."
13276 (if org-ignore-region
13277 nil
13278 (if (featurep 'xemacs)
13279 (and zmacs-regions (region-active-p))
13280 (and transient-mark-mode mark-active))))
13281
13282 (defun org-add-to-invisibility-spec (arg)
13283 "Add elements to `buffer-invisibility-spec'.
13284 See documentation for `buffer-invisibility-spec' for the kind of elements
13285 that can be added."
13286 (cond
13287 ((fboundp 'add-to-invisibility-spec)
13288 (add-to-invisibility-spec arg))
13289 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
13290 (setq buffer-invisibility-spec (list arg)))
13291 (t
13292 (setq buffer-invisibility-spec
13293 (cons arg buffer-invisibility-spec)))))
13294
13295 (defun org-remove-from-invisibility-spec (arg)
13296 "Remove elements from `buffer-invisibility-spec'."
13297 (if (fboundp 'remove-from-invisibility-spec)
13298 (remove-from-invisibility-spec arg)
13299 (if (consp buffer-invisibility-spec)
13300 (setq buffer-invisibility-spec
13301 (delete arg buffer-invisibility-spec)))))
13302
13303 (defun org-in-invisibility-spec-p (arg)
13304 "Is ARG a member of `buffer-invisibility-spec'?"
13305 (if (consp buffer-invisibility-spec)
13306 (member arg buffer-invisibility-spec)
13307 nil))
13308
13309 (defun org-image-file-name-regexp ()
13310 "Return regexp matching the file names of images."
13311 (if (fboundp 'image-file-name-regexp)
13312 (image-file-name-regexp)
13313 (let ((image-file-name-extensions
13314 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13315 "xbm" "xpm" "pbm" "pgm" "ppm")))
13316 (concat "\\."
13317 (regexp-opt (nconc (mapcar 'upcase
13318 image-file-name-extensions)
13319 image-file-name-extensions)
13320 t)
13321 "\\'"))))
13322
13323 ;; Functions needed for compatibility with old outline.el.
13324
13325 ;; Programming for the old outline.el (that uses selective display
13326 ;; instead of `invisible' text properties) is a nightmare, mostly
13327 ;; because regular expressions can no longer be anchored at
13328 ;; beginning/end of line. Therefore a number of function need special
13329 ;; treatment when the old outline.el is being used.
13330
13331 ;; The following functions capture almost the entire compatibility code
13332 ;; between the different versions of outline-mode. The only other
13333 ;; places where this is important are the font-lock-keywords, and in
13334 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
13335
13336 ;; C-a should go to the beginning of a *visible* line, also in the
13337 ;; new outline.el. I guess this should be patched into Emacs?
13338 (defun org-beginning-of-line ()
13339 "Go to the beginning of the current line. If that is invisible, continue
13340 to a visible line beginning. This makes the function of C-a more intuitive."
13341 (interactive)
13342 (beginning-of-line 1)
13343 (if (bobp)
13344 nil
13345 (backward-char 1)
13346 (if (org-invisible-p)
13347 (while (and (not (bobp)) (org-invisible-p))
13348 (backward-char 1)
13349 (beginning-of-line 1))
13350 (forward-char 1))))
13351
13352 (when org-noutline-p
13353 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
13354 ;; FIXME: should I use substitute-key-definition to reach other bindings
13355 ;; of beginning-of-line?
13356
13357 (defun org-invisible-p ()
13358 "Check if point is at a character currently not visible."
13359 (if org-noutline-p
13360 ;; Early versions of noutline don't have `outline-invisible-p'.
13361 (if (fboundp 'outline-invisible-p)
13362 (outline-invisible-p)
13363 (get-char-property (point) 'invisible))
13364 (save-excursion
13365 (skip-chars-backward "^\r\n")
13366 (equal (char-before) ?\r))))
13367
13368 (defun org-invisible-p2 ()
13369 "Check if point is at a character currently not visible."
13370 (save-excursion
13371 (if org-noutline-p
13372 (progn
13373 (if (and (eolp) (not (bobp))) (backward-char 1))
13374 ;; Early versions of noutline don't have `outline-invisible-p'.
13375 (if (fboundp 'outline-invisible-p)
13376 (outline-invisible-p)
13377 (get-char-property (point) 'invisible)))
13378 (skip-chars-backward "^\r\n")
13379 (equal (char-before) ?\r))))
13380
13381 (defun org-back-to-heading (&optional invisible-ok)
13382 "Move to previous heading line, or beg of this line if it's a heading.
13383 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
13384 (if org-noutline-p
13385 (outline-back-to-heading invisible-ok)
13386 (if (and (memq (char-before) '(?\n ?\r))
13387 (looking-at outline-regexp))
13388 t
13389 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
13390 outline-regexp)
13391 nil t)
13392 (if invisible-ok
13393 (progn (goto-char (match-end 1))
13394 (looking-at outline-regexp)))
13395 (error "Before first heading")))))
13396
13397 (defun org-on-heading-p (&optional invisible-ok)
13398 "Return t if point is on a (visible) heading line.
13399 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
13400 (if org-noutline-p
13401 (outline-on-heading-p 'invisible-ok)
13402 (save-excursion
13403 (skip-chars-backward "^\n\r")
13404 (and (looking-at outline-regexp)
13405 (or invisible-ok
13406 (bobp)
13407 (equal (char-before) ?\n))))))
13408
13409 (defun org-on-target-p ()
13410 (let ((pos (point)))
13411 (save-excursion
13412 (skip-chars-forward "<")
13413 (and (re-search-backward "<<" nil t)
13414 (or (looking-at org-radio-target-regexp)
13415 (looking-at org-target-regexp))
13416 (<= (match-beginning 0) pos)
13417 (>= (1+ (match-end 0)) pos)))))
13418
13419 (defun org-up-heading-all (arg)
13420 "Move to the heading line of which the present line is a subheading.
13421 This function considers both visible and invisible heading lines.
13422 With argument, move up ARG levels."
13423 (if org-noutline-p
13424 (if (fboundp 'outline-up-heading-all)
13425 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13426 (outline-up-heading arg t)) ; emacs 22 version of outline.el
13427 (org-back-to-heading t)
13428 (looking-at outline-regexp)
13429 (if (<= (- (match-end 0) (match-beginning 0)) arg)
13430 (error "Cannot move up %d levels" arg)
13431 (re-search-backward
13432 (concat "[\n\r]" (regexp-quote
13433 (make-string (- (match-end 0) (match-beginning 0) arg)
13434 ?*))
13435 "[^*]"))
13436 (forward-char 1))))
13437
13438 (defun org-show-hidden-entry ()
13439 "Show an entry where even the heading is hidden."
13440 (save-excursion
13441 (if (not org-noutline-p)
13442 (progn
13443 (org-back-to-heading t)
13444 (org-flag-heading nil)))
13445 (org-show-entry)))
13446
13447 (defun org-check-occur-regexp (regexp)
13448 "If REGEXP starts with \"^\", modify it to check for \\r as well.
13449 Of course, only for the old outline mode."
13450 (if org-noutline-p
13451 regexp
13452 (if (string-match "^\\^" regexp)
13453 (concat "[\n\r]" (substring regexp 1))
13454 regexp)))
13455
13456 (defun org-flag-heading (flag &optional entry)
13457 "Flag the current heading. FLAG non-nil means make invisible.
13458 When ENTRY is non-nil, show the entire entry."
13459 (save-excursion
13460 (org-back-to-heading t)
13461 (if (not org-noutline-p)
13462 ;; Make the current headline visible
13463 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
13464 ;; Check if we should show the entire entry
13465 (if entry
13466 (progn
13467 (org-show-entry)
13468 (save-excursion ;; FIXME: Is this the fix for points in the -|
13469 ;; middle of text? |
13470 (and (outline-next-heading) ;; |
13471 (org-flag-heading nil)))) ; show the next heading _|
13472 (outline-flag-region (max 1 (1- (point)))
13473 (save-excursion (outline-end-of-heading) (point))
13474 (if org-noutline-p
13475 flag
13476 (if flag ?\r ?\n))))))
13477
13478 (defun org-end-of-subtree (&optional invisible-OK)
13479 ;; This is an exact copy of the original function, but it uses
13480 ;; `org-back-to-heading', to make it work also in invisible
13481 ;; trees. And is uses an invisible-OK argument.
13482 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13483 (org-back-to-heading invisible-OK)
13484 (let ((first t)
13485 (level (funcall outline-level)))
13486 (while (and (not (eobp))
13487 (or first (> (funcall outline-level) level)))
13488 (setq first nil)
13489 (outline-next-heading))
13490 (if (memq (preceding-char) '(?\n ?\^M))
13491 (progn
13492 ;; Go to end of line before heading
13493 (forward-char -1)
13494 (if (memq (preceding-char) '(?\n ?\^M))
13495 ;; leave blank line before heading
13496 (forward-char -1))))))
13497
13498 (defun org-show-subtree ()
13499 "Show everything after this heading at deeper levels."
13500 (outline-flag-region
13501 (point)
13502 (save-excursion
13503 (outline-end-of-subtree) (outline-next-heading) (point))
13504 (if org-noutline-p nil ?\n)))
13505
13506 (defun org-show-entry ()
13507 "Show the body directly following this heading.
13508 Show the heading too, if it is currently invisible."
13509 (interactive)
13510 (save-excursion
13511 (org-back-to-heading t)
13512 (outline-flag-region
13513 (1- (point))
13514 (save-excursion
13515 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13516 (or (match-beginning 1) (point-max)))
13517 (if org-noutline-p nil ?\n))))
13518
13519 (defun org-make-options-regexp (kwds)
13520 "Make a regular expression for keyword lines."
13521 (concat
13522 (if org-noutline-p "^" "[\n\r]")
13523 "#?[ \t]*\\+\\("
13524 (mapconcat 'regexp-quote kwds "\\|")
13525 "\\):[ \t]*"
13526 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
13527
13528 ;; Make `bookmark-jump' show the jump location if it was hidden.
13529 (eval-after-load "bookmark"
13530 '(if (boundp 'bookmark-after-jump-hook)
13531 ;; We can use the hook
13532 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13533 ;; Hook not available, use advice
13534 (defadvice bookmark-jump (after org-make-visible activate)
13535 "Make the position visible."
13536 (org-bookmark-jump-unhide))))
13537
13538 (defun org-bookmark-jump-unhide ()
13539 "Unhide the current position, to show the bookmark location."
13540 (and (eq major-mode 'org-mode)
13541 (or (org-invisible-p)
13542 (save-excursion (goto-char (max (point-min) (1- (point))))
13543 (org-invisible-p)))
13544 (org-show-hierarchy-above)))
13545
13546 ;;; Finish up
13547
13548 (provide 'org)
13549
13550 (run-hooks 'org-load-hook)
13551
13552 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13553 ;;; org.el ends here
13554