]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
Remove forgotten (debug) form.
[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.25
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.25
85 ;; - Revision of the font-lock faces section, with better tty support.
86 ;; - TODO keywords in Agenda buffer are fontified.
87 ;; - Export converts links between .org files to links between .html files.
88 ;; - Better support for bold/italic/underline emphasis.
89 ;;
90 ;; Version 4.24
91 ;; - Bug fixes.
92 ;;
93 ;; Version 4.23
94 ;; - Bug fixes.
95 ;;
96 ;; Version 4.22
97 ;; - Bug fixes.
98 ;; - In agenda buffer, mouse-1 no longer follows link.
99 ;; See `org-agenda-mouse-1-follows-link' and `org-mouse-1-follows-link'.
100 ;;
101 ;; Version 4.20
102 ;; - Links use now the [[link][description]] format by default.
103 ;; When inserting links, the user is prompted for a description.
104 ;; - If a link has a description, only the description is displayed
105 ;; the link part is hidden. Use C-c C-l to edit the link part.
106 ;; - TAGS are now bold, but in the same color as the headline.
107 ;; - The width of a table column can be limited by using a field "<N>".
108 ;; - New structure for the customization tree.
109 ;; - Bug fixes.
110 ;;
111 ;; Version 4.13
112 ;; - The list of agenda files can be maintainted in an external file.
113 ;; - Bug fixes.
114 ;;
115 ;; Version 4.12
116 ;; - Templates for remember buffer. Note that the remember setup changes.
117 ;; To set up templates, see `org-remember-templates'.
118 ;; - The time in new time stamps can be rounded, see new option
119 ;; `org-time-stamp-rounding-minutes'.
120 ;; - Bug fixes (there are *always* more bugs).
121 ;;
122 ;; Version 4.10
123 ;; - Bug fixes.
124 ;;
125 ;; Version 4.09
126 ;; - Bug fixes.
127 ;; - Small improvements to font-lock support.
128 ;; - MHE support finalized.
129 ;;
130 ;; Version 4.08
131 ;; - Bug fixes.
132 ;; - Improved MHE support
133 ;;
134 ;; Version 4.07
135 ;; - Bug fixes.
136 ;; - Leading stars in headlines can be hidden, so make the outline look
137 ;; cleaner.
138 ;; - Mouse-1 can be used to follow links.
139 ;;
140 ;; Version 4.06
141 ;; - HTML exporter treats targeted internal links.
142 ;; - Bug fixes.
143 ;;
144 ;; Version 4.05
145 ;; - Changes to internal link system (thanks to David Wainberg for ideas).
146 ;; - in-file links: [[Search String]] instead of <file:::Search String>
147 ;; - automatic links to "radio targets".
148 ;; - CamelCase not longer active by default, configure org-activate-camels
149 ;; if you want to turn it back on.
150 ;; - After following a link, `C-c &' jumps back to it.
151 ;; - MH-E link support (thanks to Thomas Baumann).
152 ;; - Special table lines are no longer exported.
153 ;; - Bug fixes and minor improvements.
154 ;;
155 ;; Version 4.04
156 ;; - Cleanup tags display in agenda.
157 ;; - Bug fixes.
158 ;;
159 ;; Version 4.03
160 ;; - Table alignment fixed for use with wide characters.
161 ;; - `C-c -' leaves cursor in current table line.
162 ;; - The current TAG can be incorporated into the agenda prefix.
163 ;; See option `org-agenda-prefix-format' for details.
164 ;;
165 ;; Version 4.02
166 ;; - Minor bug fixes and improvements around tag searches.
167 ;; - XEmacs compatibility fixes.
168 ;;
169 ;; Version 4.01
170 ;; - Tags can also be set remotely from agenda buffer.
171 ;; - Boolean logic for tag searches.
172 ;; - Additional agenda commands can be configured through the variable
173 ;; `org-agenda-custom-commands'.
174 ;; - Minor bug fixes.
175 ;;
176 ;;; Code:
177
178 (eval-when-compile
179 (require 'cl)
180 (require 'calendar))
181 (require 'outline)
182 (require 'time-date)
183 (require 'easymenu)
184
185 (defvar calc-embedded-close-formula) ; defined by the calc package
186 (defvar calc-embedded-open-formula) ; defined by the calc package
187 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
188
189 ;;; Customization variables
190
191 (defvar org-version "4.25"
192 "The version number of the file org.el.")
193 (defun org-version ()
194 (interactive)
195 (message "Org-mode version %s" org-version))
196
197 ;; The following constant is for compatibility with different versions
198 ;; of outline.el.
199 (defconst org-noutline-p (featurep 'noutline)
200 "Are we using the new outline mode?")
201 (defconst org-xemacs-p (featurep 'xemacs)) ;; FIXME: used by external code?
202 (defconst org-format-transports-properties-p
203 (let ((x "a"))
204 (add-text-properties 0 1 '(test t) x)
205 (get-text-property 0 'test (format "%s" x)))
206 "Does format transport text properties?")
207
208 (defgroup org nil
209 "Outline-based notes management and organizer."
210 :tag "Org"
211 :group 'outlines
212 :group 'hypermedia
213 :group 'calendar)
214
215 (defgroup org-startup nil
216 "Options concerning startup of Org-mode."
217 :tag "Org Startup"
218 :group 'org)
219
220 (defcustom org-startup-folded t
221 "Non-nil means, entering Org-mode will switch to OVERVIEW.
222 This can also be configured on a per-file basis by adding one of
223 the following lines anywhere in the buffer:
224
225 #+STARTUP: fold
226 #+STARTUP: nofold
227 #+STARTUP: content"
228 :group 'org-startup
229 :type '(choice
230 (const :tag "nofold: show all" nil)
231 (const :tag "fold: overview" t)
232 (const :tag "content: all headlines" content)))
233
234 (defcustom org-startup-truncated t
235 "Non-nil means, entering Org-mode will set `truncate-lines'.
236 This is useful since some lines containing links can be very long and
237 uninteresting. Also tables look terrible when wrapped."
238 :group 'org-startup
239 :type 'boolean)
240
241 (defcustom org-startup-align-all-tables nil
242 "Non-nil means, align all tables when visiting a file.
243 This is useful when the column width in tables is forced with <N> cookies
244 in table fields. Such tables will look correct only after the first re-align.
245 This can also be configured on a per-file basis by adding one of
246 the following lines anywhere in the buffer:
247 #+STARTUP: align
248 #+STARTUP: noalign"
249 :group 'org-startup
250 :type 'boolean)
251
252 (defcustom org-startup-with-deadline-check nil
253 "Non-nil means, entering Org-mode will run the deadline check.
254 This means, if you start editing an org file, you will get an
255 immediate reminder of any due deadlines.
256 This can also be configured on a per-file basis by adding one of
257 the following lines anywhere in the buffer:
258 #+STARTUP: dlcheck
259 #+STARTUP: nodlcheck"
260 :group 'org-startup
261 :type 'boolean)
262
263 (defcustom org-insert-mode-line-in-empty-file nil
264 "Non-nil means insert the first line setting Org-mode in empty files.
265 When the function `org-mode' is called interactively in an empty file, this
266 normally means that the file name does not automatically trigger Org-mode.
267 To ensure that the file will always be in Org-mode in the future, a
268 line enforcing Org-mode will be inserted into the buffer, if this option
269 has been set."
270 :group 'org-startup
271 :type 'boolean)
272
273 (defcustom org-CUA-compatible nil
274 "Non-nil means use alternative key bindings for S-<cursor movement>.
275 Org-mode used S-<cursor movement> for changing timestamps and priorities.
276 S-<cursor movement> is also used for example by `CUA-mode' to select text.
277 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
278 alternative bindings. Setting this variable to t will replace the following
279 keys both in Org-mode and in the Org-agenda buffer.
280
281 S-RET -> C-S-RET
282 S-up -> M-p
283 S-down -> M-n
284 S-left -> M--
285 S-right -> M-+
286
287 If you do not like the alternative keys, take a look at the variable
288 `org-disputed-keys'.
289
290 This option is only relevant at load-time of Org-mode. Changing it requires
291 a restart of Emacs to become effective."
292 :group 'org-startup
293 :type 'boolean)
294
295 (defvar org-disputed-keys
296 '((S-up [(shift up)] [(meta ?p)])
297 (S-down [(shift down)] [(meta ?n)])
298 (S-left [(shift left)] [(meta ?-)])
299 (S-right [(shift right)] [(meta ?+)])
300 (S-return [(shift return)] [(control shift return)]))
301 "Keys for which Org-mode and other modes compete.
302 This is an alist, cars are symbols for lookup, 1st element is the default key,
303 second element will be used when `org-CUA-compatible' is t.")
304
305 (defun org-key (key)
306 "Select a key according to `org-CUA-compatible'."
307 (nth (if org-CUA-compatible 2 1)
308 (or (assq key org-disputed-keys)
309 (error "Invalid Key %s in `org-key'" key))))
310
311 (defcustom org-ellipsis nil
312 "The ellipsis to use in the Org-mode outline.
313 When nil, just use the standard three dots. When a string, use that instead,
314 and just in Org-mode (which will then use its own display table).
315 Changing this requires executing `M-x org-mode' in a buffer to become
316 effective."
317 :group 'org-startup
318 :type '(choice (const :tag "Default" nil)
319 (string :tag "String" :value "...#")))
320
321 (defvar org-display-table nil
322 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
323
324 (defgroup org-keywords nil
325 "Keywords in Org-mode."
326 :tag "Org Keywords"
327 :group 'org)
328
329 (defcustom org-deadline-string "DEADLINE:"
330 "String to mark deadline entries.
331 A deadline is this string, followed by a time stamp. Should be a word,
332 terminated by a colon. You can insert a schedule keyword and
333 a timestamp with \\[org-deadline].
334 Changes become only effective after restarting Emacs."
335 :group 'org-keywords
336 :type 'string)
337
338 (defcustom org-scheduled-string "SCHEDULED:"
339 "String to mark scheduled TODO entries.
340 A schedule is this string, followed by a time stamp. Should be a word,
341 terminated by a colon. You can insert a schedule keyword and
342 a timestamp with \\[org-schedule].
343 Changes become only effective after restarting Emacs."
344 :group 'org-keywords
345 :type 'string)
346
347 (defcustom org-closed-string "CLOSED:"
348 "String used as the prefix for timestamps logging closing a TODO entry."
349 :group 'org-keywords
350 :type 'string)
351
352 (defcustom org-comment-string "COMMENT"
353 "Entries starting with this keyword will never be exported.
354 An entry can be toggled between COMMENT and normal with
355 \\[org-toggle-comment].
356 Changes become only effective after restarting Emacs."
357 :group 'org-keywords
358 :type 'string)
359
360 (defcustom org-quote-string "QUOTE"
361 "Entries starting with this keyword will be exported in fixed-width font.
362 Quoting applies only to the text in the entry following the headline, and does
363 not extend beyond the next headline, even if that is lower level.
364 An entry can be toggled between QUOTE and normal with
365 \\[org-toggle-fixed-width-section]."
366 :group 'org-keywords
367 :type 'string)
368
369 (defgroup org-structure nil
370 "Options concerning the general structure of Org-mode files."
371 :tag "Org Structure"
372 :group 'org)
373
374 (defgroup org-cycle nil
375 "Options concerning visibility cycling in Org-mode."
376 :tag "Org Cycle"
377 :group 'org-structure)
378
379 (defcustom org-cycle-emulate-tab t
380 "Where should `org-cycle' emulate TAB.
381 nil Never
382 white Only in completely white lines
383 t Everywhere except in headlines"
384 :group 'org-cycle
385 :type '(choice (const :tag "Never" nil)
386 (const :tag "Only in completely white lines" white)
387 (const :tag "Everywhere except in headlines" t)
388 ))
389
390 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
391 "Hook that is run after `org-cycle' has changed the buffer visibility.
392 The function(s) in this hook must accept a single argument which indicates
393 the new state that was set by the most recent `org-cycle' command. The
394 argument is a symbol. After a global state change, it can have the values
395 `overview', `content', or `all'. After a local state change, it can have
396 the values `folded', `children', or `subtree'."
397 :group 'org-cycle
398 :type 'hook)
399
400 (defgroup org-edit-structure nil
401 "Options concerning structure editing in Org-mode."
402 :tag "Org Edit Structure"
403 :group 'org-structure)
404
405 (defcustom org-odd-levels-only nil
406 "Non-nil means, skip even levels and only use odd levels for the outline.
407 This has the effect that two stars are being added/taken away in
408 promotion/demotion commands. It also influences how levels are
409 handled by the exporters.
410 Changing it requires restart of `font-lock-mode' to become effective
411 for fontification also in regions already fontified.
412 You may also set this on a per-file basis by adding one of the following
413 lines to the buffer:
414
415 #+STARTUP: odd
416 #+STARTUP: oddeven"
417 :group 'org-edit-structure
418 :group 'org-font-lock
419 :type 'boolean)
420
421 (defcustom org-adapt-indentation t
422 "Non-nil means, adapt indentation when promoting and demoting.
423 When this is set and the *entire* text in an entry is indented, the
424 indentation is increased by one space in a demotion command, and
425 decreased by one in a promotion command. If any line in the entry
426 body starts at column 0, indentation is not changed at all."
427 :group 'org-edit-structure
428 :type 'boolean)
429
430 (defcustom org-enable-fixed-width-editor t
431 "Non-nil means, lines starting with \":\" are treated as fixed-width.
432 This currently only means, they are never auto-wrapped.
433 When nil, such lines will be treated like ordinary lines.
434 See also the QUOTE keyword."
435 :group 'org-edit-structure
436 :type 'boolean)
437
438 (defgroup org-sparse-trees nil
439 "Options concerning sparse trees in Org-mode."
440 :tag "Org Sparse Trees"
441 :group 'org-structure)
442
443 (defcustom org-highlight-sparse-tree-matches t
444 "Non-nil means, highlight all matches that define a sparse tree.
445 The highlights will automatically disappear the next time the buffer is
446 changed by an edit command."
447 :group 'org-sparse-trees
448 :type 'boolean)
449
450 (defcustom org-show-hierarchy-above t
451 "Non-nil means, show full hierarchy when showing a spot in the tree.
452 Turning this off makes sparse trees more compact, but also less clear."
453 :group 'org-sparse-trees
454 :type 'boolean)
455
456 (defcustom org-show-following-heading t
457 "Non-nil means, show heading following match in `org-occur'.
458 When doing an `org-occur' it is useful to show the headline which
459 follows the match, even if they do not match the regexp. This makes it
460 easier to edit directly inside the sparse tree. However, if you use
461 `org-occur' mainly as an overview, the following headlines are
462 unnecessary clutter."
463 :group 'org-sparse-trees
464 :type 'boolean)
465
466 (defcustom org-occur-hook '(org-first-headline-recenter)
467 "Hook that is run after `org-occur' has constructed a sparse tree.
468 This can be used to recenter the window to show as much of the structure
469 as possible."
470 :group 'org-sparse-trees
471 :type 'hook)
472
473 (defgroup org-plain-lists nil
474 "Options concerning plain lists in Org-mode."
475 :tag "Org Plain lists"
476 :group 'org-structure)
477
478 (defcustom org-cycle-include-plain-lists nil
479 "Non-nil means, include plain lists into visibility cycling.
480 This means that during cycling, plain list items will *temporarily* be
481 interpreted as outline headlines with a level given by 1000+i where i is the
482 indentation of the bullet. In all other operations, plain list items are
483 not seen as headlines. For example, you cannot assign a TODO keyword to
484 such an item."
485 :group 'org-plain-lists
486 :type 'boolean)
487
488
489 (defcustom org-plain-list-ordered-item-terminator t
490 "The character that makes a line with leading number an ordered list item.
491 Valid values are ?. and ?\). To get both terminators, use t. While
492 ?. may look nicer, it creates the danger that a line with leading
493 number may be incorrectly interpreted as an item. ?\) therefore is
494 the safe choice."
495 :group 'org-plain-lists
496 :type '(choice (const :tag "dot like in \"2.\"" ?.)
497 (const :tag "paren like in \"2)\"" ?\))
498 (const :tab "both" t)))
499
500 (defcustom org-auto-renumber-ordered-lists t
501 "Non-nil means, automatically renumber ordered plain lists.
502 Renumbering happens when the sequence have been changed with
503 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
504 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
505 :group 'org-plain-lists
506 :type 'boolean)
507
508 (defgroup org-archive nil
509 "Options concerning archiving in Org-mode."
510 :tag "Org Archive"
511 :group 'org-structure)
512
513 (defcustom org-archive-location "%s_archive::"
514 "The location where subtrees should be archived.
515 This string consists of two parts, separated by a double-colon.
516
517 The first part is a file name - when omitted, archiving happens in the same
518 file. %s will be replaced by the current file name (without directory part).
519 Archiving to a different file is useful to keep archived entries from
520 contributing to the Org-mode Agenda.
521
522 The part after the double colon is a headline. The archived entries will be
523 filed under that headline. When omitted, the subtrees are simply filed away
524 at the end of the file, as top-level entries.
525
526 Here are a few examples:
527 \"%s_archive::\"
528 If the current file is Projects.org, archive in file
529 Projects.org_archive, as top-level trees. This is the default.
530
531 \"::* Archived Tasks\"
532 Archive in the current file, under the top-level headline
533 \"* Archived Tasks\".
534
535 \"~/org/archive.org::\"
536 Archive in file ~/org/archive.org (absolute path), as top-level trees.
537
538 \"basement::** Finished Tasks\"
539 Archive in file ./basement (relative path), as level 3 trees
540 below the level 2 heading \"** Finished Tasks\".
541
542 You may set this option on a per-file basis by adding to the buffer a
543 line like
544
545 #+ARCHIVE: basement::** Finished Tasks"
546 :group 'org-archive
547 :type 'string)
548
549 (defcustom org-archive-mark-done t
550 "Non-nil means, mark archived entries as DONE."
551 :group 'org-archive
552 :type 'boolean)
553
554 (defcustom org-archive-stamp-time t
555 "Non-nil means, add a time stamp to archived entries.
556 The time stamp will be added directly after the TODO state keyword in the
557 first line, so it is probably best to use this in combinations with
558 `org-archive-mark-done'."
559 :group 'org-archive
560 :type 'boolean)
561
562 (defgroup org-table nil
563 "Options concerning tables in Org-mode."
564 :tag "Org Table"
565 :group 'org)
566
567 (defcustom org-enable-table-editor 'optimized
568 "Non-nil means, lines starting with \"|\" are handled by the table editor.
569 When nil, such lines will be treated like ordinary lines.
570
571 When equal to the symbol `optimized', the table editor will be optimized to
572 do the following:
573 - Use automatic overwrite mode in front of whitespace in table fields.
574 This make the structure of the table stay in tact as long as the edited
575 field does not exceed the column width.
576 - Minimize the number of realigns. Normally, the table is aligned each time
577 TAB or RET are pressed to move to another field. With optimization this
578 happens only if changes to a field might have changed the column width.
579 Optimization requires replacing the functions `self-insert-command',
580 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
581 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
582 very good at guessing when a re-align will be necessary, but you can always
583 force one with \\[org-ctrl-c-ctrl-c].
584
585 If you would like to use the optimized version in Org-mode, but the
586 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
587
588 This variable can be used to turn on and off the table editor during a session,
589 but in order to toggle optimization, a restart is required.
590
591 See also the variable `org-table-auto-blank-field'."
592 :group 'org-table
593 :type '(choice
594 (const :tag "off" nil)
595 (const :tag "on" t)
596 (const :tag "on, optimized" optimized)))
597
598 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
599 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
600 In the optimized version, the table editor takes over all simple keys that
601 normally just insert a character. In tables, the characters are inserted
602 in a way to minimize disturbing the table structure (i.e. in overwrite mode
603 for empty fields). Outside tables, the correct binding of the keys is
604 restored.
605
606 The default for this option is t if the optimized version is also used in
607 Org-mode. See the variable `org-enable-table-editor' for details. Changing
608 this variable requires a restart of Emacs to become effective."
609 :group 'org-table
610 :type 'boolean)
611
612 (defgroup org-table-settings nil
613 "Settings for tables in Org-mode."
614 :tag "Org Table Settings"
615 :group 'org-table)
616
617 (defcustom org-table-default-size "5x2"
618 "The default size for newly created tables, Columns x Rows."
619 :group 'org-table-settings
620 :type 'string)
621
622 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
623 "Regular expression for recognizing numbers in table columns.
624 If a table column contains mostly numbers, it will be aligned to the
625 right. If not, it will be aligned to the left.
626
627 The default value of this option is a regular expression which allows
628 anything which looks remotely like a number as used in scientific
629 context. For example, all of the following will be considered a
630 number:
631 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
632
633 Other options offered by the customize interface are more restrictive."
634 :group 'org-table-settings
635 :type '(choice
636 (const :tag "Positive Integers"
637 "^[0-9]+$")
638 (const :tag "Integers"
639 "^[-+]?[0-9]+$")
640 (const :tag "Floating Point Numbers"
641 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
642 (const :tag "Floating Point Number or Integer"
643 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
644 (const :tag "Exponential, Floating point, Integer"
645 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
646 (const :tag "Very General Number-Like"
647 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
648 (string :tag "Regexp:")))
649
650 (defcustom org-table-number-fraction 0.5
651 "Fraction of numbers in a column required to make the column align right.
652 In a column all non-white fields are considered. If at least this
653 fraction of fields is matched by `org-table-number-fraction',
654 alignment to the right border applies."
655 :group 'org-table-settings
656 :type 'number)
657
658 (defgroup org-table-editing nil
659 "Bahavior of tables during editing in Org-mode."
660 :tag "Org Table Editing"
661 :group 'org-table)
662
663 (defcustom org-table-automatic-realign t
664 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
665 When nil, aligning is only done with \\[org-table-align], or after column
666 removal/insertion."
667 :group 'org-table-editing
668 :type 'boolean)
669
670 (defcustom org-table-limit-column-width t ;kw
671 "Non-nil means, allow to limit the width of table columns with <N> fields."
672 :group 'org-table-editing
673 :type 'boolean)
674
675 (defcustom org-table-auto-blank-field t
676 "Non-nil means, automatically blank table field when starting to type into it.
677 This only happens when typing immediately after a field motion
678 command (TAB, S-TAB or RET).
679 Only relevant when `org-enable-table-editor' is equal to `optimized'."
680 :group 'org-table-editing
681 :type 'boolean)
682
683 (defcustom org-table-tab-jumps-over-hlines t
684 "Non-nil means, tab in the last column of a table with jump over a hline.
685 If a horizontal separator line is following the current line,
686 `org-table-next-field' can either create a new row before that line, or jump
687 over the line. When this option is nil, a new line will be created before
688 this line."
689 :group 'org-table-editing
690 :type 'boolean)
691
692 (defcustom org-table-tab-recognizes-table.el t
693 "Non-nil means, TAB will automatically notice a table.el table.
694 When it sees such a table, it moves point into it and - if necessary -
695 calls `table-recognize-table'."
696 :group 'org-table-editing
697 :type 'boolean)
698
699 (defgroup org-table-calculation nil
700 "Options concerning tables in Org-mode."
701 :tag "Org Table Calculation"
702 :group 'org-table)
703
704 (defcustom org-table-copy-increment t
705 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
706 :group 'org-table-calculation
707 :type 'boolean)
708
709 (defcustom org-calc-default-modes
710 '(calc-internal-prec 12
711 calc-float-format (float 5)
712 calc-angle-mode deg
713 calc-prefer-frac nil
714 calc-symbolic-mode nil
715 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
716 calc-display-working-message t
717 )
718 "List with Calc mode settings for use in calc-eval for table formulas.
719 The list must contain alternating symbols (Calc modes variables and values).
720 Don't remove any of the default settings, just change the values. Org-mode
721 relies on the variables to be present in the list."
722 :group 'org-table-calculation
723 :type 'plist)
724
725 (defcustom org-table-formula-evaluate-inline t
726 "Non-nil means, TAB and RET evaluate a formula in current table field.
727 If the current field starts with an equal sign, it is assumed to be a formula
728 which should be evaluated as described in the manual and in the documentation
729 string of the command `org-table-eval-formula'. This feature requires the
730 Emacs calc package.
731 When this variable is nil, formula calculation is only available through
732 the command \\[org-table-eval-formula]."
733 :group 'org-table-calculation
734 :type 'boolean)
735
736
737 (defcustom org-table-formula-use-constants t
738 "Non-nil means, interpret constants in formulas in tables.
739 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
740 by the value given in `org-table-formula-constants', or by a value obtained
741 from the `constants.el' package."
742 :group 'org-table-calculation
743 :type 'boolean)
744
745 (defcustom org-table-formula-constants nil
746 "Alist with constant names and values, for use in table formulas.
747 The car of each element is a name of a constant, without the `$' before it.
748 The cdr is the value as a string. For example, if you'd like to use the
749 speed of light in a formula, you would configure
750
751 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
752
753 and then use it in an equation like `$1*$c'."
754 :group 'org-table-calculation
755 :type '(repeat
756 (cons (string :tag "name")
757 (string :tag "value"))))
758
759 (defcustom org-table-formula-numbers-only nil
760 "Non-nil means, calculate only with numbers in table formulas.
761 Then all input fields will be converted to a number, and the result
762 must also be a number. When nil, calc's full potential is available
763 in table calculations, including symbolics etc."
764 :group 'org-table-calculation
765 :type 'boolean)
766
767 (defcustom org-table-allow-automatic-line-recalculation t
768 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
769 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
770 :group 'org-table-calculation
771 :type 'boolean)
772
773 (defgroup org-link nil
774 "Options concerning links in Org-mode."
775 :tag "Org Link"
776 :group 'org)
777
778 (defcustom org-descriptive-links t
779 "Non-nil means, hide link part and only show description of bracket links.
780 Bracket links are like [[link][descritpion]]. This variable sets the initial
781 state in new org-mode buffers. The setting can then be toggled on a
782 per-buffer basis from the Org->Hyperlinks menu."
783 :group 'org-link
784 :type 'boolean)
785
786 (defcustom org-link-style 'bracket
787 "The style of links to be inserted with \\[org-insert-link].
788 Possible values are:
789 bracket [[link][description]]. This is recommended
790 plain Description \\n link. The old way, no longer recommended."
791 :group 'org-link
792 :type '(choice
793 (const :tag "Bracket (recommended)" bracket)
794 (const :tag "Plain (no longer recommended)" plain)))
795
796 (defcustom org-link-format "%s"
797 "Default format for external, URL-like linkes in the buffer.
798 This is a format string for printf, %s will be replaced by the link text.
799 The recommended value is just \"%s\", since links will be protected by
800 enclosing them in double brackets. If you prefer plain links (see variable
801 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
802 additional URL: prefix, so the format would be \"<URL:%s>\"."
803 :group 'org-link
804 :type '(choice
805 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
806 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
807 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
808 (string :tag "Other" :value "<%s>")))
809
810 (defcustom org-activate-links '(bracket angle plain radio tag date)
811 "Types of links that should be activated in Org-mode files.
812 This is a list of symbols, each leading to the activation of a certain link
813 type. In principle, it does not hurt to turn on most link types - there may
814 be a small gain when turning off unused link types. The types are:
815
816 bracket The recommended [[link][description]] or [[link]] links with hiding.
817 angular Links in angular brackes that may contain whitespace like
818 <bbdb:Carsten Dominik>.
819 plain Plain links in normal text, no whitespace, like http://google.com.
820 radio Text that is matched by a radio target, see manual for details.
821 tag Tag settings in a headline (link to tag search).
822 date Time stamps (link to calendar).
823 camel CamelCase words defining text searches.
824
825 Changing this variable requires a restart of Emacs to become effective."
826 :group 'org-link
827 :type '(set (const :tag "Double bracket links (new style)" bracket)
828 (const :tag "Angular bracket links (old style)" angular)
829 (const :tag "plain text links" plain)
830 (const :tag "Radio target matches" radio)
831 (const :tag "Tags" tag)
832 (const :tag "Timestamps" date)
833 (const :tag "CamelCase words" camel)))
834
835 (defgroup org-link-store nil
836 "Options concerning storing links in Org-mode"
837 :tag "Org Store Link"
838 :group 'org-link)
839
840 (defcustom org-context-in-file-links t
841 "Non-nil means, file links from `org-store-link' contain context.
842 A search string will be added to the file name with :: as separator and
843 used to find the context when the link is activated by the command
844 `org-open-at-point'.
845 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
846 negates this setting for the duration of the command."
847 :group 'org-link-store
848 :type 'boolean)
849
850 (defcustom org-file-link-context-use-camel-case nil
851 "Non-nil means, use CamelCase to store a search context in a file link.
852 When nil, the search string simply consists of the words of the string.
853 CamelCase is deprecated, and support for it may be dropped in the future."
854 :group 'org-link-store
855 :type 'boolean)
856
857 (defcustom org-keep-stored-link-after-insertion nil
858 "Non-nil means, keep link in list for entire session.
859
860 The command `org-store-link' adds a link pointing to the current
861 location to an internal list. These links accumulate during a session.
862 The command `org-insert-link' can be used to insert links into any
863 Org-mode file (offering completion for all stored links). When this
864 option is nil, every link which has been inserted once using \\[org-insert-link]
865 will be removed from the list, to make completing the unused links
866 more efficient."
867 :group 'org-link-store
868 :type 'boolean)
869
870 (defcustom org-usenet-links-prefer-google nil
871 "Non-nil means, `org-store-link' will create web links to Google groups.
872 When nil, Gnus will be used for such links.
873 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
874 negates this setting for the duration of the command."
875 :group 'org-link-store
876 :type 'boolean)
877
878 (defgroup org-link-follow nil
879 "Options concerning following links in Org-mode"
880 :tag "Org Follow Link"
881 :group 'org-link)
882
883 (defcustom org-tab-follows-link nil
884 "Non-nil means, on links TAB will follow the link.
885 Needs to be set before org.el is loaded."
886 :group 'org-link-follow
887 :type 'boolean)
888
889 (defcustom org-return-follows-link nil
890 "Non-nil means, on links RET will follow the link.
891 Needs to be set before org.el is loaded."
892 :group 'org-link-follow
893 :type 'boolean)
894
895 (defcustom org-mouse-1-follows-link t
896 "Non-nil means, mouse-1 on a link will follow the link.
897 A longer mouse click will still set point. Does not wortk on XEmacs.
898 Needs to be set before org.el is loaded."
899 :group 'org-link-follow
900 :type 'boolean)
901
902 (defcustom org-mark-ring-length 4
903 "Number of different positions to be recorded in the ring
904 Changing this requires a restart of Emacs to work correctly."
905 :group 'org-link-follow
906 :type 'interger)
907
908 (defcustom org-link-frame-setup
909 '((vm . vm-visit-folder-other-frame)
910 (gnus . gnus-other-frame)
911 (file . find-file-other-window))
912 "Setup the frame configuration for following links.
913 When following a link with Emacs, it may often be useful to display
914 this link in another window or frame. This variable can be used to
915 set this up for the different types of links.
916 For VM, use any of
917 `vm-visit-folder'
918 `vm-visit-folder-other-frame'
919 For Gnus, use any of
920 `gnus'
921 `gnus-other-frame'
922 For FILE, use any of
923 `find-file'
924 `find-file-other-window'
925 `find-file-other-frame'
926 For the calendar, use the variable `calendar-setup'.
927 For BBDB, it is currently only possible to display the matches in
928 another window."
929 :group 'org-link-follow
930 :type '(list
931 (cons (const vm)
932 (choice
933 (const vm-visit-folder)
934 (const vm-visit-folder-other-window)
935 (const vm-visit-folder-other-frame)))
936 (cons (const gnus)
937 (choice
938 (const gnus)
939 (const gnus-other-frame)))
940 (cons (const file)
941 (choice
942 (const find-file)
943 (const find-file-other-window)
944 (const find-file-other-frame)))))
945
946 (defcustom org-open-non-existing-files nil
947 "Non-nil means, `org-open-file' will open non-existing file.
948 When nil, an error will be generated."
949 :group 'org-link-follow
950 :type 'boolean)
951
952 (defcustom org-confirm-shell-links 'yes-or-no-p
953 "Non-nil means, ask for confirmation before executing shell links.
954 Shell links can be dangerous, just thing about a link
955
956 [[shell:rm -rf ~/*][Google Search]]
957
958 This link would show up in your Org-mode document as \"Google Search\"
959 but really it would remove your entire home directory. Dangerous indeed.
960 Therefore I *definitely* advise agains setting this varaiable to nil.
961 Just change it to `y-or-n-p' of you want to confirm with a single key press
962 rather than having to type \"yes\"."
963 :group 'org-link-follow
964 :type '(choice
965 (const :tag "with yes-or-no (safer)" yes-or-no-p)
966 (const :tag "with y-or-n (faster)" y-or-n-p)
967 (const :tag "no confirmation (dangerous)" nil)))
968
969 (defconst org-file-apps-defaults-gnu
970 '((t . mailcap))
971 "Default file applications on a UNIX or GNU/Linux system.
972 See `org-file-apps'.")
973
974 (defconst org-file-apps-defaults-macosx
975 '((t . "open %s")
976 ("ps" . "gv %s")
977 ("ps.gz" . "gv %s")
978 ("eps" . "gv %s")
979 ("eps.gz" . "gv %s")
980 ("dvi" . "xdvi %s")
981 ("fig" . "xfig %s"))
982 "Default file applications on a MacOS X system.
983 The system \"open\" is known as a default, but we use X11 applications
984 for some files for which the OS does not have a good default.
985 See `org-file-apps'.")
986
987 (defconst org-file-apps-defaults-windowsnt
988 '((t . (w32-shell-execute "open" file)))
989 "Default file applications on a Windows NT system.
990 The system \"open\" is used for most files.
991 See `org-file-apps'.")
992
993 (defcustom org-file-apps
994 '(
995 ("txt" . emacs)
996 ("tex" . emacs)
997 ("ltx" . emacs)
998 ("org" . emacs)
999 ("el" . emacs)
1000 )
1001 "External applications for opening `file:path' items in a document.
1002 Org-mode uses system defaults for different file types, but
1003 you can use this variable to set the application for a given file
1004 extension. The entries in this list are cons cells with a file extension
1005 and the corresponding command. Possible values for the command are:
1006 `emacs' The file will be visited by the current Emacs process.
1007 `default' Use the default application for this file type.
1008 string A command to be executed by a shell; %s will be replaced
1009 by the path to the file.
1010 sexp A Lisp form which will be evaluated. The file path will
1011 be available in the Lisp variable `file'.
1012 For more examples, see the system specific constants
1013 `org-file-apps-defaults-macosx'
1014 `org-file-apps-defaults-windowsnt'
1015 `org-file-apps-defaults-gnu'."
1016 :group 'org-link-follow
1017 :type '(repeat
1018 (cons (choice :value ""
1019 (string :tag "Extension")
1020 (const :tag "Default for unrecognized files" t)
1021 (const :tag "Links to a directory" directory))
1022 (choice :value ""
1023 (const :tag "Visit with Emacs" emacs)
1024 (const :tag "Use system default" default)
1025 (string :tag "Command")
1026 (sexp :tag "Lisp form")))))
1027
1028 (defcustom org-mhe-search-all-folders nil
1029 "Non-nil means, that the search for the mh-message will be extended to
1030 all folders if the message cannot be found in the folder given in the link.
1031 Searching all folders is very effective with one of the search engines
1032 supported by MH-E, but will be slow with pick."
1033 :group 'org-link-follow
1034 :type 'boolean)
1035
1036 (defgroup org-remember nil
1037 "Options concerning interaction with remember.el."
1038 :tag "Org Remember"
1039 :group 'org)
1040
1041 (defcustom org-directory "~/org"
1042 "Directory with org files.
1043 This directory will be used as default to prompt for org files.
1044 Used by the hooks for remember.el."
1045 :group 'org-remember
1046 :type 'directory)
1047
1048 (defcustom org-default-notes-file "~/.notes"
1049 "Default target for storing notes.
1050 Used by the hooks for remember.el. This can be a string, or nil to mean
1051 the value of `remember-data-file'."
1052 :group 'org-remember
1053 :type '(choice
1054 (const :tag "Default from remember-data-file" nil)
1055 file))
1056
1057 (defcustom org-remember-templates nil
1058 "Templates for the creation of remember buffers.
1059 When nil, just let remember make the buffer.
1060 When not nil, this is a list of 3-element lists. In each entry, the first
1061 element is a character, a unique key to select this template.
1062 The second element is the template. The third element is optional and can
1063 specify a destination file for remember items created with this template.
1064 The default file is given by `org-default-notes-file'.
1065
1066 The template specifies the structure of the remember buffer. It should have
1067 a first line starting with a star, to act as the org-mode headline.
1068 Furthermore, the following %-escapes will be replaced with content:
1069 %t time stamp, date only
1070 %T time stamp with date and time
1071 %u inactive time stamp, date only
1072 %U inactive time stamp with date and time
1073 %n user name
1074 %a annotation, normally the link created with org-store-link
1075 %i initial content, the region when remember is called with C-u.
1076 If %i is indented, the entire inserted text will be indented as well.
1077 %? This will be removed, and the cursor placed at this position."
1078 :group 'org-remember
1079 :type '(repeat :tag "enabled"
1080 (list :value (?a "\n" nil)
1081 (character :tag "Selection Key")
1082 (string :tag "Template")
1083 (file :tag "Destination file (optional)"))))
1084
1085 (defcustom org-reverse-note-order nil
1086 "Non-nil means, store new notes at the beginning of a file or entry.
1087 When nil, new notes will be filed to the end of a file or entry."
1088 :group 'org-remember
1089 :type '(choice
1090 (const :tag "Reverse always" t)
1091 (const :tag "Reverse never" nil)
1092 (repeat :tag "By file name regexp"
1093 (cons regexp boolean))))
1094
1095 (defgroup org-todo nil
1096 "Options concerning TODO items in Org-mode."
1097 :tag "Org TODO"
1098 :group 'org)
1099
1100 (defcustom org-todo-keywords '("TODO" "DONE")
1101 "List of TODO entry keywords.
1102 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1103 considered to mean that the entry is \"done\". All the other mean that
1104 action is required, and will make the entry show up in todo lists, diaries
1105 etc.
1106 The command \\[org-todo] cycles an entry through these states, and an
1107 additional state where no keyword is present. For details about this
1108 cycling, see also the variable `org-todo-interpretation'
1109 Changes become only effective after restarting Emacs."
1110 :group 'org-todo
1111 :group 'org-keywords
1112 :type '(repeat (string :tag "Keyword")))
1113
1114 (defcustom org-todo-interpretation 'sequence
1115 "Controls how TODO keywords are interpreted.
1116 This variable is only relevant if `org-todo-keywords' contains more than two
1117 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1118
1119 When `sequence', \\[org-todo] will always switch to the next state in the
1120 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1121 to state when executed several times in direct succession. Otherwise, it
1122 switches directly to DONE from any state.
1123 See the manual for more information."
1124 :group 'org-todo
1125 :group 'org-keywords
1126 :type '(choice (const sequence)
1127 (const type)))
1128
1129 (defcustom org-after-todo-state-change-hook nil
1130 "Hook which is run after the state of a TODO item was changed.
1131 The new state (a string with a TODO keyword, or nil) is available in the
1132 Lisp variable `state'."
1133 :group 'org-todo
1134 :type 'hook)
1135
1136 (defcustom org-log-done nil
1137 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1138 When the state of an entry is changed from nothing to TODO, remove a previous
1139 closing date."
1140 :group 'org-todo
1141 :type 'boolean)
1142
1143 (defgroup org-priorities nil
1144 "Priorities in Org-mode."
1145 :tag "Org Priorities"
1146 :group 'org-todo)
1147
1148 (defcustom org-default-priority ?B
1149 "The default priority of TODO items.
1150 This is the priority an item get if no explicit priority is given."
1151 :group 'org-priorities
1152 :type 'character)
1153
1154 (defcustom org-lowest-priority ?C
1155 "The lowest priority of TODO items. A character like ?A, ?B etc."
1156 :group 'org-priorities
1157 :type 'character)
1158
1159 (defgroup org-time nil
1160 "Options concerning time stamps and deadlines in Org-mode."
1161 :tag "Org Time"
1162 :group 'org)
1163
1164 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1165 "Formats for `format-time-string' which are used for time stamps.
1166 It is not recommended to change this constant.")
1167
1168 (defcustom org-time-stamp-rounding-minutes 0
1169 "Number of minutes to round time stamps to upon insertion.
1170 When zero, insert the time unmodified. Useful rounding numbers
1171 should be factors of 60, so for example 5, 10, 15.
1172 When this is not zero, you can still force an exact time-stamp by using
1173 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1174 :group 'org-time
1175 :type 'integer)
1176
1177 (defcustom org-deadline-warning-days 30
1178 "No. of days before expiration during which a deadline becomes active.
1179 This variable governs the display in the org file."
1180 :group 'org-time
1181 :type 'number)
1182
1183 (defcustom org-popup-calendar-for-date-prompt t
1184 "Non-nil means, pop up a calendar when prompting for a date.
1185 In the calendar, the date can be selected with mouse-1. However, the
1186 minibuffer will also be active, and you can simply enter the date as well.
1187 When nil, only the minibuffer will be available."
1188 :group 'org-time
1189 :type 'boolean)
1190
1191 (defcustom org-calendar-follow-timestamp-change t
1192 "Non-nil means, make the calendar window follow timestamp changes.
1193 When a timestamp is modified and the calendar window is visible, it will be
1194 moved to the new date."
1195 :group 'org-time
1196 :type 'boolean)
1197
1198 (defgroup org-tags nil
1199 "Options concerning tags in Org-mode."
1200 :tag "Org Tags"
1201 :group 'org)
1202
1203 (defcustom org-tags-column 48
1204 "The column to which tags should be indented in a headline.
1205 If this number is positive, it specifies the column. If it is negative,
1206 it means that the tags should be flushright to that column. For example,
1207 -79 works well for a normal 80 character screen."
1208 :group 'org-tags
1209 :type 'integer)
1210
1211 (defcustom org-auto-align-tags t
1212 "Non-nil means, realign tags after pro/demotion of TODO state change.
1213 These operations change the length of a headline and therefore shift
1214 the tags around. With this options turned on, after each such operation
1215 the tags are again aligned to `org-tags-column'."
1216 :group 'org-tags
1217 :type 'boolean)
1218
1219 (defcustom org-use-tag-inheritance t
1220 "Non-nil means, tags in levels apply also for sublevels.
1221 When nil, only the tags directly given in a specific line apply there.
1222 If you turn off this option, you very likely want to turn on the
1223 companion option `org-tags-match-list-sublevels'."
1224 :group 'org-tags
1225 :type 'boolean)
1226
1227 (defcustom org-tags-match-list-sublevels nil
1228 "Non-nil means list also sublevels of headlines matching tag search.
1229 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1230 the sublevels of a headline matching a tag search often also match
1231 the same search. Listing all of them can create very long lists.
1232 Setting this variable to nil causes subtrees of a match to be skipped.
1233 This option is off by default, because inheritance in on. If you turn
1234 inheritance off, you very likely want to turn this option on.
1235
1236 As a special case, if the tag search is restricted to TODO items, the
1237 value of this variable is ignored and sublevels are always checked, to
1238 make sure all corresponding TODO items find their way into the list."
1239 :group 'org-tags
1240 :type 'boolean)
1241
1242 (defvar org-tags-history nil
1243 "History of minibuffer reads for tags.")
1244 (defvar org-last-tags-completion-table nil
1245 "The last used completion table for tags.")
1246
1247 (defgroup org-agenda nil
1248 "Options concerning agenda display Org-mode."
1249 :tag "Org Agenda"
1250 :group 'org)
1251
1252 (defvar org-category nil
1253 "Variable used by org files to set a category for agenda display.
1254 Such files should use a file variable to set it, for example
1255
1256 -*- mode: org; org-category: \"ELisp\"
1257
1258 or contain a special line
1259
1260 #+CATEGORY: ELisp
1261
1262 If the file does not specify a category, then file's base name
1263 is used instead.")
1264 (make-variable-buffer-local 'org-category)
1265
1266 (defcustom org-agenda-files nil
1267 "The files to be used for agenda display.
1268 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1269 \\[org-remove-file]. You can also use customize to edit the list.
1270
1271 If the value of the variable is not a list but a single file name, then
1272 the list of agenda files is actually stored and maintained in that file, one
1273 agenda file per line."
1274 :group 'org-agenda
1275 :type '(choice
1276 (repeat :tag "List of files" file)
1277 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1278
1279 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1280 "Custom commands for the agenda.
1281 These commands will be offered on the splash screen displayed by the
1282 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1283
1284 key The key (a single char as a string) to be associated with the command.
1285 type The command type, any of the following symbols:
1286 todo Entries with a specific TODO keyword, in all agenda files.
1287 tags Tags match in all agenda files.
1288 todo-tree Sparse tree of specific TODO keyword in *current* file.
1289 tags-tree Sparse tree with all tags matches in *current* file.
1290 occur-tree Occur sparse tree for current file.
1291 match What to search for:
1292 - a single keyword for TODO keyword searches
1293 - a tags match expression for tags searches
1294 - a regular expression for occur searches"
1295 :group 'org-agenda
1296 :type '(repeat
1297 (list (string :tag "Key")
1298 (choice :tag "Type"
1299 (const :tag "Tags search in all agenda files" tags)
1300 (const :tag "TODO keyword search in all agenda files" todo)
1301 (const :tag "Tags sparse tree in current buffer" tags-tree)
1302 (const :tag "TODO keyword tree in current buffer" todo-tree)
1303 (const :tag "Occur tree in current buffer" occur-tree))
1304 (string :tag "Match"))))
1305
1306 (defcustom org-agenda-include-all-todo t
1307 "Non-nil means, the agenda will always contain all TODO entries.
1308 When nil, date-less entries will only be shown if `org-agenda' is called
1309 with a prefix argument.
1310 When non-nil, the TODO entries will be listed at the top of the agenda, before
1311 the entries for specific days."
1312 :group 'org-agenda
1313 :type 'boolean)
1314
1315 (defcustom org-agenda-include-diary nil
1316 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1317 :group 'org-agenda
1318 :type 'boolean)
1319
1320 (defcustom org-calendar-to-agenda-key [?c]
1321 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1322 The command `org-calendar-goto-agenda' will be bound to this key. The
1323 default is the character `c' because then `c' can be used to switch back and
1324 forth between agenda and calendar."
1325 :group 'org-agenda
1326 :type 'sexp)
1327
1328 (defgroup org-agenda-window-setup nil
1329 "Options concerning setting up the Agenda window in Org Mode."
1330 :tag "Org Agenda Window Setup"
1331 :group 'org-agenda)
1332
1333 (defcustom org-agenda-mouse-1-follows-link nil
1334 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1335 A longer mouse click will still set point. Does not wortk on XEmacs.
1336 Needs to be set before org.el is loaded."
1337 :group 'org-agenda-setup
1338 :type 'boolean)
1339
1340 (defcustom org-select-timeline-window t
1341 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1342 When nil, cursor will remain in the current window."
1343 :group 'org-agenda-setup
1344 :type 'boolean)
1345
1346 (defcustom org-select-agenda-window t
1347 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1348 When nil, cursor will remain in the current window."
1349 :group 'org-agenda-setup
1350 :type 'boolean)
1351
1352 (defcustom org-fit-agenda-window t
1353 "Non-nil means, change window size of agenda to fit content."
1354 :group 'org-agenda-setup
1355 :type 'boolean)
1356
1357 (defgroup org-agenda-display nil
1358 "Options concerning what to display initially in Agenda."
1359 :tag "Org Agenda Display"
1360 :group 'org-agenda)
1361
1362 (defcustom org-agenda-show-all-dates t
1363 "Non-nil means, `org-agenda' shows every day in the selected range.
1364 When nil, only the days which actually have entries are shown."
1365 :group 'org-agenda-display
1366 :type 'boolean)
1367
1368 (defcustom org-agenda-start-on-weekday 1
1369 "Non-nil means, start the overview always on the specified weekday.
1370 0 denotes Sunday, 1 denotes Monday etc.
1371 When nil, always start on the current day."
1372 :group 'org-agenda-display
1373 :type '(choice (const :tag "Today" nil)
1374 (number :tag "Weekday No.")))
1375
1376 (defcustom org-agenda-ndays 7
1377 "Number of days to include in overview display.
1378 Should be 1 or 7."
1379 :group 'org-agenda-display
1380 :type 'number)
1381
1382 (defcustom org-agenda-use-time-grid t
1383 "Non-nil means, show a time grid in the agenda schedule.
1384 A time grid is a set of lines for specific times (like every two hours between
1385 8:00 and 20:00). The items scheduled for a day at specific times are
1386 sorted in between these lines.
1387 For details about when the grid will be shown, and what it will look like, see
1388 the variable `org-agenda-time-grid'."
1389 :group 'org-agenda-display
1390 :type 'boolean)
1391
1392 (defcustom org-agenda-time-grid
1393 '((daily today require-timed)
1394 "----------------"
1395 (800 1000 1200 1400 1600 1800 2000))
1396
1397 "The settings for time grid for agenda display.
1398 This is a list of three items. The first item is again a list. It contains
1399 symbols specifying conditions when the grid should be displayed:
1400
1401 daily if the agenda shows a single day
1402 weekly if the agenda shows an entire week
1403 today show grid on current date, independent of daily/weekly display
1404 require-timed show grid only if at least on item has a time specification
1405
1406 The second item is a string which will be places behing the grid time.
1407
1408 The third item is a list of integers, indicating the times that should have
1409 a grid line."
1410 :group 'org-agenda-display
1411 :type
1412 '(list
1413 (set :greedy t :tag "Grid Display Options"
1414 (const :tag "Show grid in single day agenda display" daily)
1415 (const :tag "Show grid in weekly agenda display" weekly)
1416 (const :tag "Always show grid for today" today)
1417 (const :tag "Show grid only if any timed entries are present"
1418 require-timed)
1419 (const :tag "Skip grid times already present in an entry"
1420 remove-match))
1421 (string :tag "Grid String")
1422 (repeat :tag "Grid Times" (integer :tag "Time"))))
1423
1424 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1425 "Sorting structure for the agenda items of a single day.
1426 This is a list of symbols which will be used in sequence to determine
1427 if an entry should be listed before another entry. The following
1428 symbols are recognized:
1429
1430 time-up Put entries with time-of-day indications first, early first
1431 time-down Put entries with time-of-day indications first, late first
1432 category-keep Keep the default order of categories, corresponding to the
1433 sequence in `org-agenda-files'.
1434 category-up Sort alphabetically by category, A-Z.
1435 category-down Sort alphabetically by category, Z-A.
1436 priority-up Sort numerically by priority, high priority last.
1437 priority-down Sort numerically by priority, high priority first.
1438
1439 The different possibilities will be tried in sequence, and testing stops
1440 if one comparison returns a \"not-equal\". For example, the default
1441 '(time-up category-keep priority-down)
1442 means: Pull out all entries having a specified time of day and sort them,
1443 in order to make a time schedule for the current day the first thing in the
1444 agenda listing for the day. Of the entries without a time indication, keep
1445 the grouped in categories, don't sort the categories, but keep them in
1446 the sequence given in `org-agenda-files'. Within each category sort by
1447 priority.
1448
1449 Leaving out `category-keep' would mean that items will be sorted across
1450 categories by priority."
1451 :group 'org-agenda-display
1452 :type '(repeat
1453 (choice
1454 (const time-up)
1455 (const time-down)
1456 (const category-keep)
1457 (const category-up)
1458 (const category-down)
1459 (const priority-up)
1460 (const priority-down))))
1461
1462 (defcustom org-sort-agenda-notime-is-late t
1463 "Non-nil means, items without time are considered late.
1464 This is only relevant for sorting. When t, items which have no explicit
1465 time like 15:30 will be considered as 24:01, i.e. later than any items which
1466 do have a time. When nil, the default time is before 0:00. You can use this
1467 option to decide if the schedule for today should come before or after timeless
1468 agenda entries."
1469 :group 'org-agenda-display
1470 :type 'boolean)
1471
1472
1473 (defgroup org-agenda-prefix nil
1474 "Options concerning the entry prefix in the Org-mode agenda display."
1475 :tag "Org Agenda Prefix"
1476 :group 'org-agenda)
1477
1478 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1479 "Format specification for the prefix of items in the agenda buffer.
1480 This format works similar to a printf format, with the following meaning:
1481
1482 %c the category of the item, \"Diary\" for entries from the diary, or
1483 as given by the CATEGORY keyword or derived from the file name.
1484 %T the first tag of the item.
1485 %t the time-of-day specification if one applies to the entry, in the
1486 format HH:MM
1487 %s Scheduling/Deadline information, a short string
1488
1489 All specifiers work basically like the standard `%s' of printf, but may
1490 contain two additional characters: A question mark just after the `%' and
1491 a whitespace/punctuation character just before the final letter.
1492
1493 If the first character after `%' is a question mark, the entire field
1494 will only be included if the corresponding value applies to the
1495 current entry. This is useful for fields which should have fixed
1496 width when present, but zero width when absent. For example,
1497 \"%?-12t\" will result in a 12 character time field if a time of the
1498 day is specified, but will completely disappear in entries which do
1499 not contain a time.
1500
1501 If there is punctuation or whitespace character just before the final
1502 format letter, this character will be appended to the field value if
1503 the value is not empty. For example, the format \"%-12:c\" leads to
1504 \"Diary: \" if the category is \"Diary\". If the category were be
1505 empty, no additional colon would be interted.
1506
1507 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1508 - Indent the line with two space characters
1509 - Give the category in a 12 chars wide field, padded with whitespace on
1510 the right (because of `-'). Append a colon if there is a category
1511 (because of `:').
1512 - If there is a time-of-day, put it into a 12 chars wide field. If no
1513 time, don't put in an empty field, just skip it (because of '?').
1514 - Finally, put the scheduling information and append a whitespace.
1515
1516 As another example, if you don't want the time-of-day of entries in
1517 the prefix, you could use:
1518
1519 (setq org-agenda-prefix-format \" %-11:c% s\")
1520
1521 See also the variables `org-agenda-remove-times-when-in-prefix' and
1522 `org-agenda-remove-tags-when-in-prefix'."
1523 :type 'string
1524 :group 'org-agenda-prefix)
1525
1526 (defcustom org-timeline-prefix-format " % s"
1527 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1528 :type 'string
1529 :group 'org-agenda-prefix)
1530
1531 (defvar org-prefix-format-compiled nil
1532 "The compiled version of the most recently used prefix format.
1533 Depending on which command was used last, this may be the compiled version
1534 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1535
1536 ;; FIXME: There seem to be situations where this does no work.
1537 (defcustom org-agenda-remove-times-when-in-prefix t
1538 "Non-nil means, remove duplicate time specifications in agenda items.
1539 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1540 time-of-day specification in a headline or diary entry is extracted and
1541 placed into the prefix. If this option is non-nil, the original specification
1542 \(a timestamp or -range, or just a plain time(range) specification like
1543 11:30-4pm) will be removed for agenda display. This makes the agenda less
1544 cluttered.
1545 The option can be t or nil. It may also be the symbol `beg', indicating
1546 that the time should only be removed what it is located at the beginning of
1547 the headline/diary entry."
1548 :group 'org-agenda-prefix
1549 :type '(choice
1550 (const :tag "Always" t)
1551 (const :tag "Never" nil)
1552 (const :tag "When at beginning of entry" beg)))
1553
1554 (defcustom org-agenda-remove-tags-when-in-prefix nil
1555 "Non-nil means, remove the tags from the headline copy in the agenda.
1556 When this is the symbol `prefix', only remove tags when
1557 `org-agenda-prefix-format' contains a `%T' specifier."
1558 :group 'org-agenda-prefix
1559 :type '(choice
1560 (const :tag "Always" t)
1561 (const :tag "Never" nil)
1562 (const :tag "When prefix format contains %T" prefix)))
1563
1564 (defgroup org-export nil
1565 "Options for exporting org-listings."
1566 :tag "Org Export"
1567 :group 'org)
1568
1569 (defgroup org-export-general nil
1570 "General options for exporting Org-mode files."
1571 :tag "Org Export General"
1572 :group 'org-export)
1573
1574 (defcustom org-export-language-setup
1575 '(("en" "Author" "Date" "Table of Contents")
1576 ("da" "Ophavsmand" "Dato" "Indhold")
1577 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1578 ("es" "Autor" "Fecha" "\xccndice")
1579 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1580 ("it" "Autore" "Data" "Indice")
1581 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1582 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1583 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1584 "Terms used in export text, translated to different languages.
1585 Use the variable `org-export-default-language' to set the language,
1586 or use the +OPTION lines for a per-file setting."
1587 :group 'org-export-general
1588 :type '(repeat
1589 (list
1590 (string :tag "HTML language tag")
1591 (string :tag "Author")
1592 (string :tag "Date")
1593 (string :tag "Table of Contents"))))
1594
1595 (defcustom org-export-default-language "en"
1596 "The default language of HTML export, as a string.
1597 This should have an association in `org-export-language-setup'."
1598 :group 'org-export-general
1599 :type 'string)
1600
1601 (defcustom org-export-headline-levels 3
1602 "The last level which is still exported as a headline.
1603 Inferior levels will produce itemize lists when exported.
1604 Note that a numeric prefix argument to an exporter function overrides
1605 this setting.
1606
1607 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1608 :group 'org-export-general
1609 :type 'number)
1610
1611 (defcustom org-export-with-section-numbers t
1612 "Non-nil means, add section numbers to headlines when exporting.
1613
1614 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1615 :group 'org-export-general
1616 :type 'boolean)
1617
1618 (defcustom org-export-with-toc t
1619 "Non-nil means, create a table of contents in exported files.
1620 The TOC contains headlines with levels up to`org-export-headline-levels'.
1621
1622 Headlines which contain any TODO items will be marked with \"(*)\" in
1623 ASCII export, and with red color in HTML output.
1624
1625 In HTML output, the TOC will be clickable.
1626
1627 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1628 :group 'org-export-general
1629 :type 'boolean)
1630
1631 (defcustom org-export-mark-todo-in-toc nil
1632 "Non-nil means, mark TOC lines that contain any open TODO items."
1633 :group 'org-export-general
1634 :type 'boolean)
1635
1636 (defcustom org-export-preserve-breaks nil
1637 "Non-nil means, preserve all line breaks when exporting.
1638 Normally, in HTML output paragraphs will be reformatted. In ASCII
1639 export, line breaks will always be preserved, regardless of this variable.
1640
1641 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1642 :group 'org-export-general
1643 :type 'boolean)
1644
1645 (defgroup org-export-translation nil
1646 "Options for translating special ascii sequences for the export backends."
1647 :tag "Org Export Translation"
1648 :group 'org-export)
1649
1650 (defcustom org-export-with-emphasize t
1651 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1652 If the export target supports emphasizing text, the word will be
1653 typeset in bold, italic, or underlined, respectively. Works only for
1654 single words, but you can say: I *really* *mean* *this*.
1655 Not all export backends support this.
1656
1657 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1658 :group 'org-export-translation
1659 :type 'boolean)
1660
1661 (defcustom org-export-with-sub-superscripts t
1662 "Non-nil means, interpret \"_\" and \"^\" for export.
1663 When this option is turned on, you can use TeX-like syntax for sub- and
1664 superscripts. Several characters after \"_\" or \"^\" will be
1665 considered as a single item - so grouping with {} is normally not
1666 needed. For example, the following things will be parsed as single
1667 sub- or superscripts.
1668
1669 10^24 or 10^tau several digits will be considered 1 item.
1670 10^-12 or 10^-tau a leading sign with digits or a word
1671 x^2-y^3 will be read as x^2 - y^3, because items are
1672 terminated by almost any nonword/nondigit char.
1673 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1674
1675 Still, ambiguity is possible - so when in doubt use {} to enclose the
1676 sub/superscript.
1677 Not all export backends support this, but HTML does.
1678
1679 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1680 :group 'org-export-translation
1681 :type 'boolean)
1682
1683 (defcustom org-export-with-TeX-macros t
1684 "Non-nil means, interpret simple TeX-like macros when exporting.
1685 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1686 No only real TeX macros will work here, but the standard HTML entities
1687 for math can be used as macro names as well. For a list of supported
1688 names in HTML export, see the constant `org-html-entities'.
1689 Not all export backends support this.
1690
1691 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1692 :group 'org-export-translation
1693 :type 'boolean)
1694
1695 (defcustom org-export-with-fixed-width t
1696 "Non-nil means, lines starting with \":\" will be in fixed width font.
1697 This can be used to have pre-formatted text, fragments of code etc. For
1698 example:
1699 : ;; Some Lisp examples
1700 : (while (defc cnt)
1701 : (ding))
1702 will be looking just like this in also HTML. See also the QUOTE keyword.
1703 Not all export backends support this.
1704
1705 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1706 :group 'org-export-translation
1707 :type 'boolean)
1708
1709 (defcustom org-match-sexp-depth 3
1710 "Number of stacked braces for sub/superscript matching.
1711 This has to be set before loading org.el to be effective."
1712 :group 'org-export-translation
1713 :type 'integer)
1714
1715 (defgroup org-export-tables nil
1716 "Options for exporting tables in Org-mode."
1717 :tag "Org Export Tables"
1718 :group 'org-export)
1719
1720 (defcustom org-export-with-tables t
1721 "If non-nil, lines starting with \"|\" define a table.
1722 For example:
1723
1724 | Name | Address | Birthday |
1725 |-------------+----------+-----------|
1726 | Arthur Dent | England | 29.2.2100 |
1727
1728 Not all export backends support this.
1729
1730 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1731 :group 'org-export-tables
1732 :type 'boolean)
1733
1734 (defcustom org-export-highlight-first-table-line t
1735 "Non-nil means, highlight the first table line.
1736 In HTML export, this means use <th> instead of <td>.
1737 In tables created with table.el, this applies to the first table line.
1738 In Org-mode tables, all lines before the first horizontal separator
1739 line will be formatted with <th> tags."
1740 :group 'org-export-tables
1741 :type 'boolean)
1742
1743 (defcustom org-export-table-remove-special-lines t
1744 "Remove special lines and marking characters in calculating tables.
1745 This removes the special marking character column from tables that are set
1746 up for spreadsheet calculations. It also removes the entire lines
1747 marked with `!', `_', or `^'. The lines with `$' are kept, because
1748 the values of constants may be useful to have."
1749 :group 'org-export-tables
1750 :type 'boolean)
1751
1752 (defcustom org-export-prefer-native-exporter-for-tables nil
1753 "Non-nil means, always export tables created with table.el natively.
1754 Natively means, use the HTML code generator in table.el.
1755 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1756 the table does not use row- or column-spanning). This has the
1757 advantage, that the automatic HTML conversions for math symbols and
1758 sub/superscripts can be applied. Org-mode's HTML generator is also
1759 much faster."
1760 :group 'org-export-tables
1761 :type 'boolean)
1762
1763 (defgroup org-export-ascii nil
1764 "Options specific for ASCII export of Org-mode files."
1765 :tag "Org Export ASCII"
1766 :group 'org-export)
1767
1768 (defcustom org-export-ascii-show-new-buffer t
1769 "Non-nil means, popup buffer containing the exported ASCII text.
1770 Otherwise the buffer will just be saved to a file and stay hidden."
1771 :group 'org-export-ascii
1772 :type 'boolean)
1773
1774 (defgroup org-export-xml nil
1775 "Options specific for XML export of Org-mode files."
1776 :tag "Org Export XML"
1777 :group 'org-export)
1778
1779 (defcustom org-export-xml-type 'xoxo ;kw, if we have only one.
1780 "The kind of XML to be produced by the XML exporter.
1781 Allowed values are:
1782 xoxo The XOXO exporter."
1783 :group 'org-export-xml
1784 :type '(choice
1785 (const :tag "XOXO" xoxo)))
1786
1787 (defgroup org-export-html nil
1788 "Options specific for HTML export of Org-mode files."
1789 :tag "Org Export HTML"
1790 :group 'org-export)
1791
1792 (defcustom org-export-html-style
1793 "<style type=\"text/css\">
1794 html {
1795 font-family: Times, serif;
1796 font-size: 12pt;
1797 }
1798 .title { text-align: center; }
1799 .todo, .deadline { color: red; }
1800 .done { color: green; }
1801 .target { background-color: lavender; }
1802 pre {
1803 border: 1pt solid #AEBDCC;
1804 background-color: #F3F5F7;
1805 padding: 5pt;
1806 font-family: courier, monospace;
1807 }
1808 table { border-collapse: collapse; }
1809 td, th {
1810 vertical-align: top;
1811 border: 1pt solid #ADB9CC;
1812 }
1813 </style>"
1814 "The default style specification for exported HTML files.
1815 Since there are different ways of setting style information, this variable
1816 needs to contain the full HTML structure to provide a style, including the
1817 surrounding HTML tags. The style specifications should include definitions
1818 for new classes todo, done, title, and deadline. For example, legal values
1819 would be:
1820
1821 <style type=\"text/css\">
1822 p { font-weight: normal; color: gray; }
1823 h1 { color: black; }
1824 .title { text-align: center; }
1825 .todo, .deadline { color: red; }
1826 .done { color: green; }
1827 </style>
1828
1829 or, if you want to keep the style in a file,
1830
1831 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1832
1833 As the value of this option simply gets inserted into the HTML <head> header,
1834 you can \"misuse\" it to add arbitrary text to the header."
1835 :group 'org-export-html
1836 :type 'string)
1837
1838 (defcustom org-export-html-link-org-files-as-html t
1839 "Non-nil means, make file links to `file.org' point to `file.html'.
1840 When org-mode is exporting an org-mode file to HTML, links to
1841 non-html files are directly put into a href tag in HTML.
1842 However, links to other Org-mode files (recognized by the
1843 extension `.org.) should become links to the corresponding html
1844 file, assuming that the linked org-mode file will also be
1845 converted to HTML.
1846 When nil, the links still point to the plain `.org' file."
1847 :group 'org-export-html
1848 :type 'boolean)
1849
1850 (defcustom org-export-html-inline-images t
1851 "Non-nil means, inline images into exported HTML pages.
1852 The link will still be to the original location of the image file.
1853 So if you are moving the page, lets say to your public HTML site,
1854 you will have to move the image and maybe change the link."
1855 :group 'org-export-html
1856 :type 'boolean)
1857
1858 (defcustom org-export-html-expand t
1859 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1860 When nil, these tags will be exported as plain text and therefore
1861 not be interpreted by a browser.
1862
1863 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1864 :group 'org-export-html
1865 :type 'boolean)
1866
1867 (defcustom org-export-html-table-tag
1868 "<table border=1 cellspacing=0 cellpadding=6>"
1869 "The HTML tag used to start a table.
1870 This must be a <table> tag, but you may change the options like
1871 borders and spacing."
1872 :group 'org-export-html
1873 :type 'string)
1874
1875 (defcustom org-export-html-with-timestamp nil
1876 "If non-nil, write `org-export-html-html-helper-timestamp'
1877 into the exported HTML text. Otherwise, the buffer will just be saved
1878 to a file."
1879 :group 'org-export-html
1880 :type 'boolean)
1881
1882 (defcustom org-export-html-html-helper-timestamp
1883 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1884 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1885 :group 'org-export-html
1886 :type 'string)
1887
1888 (defcustom org-export-html-show-new-buffer nil
1889 "Non-nil means, popup buffer containing the exported html text.
1890 Otherwise, the buffer will just be saved to a file and stay hidden."
1891 :group 'org-export-html
1892 :type 'boolean)
1893
1894 (defgroup org-export-icalendar nil
1895 "Options specific for iCalendar export of Org-mode files."
1896 :tag "Org Export iCalendar"
1897 :group 'org-export)
1898
1899 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1900 "The file name for the iCalendar file covering all agenda files.
1901 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1902 :group 'org-export-icalendar
1903 :type 'file)
1904
1905 (defcustom org-icalendar-include-todo nil
1906 "Non-nil means, export to iCalendar files should also cover TODO items."
1907 :group 'org-export-icalendar
1908 :type 'boolean)
1909
1910 (defcustom org-icalendar-combined-name "OrgMode"
1911 "Calendar name for the combined iCalendar representing all agenda files."
1912 :group 'org-export-icalendar
1913 :type 'string)
1914
1915 (defgroup org-font-lock nil
1916 "Font-lock settings for highlighting in Org-mode."
1917 :tag "Org Font Lock"
1918 :group 'org)
1919
1920 (defcustom org-level-color-stars-only nil
1921 "Non-nil means fontify only the stars in each headline.
1922 When nil, the entire headline is fontified.
1923 Changing it requires restart of `font-lock-mode' to become effective
1924 also in regions already fontified."
1925 :group 'org-font-lock
1926 :type 'boolean)
1927
1928 (defcustom org-hide-leading-stars nil
1929 "Non-nil means, hide the first N-1 stars in a headline.
1930 This works by using the face `org-hide' for these stars. This
1931 face is white for a light background, and black for a dark
1932 background. You may have to customize the face `org-hide' to
1933 make this work.
1934 Changing it requires restart of `font-lock-mode' to become effective
1935 also in regions already fontified.
1936 You may also set this on a per-file basis by adding one of the following
1937 lines to the buffer:
1938
1939 #+STARTUP: hidestars
1940 #+STARTUP: showstars"
1941 :group 'org-font-lock
1942 :type 'boolean)
1943
1944 (defcustom org-fontify-done-headline nil
1945 "Non-nil means, change the face of a headline if it is marked DONE.
1946 Normally, only the TODO/DONE keyword indicates the state of a headline.
1947 When this is non-nil, the headline after the keyword is set to the
1948 `org-headline-done' as an additional indication."
1949 :group 'org-font-lock
1950 :type 'boolean)
1951
1952 (defcustom org-fontify-emphasized-text t
1953 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
1954 Changing this variable requires a restart of Emacs to take effect."
1955 :group 'org-font-lock
1956 :type 'boolean)
1957
1958 (defgroup org-faces nil
1959 "Faces in Org-mode."
1960 :tag "Org Faces"
1961 :group 'org-font-lock)
1962
1963 (defun org-compatible-face (specs)
1964 "Make a compatible face specification.
1965 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
1966 For them we convert a (min-colors 8) entry to a `tty' entry and move it
1967 to the top of the list. The `min-colors' attribute will be removed from
1968 any other entries, and any resulting duplicates will be removed entirely."
1969 (if (or (featurep 'xemacs) (< emacs-major-version 22))
1970 (let (r e a)
1971 (while (setq e (pop specs))
1972 (cond
1973 ((memq (car e) '(t default)) (push e r))
1974 ((setq a (member '(min-colors 8) (car e)))
1975 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
1976 (cdr e)))))
1977 ((setq a (assq 'min-colors (car e)))
1978 (setq e (cons (delq a (car e)) (cdr e)))
1979 (or (assoc (car e) r) (push e r)))
1980 (t (or (assoc (car e) r) (push e r)))))
1981 (nreverse r))
1982 specs))
1983
1984 (defface org-hide
1985 '((((background light)) (:foreground "white"))
1986 (((background dark)) (:foreground "black")))
1987 "Face used to hide leading stars in headlines.
1988 The forground color of this face should be equal to the background
1989 color of the frame."
1990 :group 'org-faces)
1991
1992 (defface org-level-1 ;; font-lock-function-name-face
1993 (org-compatible-face
1994 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
1995 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
1996 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
1997 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
1998 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
1999 (t (:bold t))))
2000 "Face used for level 1 headlines."
2001 :group 'org-faces)
2002
2003 (defface org-level-2 ;; font-lock-variable-name-face
2004 (org-compatible-face
2005 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2006 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2007 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2008 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2009 (t (:bold t))))
2010 "Face used for level 2 headlines."
2011 :group 'org-faces)
2012
2013 (defface org-level-3 ;; font-lock-keyword-face
2014 (org-compatible-face
2015 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2016 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2017 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2018 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2019 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2020 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2021 (t (:bold t))))
2022 "Face used for level 3 headlines."
2023 :group 'org-faces)
2024
2025 (defface org-level-4 ;; font-lock-comment-face
2026 (org-compatible-face
2027 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2028 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2029 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2030 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2031 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2032 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2033 (t (:bold t))))
2034 "Face used for level 4 headlines."
2035 :group 'org-faces)
2036
2037 (defface org-level-5 ;; font-lock-type-face
2038 (org-compatible-face
2039 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2040 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2041 (((class color) (min-colors 8)) (:foreground "green"))))
2042 "Face used for level 5 headlines."
2043 :group 'org-faces)
2044
2045 (defface org-level-6 ;; font-lock-constant-face
2046 (org-compatible-face
2047 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2048 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2049 (((class color) (min-colors 8)) (:foreground "magenta"))))
2050 "Face used for level 6 headlines."
2051 :group 'org-faces)
2052
2053 (defface org-level-7 ;; font-lock-builtin-face
2054 (org-compatible-face
2055 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2056 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2057 (((class color) (min-colors 8)) (:foreground "blue")))) ;; FIXME: for dark bg?
2058 "Face used for level 7 headlines."
2059 :group 'org-faces)
2060
2061 (defface org-level-8 ;; font-lock-string-face
2062 (org-compatible-face
2063 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2064 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2065 (((class color) (min-colors 8)) (:foreground "green"))))
2066 "Face used for level 8 headlines."
2067 :group 'org-faces)
2068
2069 (defface org-special-keyword ;; font-lock-string-face
2070 (org-compatible-face
2071 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2072 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2073 (t (:italic t))))
2074 "Face used for special keywords."
2075 :group 'org-faces)
2076
2077 (defface org-warning ;; font-lock-warning-face
2078 (org-compatible-face
2079 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2080 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2081 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2082 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2083 (t (:bold t))))
2084 "Face for deadlines and TODO keywords."
2085 :group 'org-faces)
2086
2087 (defface org-headline-done ;; font-lock-string-face
2088 (org-compatible-face
2089 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2090 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2091 (((class color) (min-colors 8) (background light)) (:bold nil))))
2092 "Face used to indicate that a headline is DONE.
2093 This face is only used if `org-fontify-done-headline' is set."
2094 :group 'org-faces)
2095
2096 (defface org-link
2097 '((((class color) (background light)) (:foreground "Purple" :underline t))
2098 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2099 (t (:underline t)))
2100 "Face for links."
2101 :group 'org-faces)
2102
2103 (defface org-date
2104 '((((class color) (background light)) (:foreground "Purple" :underline t))
2105 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2106 (t (:underline t)))
2107 "Face for links."
2108 :group 'org-faces)
2109
2110 (defface org-tag
2111 '((t (:bold t)))
2112 "Face for tags."
2113 :group 'org-faces)
2114
2115 (defface org-todo ;; font-lock-warning-face
2116 (org-compatible-face
2117 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2118 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2119 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2120 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2121 (t (:inverse-video t :bold t))))
2122 "Face for TODO keywords."
2123 :group 'org-faces)
2124
2125 (defface org-done ;; font-lock-type-face
2126 (org-compatible-face
2127 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2128 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2129 (((class color) (min-colors 8)) (:foreground "green"))
2130 (t (:bold t))))
2131 "Face used for DONE."
2132 :group 'org-faces)
2133
2134 (defface org-table ;; font-lock-function-name-face
2135 (org-compatible-face
2136 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2137 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2138 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2139 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2140 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2141 (((class color) (min-colors 8) (background dark)))))
2142 "Face used for tables."
2143 :group 'org-faces)
2144
2145 (defface org-formula
2146 (org-compatible-face
2147 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2148 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2149 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2150 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2151 (t (:bold t :italic t))))
2152 "Face for formulas."
2153 :group 'org-faces)
2154
2155 (defface org-scheduled-today
2156 (org-compatible-face
2157 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2158 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2159 (((class color) (min-colors 8)) (:foreground "green"))
2160 (t (:bold t :italic t))))
2161 "Face for items scheduled for a certain day."
2162 :group 'org-faces)
2163
2164 (defface org-scheduled-previously
2165 (org-compatible-face
2166 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2167 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2168 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2169 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2170 (t (:bold t))))
2171 "Face for items scheduled previously, and not yet done."
2172 :group 'org-faces)
2173
2174 (defface org-time-grid ;; font-lock-variable-name-face
2175 (org-compatible-face
2176 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2177 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2178 (((class color) (min-colors 8)) (:foreground "yellow" :weight light)))) ; FIXME: turn off???
2179 "Face used for time grids."
2180 :group 'org-faces)
2181
2182 (defconst org-level-faces
2183 '(org-level-1 org-level-2 org-level-3 org-level-4
2184 org-level-5 org-level-6 org-level-7 org-level-8
2185 ))
2186 (defconst org-n-levels (length org-level-faces))
2187
2188 (defconst org-bold-re
2189 (if (featurep 'xemacs)
2190 "\\([ ]\\|^\\)\\(\\*\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)\\*\\)\\([ ,.]\\|$\\)"
2191 "\\([ ]\\|^\\)\\(\\*\\(\\w[[:word:] -_]*?\\w\\)\\*\\)\\([ ,.]\\|$\\)")
2192 "Regular expression for bold emphasis.")
2193 (defconst org-italic-re
2194 (if (featurep 'xemacs)
2195 "\\([ ]\\|^\\)\\(/\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)/\\)\\([ ,.]\\|$\\)"
2196 "\\([ ]\\|^\\)\\(/\\(\\w[[:word:] -_]*?\\w\\)/\\)\\([ ,.]\\|$\\)")
2197 "Regular expression for italic emphasis.")
2198 (defconst org-underline-re
2199 (if (featurep 'xemacs)
2200 "\\([ ]\\|^\\)\\(_\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)_\\)\\([ ,.]\\|$\\)"
2201 "\\([ ]\\|^\\)\\(_\\(\\w[[:word:] -_]*?\\w\\)_\\)\\([ ,.]\\|$\\)")
2202 "Regular expression for underline emphasis.")
2203
2204 ;; Variables for pre-computed regular expressions, all buffer local
2205 (defvar org-done-string nil
2206 "The last string in `org-todo-keywords', indicating an item is DONE.")
2207 (make-variable-buffer-local 'org-done-string)
2208 (defvar org-todo-regexp nil
2209 "Matches any of the TODO state keywords.")
2210 (make-variable-buffer-local 'org-todo-regexp)
2211 (defvar org-not-done-regexp nil
2212 "Matches any of the TODO state keywords except the last one.")
2213 (make-variable-buffer-local 'org-not-done-regexp)
2214 (defvar org-todo-line-regexp nil
2215 "Matches a headline and puts TODO state into group 2 if present.")
2216 (make-variable-buffer-local 'org-todo-line-regexp)
2217 (defvar org-nl-done-regexp nil
2218 "Matches newline followed by a headline with the DONE keyword.")
2219 (make-variable-buffer-local 'org-nl-done-regexp)
2220 (defvar org-looking-at-done-regexp nil
2221 "Matches the DONE keyword a point.")
2222 (make-variable-buffer-local 'org-looking-at-done-regexp)
2223 (defvar org-todo-kwd-priority-p nil
2224 "Do TODO items have priorities?")
2225 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2226 (defvar org-todo-kwd-max-priority nil
2227 "Maximum priority of TODO items.")
2228 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2229 (defvar org-ds-keyword-length 12
2230 "Maximum length of the Deadline and SCHEDULED keywords.")
2231 (make-variable-buffer-local 'org-ds-keyword-length)
2232 (defvar org-deadline-regexp nil
2233 "Matches the DEADLINE keyword.")
2234 (make-variable-buffer-local 'org-deadline-regexp)
2235 (defvar org-deadline-time-regexp nil
2236 "Matches the DEADLINE keyword together with a time stamp.")
2237 (make-variable-buffer-local 'org-deadline-time-regexp)
2238 (defvar org-deadline-line-regexp nil
2239 "Matches the DEADLINE keyword and the rest of the line.")
2240 (make-variable-buffer-local 'org-deadline-line-regexp)
2241 (defvar org-scheduled-regexp nil
2242 "Matches the SCHEDULED keyword.")
2243 (make-variable-buffer-local 'org-scheduled-regexp)
2244 (defvar org-scheduled-time-regexp nil
2245 "Matches the SCHEDULED keyword together with a time stamp.")
2246 (make-variable-buffer-local 'org-scheduled-time-regexp)
2247
2248 (defun org-set-regexps-and-options ()
2249 "Precompute regular expressions for current buffer."
2250 (when (eq major-mode 'org-mode)
2251 (let ((re (org-make-options-regexp
2252 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2253 "STARTUP" "ARCHIVE")))
2254 (splitre "[ \t]+")
2255 kwds int key value cat arch)
2256 (save-excursion
2257 (save-restriction
2258 (widen)
2259 (goto-char (point-min))
2260 (while (re-search-forward re nil t)
2261 (setq key (match-string 1) value (match-string 2))
2262 (cond
2263 ((equal key "CATEGORY")
2264 (if (string-match "[ \t]+$" value)
2265 (setq value (replace-match "" t t value)))
2266 (setq cat (intern value)))
2267 ((equal key "SEQ_TODO")
2268 (setq int 'sequence
2269 kwds (append kwds (org-split-string value splitre))))
2270 ((equal key "PRI_TODO")
2271 (setq int 'priority
2272 kwds (append kwds (org-split-string value splitre))))
2273 ((equal key "TYP_TODO")
2274 (setq int 'type
2275 kwds (append kwds (org-split-string value splitre))))
2276 ((equal key "STARTUP")
2277 (let ((opts (org-split-string value splitre))
2278 (set '(("fold" org-startup-folded t)
2279 ("overview" org-startup-folded t)
2280 ("nofold" org-startup-folded nil)
2281 ("showall" org-startup-folded nil)
2282 ("content" org-startup-folded content)
2283 ("hidestars" org-hide-leading-stars t)
2284 ("showstars" org-hide-leading-stars nil)
2285 ("odd" org-odd-levels-only t)
2286 ("oddeven" org-odd-levels-only nil)
2287 ("align" org-startup-align-all-tables t)
2288 ("noalign" org-startup-align-all-tables nil)
2289 ("dlcheck" org-startup-with-deadline-check t)
2290 ("nodlcheck" org-startup-with-deadline-check nil)))
2291 l var val)
2292 (while (setq l (assoc (pop opts) set))
2293 (setq var (nth 1 l) val (nth 2 l))
2294 (set (make-local-variable var) val))))
2295 ((equal key "ARCHIVE")
2296 (string-match " *$" value)
2297 (setq arch (replace-match "" t t value))
2298 (remove-text-properties 0 (length arch)
2299 '(face t fontified t) arch)))
2300 )))
2301 (and cat (set (make-local-variable 'org-category) cat))
2302 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2303 (and arch (set (make-local-variable 'org-archive-location) arch))
2304 (and int (set (make-local-variable 'org-todo-interpretation) int)))
2305 ;; Compute the regular expressions and other local variables
2306 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2307 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2308 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2309 (length org-scheduled-string)))
2310 org-done-string
2311 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2312 org-todo-regexp
2313 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2314 "\\|") "\\)\\>")
2315 org-not-done-regexp
2316 (concat "\\<\\("
2317 (mapconcat 'regexp-quote
2318 (nreverse (cdr (reverse org-todo-keywords)))
2319 "\\|")
2320 "\\)\\>")
2321 org-todo-line-regexp
2322 (concat "^\\(\\*+\\)[ \t]*\\("
2323 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2324 "\\)? *\\(.*\\)")
2325 org-nl-done-regexp
2326 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2327 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2328 org-deadline-regexp (concat "\\<" org-deadline-string)
2329 org-deadline-time-regexp
2330 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2331 org-deadline-line-regexp
2332 (concat "\\<\\(" org-deadline-string "\\).*")
2333 org-scheduled-regexp
2334 (concat "\\<" org-scheduled-string)
2335 org-scheduled-time-regexp
2336 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
2337 (org-set-font-lock-defaults)))
2338
2339 ;; Tell the compiler about dynamically scoped variables,
2340 ;; and variables from other packages
2341 (defvar zmacs-regions) ; XEmacs regions
2342 (defvar original-date) ; dynamically scoped in calendar
2343 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2344 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2345 (defvar org-html-entities) ; defined later in this file
2346 (defvar org-goto-start-pos) ; dynamically scoped parameter
2347 (defvar org-time-was-given) ; dynamically scoped parameter
2348 (defvar org-ts-what) ; dynamically scoped parameter
2349 (defvar mark-active) ; Emacs only, not available in XEmacs.
2350 (defvar timecnt) ; dynamically scoped parameter
2351 (defvar levels-open) ; dynamically scoped parameter
2352 (defvar title) ; dynamically scoped parameter
2353 (defvar author) ; dynamically scoped parameter
2354 (defvar email) ; dynamically scoped parameter
2355 (defvar text) ; dynamically scoped parameter
2356 (defvar entry) ; dynamically scoped parameter
2357 (defvar date) ; dynamically scoped parameter
2358 (defvar language) ; dynamically scoped parameter
2359 (defvar options) ; dynamically scoped parameter
2360 (defvar ans1) ; dynamically scoped parameter
2361 (defvar ans2) ; dynamically scoped parameter
2362 (defvar starting-day) ; local variable
2363 (defvar include-all-loc) ; local variable
2364 (defvar vm-message-pointer) ; from vm
2365 (defvar vm-folder-directory) ; from vm
2366 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2367 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2368 (defvar gnus-group-name) ; from gnus
2369 (defvar gnus-article-current) ; from gnus
2370 (defvar w3m-current-url) ; from w3m
2371 (defvar mh-progs) ; from MH-E
2372 (defvar mh-current-folder) ; from MH-E
2373 (defvar mh-show-folder-buffer) ; from MH-E
2374 (defvar mh-index-folder) ; from MH-E
2375 (defvar mh-searcher) ; from MH-E
2376 (defvar org-selected-point) ; dynamically scoped parameter
2377 (defvar calendar-mode-map) ; from calendar.el
2378 (defvar last-arg) ; local variable
2379 (defvar remember-save-after-remembering) ; from remember.el
2380 (defvar remember-data-file) ; from remember.el
2381 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2382 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2383 (defvar orgtbl-mode) ; defined later in this file
2384 ;;; Define the mode
2385
2386 (defvar org-mode-map (copy-keymap outline-mode-map)
2387 "Keymap for Org-mode.")
2388
2389 (defvar org-struct-menu) ; defined later in this file
2390 (defvar org-org-menu) ; defined later in this file
2391 (defvar org-tbl-menu) ; defined later in this file
2392
2393 ;; We use a before-change function to check if a table might need
2394 ;; an update.
2395 (defvar org-table-may-need-update t
2396 "Indicates that a table might need an update.
2397 This variable is set by `org-before-change-function'.
2398 `org-table-align' sets it back to nil.")
2399 (defvar org-mode-hook nil)
2400 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2401 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2402
2403
2404 ;;;###autoload
2405 (define-derived-mode org-mode outline-mode "Org"
2406 "Outline-based notes management and organizer, alias
2407 \"Carsten's outline-mode for keeping track of everything.\"
2408
2409 Org-mode develops organizational tasks around a NOTES file which
2410 contains information about projects as plain text. Org-mode is
2411 implemented on top of outline-mode, which is ideal to keep the content
2412 of large files well structured. It supports ToDo items, deadlines and
2413 time stamps, which magically appear in the diary listing of the Emacs
2414 calendar. Tables are easily created with a built-in table editor.
2415 Plain text URL-like links connect to websites, emails (VM), Usenet
2416 messages (Gnus), BBDB entries, and any files related to the project.
2417 For printing and sharing of notes, an Org-mode file (or a part of it)
2418 can be exported as a structured ASCII or HTML file.
2419
2420 The following commands are available:
2421
2422 \\{org-mode-map}"
2423 (easy-menu-add org-org-menu)
2424 (easy-menu-add org-tbl-menu)
2425 (org-install-agenda-files-menu)
2426 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2427 (org-add-to-invisibility-spec '(org-cwidth))
2428 (setq outline-regexp "\\*+")
2429 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2430 (setq outline-level 'org-outline-level)
2431 (when (and org-ellipsis (stringp org-ellipsis))
2432 (unless org-display-table
2433 (setq org-display-table (make-display-table)))
2434 (set-display-table-slot org-display-table
2435 4 (string-to-vector org-ellipsis))
2436 (setq buffer-display-table org-display-table))
2437 (org-set-regexps-and-options)
2438 (if org-startup-truncated (setq truncate-lines t))
2439 (set (make-local-variable 'font-lock-unfontify-region-function)
2440 'org-unfontify-region)
2441 ;; Activate before-change-function
2442 (set (make-local-variable 'org-table-may-need-update) t)
2443 (org-add-hook 'before-change-functions 'org-before-change-function nil
2444 'local)
2445 ;; Paragraphs and auto-filling
2446 (org-set-autofill-regexps)
2447 (org-update-radio-target-regexp)
2448 ;; Settings for Calc embedded mode
2449 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2450 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2451 (if (and org-insert-mode-line-in-empty-file
2452 (interactive-p)
2453 (= (point-min) (point-max)))
2454 (insert " -*- mode: org -*-\n\n"))
2455
2456 ;; Get rid of Outline menus, they are not needed
2457 ;; Need to do this here because define-derived-mode sets up
2458 ;; the keymap so late.
2459 (if (featurep 'xemacs)
2460 (progn
2461 (delete-menu-item '("Headings"))
2462 (delete-menu-item '("Show"))
2463 (delete-menu-item '("Hide"))
2464 (set-menubar-dirty-flag))
2465 (define-key org-mode-map [menu-bar headings] 'undefined)
2466 (define-key org-mode-map [menu-bar hide] 'undefined)
2467 (define-key org-mode-map [menu-bar show] 'undefined))
2468
2469 (unless org-inhibit-startup
2470 (if org-startup-align-all-tables
2471 (org-table-map-tables 'org-table-align))
2472 (if org-startup-with-deadline-check
2473 (call-interactively 'org-check-deadlines)
2474 (cond
2475 ((eq org-startup-folded t)
2476 (org-cycle '(4)))
2477 ((eq org-startup-folded 'content)
2478 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2479 (org-cycle '(4)) (org-cycle '(4))))))))
2480
2481 (defsubst org-current-line (&optional pos)
2482 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2483
2484 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2485 mouse-map t)
2486 "Properties to remove when a string without properties is wanted.")
2487
2488 (defsubst org-match-string-no-properties (num &optional string)
2489 (if (featurep 'xemacs)
2490 (let ((s (match-string num string)))
2491 (remove-text-properties 0 (length s) org-rm-props s)
2492 s)
2493 (match-string-no-properties num string)))
2494
2495 (defsubst org-no-properties (s)
2496 (remove-text-properties 0 (length s) org-rm-props s)
2497 s)
2498
2499 (defun org-current-time ()
2500 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2501 (if (> org-time-stamp-rounding-minutes 0)
2502 (let ((r org-time-stamp-rounding-minutes)
2503 (time (decode-time)))
2504 (apply 'encode-time
2505 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2506 (nthcdr 2 time))))
2507 (current-time)))
2508
2509 (defun org-add-props (string plist &rest props)
2510 "Add text properties to entire string, from beginning to end.
2511 PLIST may be a list of properties, PROPS are individual properties and values
2512 that will be added to PLIST. Returns the string that was modified."
2513 (add-text-properties
2514 0 (length string) (if props (append plist props) plist) string)
2515 string)
2516 (put 'org-add-props 'lisp-indent-function 2)
2517
2518
2519 ;;; Font-Lock stuff
2520
2521 (defvar org-mouse-map (make-sparse-keymap))
2522 (define-key org-mouse-map
2523 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
2524 (define-key org-mouse-map
2525 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
2526 (when org-mouse-1-follows-link
2527 (define-key org-mouse-map [follow-link] 'mouse-face))
2528 (when org-tab-follows-link
2529 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2530 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2531 (when org-return-follows-link
2532 (define-key org-mouse-map [(return)] 'org-open-at-point)
2533 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2534
2535 (require 'font-lock)
2536
2537 (defconst org-non-link-chars "]\t\n\r<>")
2538 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
2539 "wl" "mhe" "rmail" "gnus" "shell"))
2540 (defconst org-link-re-with-space
2541 (concat
2542 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2543 "\\([^" org-non-link-chars " ]"
2544 "[^" org-non-link-chars "]*"
2545 "[^" org-non-link-chars " ]\\)>?")
2546 "Matches a link with spaces, optional angular brackets around it.")
2547
2548 (defconst org-link-re-with-space2
2549 (concat
2550 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2551 "\\([^" org-non-link-chars " ]"
2552 "[^]\t\n\r]*"
2553 "[^" org-non-link-chars " ]\\)>?")
2554 "Matches a link with spaces, optional angular brackets around it.")
2555
2556 (defconst org-angle-link-re
2557 (concat
2558 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2559 "\\([^" org-non-link-chars " ]"
2560 "[^" org-non-link-chars "]*"
2561 "\\)>")
2562 "Matches link with angular brackets, spaces are allowed.")
2563 (defconst org-plain-link-re
2564 (concat
2565 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2566 "\\([^]\t\n\r<>,;() ]+\\)")
2567 "Matches plain link, without spaces.")
2568
2569 (defconst org-bracket-link-regexp
2570 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2571 "Matches a link in double brackets.")
2572
2573 (defconst org-bracket-link-analytic-regexp
2574 (concat
2575 "\\[\\["
2576 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
2577 "\\([^]]+\\)"
2578 "\\]"
2579 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
2580 "\\]"))
2581 ; 1: http:
2582 ; 2: http
2583 ; 3: path
2584 ; 4: [desc]
2585 ; 5: desc
2586
2587
2588 (defconst org-ts-lengths
2589 (cons (length (format-time-string (car org-time-stamp-formats)))
2590 (length (format-time-string (cdr org-time-stamp-formats))))
2591 "This holds the lengths of the two different time formats.")
2592 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2593 "Regular expression for fast time stamp matching.")
2594 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2595 "Regular expression for fast time stamp matching.")
2596 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2597 "Regular expression matching time strings for analysis.")
2598 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2599 "Regular expression matching time stamps, with groups.")
2600 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2601 "Regular expression matching a time stamp range.")
2602 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2603 org-ts-regexp "\\)?")
2604 "Regular expression matching a time stamp or time stamp range.")
2605
2606 (defun org-activate-plain-links (limit)
2607 "Run through the buffer and add overlays to links."
2608 (if (re-search-forward org-plain-link-re limit t)
2609 (progn
2610 (add-text-properties (match-beginning 0) (match-end 0)
2611 (list 'mouse-face 'highlight
2612 'keymap org-mouse-map
2613 ))
2614 t)))
2615
2616 (defun org-activate-angle-links (limit)
2617 "Run through the buffer and add overlays to links."
2618 (if (re-search-forward org-angle-link-re limit t)
2619 (progn
2620 (add-text-properties (match-beginning 0) (match-end 0)
2621 (list 'mouse-face 'highlight
2622 'keymap org-mouse-map
2623 ))
2624 t)))
2625
2626 (defun org-activate-bracket-links (limit)
2627 "Run through the buffer and add overlays to bracketed links."
2628 (if (re-search-forward org-bracket-link-regexp limit t)
2629 (let* ((help (concat "LINK: "
2630 (org-match-string-no-properties 1)))
2631 ;; FIXME: above we should remove the escapes.
2632 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
2633 'keymap org-mouse-map 'mouse-face 'highlight
2634 'help-echo help))
2635 (vp (list 'rear-nonsticky t
2636 'keymap org-mouse-map 'mouse-face 'highlight
2637 'help-echo help)))
2638 ;; We need to remove the invisible property here. Table narrowing
2639 ;; may have made some of this invisible.
2640 (remove-text-properties (match-beginning 0) (match-end 0)
2641 '(invisible nil))
2642 (if (match-end 3)
2643 (progn
2644 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
2645 (add-text-properties (match-beginning 3) (match-end 3) vp)
2646 (add-text-properties (match-end 3) (match-end 0) ip))
2647 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
2648 (add-text-properties (match-beginning 1) (match-end 1) vp)
2649 (add-text-properties (match-end 1) (match-end 0) ip))
2650 t)))
2651
2652 (defun org-activate-dates (limit)
2653 "Run through the buffer and add overlays to dates."
2654 (if (re-search-forward org-tsr-regexp limit t)
2655 (progn
2656 (add-text-properties (match-beginning 0) (match-end 0)
2657 (list 'mouse-face 'highlight
2658 'keymap org-mouse-map))
2659 t)))
2660
2661 (defvar org-target-link-regexp nil
2662 "Regular expression matching radio targets in plain text.")
2663 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2664 "Regular expression matching a link target.")
2665 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2666 "Regular expression matching a link target.")
2667
2668 (defun org-activate-target-links (limit)
2669 "Run through the buffer and add overlays to target matches."
2670 (when org-target-link-regexp
2671 (let ((case-fold-search t))
2672 (if (re-search-forward org-target-link-regexp limit t)
2673 (progn
2674 (add-text-properties (match-beginning 0) (match-end 0)
2675 (list 'mouse-face 'highlight
2676 'keymap org-mouse-map
2677 'help-echo "Radio target link"
2678 'org-linked-text t))
2679 t)))))
2680
2681 (defun org-update-radio-target-regexp ()
2682 "Find all radio targets in this file and update the regular expression."
2683 (interactive)
2684 (when (memq 'radio org-activate-links)
2685 (setq org-target-link-regexp
2686 (org-make-target-link-regexp (org-all-targets 'radio)))
2687 (org-restart-font-lock)))
2688
2689 (defun org-hide-wide-columns (limit)
2690 (let (s e)
2691 (setq s (text-property-any (point) (or limit (point-max))
2692 'org-cwidth t))
2693 (when s
2694 (setq e (next-single-property-change s 'org-cwidth))
2695 (add-text-properties s e '(invisible org-cwidth intangible t))
2696 (goto-char e)
2697 t)))
2698
2699 (defun org-restart-font-lock ()
2700 "Restart font-lock-mode, to force refontification."
2701 (when (and (boundp 'font-lock-mode) font-lock-mode)
2702 (font-lock-mode -1)
2703 (font-lock-mode 1)))
2704
2705 (defun org-all-targets (&optional radio)
2706 "Return a list of all targets in this file.
2707 With optional argument RADIO, only find radio targets."
2708 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2709 rtn)
2710 (save-excursion
2711 (goto-char (point-min))
2712 (while (re-search-forward re nil t)
2713 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
2714 rtn)))
2715
2716 (defun org-make-target-link-regexp (targets)
2717 "Make regular expression matching all strings in TARGETS.
2718 The regular expression finds the targets also if there is a line break
2719 between words."
2720 (and targets
2721 (concat
2722 "\\<\\("
2723 (mapconcat
2724 (lambda (x)
2725 (while (string-match " +" x)
2726 (setq x (replace-match "\\s-+" t t x)))
2727 x)
2728 targets
2729 "\\|")
2730 "\\)\\>")))
2731
2732 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2733 "Matches CamelCase words, possibly with a star before it.")
2734
2735 (defun org-activate-camels (limit)
2736 "Run through the buffer and add overlays to dates."
2737 (if (re-search-forward org-camel-regexp limit t)
2738 (progn
2739 (add-text-properties (match-beginning 0) (match-end 0)
2740 (list 'mouse-face 'highlight
2741 'keymap org-mouse-map))
2742 t)))
2743
2744 (defun org-activate-tags (limit)
2745 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2746 (progn
2747 (add-text-properties (match-beginning 1) (match-end 1)
2748 (list 'mouse-face 'highlight
2749 'keymap org-mouse-map))
2750 t)))
2751
2752 (defun org-font-lock-level ()
2753 (save-excursion
2754 (org-back-to-heading t)
2755 (- (match-end 0) (match-beginning 0))))
2756
2757 (defun org-outline-level ()
2758 (save-excursion
2759 (looking-at outline-regexp)
2760 (if (match-beginning 1)
2761 (+ (org-get-string-indentation (match-string 1)) 1000)
2762 (- (match-end 0) (match-beginning 0)))))
2763
2764 (defvar org-font-lock-keywords nil)
2765
2766 (defun org-set-font-lock-defaults ()
2767 (let* ((em org-fontify-emphasized-text)
2768 (lk org-activate-links)
2769 (org-font-lock-extra-keywords
2770 (list
2771 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
2772 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
2773 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2774 (1 'org-table))
2775 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
2776 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
2777 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
2778 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
2779 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
2780 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
2781 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
2782 (if org-table-limit-column-width
2783 '(org-hide-wide-columns (0 nil append)))
2784 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2785 '(1 'org-todo t))
2786 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2787 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2788 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2789 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2790 ; (if em '("\\(\\W\\|^\\)\\(\\*\\w+\\*\\)\\(\\W\\|$\\)" 2 'bold prepend))
2791 ; (if em '("\\(\\W\\|^\\)\\(/\\w+/\\)\\(\\W\\|$\\)" 2 'italic prepend))
2792 ; (if em '("\\(\\W\\|^\\)\\(_\\w+_\\)\\(\\W\\|$\\)" 2 'underline prepend))
2793 (if em (list org-bold-re 2 ''bold 'prepend))
2794 (if em (list org-italic-re 2 ''italic 'prepend))
2795 (if em (list org-underline-re 2 ''underline 'prepend))
2796 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2797 "\\|" org-quote-string "\\)\\>")
2798 '(1 'org-special-keyword t))
2799 '("^#.*" (0 'font-lock-comment-face t))
2800 (if org-fontify-done-headline
2801 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2802 '(1 'org-done t) '(2 'org-headline-done t))
2803 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2804 '(1 'org-done t)))
2805 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2806 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2807 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2808 (if org-format-transports-properties-p
2809 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
2810 )))
2811 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
2812 ;; Now set the full font-lock-keywords
2813 (set (make-local-variable 'org-font-lock-keywords)
2814 org-font-lock-extra-keywords)
2815 (set (make-local-variable 'font-lock-defaults)
2816 '(org-font-lock-keywords t nil nil backward-paragraph))
2817 (kill-local-variable 'font-lock-keywords) nil))
2818
2819 (defvar org-m nil)
2820 (defvar org-l nil)
2821 (defvar org-f nil)
2822 (defun org-get-level-face (n)
2823 "Get the right face for match N in font-lock matching of healdines."
2824 (setq org-l (- (match-end 2) (match-beginning 1)))
2825 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
2826 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
2827 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
2828 (cond
2829 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
2830 ((eq n 2) org-f)
2831 (t (if org-level-color-stars-only nil org-f))))
2832
2833 (defun org-unfontify-region (beg end &optional maybe_loudly)
2834 "Remove fontification and activation overlays from links."
2835 (font-lock-default-unfontify-region beg end)
2836 (let* ((buffer-undo-list t)
2837 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2838 (inhibit-modification-hooks t)
2839 deactivate-mark buffer-file-name buffer-file-truename)
2840 (remove-text-properties beg end
2841 '(mouse-face nil keymap nil org-linked-text nil
2842 invisible nil intangible nil))))
2843 ;;; Visibility cycling
2844
2845 (defvar org-cycle-global-status nil)
2846 (defvar org-cycle-subtree-status nil)
2847 (defun org-cycle (&optional arg)
2848 "Visibility cycling for Org-mode.
2849
2850 - When this function is called with a prefix argument, rotate the entire
2851 buffer through 3 states (global cycling)
2852 1. OVERVIEW: Show only top-level headlines.
2853 2. CONTENTS: Show all headlines of all levels, but no body text.
2854 3. SHOW ALL: Show everything.
2855
2856 - When point is at the beginning of a headline, rotate the subtree started
2857 by this line through 3 different states (local cycling)
2858 1. FOLDED: Only the main headline is shown.
2859 2. CHILDREN: The main headline and the direct children are shown.
2860 From this state, you can move to one of the children
2861 and zoom in further.
2862 3. SUBTREE: Show the entire subtree, including body text.
2863
2864 - When there is a numeric prefix, go up to a heading with level ARG, do
2865 a `show-subtree' and return to the previous cursor position. If ARG
2866 is negative, go up that many levels.
2867
2868 - When point is not at the beginning of a headline, execute
2869 `indent-relative', like TAB normally does. See the option
2870 `org-cycle-emulate-tab' for details.
2871
2872 - Special case: if point is the the beginning of the buffer and there is
2873 no headline in line 1, this function will act as if called with prefix arg."
2874 (interactive "P")
2875
2876 (if (or (and (bobp) (not (looking-at outline-regexp)))
2877 (equal arg '(4)))
2878 ;; special case: use global cycling
2879 (setq arg t))
2880
2881 (let ((outline-regexp
2882 (if org-cycle-include-plain-lists
2883 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2884 outline-regexp)))
2885
2886 (cond
2887
2888 ((org-at-table-p 'any)
2889 ;; Enter the table or move to the next field in the table
2890 (or (org-table-recognize-table.el)
2891 (progn
2892 (if arg (org-table-edit-field t)
2893 (org-table-justify-field-maybe)
2894 (org-table-next-field)))))
2895
2896 ((eq arg t) ;; Global cycling
2897
2898 (cond
2899 ((and (eq last-command this-command)
2900 (eq org-cycle-global-status 'overview))
2901 ;; We just created the overview - now do table of contents
2902 ;; This can be slow in very large buffers, so indicate action
2903 (message "CONTENTS...")
2904 (save-excursion
2905 ;; Visit all headings and show their offspring
2906 (goto-char (point-max))
2907 (catch 'exit
2908 (while (and (progn (condition-case nil
2909 (outline-previous-visible-heading 1)
2910 (error (goto-char (point-min))))
2911 t)
2912 (looking-at outline-regexp))
2913 (show-branches)
2914 (if (bobp) (throw 'exit nil))))
2915 (message "CONTENTS...done"))
2916 (setq org-cycle-global-status 'contents)
2917 (run-hook-with-args 'org-cycle-hook 'contents))
2918
2919 ((and (eq last-command this-command)
2920 (eq org-cycle-global-status 'contents))
2921 ;; We just showed the table of contents - now show everything
2922 (show-all)
2923 (message "SHOW ALL")
2924 (setq org-cycle-global-status 'all)
2925 (run-hook-with-args 'org-cycle-hook 'all))
2926
2927 (t
2928 ;; Default action: go to overview
2929 (hide-sublevels 1)
2930 (message "OVERVIEW")
2931 (setq org-cycle-global-status 'overview)
2932 (run-hook-with-args 'org-cycle-hook 'overview))))
2933
2934 ((integerp arg)
2935 ;; Show-subtree, ARG levels up from here.
2936 (save-excursion
2937 (org-back-to-heading)
2938 (outline-up-heading (if (< arg 0) (- arg)
2939 (- (funcall outline-level) arg)))
2940 (org-show-subtree)))
2941
2942 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2943 ;; At a heading: rotate between three different views
2944 (org-back-to-heading)
2945 (let ((goal-column 0) eoh eol eos)
2946 ;; First, some boundaries
2947 (save-excursion
2948 (org-back-to-heading)
2949 (save-excursion
2950 (beginning-of-line 2)
2951 (while (and (not (eobp)) ;; this is like `next-line'
2952 (get-char-property (1- (point)) 'invisible))
2953 (beginning-of-line 2)) (setq eol (point)))
2954 (outline-end-of-heading) (setq eoh (point))
2955 (org-end-of-subtree t) (setq eos (point))
2956 (outline-next-heading))
2957 ;; Find out what to do next and set `this-command'
2958 (cond
2959 ((= eos eoh)
2960 ;; Nothing is hidden behind this heading
2961 (message "EMPTY ENTRY")
2962 (setq org-cycle-subtree-status nil))
2963 ((>= eol eos)
2964 ;; Entire subtree is hidden in one line: open it
2965 (org-show-entry)
2966 (show-children)
2967 (message "CHILDREN")
2968 (setq org-cycle-subtree-status 'children)
2969 (run-hook-with-args 'org-cycle-hook 'children))
2970 ((and (eq last-command this-command)
2971 (eq org-cycle-subtree-status 'children))
2972 ;; We just showed the children, now show everything.
2973 (org-show-subtree)
2974 (message "SUBTREE")
2975 (setq org-cycle-subtree-status 'subtree)
2976 (run-hook-with-args 'org-cycle-hook 'subtree))
2977 (t
2978 ;; Default action: hide the subtree.
2979 (hide-subtree)
2980 (message "FOLDED")
2981 (setq org-cycle-subtree-status 'folded)
2982 (run-hook-with-args 'org-cycle-hook 'folded)))))
2983
2984 ;; TAB emulation
2985 (buffer-read-only (org-back-to-heading))
2986 ((if (and (eq org-cycle-emulate-tab 'white)
2987 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2988 t
2989 (eq org-cycle-emulate-tab t))
2990 (if (and (looking-at "[ \n\r\t]")
2991 (string-match "^[ \t]*$" (buffer-substring
2992 (point-at-bol) (point))))
2993 (progn
2994 (beginning-of-line 1)
2995 (and (looking-at "[ \t]+") (replace-match ""))))
2996 (indent-relative))
2997
2998 (t (save-excursion
2999 (org-back-to-heading)
3000 (org-cycle))))))
3001
3002 (defun org-optimize-window-after-visibility-change (state)
3003 "Adjust the window after a change in outline visibility.
3004 This function is the default value of the hook `org-cycle-hook'."
3005 (when (get-buffer-window (current-buffer))
3006 (cond
3007 ((eq state 'overview) (org-first-headline-recenter 1))
3008 ((eq state 'content) nil)
3009 ((eq state 'all) nil)
3010 ((eq state 'folded) nil)
3011 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3012 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3013
3014 (defun org-subtree-end-visible-p ()
3015 "Is the end of the current subtree visible?"
3016 (pos-visible-in-window-p
3017 (save-excursion (org-end-of-subtree t) (point))))
3018
3019 (defun org-first-headline-recenter (&optional N)
3020 "Move cursor to the first headline and recenter the headline.
3021 Optional argument N means, put the headline into the Nth line of the window."
3022 (goto-char (point-min))
3023 (when (re-search-forward (concat "^" outline-regexp) nil t)
3024 (beginning-of-line)
3025 (recenter (prefix-numeric-value N))))
3026
3027 (defvar org-goto-window-configuration nil)
3028 (defvar org-goto-marker nil)
3029 (defvar org-goto-map (make-sparse-keymap))
3030 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3031 (while (setq cmd (pop cmds))
3032 (substitute-key-definition cmd cmd org-goto-map global-map)))
3033 (define-key org-goto-map "\C-m" 'org-goto-ret)
3034 (define-key org-goto-map [(left)] 'org-goto-left)
3035 (define-key org-goto-map [(right)] 'org-goto-right)
3036 (define-key org-goto-map [(?q)] 'org-goto-quit)
3037 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3038 (define-key org-goto-map "\C-i" 'org-cycle)
3039 (define-key org-goto-map [(tab)] 'org-cycle)
3040 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3041 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3042 (define-key org-goto-map "n" 'outline-next-visible-heading)
3043 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3044 (define-key org-goto-map "f" 'outline-forward-same-level)
3045 (define-key org-goto-map "b" 'outline-backward-same-level)
3046 (define-key org-goto-map "u" 'outline-up-heading)
3047 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3048 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3049 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3050 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3051 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3052 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3053 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3054
3055 (defconst org-goto-help
3056 "Select a location to jump to, press RET
3057 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3058
3059 (defun org-goto ()
3060 "Go to a different location of the document, keeping current visibility.
3061
3062 When you want to go to a different location in a document, the fastest way
3063 is often to fold the entire buffer and then dive into the tree. This
3064 method has the disadvantage, that the previous location will be folded,
3065 which may not be what you want.
3066
3067 This command works around this by showing a copy of the current buffer in
3068 overview mode. You can dive into the tree in that copy, to find the
3069 location you want to reach. When pressing RET, the command returns to the
3070 original buffer in which the visibility is still unchanged. It then jumps
3071 to the new location, making it and the headline hierarchy above it visible."
3072 (interactive)
3073 (let* ((org-goto-start-pos (point))
3074 (selected-point
3075 (org-get-location (current-buffer) org-goto-help)))
3076 (if selected-point
3077 (progn
3078 (org-mark-ring-push org-goto-start-pos)
3079 (goto-char selected-point)
3080 (if (or (org-invisible-p) (org-invisible-p2))
3081 (org-show-hierarchy-above)))
3082 (error "Quit"))))
3083
3084 (defun org-get-location (buf help)
3085 "Let the user select a location in the Org-mode buffer BUF.
3086 This function uses a recursive edit. It returns the selected position
3087 or nil."
3088 (let (org-selected-point)
3089 (save-excursion
3090 (save-window-excursion
3091 (delete-other-windows)
3092 (switch-to-buffer (get-buffer-create "*org-goto*"))
3093 (with-output-to-temp-buffer "*Help*"
3094 (princ help))
3095 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3096 (setq buffer-read-only nil)
3097 (erase-buffer)
3098 (insert-buffer-substring buf)
3099 (let ((org-startup-truncated t)
3100 (org-startup-folded t)
3101 (org-startup-align-all-tables nil)
3102 (org-startup-with-deadline-check nil))
3103 (org-mode))
3104 (setq buffer-read-only t)
3105 (if (boundp 'org-goto-start-pos)
3106 (goto-char org-goto-start-pos)
3107 (goto-char (point-min)))
3108 (org-beginning-of-line)
3109 (message "Select location and press RET")
3110 ;; now we make sure that during selection, ony very few keys work
3111 ;; and that it is impossible to switch to another window.
3112 (let ((gm (current-global-map))
3113 (overriding-local-map org-goto-map))
3114 (unwind-protect
3115 (progn
3116 (use-global-map org-goto-map)
3117 (recursive-edit))
3118 (use-global-map gm)))))
3119 (kill-buffer "*org-goto*")
3120 org-selected-point))
3121
3122 ;; FIXME: It may not be a good idea to temper with the prefix argument...
3123 (defun org-goto-ret (&optional arg)
3124 "Finish `org-goto' by going to the new location."
3125 (interactive "P")
3126 (setq org-selected-point (point)
3127 current-prefix-arg arg)
3128 (throw 'exit nil))
3129
3130 (defun org-goto-left ()
3131 "Finish `org-goto' by going to the new location."
3132 (interactive)
3133 (if (org-on-heading-p)
3134 (progn
3135 (beginning-of-line 1)
3136 (setq org-selected-point (point)
3137 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3138 (throw 'exit nil))
3139 (error "Not on a heading")))
3140
3141 (defun org-goto-right ()
3142 "Finish `org-goto' by going to the new location."
3143 (interactive)
3144 (if (org-on-heading-p)
3145 (progn
3146 (outline-end-of-subtree)
3147 (or (eobp) (forward-char 1))
3148 (setq org-selected-point (point)
3149 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3150 (throw 'exit nil))
3151 (error "Not on a heading")))
3152
3153 (defun org-goto-quit ()
3154 "Finish `org-goto' without cursor motion."
3155 (interactive)
3156 (setq org-selected-point nil)
3157 (throw 'exit nil))
3158
3159 ;;; Promotion, Demotion, Inserting new headlines
3160
3161 (defvar org-ignore-region nil
3162 "To temporarily disable the active region.")
3163
3164 (defun org-insert-heading (&optional force-heading)
3165 "Insert a new heading or item with same depth at point."
3166 (interactive "P")
3167 (when (or force-heading (not (org-insert-item)))
3168 (let* ((head (save-excursion
3169 (condition-case nil
3170 (org-back-to-heading)
3171 (error (outline-next-heading)))
3172 (prog1 (match-string 0)
3173 (funcall outline-level)))))
3174 (cond
3175 ((and (org-on-heading-p) (bolp)
3176 (save-excursion (backward-char 1) (not (org-invisible-p))))
3177 (open-line 1))
3178 ((bolp) nil)
3179 (t (newline)))
3180 (insert head)
3181 (just-one-space)
3182 (run-hooks 'org-insert-heading-hook))))
3183
3184 (defun org-insert-item ()
3185 "Insert a new item at the current level.
3186 Return t when things worked, nil when we are not in an item."
3187 (when (save-excursion
3188 (condition-case nil
3189 (progn
3190 (org-beginning-of-item)
3191 (org-at-item-p)
3192 t)
3193 (error nil)))
3194 (let* ((bul (match-string 0))
3195 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3196 (match-end 0)))
3197 (eowcol (save-excursion (goto-char eow) (current-column))))
3198 (cond
3199 ((and (org-at-item-p) (<= (point) eow))
3200 ;; before the bullet
3201 (beginning-of-line 1)
3202 (open-line 1))
3203 ((<= (point) eow)
3204 (beginning-of-line 1))
3205 (t (newline)))
3206 (insert bul)
3207 (just-one-space))
3208 (org-maybe-renumber-ordered-list)
3209 t))
3210
3211 (defun org-insert-todo-heading (arg)
3212 "Insert a new heading with the same level and TODO state as current heading.
3213 If the heading has no TODO state, or if the state is DONE, use the first
3214 state (TODO by default). Also with prefix arg, force first state."
3215 (interactive "P")
3216 (org-insert-heading)
3217 (save-excursion
3218 (org-back-to-heading)
3219 (outline-previous-heading)
3220 (looking-at org-todo-line-regexp))
3221 (if (or arg
3222 (not (match-beginning 2))
3223 (equal (match-string 2) org-done-string))
3224 (insert (car org-todo-keywords) " ")
3225 (insert (match-string 2) " ")))
3226
3227 (defun org-promote-subtree ()
3228 "Promote the entire subtree.
3229 See also `org-promote'."
3230 (interactive)
3231 (save-excursion
3232 (org-map-tree 'org-promote)))
3233
3234 (defun org-demote-subtree ()
3235 "Demote the entire subtree. See `org-demote'.
3236 See also `org-promote'."
3237 (interactive)
3238 (save-excursion
3239 (org-map-tree 'org-demote)))
3240
3241 (defun org-do-promote ()
3242 "Promote the current heading higher up the tree.
3243 If the region is active in `transient-mark-mode', promote all headings
3244 in the region."
3245 (interactive)
3246 (save-excursion
3247 (if (org-region-active-p)
3248 (org-map-region 'org-promote (region-beginning) (region-end))
3249 (org-promote)))
3250 (org-fix-position-after-promote))
3251
3252 (defun org-do-demote ()
3253 "Demote the current heading lower down the tree.
3254 If the region is active in `transient-mark-mode', demote all headings
3255 in the region."
3256 (interactive)
3257 (save-excursion
3258 (if (org-region-active-p)
3259 (org-map-region 'org-demote (region-beginning) (region-end))
3260 (org-demote)))
3261 (org-fix-position-after-promote))
3262
3263 (defun org-fix-position-after-promote ()
3264 "Make sure that after pro/demotion cursor position is right."
3265 (and (equal (char-after) ?\ )
3266 (equal (char-before) ?*)
3267 (forward-char 1)))
3268
3269 (defun org-get-legal-level (level change)
3270 "Rectify a level change under the influence of `org-odd-levels-only'
3271 LEVEL is a current level, CHANGE is by how much the level should be
3272 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3273 even level numbers will become the next higher odd number."
3274 (if org-odd-levels-only
3275 (cond ((not change) (1+ (* 2 (/ level 2))))
3276 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3277 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3278 (max 1 (+ level change))))
3279
3280 (defun org-promote ()
3281 "Promote the current heading higher up the tree.
3282 If the region is active in `transient-mark-mode', promote all headings
3283 in the region."
3284 (org-back-to-heading t)
3285 (let* ((level (save-match-data (funcall outline-level)))
3286 (up-head (make-string (org-get-legal-level level -1) ?*))
3287 (diff (abs (- level (length up-head)))))
3288 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3289 (replace-match up-head nil t)
3290 ;; Fixup tag positioning
3291 (and org-auto-align-tags (org-set-tags nil t))
3292 (if org-adapt-indentation
3293 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
3294 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
3295
3296 (defun org-demote ()
3297 "Demote the current heading lower down the tree.
3298 If the region is active in `transient-mark-mode', demote all headings
3299 in the region."
3300 (org-back-to-heading t)
3301 (let* ((level (save-match-data (funcall outline-level)))
3302 (down-head (make-string (org-get-legal-level level 1) ?*))
3303 (diff (abs (- level (length down-head)))))
3304 (replace-match down-head nil t)
3305 ;; Fixup tag positioning
3306 (and org-auto-align-tags (org-set-tags nil t))
3307 (if org-adapt-indentation
3308 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
3309
3310 (defun org-map-tree (fun)
3311 "Call FUN for every heading underneath the current one."
3312 (org-back-to-heading)
3313 (let ((level (funcall outline-level)))
3314 (save-excursion
3315 (funcall fun)
3316 (while (and (progn
3317 (outline-next-heading)
3318 (> (funcall outline-level) level))
3319 (not (eobp)))
3320 (funcall fun)))))
3321
3322 (defun org-map-region (fun beg end)
3323 "Call FUN for every heading between BEG and END."
3324 (let ((org-ignore-region t))
3325 (save-excursion
3326 (setq end (copy-marker end))
3327 (goto-char beg)
3328 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3329 (< (point) end))
3330 (funcall fun))
3331 (while (and (progn
3332 (outline-next-heading)
3333 (< (point) end))
3334 (not (eobp)))
3335 (funcall fun)))))
3336
3337 (defun org-fixup-indentation (from to prohibit)
3338 "Change the indentation in the current entry by re-replacing FROM with TO.
3339 However, if the regexp PROHIBIT matches at all, don't do anything.
3340 This is being used to change indentation along with the length of the
3341 heading marker. But if there are any lines which are not indented, nothing
3342 is changed at all."
3343 (save-excursion
3344 (let ((end (save-excursion (outline-next-heading)
3345 (point-marker))))
3346 (unless (save-excursion (re-search-forward prohibit end t))
3347 (while (re-search-forward from end t)
3348 (replace-match to)
3349 (beginning-of-line 2)))
3350 (move-marker end nil))))
3351
3352 ;;; Vertical tree motion, cutting and pasting of subtrees
3353
3354 (defun org-move-subtree-up (&optional arg)
3355 "Move the current subtree up past ARG headlines of the same level."
3356 (interactive "p")
3357 (org-move-subtree-down (- (prefix-numeric-value arg))))
3358
3359 (defun org-move-subtree-down (&optional arg)
3360 "Move the current subtree down past ARG headlines of the same level."
3361 (interactive "p")
3362 (setq arg (prefix-numeric-value arg))
3363 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3364 'outline-get-last-sibling))
3365 (ins-point (make-marker))
3366 (cnt (abs arg))
3367 beg end txt folded)
3368 ;; Select the tree
3369 (org-back-to-heading)
3370 (setq beg (point))
3371 (save-match-data
3372 (save-excursion (outline-end-of-heading)
3373 (setq folded (org-invisible-p)))
3374 (outline-end-of-subtree))
3375 (outline-next-heading)
3376 (setq end (point))
3377 ;; Find insertion point, with error handling
3378 (goto-char beg)
3379 (while (> cnt 0)
3380 (or (and (funcall movfunc) (looking-at outline-regexp))
3381 (progn (goto-char beg)
3382 (error "Cannot move past superior level or buffer limit")))
3383 (setq cnt (1- cnt)))
3384 (if (> arg 0)
3385 ;; Moving forward - still need to move over subtree
3386 (progn (outline-end-of-subtree)
3387 (outline-next-heading)
3388 (if (not (or (looking-at (concat "^" outline-regexp))
3389 (bolp)))
3390 (newline))))
3391 (move-marker ins-point (point))
3392 (setq txt (buffer-substring beg end))
3393 (delete-region beg end)
3394 (insert txt)
3395 (goto-char ins-point)
3396 (if folded (hide-subtree))
3397 (move-marker ins-point nil)))
3398
3399 (defvar org-subtree-clip ""
3400 "Clipboard for cut and paste of subtrees.
3401 This is actually only a copy of the kill, because we use the normal kill
3402 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3403
3404 (defvar org-subtree-clip-folded nil
3405 "Was the last copied subtree folded?
3406 This is used to fold the tree back after pasting.")
3407
3408 (defun org-cut-subtree ()
3409 "Cut the current subtree into the clipboard.
3410 This is a short-hand for marking the subtree and then cutting it."
3411 (interactive)
3412 (org-copy-subtree 'cut))
3413
3414 (defun org-copy-subtree (&optional cut)
3415 "Cut the current subtree into the clipboard.
3416 This is a short-hand for marking the subtree and then copying it.
3417 If CUT is non nil, actually cut the subtree."
3418 (interactive)
3419 (let (beg end folded)
3420 (org-back-to-heading)
3421 (setq beg (point))
3422 (save-match-data
3423 (save-excursion (outline-end-of-heading)
3424 (setq folded (org-invisible-p)))
3425 (outline-end-of-subtree))
3426 (if (equal (char-after) ?\n) (forward-char 1))
3427 (setq end (point))
3428 (goto-char beg)
3429 (when (> end beg)
3430 (setq org-subtree-clip-folded folded)
3431 (if cut (kill-region beg end) (copy-region-as-kill beg end))
3432 (setq org-subtree-clip (current-kill 0))
3433 (message "%s: Subtree with %d characters"
3434 (if cut "Cut" "Copied")
3435 (length org-subtree-clip)))))
3436
3437 (defun org-paste-subtree (&optional level tree)
3438 "Paste the clipboard as a subtree, with modification of headline level.
3439 The entire subtree is promoted or demoted in order to match a new headline
3440 level. By default, the new level is derived from the visible headings
3441 before and after the insertion point, and taken to be the inferior headline
3442 level of the two. So if the previous visible heading is level 3 and the
3443 next is level 4 (or vice versa), level 4 will be used for insertion.
3444 This makes sure that the subtree remains an independent subtree and does
3445 not swallow low level entries.
3446
3447 You can also force a different level, either by using a numeric prefix
3448 argument, or by inserting the heading marker by hand. For example, if the
3449 cursor is after \"*****\", then the tree will be shifted to level 5.
3450
3451 If you want to insert the tree as is, just use \\[yank].
3452
3453 If optional TREE is given, use this text instead of the kill ring."
3454 (interactive "P")
3455 (unless (org-kill-is-subtree-p tree)
3456 (error
3457 (substitute-command-keys
3458 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
3459 (let* ((txt (or tree (current-kill 0)))
3460 (^re (concat "^\\(" outline-regexp "\\)"))
3461 (re (concat "\\(" outline-regexp "\\)"))
3462 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3463
3464 (old-level (if (string-match ^re txt)
3465 (- (match-end 0) (match-beginning 0))
3466 -1))
3467 (force-level (cond (level (prefix-numeric-value level))
3468 ((string-match
3469 ^re_ (buffer-substring (point-at-bol) (point)))
3470 (- (match-end 0) (match-beginning 0)))
3471 (t nil)))
3472 (previous-level (save-excursion
3473 (condition-case nil
3474 (progn
3475 (outline-previous-visible-heading 1)
3476 (if (looking-at re)
3477 (- (match-end 0) (match-beginning 0))
3478 1))
3479 (error 1))))
3480 (next-level (save-excursion
3481 (condition-case nil
3482 (progn
3483 (outline-next-visible-heading 1)
3484 (if (looking-at re)
3485 (- (match-end 0) (match-beginning 0))
3486 1))
3487 (error 1))))
3488 (new-level (or force-level (max previous-level next-level)))
3489 (shift (if (or (= old-level -1)
3490 (= new-level -1)
3491 (= old-level new-level))
3492 0
3493 (- new-level old-level)))
3494 (shift1 shift)
3495 (delta (if (> shift 0) -1 1))
3496 (func (if (> shift 0) 'org-demote 'org-promote))
3497 (org-odd-levels-only nil)
3498 beg end)
3499 ;; Remove the forces level indicator
3500 (if force-level
3501 (delete-region (point-at-bol) (point)))
3502 ;; Make sure we start at the beginning of an empty line
3503 (if (not (bolp)) (insert "\n"))
3504 (if (not (looking-at "[ \t]*$"))
3505 (progn (insert "\n") (backward-char 1)))
3506 ;; Paste
3507 (setq beg (point))
3508 (insert txt)
3509 (setq end (point))
3510 (goto-char beg)
3511 ;; Shift if necessary
3512 (if (= shift 0)
3513 (message "Pasted at level %d, without shift" new-level)
3514 (save-restriction
3515 (narrow-to-region beg end)
3516 (while (not (= shift 0))
3517 (org-map-region func (point-min) (point-max))
3518 (setq shift (+ delta shift)))
3519 (goto-char (point-min))
3520 (message "Pasted at level %d, with shift by %d levels"
3521 new-level shift1)))
3522 (if (and (eq org-subtree-clip (current-kill 0))
3523 org-subtree-clip-folded)
3524 ;; The tree was folded before it was killed/copied
3525 (hide-subtree))))
3526
3527 (defun org-kill-is-subtree-p (&optional txt)
3528 "Check if the current kill is an outline subtree, or a set of trees.
3529 Returns nil if kill does not start with a headline, or if the first
3530 headline level is not the largest headline level in the tree.
3531 So this will actually accept several entries of equal levels as well,
3532 which is OK for `org-paste-subtree'.
3533 If optional TXT is given, check this string instead of the current kill."
3534 (let* ((kill (or txt (current-kill 0) ""))
3535 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3536 (- (match-end 0) (match-beginning 0))))
3537 (re (concat "^" outline-regexp))
3538 (start 1))
3539 (if (not start-level)
3540 nil ;; does not even start with a heading
3541 (catch 'exit
3542 (while (setq start (string-match re kill (1+ start)))
3543 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3544 (throw 'exit nil)))
3545 t))))
3546
3547 ;;; Plain list items
3548
3549 (defun org-at-item-p ()
3550 "Is point in a line starting a hand-formatted item?"
3551 (let ((llt org-plain-list-ordered-item-terminator))
3552 (save-excursion
3553 (goto-char (point-at-bol))
3554 (looking-at
3555 (cond
3556 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3557 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3558 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3559 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3560
3561 (defun org-get-indentation ()
3562 "Get the indentation of the current line, interpreting tabs."
3563 (save-excursion
3564 (beginning-of-line 1)
3565 (skip-chars-forward " \t")
3566 (current-column)))
3567
3568 (defun org-beginning-of-item ()
3569 "Go to the beginning of the current hand-formatted item.
3570 If the cursor is not in an item, throw an error."
3571 (let ((pos (point))
3572 (limit (save-excursion (org-back-to-heading)
3573 (beginning-of-line 2) (point)))
3574 ind ind1)
3575 (if (org-at-item-p)
3576 (beginning-of-line 1)
3577 (beginning-of-line 1)
3578 (skip-chars-forward " \t")
3579 (setq ind (current-column))
3580 (if (catch 'exit
3581 (while t
3582 (beginning-of-line 0)
3583 (if (< (point) limit) (throw 'exit nil))
3584 (unless (looking-at " \t]*$")
3585 (skip-chars-forward " \t")
3586 (setq ind1 (current-column))
3587 (if (< ind1 ind)
3588 (throw 'exit (org-at-item-p))))))
3589 nil
3590 (goto-char pos)
3591 (error "Not in an item")))))
3592
3593 (defun org-end-of-item ()
3594 "Go to the end of the current hand-formatted item.
3595 If the cursor is not in an item, throw an error."
3596 (let ((pos (point))
3597 (limit (save-excursion (outline-next-heading) (point)))
3598 (ind (save-excursion
3599 (org-beginning-of-item)
3600 (skip-chars-forward " \t")
3601 (current-column)))
3602 ind1)
3603 (if (catch 'exit
3604 (while t
3605 (beginning-of-line 2)
3606 (if (>= (point) limit) (throw 'exit t))
3607 (unless (looking-at "[ \t]*$")
3608 (skip-chars-forward " \t")
3609 (setq ind1 (current-column))
3610 (if (<= ind1 ind) (throw 'exit t)))))
3611 (beginning-of-line 1)
3612 (goto-char pos)
3613 (error "Not in an item"))))
3614
3615 (defun org-move-item-down (arg)
3616 "Move the plain list item at point down, i.e. swap with following item.
3617 Subitems (items with larger indentation) are considered part of the item,
3618 so this really moves item trees."
3619 (interactive "p")
3620 (let (beg end ind ind1 (pos (point)) txt)
3621 (org-beginning-of-item)
3622 (setq beg (point))
3623 (setq ind (org-get-indentation))
3624 (org-end-of-item)
3625 (setq end (point))
3626 (setq ind1 (org-get-indentation))
3627 (if (and (org-at-item-p) (= ind ind1))
3628 (progn
3629 (org-end-of-item)
3630 (setq txt (buffer-substring beg end))
3631 (save-excursion
3632 (delete-region beg end))
3633 (setq pos (point))
3634 (insert txt)
3635 (goto-char pos)
3636 (org-maybe-renumber-ordered-list))
3637 (goto-char pos)
3638 (error "Cannot move this item further down"))))
3639
3640 (defun org-move-item-up (arg)
3641 "Move the plain list item at point up, i.e. swap with previous item.
3642 Subitems (items with larger indentation) are considered part of the item,
3643 so this really moves item trees."
3644 (interactive "p")
3645 (let (beg end ind ind1 (pos (point)) txt)
3646 (org-beginning-of-item)
3647 (setq beg (point))
3648 (setq ind (org-get-indentation))
3649 (org-end-of-item)
3650 (setq end (point))
3651 (goto-char beg)
3652 (catch 'exit
3653 (while t
3654 (beginning-of-line 0)
3655 (if (looking-at "[ \t]*$")
3656 nil
3657 (if (<= (setq ind1 (org-get-indentation)) ind)
3658 (throw 'exit t)))))
3659 (condition-case nil
3660 (org-beginning-of-item)
3661 (error (goto-char beg)
3662 (error "Cannot move this item further up")))
3663 (setq ind1 (org-get-indentation))
3664 (if (and (org-at-item-p) (= ind ind1))
3665 (progn
3666 (setq txt (buffer-substring beg end))
3667 (save-excursion
3668 (delete-region beg end))
3669 (setq pos (point))
3670 (insert txt)
3671 (goto-char pos)
3672 (org-maybe-renumber-ordered-list))
3673 (goto-char pos)
3674 (error "Cannot move this item further up"))))
3675
3676 (defun org-maybe-renumber-ordered-list ()
3677 "Renumber the ordered list at point if setup allows it.
3678 This tests the user option `org-auto-renumber-ordered-lists' before
3679 doing the renumbering."
3680 (and org-auto-renumber-ordered-lists
3681 (org-at-item-p)
3682 (match-beginning 3)
3683 (org-renumber-ordered-list 1)))
3684
3685 (defun org-get-string-indentation (s)
3686 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3687 (let ((n -1) (i 0) (w tab-width) c)
3688 (catch 'exit
3689 (while (< (setq n (1+ n)) (length s))
3690 (setq c (aref s n))
3691 (cond ((= c ?\ ) (setq i (1+ i)))
3692 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3693 (t (throw 'exit t)))))
3694 i))
3695
3696 (defun org-renumber-ordered-list (arg)
3697 "Renumber an ordered plain list.
3698 Cursor next to be in the first line of an item, the line that starts
3699 with something like \"1.\" or \"2)\"."
3700 (interactive "p")
3701 (unless (and (org-at-item-p)
3702 (match-beginning 3))
3703 (error "This is not an ordered list"))
3704 (let ((line (org-current-line))
3705 (col (current-column))
3706 (ind (org-get-string-indentation
3707 (buffer-substring (point-at-bol) (match-beginning 3))))
3708 ;; (term (substring (match-string 3) -1))
3709 ind1 (n (1- arg)))
3710 ;; find where this list begins
3711 (catch 'exit
3712 (while t
3713 (catch 'next
3714 (beginning-of-line 0)
3715 (if (looking-at "[ \t]*$") (throw 'next t))
3716 (skip-chars-forward " \t") (setq ind1 (current-column))
3717 (if (or (< ind1 ind)
3718 (and (= ind1 ind)
3719 (not (org-at-item-p))))
3720 (throw 'exit t)))))
3721 ;; Walk forward and replace these numbers
3722 (catch 'exit
3723 (while t
3724 (catch 'next
3725 (beginning-of-line 2)
3726 (if (eobp) (throw 'exit nil))
3727 (if (looking-at "[ \t]*$") (throw 'next nil))
3728 (skip-chars-forward " \t") (setq ind1 (current-column))
3729 (if (> ind1 ind) (throw 'next t))
3730 (if (< ind1 ind) (throw 'exit t))
3731 (if (not (org-at-item-p)) (throw 'exit nil))
3732 (if (not (match-beginning 3))
3733 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3734 (delete-region (match-beginning 3) (1- (match-end 3)))
3735 (goto-char (match-beginning 3))
3736 (insert (format "%d" (setq n (1+ n)))))))
3737 (goto-line line)
3738 (move-to-column col)))
3739
3740 (defvar org-last-indent-begin-marker (make-marker))
3741 (defvar org-last-indent-end-marker (make-marker))
3742
3743 (defun org-outdent-item (arg)
3744 "Outdent a local list item."
3745 (interactive "p")
3746 (org-indent-item (- arg)))
3747
3748 (defun org-indent-item (arg)
3749 "Indent a local list item."
3750 (interactive "p")
3751 (unless (org-at-item-p)
3752 (error "Not on an item"))
3753 (let (beg end ind ind1)
3754 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3755 (setq beg org-last-indent-begin-marker
3756 end org-last-indent-end-marker)
3757 (org-beginning-of-item)
3758 (setq beg (move-marker org-last-indent-begin-marker (point)))
3759 (org-end-of-item)
3760 (setq end (move-marker org-last-indent-end-marker (point))))
3761 (goto-char beg)
3762 (skip-chars-forward " \t") (setq ind (current-column))
3763 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3764 (while (< (point) end)
3765 (beginning-of-line 1)
3766 (skip-chars-forward " \t") (setq ind1 (current-column))
3767 (delete-region (point-at-bol) (point))
3768 (indent-to-column (+ ind1 arg))
3769 (beginning-of-line 2))
3770 (goto-char beg)))
3771
3772 ;;; Archiving
3773
3774 (defun org-archive-subtree ()
3775 "Move the current subtree to the archive.
3776 The archive can be a certain top-level heading in the current file, or in
3777 a different file. The tree will be moved to that location, the subtree
3778 heading be marked DONE, and the current time will be added."
3779 (interactive)
3780 ;; Save all relevant TODO keyword-relatex variables
3781 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3782 (tr-org-todo-keywords org-todo-keywords)
3783 (tr-org-todo-interpretation org-todo-interpretation)
3784 (tr-org-done-string org-done-string)
3785 (tr-org-todo-regexp org-todo-regexp)
3786 (tr-org-todo-line-regexp org-todo-line-regexp)
3787 (this-buffer (current-buffer))
3788 file heading buffer level newfile-p)
3789 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3790 (progn
3791 (setq file (format (match-string 1 org-archive-location)
3792 (file-name-nondirectory buffer-file-name))
3793 heading (match-string 2 org-archive-location)))
3794 (error "Invalid `org-archive-location'"))
3795 (if (> (length file) 0)
3796 (setq newfile-p (not (file-exists-p file))
3797 buffer (find-file-noselect file))
3798 (setq buffer (current-buffer)))
3799 (unless buffer
3800 (error "Cannot access file \"%s\"" file))
3801 (if (and (> (length heading) 0)
3802 (string-match "^\\*+" heading))
3803 (setq level (match-end 0))
3804 (setq heading nil level 0))
3805 (save-excursion
3806 ;; We first only copy, in case something goes wrong
3807 ;; we need to protect this-command, to avoid kill-region sets it,
3808 ;; which would lead to duplication of subtrees
3809 (let (this-command) (org-copy-subtree))
3810 (set-buffer buffer)
3811 ;; Enforce org-mode for the archive buffer
3812 (if (not (eq major-mode 'org-mode))
3813 ;; Force the mode for future visits.
3814 (let ((org-insert-mode-line-in-empty-file t))
3815 (call-interactively 'org-mode)))
3816 (when newfile-p
3817 (goto-char (point-max))
3818 (insert (format "\nArchived entries from file %s\n\n"
3819 (buffer-file-name this-buffer))))
3820 ;; Force the TODO keywords of the original buffer
3821 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3822 (org-todo-keywords tr-org-todo-keywords)
3823 (org-todo-interpretation tr-org-todo-interpretation)
3824 (org-done-string tr-org-done-string)
3825 (org-todo-regexp tr-org-todo-regexp)
3826 (org-todo-line-regexp tr-org-todo-line-regexp))
3827 (goto-char (point-min))
3828 (if heading
3829 (progn
3830 (if (re-search-forward
3831 (concat "\\(^\\|\r\\)"
3832 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3833 nil t)
3834 (goto-char (match-end 0))
3835 ;; Heading not found, just insert it at the end
3836 (goto-char (point-max))
3837 (or (bolp) (insert "\n"))
3838 (insert "\n" heading "\n")
3839 (end-of-line 0))
3840 ;; Make the heading visible, and the following as well
3841 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3842 (if (re-search-forward
3843 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3844 nil t)
3845 (progn (goto-char (match-beginning 0)) (insert "\n")
3846 (beginning-of-line 0))
3847 (goto-char (point-max)) (insert "\n")))
3848 (goto-char (point-max)) (insert "\n"))
3849 ;; Paste
3850 (org-paste-subtree (1+ level))
3851 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3852 (if org-archive-mark-done
3853 (org-todo (length org-todo-keywords)))
3854 ;; Move cursor to right after the TODO keyword
3855 (when org-archive-stamp-time
3856 (beginning-of-line 1)
3857 (looking-at org-todo-line-regexp)
3858 (goto-char (or (match-end 2) (match-beginning 3)))
3859 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3860 (org-current-time))
3861 ")"))
3862 ;; Save the buffer, if it is not the same buffer.
3863 (if (not (eq this-buffer buffer)) (save-buffer))))
3864 ;; Here we are back in the original buffer. Everything seems to have
3865 ;; worked. So now cut the tree and finish up.
3866 (let (this-command) (org-cut-subtree))
3867 (if (looking-at "[ \t]*$") (kill-line))
3868 (message "Subtree archived %s"
3869 (if (eq this-buffer buffer)
3870 (concat "under heading: " heading)
3871 (concat "in file: " (abbreviate-file-name file))))))
3872
3873 ;;; Completion
3874
3875 (defun org-complete (&optional arg)
3876 "Perform completion on word at point.
3877 At the beginning of a headline, this completes TODO keywords as given in
3878 `org-todo-keywords'.
3879 If the current word is preceded by a backslash, completes the TeX symbols
3880 that are supported for HTML support.
3881 If the current word is preceded by \"#+\", completes special words for
3882 setting file options.
3883 At all other locations, this simply calls `ispell-complete-word'."
3884 (interactive "P")
3885 (catch 'exit
3886 (let* ((end (point))
3887 (beg1 (save-excursion
3888 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3889 (skip-chars-backward "a-zA-Z_@0-9")
3890 (point)))
3891 (beg (save-excursion
3892 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3893 (skip-chars-backward "a-zA-Z0-9_:$")
3894 (point)))
3895 (camel (equal (char-before beg) ?*))
3896 (tag (equal (char-before beg1) ?:))
3897 (texp (equal (char-before beg) ?\\))
3898 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3899 beg)
3900 "#+"))
3901 (completion-ignore-case opt)
3902 (type nil)
3903 (tbl nil)
3904 (table (cond
3905 (opt
3906 (setq type :opt)
3907 (mapcar (lambda (x)
3908 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3909 (cons (match-string 2 x) (match-string 1 x)))
3910 (org-split-string (org-get-current-options) "\n")))
3911 (texp
3912 (setq type :tex)
3913 org-html-entities)
3914 ((string-match "\\`\\*+[ \t]*\\'"
3915 (buffer-substring (point-at-bol) beg))
3916 (setq type :todo)
3917 (mapcar 'list org-todo-keywords))
3918 (camel
3919 (setq type :camel)
3920 (save-excursion
3921 (goto-char (point-min))
3922 (while (re-search-forward org-todo-line-regexp nil t)
3923 (push (list
3924 (if org-file-link-context-use-camel-case
3925 (org-make-org-heading-camel (match-string 3) t)
3926 (org-make-org-heading-search-string
3927 (match-string 3) t)))
3928 tbl)))
3929 tbl)
3930 (tag (setq type :tag beg beg1)
3931 (org-get-buffer-tags))
3932 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3933 (pattern (buffer-substring-no-properties beg end))
3934 (completion (try-completion pattern table)))
3935 (cond ((eq completion t)
3936 (if (equal type :opt)
3937 (insert (substring (cdr (assoc (upcase pattern) table))
3938 (length pattern)))))
3939 ((null completion)
3940 (message "Can't find completion for \"%s\"" pattern)
3941 (ding))
3942 ((not (string= pattern completion))
3943 (delete-region beg end)
3944 (if (string-match " +$" completion)
3945 (setq completion (replace-match "" t t completion)))
3946 (insert completion)
3947 (if (get-buffer-window "*Completions*")
3948 (delete-window (get-buffer-window "*Completions*")))
3949 (if (assoc completion table)
3950 (if (eq type :todo) (insert " ")
3951 (if (eq type :tag) (insert ":"))))
3952 (if (and (equal type :opt) (assoc completion table))
3953 (message "%s" (substitute-command-keys
3954 "Press \\[org-complete] again to insert example settings"))))
3955 (t
3956 (message "Making completion list...")
3957 (let ((list (sort (all-completions pattern table) 'string<)))
3958 (with-output-to-temp-buffer "*Completions*"
3959 (condition-case nil
3960 ;; Protection needed for XEmacs and emacs 21
3961 (display-completion-list list pattern)
3962 (error (display-completion-list list)))))
3963 (message "Making completion list...%s" "done"))))))
3964
3965 ;;; Comments, TODO and DEADLINE
3966
3967 (defun org-toggle-comment ()
3968 "Change the COMMENT state of an entry."
3969 (interactive)
3970 (save-excursion
3971 (org-back-to-heading)
3972 (if (looking-at (concat outline-regexp
3973 "\\( +\\<" org-comment-string "\\>\\)"))
3974 (replace-match "" t t nil 1)
3975 (if (looking-at outline-regexp)
3976 (progn
3977 (goto-char (match-end 0))
3978 (insert " " org-comment-string))))))
3979
3980 (defvar org-last-todo-state-is-todo nil
3981 "This is non-nil when the last TODO state change led to a TODO state.
3982 If the last change removed the TODO tag or switched to DONE, then
3983 this is nil.")
3984
3985 (defun org-todo (&optional arg)
3986 "Change the TODO state of an item.
3987 The state of an item is given by a keyword at the start of the heading,
3988 like
3989 *** TODO Write paper
3990 *** DONE Call mom
3991
3992 The different keywords are specified in the variable `org-todo-keywords'.
3993 By default the available states are \"TODO\" and \"DONE\".
3994 So for this example: when the item starts with TODO, it is changed to DONE.
3995 When it starts with DONE, the DONE is removed. And when neither TODO nor
3996 DONE are present, add TODO at the beginning of the heading.
3997
3998 With prefix arg, use completion to determine the new state. With numeric
3999 prefix arg, switch to that state."
4000 (interactive "P")
4001 (save-excursion
4002 (org-back-to-heading)
4003 (if (looking-at outline-regexp) (goto-char (match-end 0)))
4004 (or (looking-at (concat " +" org-todo-regexp " *"))
4005 (looking-at " *"))
4006 (let* ((this (match-string 1))
4007 (completion-ignore-case t)
4008 (member (member this org-todo-keywords))
4009 (tail (cdr member))
4010 (state (cond
4011 ((equal arg '(4))
4012 ;; Read a state with completion
4013 (completing-read "State: " (mapcar (lambda(x) (list x))
4014 org-todo-keywords)
4015 nil t))
4016 ((eq arg 'right)
4017 (if this
4018 (if tail (car tail) nil)
4019 (car org-todo-keywords)))
4020 ((eq arg 'left)
4021 (if (equal member org-todo-keywords)
4022 nil
4023 (if this
4024 (nth (- (length org-todo-keywords) (length tail) 2)
4025 org-todo-keywords)
4026 org-done-string)))
4027 (arg
4028 ;; user requests a specific state
4029 (nth (1- (prefix-numeric-value arg))
4030 org-todo-keywords))
4031 ((null member) (car org-todo-keywords))
4032 ((null tail) nil) ;; -> first entry
4033 ((eq org-todo-interpretation 'sequence)
4034 (car tail))
4035 ((memq org-todo-interpretation '(type priority))
4036 (if (eq this-command last-command)
4037 (car tail)
4038 (if (> (length tail) 0) org-done-string nil)))
4039 (t nil)))
4040 (next (if state (concat " " state " ") " ")))
4041 (replace-match next t t)
4042 (setq org-last-todo-state-is-todo
4043 (not (equal state org-done-string)))
4044 (when org-log-done
4045 (if (equal state org-done-string)
4046 (org-log-done)
4047 (if (not this)
4048 (org-log-done t))))
4049 ;; Fixup tag positioning
4050 (and org-auto-align-tags (org-set-tags nil t))
4051 (run-hooks 'org-after-todo-state-change-hook)))
4052 ;; Fixup cursor location if close to the keyword
4053 (if (and (outline-on-heading-p)
4054 (not (bolp))
4055 (save-excursion (beginning-of-line 1)
4056 (looking-at org-todo-line-regexp))
4057 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
4058 (progn
4059 (goto-char (or (match-end 2) (match-end 1)))
4060 (just-one-space))))
4061
4062 (defun org-log-done (&optional undone)
4063 "Add a time stamp logging that a TODO entry has been closed.
4064 When UNDONE is non-nil, remove such a time stamp again."
4065 (interactive)
4066 (let (beg end col)
4067 (save-excursion
4068 (org-back-to-heading t)
4069 (setq beg (point))
4070 (looking-at (concat outline-regexp " *"))
4071 (goto-char (match-end 0))
4072 (setq col (current-column))
4073 (outline-next-heading)
4074 (setq end (point))
4075 (goto-char beg)
4076 (when (re-search-forward (concat
4077 "[\r\n]\\([ \t]*"
4078 (regexp-quote org-closed-string)
4079 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
4080 (delete-region (match-beginning 1) (match-end 1)))
4081 (unless undone
4082 (org-back-to-heading t)
4083 (skip-chars-forward "^\n\r")
4084 (goto-char (min (1+ (point)) (point-max)))
4085 (when (not (member (char-before) '(?\r ?\n)))
4086 (insert "\n"))
4087 (indent-to col)
4088 (insert org-closed-string " "
4089 (format-time-string
4090 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
4091 (org-current-time))
4092 "\n")))))
4093
4094 (defun org-show-todo-tree (arg)
4095 "Make a compact tree which shows all headlines marked with TODO.
4096 The tree will show the lines where the regexp matches, and all higher
4097 headlines above the match.
4098 With \\[universal-argument] prefix, also show the DONE entries.
4099 With a numeric prefix N, construct a sparse tree for the Nth element
4100 of `org-todo-keywords'."
4101 (interactive "P")
4102 (let ((case-fold-search nil)
4103 (kwd-re
4104 (cond ((null arg) org-not-done-regexp)
4105 ((equal arg '(4)) org-todo-regexp)
4106 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
4107 (regexp-quote (nth (1- (prefix-numeric-value arg))
4108 org-todo-keywords)))
4109 (t (error "Invalid prefix argument: %s" arg)))))
4110 (message "%d TODO entries found"
4111 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
4112
4113 (defun org-deadline ()
4114 "Insert the DEADLINE: string to make a deadline.
4115 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4116 to modify it to the correct date."
4117 (interactive)
4118 (insert
4119 org-deadline-string " "
4120 (format-time-string (car org-time-stamp-formats)
4121 (org-read-date nil 'to-time)))
4122 (message "%s" (substitute-command-keys
4123 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
4124
4125 (defun org-schedule ()
4126 "Insert the SCHEDULED: string to schedule a TODO item.
4127 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4128 to modify it to the correct date."
4129 (interactive)
4130 (insert
4131 org-scheduled-string " "
4132 (format-time-string (car org-time-stamp-formats)
4133 (org-read-date nil 'to-time)))
4134 (message "%s" (substitute-command-keys
4135 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
4136
4137
4138 (defun org-occur (regexp &optional callback)
4139 "Make a compact tree which shows all matches of REGEXP.
4140 The tree will show the lines where the regexp matches, and all higher
4141 headlines above the match. It will also show the heading after the match,
4142 to make sure editing the matching entry is easy.
4143 If CALLBACK is non-nil, it is a function which is called to confirm
4144 that the match should indeed be shown."
4145 (interactive "sRegexp: ")
4146 (org-remove-occur-highlights nil nil t)
4147 (setq regexp (org-check-occur-regexp regexp))
4148 (let ((cnt 0))
4149 (save-excursion
4150 (goto-char (point-min))
4151 (hide-sublevels 1)
4152 (while (re-search-forward regexp nil t)
4153 (when (or (not callback)
4154 (save-match-data (funcall callback)))
4155 (setq cnt (1+ cnt))
4156 (org-highlight-new-match (match-beginning 0) (match-end 0))
4157 (org-show-hierarchy-above))))
4158 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
4159 nil 'local)
4160 (run-hooks 'org-occur-hook)
4161 (if (interactive-p)
4162 (message "%d match(es) for regexp %s" cnt regexp))
4163 cnt))
4164
4165 (defun org-show-hierarchy-above ()
4166 "Make sure point and the headings hierarchy above is visible."
4167 (catch 'exit
4168 (if (org-on-heading-p t)
4169 (org-flag-heading nil) ; only show the heading
4170 (and (or (org-invisible-p) (org-invisible-p2))
4171 (org-show-hidden-entry))) ; show entire entry
4172 (save-excursion
4173 (and org-show-following-heading
4174 (outline-next-heading)
4175 (org-flag-heading nil))) ; show the next heading
4176 (when org-show-hierarchy-above
4177 (save-excursion ; show all higher headings
4178 (while (and (condition-case nil
4179 (progn (org-up-heading-all 1) t)
4180 (error nil))
4181 (not (bobp)))
4182 (org-flag-heading nil))))))
4183
4184 ;; Overlay compatibility functions
4185 (defun org-make-overlay (beg end &optional buffer)
4186 (if (featurep 'xemacs)
4187 (make-extent beg end buffer)
4188 (make-overlay beg end buffer)))
4189 (defun org-delete-overlay (ovl)
4190 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4191 (defun org-detatch-overlay (ovl)
4192 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4193 (defun org-move-overlay (ovl beg end &optional buffer)
4194 (if (featurep 'xemacs)
4195 (set-extent-endpoints ovl beg end buffer)
4196 (move-overlay ovl beg end buffer)))
4197 (defun org-overlay-put (ovl prop value)
4198 (if (featurep 'xemacs)
4199 (set-extent-property ovl prop value)
4200 (overlay-put ovl prop value)))
4201
4202 (defvar org-occur-highlights nil)
4203 (defun org-highlight-new-match (beg end)
4204 "Highlight from BEG to END and mark the highlight is an occur headline."
4205 (let ((ov (org-make-overlay beg end)))
4206 (org-overlay-put ov 'face 'secondary-selection)
4207 (push ov org-occur-highlights)))
4208
4209 (defun org-remove-occur-highlights (&optional beg end noremove)
4210 "Remove the occur highlights from the buffer.
4211 BEG and END are ignored. If NOREMOVE is nil, remove this function
4212 from the `before-change-functions' in the current buffer."
4213 (interactive)
4214 (mapc 'org-delete-overlay org-occur-highlights)
4215 (setq org-occur-highlights nil)
4216 (unless noremove
4217 (remove-hook 'before-change-functions
4218 'org-remove-occur-highlights 'local)))
4219
4220 ;;; Priorities
4221
4222 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
4223 "Regular expression matching the priority indicator.")
4224
4225 (defvar org-remove-priority-next-time nil)
4226
4227 (defun org-priority-up ()
4228 "Increase the priority of the current item."
4229 (interactive)
4230 (org-priority 'up))
4231
4232 (defun org-priority-down ()
4233 "Decrease the priority of the current item."
4234 (interactive)
4235 (org-priority 'down))
4236
4237 (defun org-priority (&optional action)
4238 "Change the priority of an item by ARG.
4239 ACTION can be set, up, or down."
4240 (interactive)
4241 (setq action (or action 'set))
4242 (let (current new news have remove)
4243 (save-excursion
4244 (org-back-to-heading)
4245 (if (looking-at org-priority-regexp)
4246 (setq current (string-to-char (match-string 2))
4247 have t)
4248 (setq current org-default-priority))
4249 (cond
4250 ((eq action 'set)
4251 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
4252 (setq new (read-char-exclusive))
4253 (cond ((equal new ?\ ) (setq remove t))
4254 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
4255 (error "Priority must be between `%c' and `%c'"
4256 ?A org-lowest-priority))))
4257 ((eq action 'up)
4258 (setq new (1- current)))
4259 ((eq action 'down)
4260 (setq new (1+ current)))
4261 (t (error "Invalid action")))
4262 (setq new (min (max ?A (upcase new)) org-lowest-priority))
4263 (setq news (format "%c" new))
4264 (if have
4265 (if remove
4266 (replace-match "" t t nil 1)
4267 (replace-match news t t nil 2))
4268 (if remove
4269 (error "No priority cookie found in line")
4270 (looking-at org-todo-line-regexp)
4271 (if (match-end 2)
4272 (progn
4273 (goto-char (match-end 2))
4274 (insert " [#" news "]"))
4275 (goto-char (match-beginning 3))
4276 (insert "[#" news "] ")))))
4277 (if remove
4278 (message "Priority removed")
4279 (message "Priority of current item set to %s" news))))
4280
4281
4282 (defun org-get-priority (s)
4283 "Find priority cookie and return priority."
4284 (save-match-data
4285 (if (not (string-match org-priority-regexp s))
4286 (* 1000 (- org-lowest-priority org-default-priority))
4287 (* 1000 (- org-lowest-priority
4288 (string-to-char (match-string 2 s)))))))
4289
4290 ;;; Timestamps
4291
4292 (defvar org-last-changed-timestamp nil)
4293
4294 (defun org-time-stamp (arg)
4295 "Prompt for a date/time and insert a time stamp.
4296 If the user specifies a time like HH:MM, or if this command is called
4297 with a prefix argument, the time stamp will contain date and time.
4298 Otherwise, only the date will be included. All parts of a date not
4299 specified by the user will be filled in from the current date/time.
4300 So if you press just return without typing anything, the time stamp
4301 will represent the current date/time. If there is already a timestamp
4302 at the cursor, it will be modified."
4303 (interactive "P")
4304 (let ((fmt (if arg (cdr org-time-stamp-formats)
4305 (car org-time-stamp-formats)))
4306 (org-time-was-given nil)
4307 time)
4308 (cond
4309 ((and (org-at-timestamp-p)
4310 (eq last-command 'org-time-stamp)
4311 (eq this-command 'org-time-stamp))
4312 (insert "--")
4313 (setq time (let ((this-command this-command))
4314 (org-read-date arg 'totime)))
4315 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4316 (insert (format-time-string fmt time)))
4317 ((org-at-timestamp-p)
4318 (setq time (let ((this-command this-command))
4319 (org-read-date arg 'totime)))
4320 (and (org-at-timestamp-p) (replace-match
4321 (setq org-last-changed-timestamp
4322 (format-time-string fmt time))
4323 t t))
4324 (message "Timestamp updated"))
4325 (t
4326 (setq time (let ((this-command this-command))
4327 (org-read-date arg 'totime)))
4328 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4329 (insert (format-time-string fmt time))))))
4330
4331 (defun org-time-stamp-inactive (&optional arg)
4332 "Insert an inactive time stamp.
4333 An inactive time stamp is enclosed in square brackets instead of angle
4334 brackets. It is inactive in the sense that it does not trigger agenda entries,
4335 does not link to the calendar and cannot be changed with the S-cursor keys.
4336 So these are more for recording a certain time/date."
4337 (interactive "P")
4338 (let ((fmt (if arg (cdr org-time-stamp-formats)
4339 (car org-time-stamp-formats)))
4340 (org-time-was-given nil)
4341 time)
4342 (setq time (org-read-date arg 'totime))
4343 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4344 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
4345 (insert (format-time-string fmt time))))
4346
4347 (defvar org-date-ovl (org-make-overlay 1 1))
4348 (org-overlay-put org-date-ovl 'face 'org-warning)
4349 (org-detatch-overlay org-date-ovl)
4350
4351 (defun org-read-date (&optional with-time to-time)
4352 "Read a date and make things smooth for the user.
4353 The prompt will suggest to enter an ISO date, but you can also enter anything
4354 which will at least partially be understood by `parse-time-string'.
4355 Unrecognized parts of the date will default to the current day, month, year,
4356 hour and minute. For example,
4357 3-2-5 --> 2003-02-05
4358 feb 15 --> currentyear-02-15
4359 sep 12 9 --> 2009-09-12
4360 12:45 --> today 12:45
4361 22 sept 0:34 --> currentyear-09-22 0:34
4362 12 --> currentyear-currentmonth-12
4363 Fri --> nearest Friday (today or later)
4364 etc.
4365 The function understands only English month and weekday abbreviations,
4366 but this can be configured with the variables `parse-time-months' and
4367 `parse-time-weekdays'.
4368
4369 While prompting, a calendar is popped up - you can also select the
4370 date with the mouse (button 1). The calendar shows a period of three
4371 months. To scroll it to other months, use the keys `>' and `<'.
4372 If you don't like the calendar, turn it off with
4373 \(setq org-popup-calendar-for-date-prompt nil)
4374
4375 With optional argument TO-TIME, the date will immediately be converted
4376 to an internal time.
4377 With an optional argument WITH-TIME, the prompt will suggest to also
4378 insert a time. Note that when WITH-TIME is not set, you can still
4379 enter a time, and this function will inform the calling routine about
4380 this change. The calling routine may then choose to change the format
4381 used to insert the time stamp into the buffer to include the time."
4382 (require 'parse-time)
4383 (let* ((org-time-stamp-rounding-minutes
4384 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
4385 (ct (org-current-time))
4386 (default-time
4387 ;; Default time is either today, or, when entering a range,
4388 ;; the range start.
4389 (if (save-excursion
4390 (re-search-backward
4391 (concat org-ts-regexp "--\\=") ; FIXME: exactly two minuses?
4392 (- (point) 20) t))
4393 (apply
4394 'encode-time
4395 (mapcar (lambda(x) (or x 0))
4396 (parse-time-string (match-string 1))))
4397 ct))
4398 (calendar-move-hook nil)
4399 (view-diary-entries-initially nil)
4400 (timestr (format-time-string
4401 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
4402 (prompt (format "YYYY-MM-DD [%s]: " timestr))
4403 ans ans1 ans2
4404 second minute hour day month year tl wday wday1)
4405
4406 (if org-popup-calendar-for-date-prompt
4407 (save-excursion
4408 (save-window-excursion
4409 (calendar)
4410 (calendar-forward-day (- (time-to-days default-time)
4411 (calendar-absolute-from-gregorian
4412 (calendar-current-date))))
4413 (org-eval-in-calendar nil)
4414 (let* ((old-map (current-local-map))
4415 (map (copy-keymap calendar-mode-map))
4416 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
4417 (define-key map (kbd "RET") 'org-calendar-select)
4418 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
4419 'org-calendar-select-mouse)
4420 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
4421 'org-calendar-select-mouse)
4422 (define-key minibuffer-local-map [(meta shift left)]
4423 (lambda () (interactive)
4424 (org-eval-in-calendar '(calendar-backward-month 1))))
4425 (define-key minibuffer-local-map [(meta shift right)]
4426 (lambda () (interactive)
4427 (org-eval-in-calendar '(calendar-forward-month 1))))
4428 (define-key minibuffer-local-map [(shift up)]
4429 (lambda () (interactive)
4430 (org-eval-in-calendar '(calendar-backward-week 1))))
4431 (define-key minibuffer-local-map [(shift down)]
4432 (lambda () (interactive)
4433 (org-eval-in-calendar '(calendar-forward-week 1))))
4434 (define-key minibuffer-local-map [(shift left)]
4435 (lambda () (interactive)
4436 (org-eval-in-calendar '(calendar-backward-day 1))))
4437 (define-key minibuffer-local-map [(shift right)]
4438 (lambda () (interactive)
4439 (org-eval-in-calendar '(calendar-forward-day 1))))
4440 (define-key minibuffer-local-map ">"
4441 (lambda () (interactive)
4442 (org-eval-in-calendar '(scroll-calendar-left 1))))
4443 (define-key minibuffer-local-map "<"
4444 (lambda () (interactive)
4445 (org-eval-in-calendar '(scroll-calendar-right 1))))
4446 (unwind-protect
4447 (progn
4448 (use-local-map map)
4449 (setq ans (read-string prompt "" nil nil))
4450 (if (not (string-match "\\S-" ans)) (setq ans nil))
4451 (setq ans (or ans1 ans ans2)))
4452 (use-local-map old-map)))))
4453 ;; Naked prompt only
4454 (setq ans (read-string prompt "" nil timestr)))
4455 (org-detatch-overlay org-date-ovl)
4456
4457 (if (string-match
4458 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
4459 (progn
4460 (setq year (if (match-end 2)
4461 (string-to-number (match-string 2 ans))
4462 (string-to-number (format-time-string "%Y")))
4463 month (string-to-number (match-string 3 ans))
4464 day (string-to-number (match-string 4 ans)))
4465 (if (< year 100) (setq year (+ 2000 year)))
4466 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
4467 t nil ans))))
4468 (setq tl (parse-time-string ans)
4469 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
4470 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
4471 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
4472 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
4473 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
4474 second (or (nth 0 tl) 0)
4475 wday (nth 6 tl))
4476 (when (and wday (not (nth 3 tl)))
4477 ;; Weekday was given, but no day, so pick that day in the week
4478 ;; on or after the derived date.
4479 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
4480 (unless (equal wday wday1)
4481 (setq day (+ day (% (- wday wday1 -7) 7)))))
4482 (if (and (boundp 'org-time-was-given)
4483 (nth 2 tl))
4484 (setq org-time-was-given t))
4485 (if (< year 100) (setq year (+ 2000 year)))
4486 (if to-time
4487 (encode-time second minute hour day month year)
4488 (if (or (nth 1 tl) (nth 2 tl))
4489 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
4490 (format "%04d-%02d-%02d" year month day)))))
4491
4492 (defun org-eval-in-calendar (form)
4493 "Eval FORM in the calendar window and return to current window.
4494 Also, store the cursor date in variable ans2."
4495 (let ((sw (selected-window)))
4496 (select-window (get-buffer-window "*Calendar*"))
4497 (eval form)
4498 (when (calendar-cursor-to-date)
4499 (let* ((date (calendar-cursor-to-date))
4500 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4501 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4502 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4503 (select-window sw)))
4504
4505 (defun org-calendar-select ()
4506 "Return to `org-read-date' with the date currently selected.
4507 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4508 (interactive)
4509 (when (calendar-cursor-to-date)
4510 (let* ((date (calendar-cursor-to-date))
4511 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4512 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4513 (if (active-minibuffer-window) (exit-minibuffer))))
4514
4515 (defun org-calendar-select-mouse (ev)
4516 "Return to `org-read-date' with the date currently selected.
4517 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4518 (interactive "e")
4519 (mouse-set-point ev)
4520 (when (calendar-cursor-to-date)
4521 (let* ((date (calendar-cursor-to-date))
4522 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4523 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4524 (if (active-minibuffer-window) (exit-minibuffer))))
4525
4526 (defun org-check-deadlines (ndays)
4527 "Check if there are any deadlines due or past due.
4528 A deadline is considered due if it happens within `org-deadline-warning-days'
4529 days from today's date. If the deadline appears in an entry marked DONE,
4530 it is not shown. The prefix arg NDAYS can be used to test that many
4531 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4532 (interactive "P")
4533 (let* ((org-warn-days
4534 (cond
4535 ((equal ndays '(4)) 100000)
4536 (ndays (prefix-numeric-value ndays))
4537 (t org-deadline-warning-days)))
4538 (case-fold-search nil)
4539 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4540 (callback
4541 (lambda ()
4542 (and (let ((d1 (time-to-days (current-time)))
4543 (d2 (time-to-days
4544 (org-time-string-to-time (match-string 1)))))
4545 (< (- d2 d1) org-warn-days))
4546 (not (org-entry-is-done-p))))))
4547 (message "%d deadlines past-due or due within %d days"
4548 (org-occur regexp callback)
4549 org-warn-days)))
4550
4551 (defun org-evaluate-time-range (&optional to-buffer)
4552 "Evaluate a time range by computing the difference between start and end.
4553 Normally the result is just printed in the echo area, but with prefix arg
4554 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4555 If the time range is actually in a table, the result is inserted into the
4556 next column.
4557 For time difference computation, a year is assumed to be exactly 365
4558 days in order to avoid rounding problems."
4559 (interactive "P")
4560 (save-excursion
4561 (unless (org-at-date-range-p)
4562 (goto-char (point-at-bol))
4563 (re-search-forward org-tr-regexp (point-at-eol) t))
4564 (if (not (org-at-date-range-p))
4565 (error "Not at a time-stamp range, and none found in current line")))
4566 (let* ((ts1 (match-string 1))
4567 (ts2 (match-string 2))
4568 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4569 (match-end (match-end 0))
4570 (time1 (org-time-string-to-time ts1))
4571 (time2 (org-time-string-to-time ts2))
4572 (t1 (time-to-seconds time1))
4573 (t2 (time-to-seconds time2))
4574 (diff (abs (- t2 t1)))
4575 (negative (< (- t2 t1) 0))
4576 ;; (ys (floor (* 365 24 60 60)))
4577 (ds (* 24 60 60))
4578 (hs (* 60 60))
4579 (fy "%dy %dd %02d:%02d")
4580 (fy1 "%dy %dd")
4581 (fd "%dd %02d:%02d")
4582 (fd1 "%dd")
4583 (fh "%02d:%02d")
4584 y d h m align)
4585 (if havetime
4586 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4587 y 0
4588 d (floor (/ diff ds)) diff (mod diff ds)
4589 h (floor (/ diff hs)) diff (mod diff hs)
4590 m (floor (/ diff 60)))
4591 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4592 y 0
4593 d (floor (+ (/ diff ds) 0.5))
4594 h 0 m 0))
4595 (if (not to-buffer)
4596 (message (org-make-tdiff-string y d h m))
4597 (when (org-at-table-p)
4598 (goto-char match-end)
4599 (setq align t)
4600 (and (looking-at " *|") (goto-char (match-end 0))))
4601 (if (looking-at
4602 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4603 (replace-match ""))
4604 (if negative (insert " -"))
4605 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4606 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4607 (insert " " (format fh h m))))
4608 (if align (org-table-align))
4609 (message "Time difference inserted"))))
4610
4611 (defun org-make-tdiff-string (y d h m)
4612 (let ((fmt "")
4613 (l nil))
4614 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4615 l (push y l)))
4616 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4617 l (push d l)))
4618 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4619 l (push h l)))
4620 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4621 l (push m l)))
4622 (apply 'format fmt (nreverse l))))
4623
4624 (defun org-time-string-to-time (s)
4625 (apply 'encode-time (org-parse-time-string s)))
4626
4627 (defun org-parse-time-string (s &optional nodefault)
4628 "Parse the standard Org-mode time string.
4629 This should be a lot faster than the normal `parse-time-string'.
4630 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4631 hour and minute fields will be nil if not given."
4632 (if (string-match org-ts-regexp1 s)
4633 (list 0
4634 (if (or (match-beginning 8) (not nodefault))
4635 (string-to-number (or (match-string 8 s) "0")))
4636 (if (or (match-beginning 7) (not nodefault))
4637 (string-to-number (or (match-string 7 s) "0")))
4638 (string-to-number (match-string 4 s))
4639 (string-to-number (match-string 3 s))
4640 (string-to-number (match-string 2 s))
4641 nil nil nil)
4642 (make-list 9 0)))
4643
4644 (defun org-timestamp-up (&optional arg)
4645 "Increase the date item at the cursor by one.
4646 If the cursor is on the year, change the year. If it is on the month or
4647 the day, change that.
4648 With prefix ARG, change by that many units."
4649 (interactive "p")
4650 (org-timestamp-change (prefix-numeric-value arg)))
4651
4652 (defun org-timestamp-down (&optional arg)
4653 "Decrease the date item at the cursor by one.
4654 If the cursor is on the year, change the year. If it is on the month or
4655 the day, change that.
4656 With prefix ARG, change by that many units."
4657 (interactive "p")
4658 (org-timestamp-change (- (prefix-numeric-value arg))))
4659
4660 (defun org-timestamp-up-day (&optional arg)
4661 "Increase the date in the time stamp by one day.
4662 With prefix ARG, change that many days."
4663 (interactive "p")
4664 (if (and (not (org-at-timestamp-p))
4665 (org-on-heading-p))
4666 (org-todo 'up)
4667 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4668
4669 (defun org-timestamp-down-day (&optional arg)
4670 "Decrease the date in the time stamp by one day.
4671 With prefix ARG, change that many days."
4672 (interactive "p")
4673 (if (and (not (org-at-timestamp-p))
4674 (org-on-heading-p))
4675 (org-todo 'down)
4676 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4677
4678 (defsubst org-pos-in-match-range (pos n)
4679 (and (match-beginning n)
4680 (<= (match-beginning n) pos)
4681 (>= (match-end n) pos)))
4682
4683 (defun org-at-timestamp-p ()
4684 "Determine if the cursor is in or at a timestamp."
4685 (interactive)
4686 (let* ((tsr org-ts-regexp2)
4687 (pos (point))
4688 (ans (or (looking-at tsr)
4689 (save-excursion
4690 (skip-chars-backward "^<\n\r\t")
4691 (if (> (point) 1) (backward-char 1))
4692 (and (looking-at tsr)
4693 (> (- (match-end 0) pos) -1))))))
4694 (and (boundp 'org-ts-what)
4695 (setq org-ts-what
4696 (cond
4697 ((org-pos-in-match-range pos 2) 'year)
4698 ((org-pos-in-match-range pos 3) 'month)
4699 ((org-pos-in-match-range pos 7) 'hour)
4700 ((org-pos-in-match-range pos 8) 'minute)
4701 ((or (org-pos-in-match-range pos 4)
4702 (org-pos-in-match-range pos 5)) 'day)
4703 (t 'day))))
4704 ans))
4705
4706 (defun org-timestamp-change (n &optional what)
4707 "Change the date in the time stamp at point.
4708 The date will be changed by N times WHAT. WHAT can be `day', `month',
4709 `year', `minute', `second'. If WHAT is not given, the cursor position
4710 in the timestamp determines what will be changed."
4711 (let ((fmt (car org-time-stamp-formats))
4712 org-ts-what
4713 (pos (point))
4714 ts time time0)
4715 (if (not (org-at-timestamp-p))
4716 (error "Not at a timestamp"))
4717 (setq org-ts-what (or what org-ts-what))
4718 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4719 (- (match-end 0) (match-beginning 0))))
4720 1)
4721 (cdr org-time-stamp-formats)
4722 (car org-time-stamp-formats)))
4723 (setq ts (match-string 0))
4724 (replace-match "")
4725 (setq time0 (org-parse-time-string ts))
4726 (setq time
4727 (apply 'encode-time
4728 (append
4729 (list (or (car time0) 0))
4730 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4731 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4732 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4733 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4734 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4735 (nthcdr 6 time0))))
4736 (if (eq what 'calendar)
4737 (let ((cal-date
4738 (save-excursion
4739 (save-match-data
4740 (set-buffer "*Calendar*")
4741 (calendar-cursor-to-date)))))
4742 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4743 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4744 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4745 (setcar time0 (or (car time0) 0))
4746 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4747 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4748 (setq time (apply 'encode-time time0))))
4749 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4750 (goto-char pos)
4751 ;; Try to recenter the calendar window, if any
4752 (if (and org-calendar-follow-timestamp-change
4753 (get-buffer-window "*Calendar*" t)
4754 (memq org-ts-what '(day month year)))
4755 (org-recenter-calendar (time-to-days time)))))
4756
4757 (defun org-recenter-calendar (date)
4758 "If the calendar is visible, recenter it to DATE."
4759 (let* ((win (selected-window))
4760 (cwin (get-buffer-window "*Calendar*" t))
4761 (calendar-move-hook nil))
4762 (when cwin
4763 (select-window cwin)
4764 (calendar-goto-date (if (listp date) date
4765 (calendar-gregorian-from-absolute date)))
4766 (select-window win))))
4767
4768 (defun org-goto-calendar (&optional arg)
4769 "Go to the Emacs calendar at the current date.
4770 If there is a time stamp in the current line, go to that date.
4771 A prefix ARG can be used to force the current date."
4772 (interactive "P")
4773 (let ((tsr org-ts-regexp) diff
4774 (calendar-move-hook nil)
4775 (view-diary-entries-initially nil))
4776 (if (or (org-at-timestamp-p)
4777 (save-excursion
4778 (beginning-of-line 1)
4779 (looking-at (concat ".*" tsr))))
4780 (let ((d1 (time-to-days (current-time)))
4781 (d2 (time-to-days
4782 (org-time-string-to-time (match-string 1)))))
4783 (setq diff (- d2 d1))))
4784 (calendar)
4785 (calendar-goto-today)
4786 (if (and diff (not arg)) (calendar-forward-day diff))))
4787
4788 (defun org-date-from-calendar ()
4789 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4790 If there is already a time stamp at the cursor position, update it."
4791 (interactive)
4792 (org-timestamp-change 0 'calendar))
4793
4794 ;;; Agenda, and Diary Integration
4795
4796 ;;; Define the mode
4797
4798 (defvar org-agenda-mode-map (make-sparse-keymap)
4799 "Keymap for `org-agenda-mode'.")
4800
4801 (defvar org-agenda-menu) ; defined later in this file.
4802 (defvar org-agenda-follow-mode nil)
4803 (defvar org-agenda-show-log nil)
4804 (defvar org-agenda-buffer-name "*Org Agenda*")
4805 (defvar org-agenda-redo-command nil)
4806 (defvar org-agenda-mode-hook nil)
4807 (defvar org-agenda-type nil)
4808 (defvar org-agenda-force-single-file nil)
4809
4810 ;;;###autoload
4811 (defun org-agenda-mode ()
4812 "Mode for time-sorted view on action items in Org-mode files.
4813
4814 The following commands are available:
4815
4816 \\{org-agenda-mode-map}"
4817 (interactive)
4818 (kill-all-local-variables)
4819 (setq major-mode 'org-agenda-mode)
4820 (setq mode-name "Org-Agenda")
4821 (use-local-map org-agenda-mode-map)
4822 (easy-menu-add org-agenda-menu)
4823 (if org-startup-truncated (setq truncate-lines t))
4824 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4825 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4826 (unless org-agenda-keep-modes
4827 (setq org-agenda-follow-mode nil
4828 org-agenda-show-log nil))
4829 (easy-menu-change
4830 '("Agenda") "Agenda Files"
4831 (append
4832 (list
4833 (vector
4834 (if (get 'org-agenda-files 'org-restrict)
4835 "Restricted to single file"
4836 "Edit File List")
4837 '(org-edit-agenda-file-list)
4838 (not (get 'org-agenda-files 'org-restrict)))
4839 "--")
4840 (mapcar 'org-file-menu-entry (org-agenda-files))))
4841 (org-agenda-set-mode-name)
4842 (apply
4843 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4844 (list 'org-agenda-mode-hook)))
4845
4846 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4847 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
4848 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4849 (define-key org-agenda-mode-map " " 'org-agenda-show)
4850 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4851 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4852 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4853 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4854 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4855 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4856 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4857 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4858 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4859 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4860 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4861 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4862
4863 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4864 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4865 (while l (define-key org-agenda-mode-map
4866 (int-to-string (pop l)) 'digit-argument)))
4867
4868 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4869 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4870 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4871 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4872 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4873 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4874 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4875 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4876 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4877 (define-key org-agenda-mode-map "n" 'next-line)
4878 (define-key org-agenda-mode-map "p" 'previous-line)
4879 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4880 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4881 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4882 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4883 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4884 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4885 (eval-after-load "calendar"
4886 '(define-key calendar-mode-map org-calendar-to-agenda-key
4887 'org-calendar-goto-agenda))
4888 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4889 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4890 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4891 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4892 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4893 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4894 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4895 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4896 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4897 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4898 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4899 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4900 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4901 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4902 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4903 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4904 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4905 "Local keymap for agenda entries from Org-mode.")
4906
4907 (define-key org-agenda-keymap
4908 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4909 (define-key org-agenda-keymap
4910 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4911 (when org-agenda-mouse-1-follows-link
4912 (define-key org-agenda-keymap [follow-link] 'mouse-face))
4913 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4914 '("Agenda"
4915 ("Agenda Files")
4916 "--"
4917 ["Show" org-agenda-show t]
4918 ["Go To (other window)" org-agenda-goto t]
4919 ["Go To (one window)" org-agenda-switch-to t]
4920 ["Follow Mode" org-agenda-follow-mode
4921 :style toggle :selected org-agenda-follow-mode :active t]
4922 "--"
4923 ["Cycle TODO" org-agenda-todo t]
4924 ("Tags"
4925 ["Show all Tags" org-agenda-show-tags t]
4926 ["Set Tags" org-agenda-set-tags t])
4927 ("Reschedule"
4928 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4929 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4930 "--"
4931 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4932 ("Priority"
4933 ["Set Priority" org-agenda-priority t]
4934 ["Increase Priority" org-agenda-priority-up t]
4935 ["Decrease Priority" org-agenda-priority-down t]
4936 ["Show Priority" org-agenda-show-priority t])
4937 "--"
4938 ;; ["New agenda command" org-agenda t]
4939 ["Rebuild buffer" org-agenda-redo t]
4940 "--"
4941 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4942 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4943 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4944 "--"
4945 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4946 :style radio :selected (equal org-agenda-ndays 1)]
4947 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4948 :style radio :selected (equal org-agenda-ndays 7)]
4949 "--"
4950 ["Show Logbook entries" org-agenda-log-mode
4951 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4952 ["Include Diary" org-agenda-toggle-diary
4953 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4954 ["Use Time Grid" org-agenda-toggle-time-grid
4955 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4956 "--"
4957 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4958 ("Calendar Commands"
4959 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4960 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4961 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4962 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4963 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4964 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4965 "--"
4966 ["Quit" org-agenda-quit t]
4967 ["Exit and Release Buffers" org-agenda-exit t]
4968 ))
4969
4970 ;;;###autoload
4971 (defun org-agenda (arg)
4972 "Dispatch agenda commands to collect entries to the agenda buffer.
4973 Prompts for a character to select a command. Any prefix arg will be passed
4974 on to the selected command. The default selections are:
4975
4976 a Call `org-agenda' to display the agenda for the current day or week.
4977 t Call `org-todo-list' to display the global todo list.
4978 T Call `org-todo-list' to display the global todo list, select only
4979 entries with a specific TODO keyword (the user gets a prompt).
4980 m Call `org-tags-view' to display headlines with tags matching
4981 a condition (the user is prompted for the condition).
4982 M Like `m', but select only TODO entries, no ordinary headlines.
4983
4984 More commands can be added by configuring the variable
4985 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4986 searches can be pre-defined in this way.
4987
4988 If the current buffer is in Org-mode and visiting a file, you can also
4989 first press `1' to indicate that the agenda should be temporarily (until the
4990 next use of \\[org-agenda]) restricted to the current file."
4991 (interactive "P")
4992 (catch 'exit
4993 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
4994 (custom org-agenda-custom-commands)
4995 c entry key type string)
4996 (put 'org-agenda-files 'org-restrict nil)
4997 (save-window-excursion
4998 (delete-other-windows)
4999 (switch-to-buffer-other-window " *Agenda Commands*")
5000 (erase-buffer)
5001 (insert
5002 "Press key for an agenda command:
5003 --------------------------------
5004 a Agenda for current week or day
5005 t List of all TODO entries T Entries with special TODO kwd
5006 m Match a TAGS query M Like m, but only TODO entries
5007 C Configure your own agenda commands")
5008 (while (setq entry (pop custom))
5009 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
5010 (insert (format "\n%-4s%-14s: %s"
5011 key
5012 (cond
5013 ((eq type 'tags) "Tags query")
5014 ((eq type 'todo) "TODO keyword")
5015 ((eq type 'tags-tree) "Tags tree")
5016 ((eq type 'todo-tree) "TODO kwd tree")
5017 ((eq type 'occur-tree) "Occur tree")
5018 (t "???"))
5019 (org-add-props string nil 'face 'org-warning))))
5020 (goto-char (point-min))
5021 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
5022 (message "Press key for agenda command%s"
5023 (if restrict-ok ", or [1] to restrict to current file" ""))
5024 (setq c (read-char-exclusive))
5025 (message "")
5026 (when (equal c ?1)
5027 (if restrict-ok
5028 (put 'org-agenda-files 'org-restrict (list buffer-file-name))
5029 (error "Cannot restrict agenda to current buffer"))
5030 (message "Press key for agenda command%s"
5031 (if restrict-ok " (restricted to current file)" ""))
5032 (setq c (read-char-exclusive))
5033 (message "")))
5034 (require 'calendar) ; FIXME: can we avoid this for some commands?
5035 ;; For example the todo list should not need it (but does...)
5036 (cond
5037 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
5038 ((equal c ?a) (call-interactively 'org-agenda-list))
5039 ((equal c ?t) (call-interactively 'org-todo-list))
5040 ((equal c ?T)
5041 (setq current-prefix-arg (or arg '(4)))
5042 (call-interactively 'org-todo-list))
5043 ((equal c ?m) (call-interactively 'org-tags-view))
5044 ((equal c ?M)
5045 (setq current-prefix-arg (or arg '(4)))
5046 (call-interactively 'org-tags-view))
5047 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
5048 (setq type (nth 1 entry) string (nth 2 entry))
5049 (cond
5050 ((eq type 'tags)
5051 (org-tags-view current-prefix-arg string))
5052 ((eq type 'todo)
5053 (org-todo-list string))
5054 ((eq type 'tags-tree)
5055 (org-check-for-org-mode)
5056 (org-tags-sparse-tree current-prefix-arg string))
5057 ((eq type 'todo-tree)
5058 (org-check-for-org-mode)
5059 (org-occur (concat "^" outline-regexp "[ \t]*"
5060 (regexp-quote string) "\\>")))
5061 ((eq type 'occur-tree)
5062 (org-check-for-org-mode)
5063 (org-occur string))
5064 (t (error "Invalid custom agenda command type %s" type))))
5065 (t (error "Invalid key"))))))
5066
5067 (defun org-check-for-org-mode ()
5068 "Make sure current buffer is in org-mode. Error if not."
5069 (or (eq major-mode 'org-mode)
5070 (error "Cannot execute org-mode agenda command on buffer in %s."
5071 major-mode)))
5072
5073 (defun org-fit-agenda-window ()
5074 "Fit the window to the buffer size."
5075 (and org-fit-agenda-window
5076 (fboundp 'fit-window-to-buffer)
5077 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
5078 (/ (frame-height) 2))))
5079
5080 (defun org-agenda-files (&optional unrestricted)
5081 "Get the list of agenda files.
5082 Optional UNRESTRICTED means return the full list even if a restriction
5083 is currently in place."
5084 (cond
5085 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
5086 ((stringp org-agenda-files) (org-read-agenda-file-list))
5087 ((listp org-agenda-files) org-agenda-files)
5088 (t (error "Invalid value of `org-agenda-files'"))))
5089
5090 (defvar org-window-configuration)
5091
5092 (defun org-edit-agenda-file-list ()
5093 "Edit the list of agenda files.
5094 Depending on setup, this either uses customize to edit the variable
5095 `org-agenda-files', or it visits the file that is holding the list. In the
5096 latter case, the buffer is set up in a way that saving it automatically kills
5097 the buffer and restores the previous window configuration."
5098 (interactive)
5099 (if (stringp org-agenda-files)
5100 (let ((cw (current-window-configuration)))
5101 (find-file org-agenda-files)
5102 (set (make-local-variable 'org-window-configuration) cw)
5103 (org-add-hook 'after-save-hook
5104 (lambda ()
5105 (set-window-configuration
5106 (prog1 org-window-configuration
5107 (kill-buffer (current-buffer))))
5108 (org-install-agenda-files-menu)
5109 (message "New agenda file list installed"))
5110 nil 'local)
5111 (message (substitute-command-keys
5112 "Edit list and finish with \\[save-buffer]")))
5113 (customize-variable 'org-agenda-files)))
5114
5115 (defun org-store-new-agenda-file-list (list)
5116 "Set new value for the agenda file list and save it correcly."
5117 (if (stringp org-agenda-files)
5118 (let ((f org-agenda-files) b)
5119 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
5120 (with-temp-file f
5121 (insert (mapconcat 'identity list "\n") "\n")))
5122 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5123 (setq org-agenda-files list)
5124 (customize-save-variable 'org-agenda-files org-agenda-files))))
5125
5126 (defun org-read-agenda-file-list ()
5127 "Read the list of agenda files from a file."
5128 (when (stringp org-agenda-files)
5129 (with-temp-buffer
5130 (insert-file-contents org-agenda-files)
5131 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
5132
5133 (defvar org-agenda-markers nil
5134 "List of all currently active markers created by `org-agenda'.")
5135 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
5136 "Creation time of the last agenda marker.")
5137
5138 (defun org-agenda-new-marker (&optional pos)
5139 "Return a new agenda marker.
5140 Org-mode keeps a list of these markers and resets them when they are
5141 no longer in use."
5142 (let ((m (copy-marker (or pos (point)))))
5143 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
5144 (push m org-agenda-markers)
5145 m))
5146
5147 (defun org-agenda-maybe-reset-markers (&optional force)
5148 "Reset markers created by `org-agenda'. But only if they are old enough."
5149 (if (or force
5150 (> (- (time-to-seconds (current-time))
5151 org-agenda-last-marker-time)
5152 5))
5153 (while org-agenda-markers
5154 (move-marker (pop org-agenda-markers) nil))))
5155
5156 (defvar org-agenda-new-buffers nil
5157 "Buffers created to visit agenda files.")
5158
5159 (defun org-get-agenda-file-buffer (file)
5160 "Get a buffer visiting FILE. If the buffer needs to be created, add
5161 it to the list of buffers which might be released later."
5162 (let ((buf (find-buffer-visiting file)))
5163 (if buf
5164 buf ; just return it
5165 ;; Make a new buffer and remember it
5166 (setq buf (find-file-noselect file))
5167 (if buf (push buf org-agenda-new-buffers))
5168 buf)))
5169
5170 (defun org-release-buffers (blist)
5171 "Release all buffers in list, asking the user for confirmation when needed.
5172 When a buffer is unmodified, it is just killed. When modified, it is saved
5173 \(if the user agrees) and then killed."
5174 (let (buf file)
5175 (while (setq buf (pop blist))
5176 (setq file (buffer-file-name buf))
5177 (when (and (buffer-modified-p buf)
5178 file
5179 (y-or-n-p (format "Save file %s? " file)))
5180 (with-current-buffer buf (save-buffer)))
5181 (kill-buffer buf))))
5182
5183 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
5184
5185 (defun org-timeline (&optional include-all keep-modes)
5186 "Show a time-sorted view of the entries in the current org file.
5187 Only entries with a time stamp of today or later will be listed. With
5188 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
5189 under the current date.
5190 If the buffer contains an active region, only check the region for
5191 dates."
5192 (interactive "P")
5193 (require 'calendar)
5194 (org-agenda-maybe-reset-markers 'force)
5195 (org-compile-prefix-format org-timeline-prefix-format)
5196 (let* ((dopast t)
5197 (dotodo include-all)
5198 (doclosed org-agenda-show-log)
5199 (org-agenda-keep-modes keep-modes)
5200 (entry buffer-file-name)
5201 (org-agenda-files (list buffer-file-name))
5202 (date (calendar-current-date))
5203 (win (selected-window))
5204 (pos1 (point))
5205 (beg (if (org-region-active-p) (region-beginning) (point-min)))
5206 (end (if (org-region-active-p) (region-end) (point-max)))
5207 (day-numbers (org-get-all-dates beg end 'no-ranges
5208 t doclosed)) ; always include today
5209 (today (time-to-days (current-time)))
5210 (org-respect-restriction t)
5211 (past t)
5212 args
5213 s e rtn d)
5214 (setq org-agenda-redo-command
5215 (list 'progn
5216 (list 'switch-to-buffer-other-window (current-buffer))
5217 (list 'org-timeline (list 'quote include-all) t)))
5218 (if (not dopast)
5219 ;; Remove past dates from the list of dates.
5220 (setq day-numbers (delq nil (mapcar (lambda(x)
5221 (if (>= x today) x nil))
5222 day-numbers))))
5223 (switch-to-buffer-other-window
5224 (get-buffer-create org-agenda-buffer-name))
5225 (setq buffer-read-only nil)
5226 (erase-buffer)
5227 (org-agenda-mode) (setq buffer-read-only nil)
5228 (set (make-local-variable 'org-agenda-type) 'timeline)
5229 (if doclosed (push :closed args))
5230 (push :timestamp args)
5231 (if dotodo (push :todo args))
5232 (while (setq d (pop day-numbers))
5233 (if (and (>= d today)
5234 dopast
5235 past)
5236 (progn
5237 (setq past nil)
5238 (insert (make-string 79 ?-) "\n")))
5239 (setq date (calendar-gregorian-from-absolute d))
5240 (setq s (point))
5241 (setq rtn (apply 'org-agenda-get-day-entries
5242 entry date args))
5243 (if (or rtn (equal d today))
5244 (progn
5245 (insert (calendar-day-name date) " "
5246 (number-to-string (extract-calendar-day date)) " "
5247 (calendar-month-name (extract-calendar-month date)) " "
5248 (number-to-string (extract-calendar-year date)) "\n")
5249 (put-text-property s (1- (point)) 'face
5250 'org-level-3)
5251 (if (equal d today)
5252 (put-text-property s (1- (point)) 'org-today t))
5253 (insert (org-finalize-agenda-entries rtn) "\n")
5254 (put-text-property s (1- (point)) 'day d))))
5255 (goto-char (point-min))
5256 (setq buffer-read-only t)
5257 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5258 (point-min)))
5259 (when (not org-select-timeline-window)
5260 (select-window win)
5261 (goto-char pos1))))
5262
5263 ;;;###autoload
5264 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
5265 "Produce a weekly view from all files in variable `org-agenda-files'.
5266 The view will be for the current week, but from the overview buffer you
5267 will be able to go to other weeks.
5268 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
5269 also be shown, under the current date.
5270 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
5271 on the days are also shown. See the variable `org-log-done' for how
5272 to turn on logging.
5273 START-DAY defaults to TODAY, or to the most recent match for the weekday
5274 given in `org-agenda-start-on-weekday'.
5275 NDAYS defaults to `org-agenda-ndays'."
5276 (interactive "P")
5277 (org-agenda-maybe-reset-markers 'force)
5278 (org-compile-prefix-format org-agenda-prefix-format)
5279 (require 'calendar)
5280 (let* ((org-agenda-start-on-weekday
5281 (if (or (equal ndays 1)
5282 (and (null ndays) (equal 1 org-agenda-ndays)))
5283 nil org-agenda-start-on-weekday))
5284 (org-agenda-keep-modes keep-modes)
5285 (thefiles (org-agenda-files))
5286 (files thefiles)
5287 (win (selected-window))
5288 (today (time-to-days (current-time)))
5289 (sd (or start-day today))
5290 (start (if (or (null org-agenda-start-on-weekday)
5291 (< org-agenda-ndays 7))
5292 sd
5293 (let* ((nt (calendar-day-of-week
5294 (calendar-gregorian-from-absolute sd)))
5295 (n1 org-agenda-start-on-weekday)
5296 (d (- nt n1)))
5297 (- sd (+ (if (< d 0) 7 0) d)))))
5298 (day-numbers (list start))
5299 (inhibit-redisplay t)
5300 s e rtn rtnall file date d start-pos end-pos todayp nd)
5301 (setq org-agenda-redo-command
5302 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
5303 ;; Make the list of days
5304 (setq ndays (or ndays org-agenda-ndays)
5305 nd ndays)
5306 (while (> ndays 1)
5307 (push (1+ (car day-numbers)) day-numbers)
5308 (setq ndays (1- ndays)))
5309 (setq day-numbers (nreverse day-numbers))
5310 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5311 (progn
5312 (delete-other-windows)
5313 (switch-to-buffer-other-window
5314 (get-buffer-create org-agenda-buffer-name))))
5315 (setq buffer-read-only nil)
5316 (erase-buffer)
5317 (org-agenda-mode) (setq buffer-read-only nil)
5318 (set (make-local-variable 'org-agenda-type) 'agenda)
5319 (set (make-local-variable 'starting-day) (car day-numbers))
5320 (set (make-local-variable 'include-all-loc) include-all)
5321 (when (and (or include-all org-agenda-include-all-todo)
5322 (member today day-numbers))
5323 (setq files thefiles
5324 rtnall nil)
5325 (while (setq file (pop files))
5326 (catch 'nextfile
5327 (org-check-agenda-file file)
5328 (setq date (calendar-gregorian-from-absolute today)
5329 rtn (org-agenda-get-day-entries
5330 file date :todo))
5331 (setq rtnall (append rtnall rtn))))
5332 (when rtnall
5333 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
5334 (add-text-properties (point-min) (1- (point))
5335 (list 'face 'org-level-3))
5336 (insert (org-finalize-agenda-entries rtnall) "\n")))
5337 (while (setq d (pop day-numbers))
5338 (setq date (calendar-gregorian-from-absolute d)
5339 s (point))
5340 (if (or (setq todayp (= d today))
5341 (and (not start-pos) (= d sd)))
5342 (setq start-pos (point))
5343 (if (and start-pos (not end-pos))
5344 (setq end-pos (point))))
5345 (setq files thefiles
5346 rtnall nil)
5347 (while (setq file (pop files))
5348 (catch 'nextfile
5349 (org-check-agenda-file file)
5350 (if org-agenda-show-log
5351 (setq rtn (org-agenda-get-day-entries
5352 file date
5353 :deadline :scheduled :timestamp :closed))
5354 (setq rtn (org-agenda-get-day-entries
5355 file date
5356 :deadline :scheduled :timestamp)))
5357 (setq rtnall (append rtnall rtn))))
5358 (if org-agenda-include-diary
5359 (progn
5360 (require 'diary-lib)
5361 (setq rtn (org-get-entries-from-diary date))
5362 (setq rtnall (append rtnall rtn))))
5363 (if (or rtnall org-agenda-show-all-dates)
5364 (progn
5365 (insert (format "%-9s %2d %s %4d\n"
5366 (calendar-day-name date)
5367 (extract-calendar-day date)
5368 (calendar-month-name (extract-calendar-month date))
5369 (extract-calendar-year date)))
5370 (put-text-property s (1- (point)) 'face
5371 'org-level-3)
5372 (if rtnall (insert
5373 (org-finalize-agenda-entries
5374 (org-agenda-add-time-grid-maybe
5375 rtnall nd todayp))
5376 "\n"))
5377 (put-text-property s (1- (point)) 'day d))))
5378 (goto-char (point-min))
5379 (setq buffer-read-only t)
5380 (org-fit-agenda-window)
5381 (unless (and (pos-visible-in-window-p (point-min))
5382 (pos-visible-in-window-p (point-max)))
5383 (goto-char (1- (point-max)))
5384 (recenter -1)
5385 (if (not (pos-visible-in-window-p (or start-pos 1)))
5386 (progn
5387 (goto-char (or start-pos 1))
5388 (recenter 1))))
5389 (goto-char (or start-pos 1))
5390 (if (not org-select-agenda-window) (select-window win))
5391 (message "")))
5392
5393 (defvar org-select-this-todo-keyword nil)
5394
5395 ;;;###autoload
5396 (defun org-todo-list (arg &optional keep-modes)
5397 "Show all TODO entries from all agenda file in a single list.
5398 The prefix arg can be used to select a specific TODO keyword and limit
5399 the list to these. When using \\[universal-argument], you will be prompted
5400 for a keyword. A numeric prefix directly selects the Nth keyword in
5401 `org-todo-keywords'."
5402 (interactive "P")
5403 (org-agenda-maybe-reset-markers 'force)
5404 (org-compile-prefix-format org-agenda-prefix-format)
5405 (let* ((org-agenda-keep-modes keep-modes)
5406 (today (time-to-days (current-time)))
5407 (date (calendar-gregorian-from-absolute today))
5408 (win (selected-window))
5409 (kwds org-todo-keywords)
5410 (completion-ignore-case t)
5411 (org-select-this-todo-keyword
5412 (if (stringp arg) arg
5413 (and arg (integerp arg) (> arg 0)
5414 (nth (1- arg) org-todo-keywords))))
5415 rtn rtnall files file pos)
5416 (when (equal arg '(4))
5417 (setq org-select-this-todo-keyword
5418 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
5419 nil t)))
5420 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
5421 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5422 (progn
5423 (delete-other-windows)
5424 (switch-to-buffer-other-window
5425 (get-buffer-create org-agenda-buffer-name))))
5426 (setq buffer-read-only nil)
5427 (erase-buffer)
5428 (org-agenda-mode) (setq buffer-read-only nil)
5429 (set (make-local-variable 'org-agenda-type) 'todo)
5430 (set (make-local-variable 'last-arg) arg)
5431 (set (make-local-variable 'org-todo-keywords) kwds)
5432 (set (make-local-variable 'org-agenda-redo-command)
5433 '(org-todo-list (or current-prefix-arg last-arg) t))
5434 (setq files (org-agenda-files)
5435 rtnall nil)
5436 (while (setq file (pop files))
5437 (catch 'nextfile
5438 (org-check-agenda-file file)
5439 (setq rtn (org-agenda-get-day-entries file date :todo))
5440 (setq rtnall (append rtnall rtn))))
5441 (insert "Global list of TODO items of type: ")
5442 (add-text-properties (point-min) (1- (point))
5443 (list 'face 'org-level-3))
5444 (setq pos (point))
5445 (insert (or org-select-this-todo-keyword "ALL") "\n")
5446 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
5447 (setq pos (point))
5448 (insert
5449 "Available with `N r': (0)ALL "
5450 (let ((n 0))
5451 (mapconcat (lambda (x)
5452 (format "(%d)%s" (setq n (1+ n)) x))
5453 org-todo-keywords " "))
5454 "\n")
5455 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
5456 (when rtnall
5457 (insert (org-finalize-agenda-entries rtnall) "\n"))
5458 (goto-char (point-min))
5459 (setq buffer-read-only t)
5460 (org-fit-agenda-window)
5461 (if (not org-select-agenda-window) (select-window win))))
5462
5463 (defun org-check-agenda-file (file)
5464 "Make sure FILE exists. If not, ask user what to do."
5465 (when (not (file-exists-p file))
5466 (message "non-existent file %s. [R]emove from list or [A]bort?"
5467 (abbreviate-file-name file))
5468 (let ((r (downcase (read-char-exclusive))))
5469 (cond
5470 ((equal r ?r)
5471 (org-remove-file file)
5472 (throw 'nextfile t))
5473 (t (error "Abort"))))))
5474
5475 (defun org-agenda-check-type (error &rest types)
5476 "Check if agenda buffer is of allowed type.
5477 If ERROR is non-nil, throw an error, otherwise just return nil."
5478 (if (memq org-agenda-type types)
5479 t
5480 (if error
5481 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
5482 nil)))
5483
5484 (defun org-agenda-quit ()
5485 "Exit agenda by removing the window or the buffer."
5486 (interactive)
5487 (let ((buf (current-buffer)))
5488 (if (not (one-window-p)) (delete-window))
5489 (kill-buffer buf)
5490 (org-agenda-maybe-reset-markers 'force)))
5491
5492 (defun org-agenda-exit ()
5493 "Exit agenda by removing the window or the buffer.
5494 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
5495 Org-mode buffers visited directly by the user will not be touched."
5496 (interactive)
5497 (org-release-buffers org-agenda-new-buffers)
5498 (setq org-agenda-new-buffers nil)
5499 (org-agenda-quit))
5500
5501 (defun org-agenda-redo ()
5502 "Rebuild Agenda.
5503 When this is the global TODO list, a prefix argument will be interpreted."
5504 (interactive)
5505 (message "Rebuilding agenda buffer...")
5506 (eval org-agenda-redo-command)
5507 (message "Rebuilding agenda buffer...done"))
5508
5509 (defun org-agenda-goto-today ()
5510 "Go to today."
5511 (interactive)
5512 (org-agenda-check-type t 'timeline 'agenda)
5513 (if (boundp 'starting-day)
5514 (let ((cmd (car org-agenda-redo-command))
5515 (iall (nth 1 org-agenda-redo-command))
5516 (nday (nth 3 org-agenda-redo-command))
5517 (keep (nth 4 org-agenda-redo-command)))
5518 (eval (list cmd iall nil nday keep)))
5519 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5520 (point-min)))))
5521
5522 (defun org-agenda-later (arg)
5523 "Go forward in time by `org-agenda-ndays' days.
5524 With prefix ARG, go forward that many times `org-agenda-ndays'."
5525 (interactive "p")
5526 (org-agenda-check-type t 'agenda)
5527 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5528 (+ starting-day (* arg org-agenda-ndays)) nil t))
5529
5530 (defun org-agenda-earlier (arg)
5531 "Go back in time by `org-agenda-ndays' days.
5532 With prefix ARG, go back that many times `org-agenda-ndays'."
5533 (interactive "p")
5534 (org-agenda-check-type t 'agenda)
5535 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5536 (- starting-day (* arg org-agenda-ndays)) nil t))
5537
5538 (defun org-agenda-week-view ()
5539 "Switch to weekly view for agenda."
5540 (interactive)
5541 (org-agenda-check-type t 'agenda)
5542 (setq org-agenda-ndays 7)
5543 (org-agenda-list include-all-loc
5544 (or (get-text-property (point) 'day)
5545 starting-day)
5546 nil t)
5547 (org-agenda-set-mode-name)
5548 (message "Switched to week view"))
5549
5550 (defun org-agenda-day-view ()
5551 "Switch to daily view for agenda."
5552 (interactive)
5553 (org-agenda-check-type t 'agenda)
5554 (setq org-agenda-ndays 1)
5555 (org-agenda-list include-all-loc
5556 (or (get-text-property (point) 'day)
5557 starting-day)
5558 nil t)
5559 (org-agenda-set-mode-name)
5560 (message "Switched to day view"))
5561
5562 (defun org-agenda-next-date-line (&optional arg)
5563 "Jump to the next line indicating a date in agenda buffer."
5564 (interactive "p")
5565 (org-agenda-check-type t 'agenda 'timeline)
5566 (beginning-of-line 1)
5567 (if (looking-at "^\\S-") (forward-char 1))
5568 (if (not (re-search-forward "^\\S-" nil t arg))
5569 (progn
5570 (backward-char 1)
5571 (error "No next date after this line in this buffer")))
5572 (goto-char (match-beginning 0)))
5573
5574 (defun org-agenda-previous-date-line (&optional arg)
5575 "Jump to the previous line indicating a date in agenda buffer."
5576 (interactive "p")
5577 (org-agenda-check-type t 'agenda 'timeline)
5578 (beginning-of-line 1)
5579 (if (not (re-search-backward "^\\S-" nil t arg))
5580 (error "No previous date before this line in this buffer")))
5581
5582 ;; Initialize the highlight
5583 (defvar org-hl (org-make-overlay 1 1))
5584 (org-overlay-put org-hl 'face 'highlight)
5585
5586 (defun org-highlight (begin end &optional buffer)
5587 "Highlight a region with overlay."
5588 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
5589 org-hl begin end (or buffer (current-buffer))))
5590
5591 (defun org-unhighlight ()
5592 "Detach overlay INDEX."
5593 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
5594
5595
5596 (defun org-agenda-follow-mode ()
5597 "Toggle follow mode in an agenda buffer."
5598 (interactive)
5599 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5600 (org-agenda-set-mode-name)
5601 (message "Follow mode is %s"
5602 (if org-agenda-follow-mode "on" "off")))
5603
5604 (defun org-agenda-log-mode ()
5605 "Toggle log mode in an agenda buffer."
5606 (interactive)
5607 (org-agenda-check-type t 'agenda 'timeline)
5608 (setq org-agenda-show-log (not org-agenda-show-log))
5609 (org-agenda-set-mode-name)
5610 (org-agenda-redo)
5611 (message "Log mode is %s"
5612 (if org-agenda-show-log "on" "off")))
5613
5614 (defun org-agenda-toggle-diary ()
5615 "Toggle diary inclusion in an agenda buffer."
5616 (interactive)
5617 (org-agenda-check-type t 'agenda)
5618 (setq org-agenda-include-diary (not org-agenda-include-diary))
5619 (org-agenda-redo)
5620 (org-agenda-set-mode-name)
5621 (message "Diary inclusion turned %s"
5622 (if org-agenda-include-diary "on" "off")))
5623
5624 (defun org-agenda-toggle-time-grid ()
5625 "Toggle time grid in an agenda buffer."
5626 (interactive)
5627 (org-agenda-check-type t 'agenda)
5628 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5629 (org-agenda-redo)
5630 (org-agenda-set-mode-name)
5631 (message "Time-grid turned %s"
5632 (if org-agenda-use-time-grid "on" "off")))
5633
5634 (defun org-agenda-set-mode-name ()
5635 "Set the mode name to indicate all the small mode settings."
5636 (setq mode-name
5637 (concat "Org-Agenda"
5638 (if (equal org-agenda-ndays 1) " Day" "")
5639 (if (equal org-agenda-ndays 7) " Week" "")
5640 (if org-agenda-follow-mode " Follow" "")
5641 (if org-agenda-include-diary " Diary" "")
5642 (if org-agenda-use-time-grid " Grid" "")
5643 (if org-agenda-show-log " Log" "")))
5644 (force-mode-line-update))
5645
5646 (defun org-agenda-post-command-hook ()
5647 (and (eolp) (not (bolp)) (backward-char 1))
5648 (if (and org-agenda-follow-mode
5649 (get-text-property (point) 'org-marker))
5650 (org-agenda-show)))
5651
5652 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5653
5654 (defun org-get-entries-from-diary (date)
5655 "Get the (Emacs Calendar) diary entries for DATE."
5656 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5657 (diary-display-hook '(fancy-diary-display))
5658 (list-diary-entries-hook
5659 (cons 'org-diary-default-entry list-diary-entries-hook))
5660 (diary-file-name-prefix-function nil) ; turn this feature off
5661 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5662 entries
5663 (org-disable-agenda-to-diary t))
5664 (save-excursion
5665 (save-window-excursion
5666 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
5667 (if (not (get-buffer fancy-diary-buffer))
5668 (setq entries nil)
5669 (with-current-buffer fancy-diary-buffer
5670 (setq buffer-read-only nil)
5671 (if (= (point-max) 1)
5672 ;; No entries
5673 (setq entries nil)
5674 ;; Omit the date and other unnecessary stuff
5675 (org-agenda-cleanup-fancy-diary)
5676 ;; Add prefix to each line and extend the text properties
5677 (if (= (point-max) 1)
5678 (setq entries nil)
5679 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5680 (set-buffer-modified-p nil)
5681 (kill-buffer fancy-diary-buffer)))
5682 (when entries
5683 (setq entries (org-split-string entries "\n"))
5684 (setq entries
5685 (mapcar
5686 (lambda (x)
5687 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5688 ;; Extend the text properties to the beginning of the line
5689 (org-add-props x (text-properties-at (1- (length x)) x)))
5690 entries)))))
5691
5692 (defun org-agenda-cleanup-fancy-diary ()
5693 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5694 This gets rid of the date, the underline under the date, and
5695 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5696 date. It also removes lines that contain only whitespace."
5697 (goto-char (point-min))
5698 (if (looking-at ".*?:[ \t]*")
5699 (progn
5700 (replace-match "")
5701 (re-search-forward "\n=+$" nil t)
5702 (replace-match "")
5703 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5704 (re-search-forward "\n=+$" nil t)
5705 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5706 (goto-char (point-min))
5707 (while (re-search-forward "^ +\n" nil t)
5708 (replace-match ""))
5709 (goto-char (point-min))
5710 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5711 (replace-match "")))
5712
5713 ;; Make sure entries from the diary have the right text properties.
5714 (eval-after-load "diary-lib"
5715 '(if (boundp 'diary-modify-entry-list-string-function)
5716 ;; We can rely on the hook, nothing to do
5717 nil
5718 ;; Hook not avaiable, must use advice to make this work
5719 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5720 "Make the position visible."
5721 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5722 (stringp string)
5723 buffer-file-name)
5724 (setq string (org-modify-diary-entry-string string))))))
5725
5726 (defun org-modify-diary-entry-string (string)
5727 "Add text properties to string, allowing org-mode to act on it."
5728 (org-add-props string nil
5729 'mouse-face 'highlight
5730 'keymap org-agenda-keymap
5731 'help-echo (format "mouse-2 or RET jump to diary file %s"
5732 (abbreviate-file-name buffer-file-name))
5733 'org-agenda-diary-link t
5734 'org-marker (org-agenda-new-marker (point-at-bol))))
5735
5736 (defun org-diary-default-entry ()
5737 "Add a dummy entry to the diary.
5738 Needed to avoid empty dates which mess up holiday display."
5739 ;; Catch the error if dealing with the new add-to-diary-alist
5740 (when org-disable-agenda-to-diary
5741 (condition-case nil
5742 (add-to-diary-list original-date "Org-mode dummy" "")
5743 (error
5744 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5745
5746 (defun org-cycle-agenda-files ()
5747 "Cycle through the files in `org-agenda-files'.
5748 If the current buffer visits an agenda file, find the next one in the list.
5749 If the current buffer does not, find the first agenda file."
5750 (interactive)
5751 (let* ((fs (org-agenda-files t))
5752 (files (append fs (list (car fs))))
5753 (tcf (if buffer-file-name (file-truename buffer-file-name)))
5754 file)
5755 (unless files (error "No agenda files"))
5756 (catch 'exit
5757 (while (setq file (pop files))
5758 (if (equal (file-truename file) tcf)
5759 (when (car files)
5760 (find-file (car files))
5761 (throw 'exit t))))
5762 (find-file (car fs)))))
5763
5764 (defun org-agenda-file-to-end ()
5765 "Move/add the current file to the end of the agenda file list.
5766 If the file is not present in the list, it is appended to the list. If it is
5767 present, it is moved there."
5768 (interactive)
5769 (org-agenda-file-to-front 'to-end))
5770
5771 (defun org-agenda-file-to-front (&optional to-end)
5772 "Move/add the current file to the top of the agenda file list.
5773 If the file is not present in the list, it is added to the front. If it is
5774 present, it is moved there. With optional argument TO-END, add/move to the
5775 end of the list."
5776 (interactive "P")
5777 (let ((file-alist (mapcar (lambda (x)
5778 (cons (file-truename x) x))
5779 (org-agenda-files t)))
5780 (ctf (file-truename buffer-file-name))
5781 x had)
5782 (setq x (assoc ctf file-alist) had x)
5783
5784 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
5785 (if to-end
5786 (setq file-alist (append (delq x file-alist) (list x)))
5787 (setq file-alist (cons x (delq x file-alist))))
5788 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
5789 (org-install-agenda-files-menu)
5790 (message "File %s to %s of agenda file list"
5791 (if had "moved" "added") (if to-end "end" "front"))))
5792
5793 (defun org-remove-file (&optional file)
5794 "Remove current file from the list of files in variable `org-agenda-files'.
5795 These are the files which are being checked for agenda entries.
5796 Optional argument FILE means, use this file instead of the current."
5797 (interactive)
5798 (let* ((file (or file buffer-file-name))
5799 (true-file (file-truename file))
5800 (afile (abbreviate-file-name file))
5801 (files (delq nil (mapcar
5802 (lambda (x)
5803 (if (equal true-file
5804 (file-truename x))
5805 nil x))
5806 (org-agenda-files t)))))
5807 (if (not (= (length files) (length (org-agenda-files t))))
5808 (progn
5809 (org-store-new-agenda-file-list files)
5810 (org-install-agenda-files-menu)
5811 (message "Removed file: %s" afile))
5812 (message "File was not in list: %s" afile))))
5813
5814 (defun org-file-menu-entry (file)
5815 (vector file (list 'find-file file) t))
5816
5817 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5818 "Return a list of all relevant day numbers from BEG to END buffer positions.
5819 If NO-RANGES is non-nil, include only the start and end dates of a range,
5820 not every single day in the range. If FORCE-TODAY is non-nil, make
5821 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5822 inactive time stamps (those in square brackets) are included."
5823 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5824 dates date day day1 day2 ts1 ts2)
5825 (if force-today
5826 (setq dates (list (time-to-days (current-time)))))
5827 (save-excursion
5828 (goto-char beg)
5829 (while (re-search-forward re end t)
5830 (setq day (time-to-days (org-time-string-to-time
5831 (substring (match-string 1) 0 10))))
5832 (or (memq day dates) (push day dates)))
5833 (unless no-ranges
5834 (goto-char beg)
5835 (while (re-search-forward org-tr-regexp end t)
5836 (setq ts1 (substring (match-string 1) 0 10)
5837 ts2 (substring (match-string 2) 0 10)
5838 day1 (time-to-days (org-time-string-to-time ts1))
5839 day2 (time-to-days (org-time-string-to-time ts2)))
5840 (while (< (setq day1 (1+ day1)) day2)
5841 (or (memq day1 dates) (push day1 dates)))))
5842 (sort dates '<))))
5843
5844 ;;;###autoload
5845 (defun org-diary (&rest args)
5846 "Return diary information from org-files.
5847 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5848 It accesses org files and extracts information from those files to be
5849 listed in the diary. The function accepts arguments specifying what
5850 items should be listed. The following arguments are allowed:
5851
5852 :timestamp List the headlines of items containing a date stamp or
5853 date range matching the selected date. Deadlines will
5854 also be listed, on the expiration day.
5855
5856 :deadline List any deadlines past due, or due within
5857 `org-deadline-warning-days'. The listing occurs only
5858 in the diary for *today*, not at any other date. If
5859 an entry is marked DONE, it is no longer listed.
5860
5861 :scheduled List all items which are scheduled for the given date.
5862 The diary for *today* also contains items which were
5863 scheduled earlier and are not yet marked DONE.
5864
5865 :todo List all TODO items from the org-file. This may be a
5866 long list - so this is not turned on by default.
5867 Like deadlines, these entries only show up in the
5868 diary for *today*, not at any other date.
5869
5870 The call in the diary file should look like this:
5871
5872 &%%(org-diary) ~/path/to/some/orgfile.org
5873
5874 Use a separate line for each org file to check. Or, if you omit the file name,
5875 all files listed in `org-agenda-files' will be checked automatically:
5876
5877 &%%(org-diary)
5878
5879 If you don't give any arguments (as in the example above), the default
5880 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5881 also be written as
5882
5883 &%%(org-diary :deadline :timestamp :scheduled)
5884
5885 The function expects the lisp variables `entry' and `date' to be provided
5886 by the caller, because this is how the calendar works. Don't use this
5887 function from a program - use `org-agenda-get-day-entries' instead."
5888 (org-agenda-maybe-reset-markers)
5889 (org-compile-prefix-format org-agenda-prefix-format)
5890 (setq args (or args '(:deadline :scheduled :timestamp)))
5891 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5892 (list entry)
5893 (org-agenda-files t)))
5894 file rtn results)
5895 ;; If this is called during org-agenda, don't return any entries to
5896 ;; the calendar. Org Agenda will list these entries itself.
5897 (if org-disable-agenda-to-diary (setq files nil))
5898 (while (setq file (pop files))
5899 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5900 (setq results (append results rtn)))
5901 (if results
5902 (concat (org-finalize-agenda-entries results) "\n"))))
5903 (defvar org-category-table nil)
5904 (defun org-get-category-table ()
5905 "Get the table of categories and positions in current buffer."
5906 (let (tbl)
5907 (save-excursion
5908 (goto-char (point-min))
5909 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5910 (push (cons (point) (org-trim (match-string 2))) tbl)))
5911 tbl))
5912 (defun org-get-category (&optional pos)
5913 "Get the category applying to position POS."
5914 (if (not org-category-table)
5915 (cond
5916 ((null org-category)
5917 (setq org-category
5918 (if buffer-file-name
5919 (file-name-sans-extension
5920 (file-name-nondirectory buffer-file-name))
5921 "???")))
5922 ((symbolp org-category) (symbol-name org-category))
5923 (t org-category))
5924 (let ((tbl org-category-table)
5925 (pos (or pos (point))))
5926 (while (and tbl (> (caar tbl) pos))
5927 (pop tbl))
5928 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5929 org-category-table))))))
5930
5931 (defun org-agenda-get-day-entries (file date &rest args)
5932 "Does the work for `org-diary' and `org-agenda'.
5933 FILE is the path to a file to be checked for entries. DATE is date like
5934 the one returned by `calendar-current-date'. ARGS are symbols indicating
5935 which kind of entries should be extracted. For details about these, see
5936 the documentation of `org-diary'."
5937 (setq args (or args '(:deadline :scheduled :timestamp)))
5938 (let* ((org-startup-with-deadline-check nil)
5939 (org-startup-folded nil)
5940 (org-startup-align-all-tables nil)
5941 (buffer (if (file-exists-p file)
5942 (org-get-agenda-file-buffer file)
5943 (error "No such file %s" file)))
5944 arg results rtn)
5945 (if (not buffer)
5946 ;; If file does not exist, make sure an error message ends up in diary
5947 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5948 (with-current-buffer buffer
5949 (unless (eq major-mode 'org-mode)
5950 (error "Agenda file %s is not in `org-mode'" file))
5951 (setq org-category-table (org-get-category-table))
5952 (let ((case-fold-search nil))
5953 (save-excursion
5954 (save-restriction
5955 (if org-respect-restriction
5956 (if (org-region-active-p)
5957 ;; Respect a region to restrict search
5958 (narrow-to-region (region-beginning) (region-end)))
5959 ;; If we work for the calendar or many files,
5960 ;; get rid of any restriction
5961 (widen))
5962 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5963 (while (setq arg (pop args))
5964 (cond
5965 ((and (eq arg :todo)
5966 (equal date (calendar-current-date)))
5967 (setq rtn (org-agenda-get-todos))
5968 (setq results (append results rtn)))
5969 ((eq arg :timestamp)
5970 (setq rtn (org-agenda-get-blocks))
5971 (setq results (append results rtn))
5972 (setq rtn (org-agenda-get-timestamps))
5973 (setq results (append results rtn)))
5974 ((eq arg :scheduled)
5975 (setq rtn (org-agenda-get-scheduled))
5976 (setq results (append results rtn)))
5977 ((eq arg :closed)
5978 (setq rtn (org-agenda-get-closed))
5979 (setq results (append results rtn)))
5980 ((and (eq arg :deadline)
5981 (equal date (calendar-current-date)))
5982 (setq rtn (org-agenda-get-deadlines))
5983 (setq results (append results rtn))))))))
5984 results))))
5985
5986 (defun org-entry-is-done-p ()
5987 "Is the current entry marked DONE?"
5988 (save-excursion
5989 (and (re-search-backward "[\r\n]\\*" nil t)
5990 (looking-at org-nl-done-regexp))))
5991
5992 (defun org-at-date-range-p ()
5993 "Is the cursor inside a date range?"
5994 (interactive)
5995 (save-excursion
5996 (catch 'exit
5997 (let ((pos (point)))
5998 (skip-chars-backward "^<\r\n")
5999 (skip-chars-backward "<")
6000 (and (looking-at org-tr-regexp)
6001 (>= (match-end 0) pos)
6002 (throw 'exit t))
6003 (skip-chars-backward "^<\r\n")
6004 (skip-chars-backward "<")
6005 (and (looking-at org-tr-regexp)
6006 (>= (match-end 0) pos)
6007 (throw 'exit t)))
6008 nil)))
6009
6010 (defun org-agenda-get-todos ()
6011 "Return the TODO information for agenda display."
6012 (let* ((props (list 'face nil
6013 'done-face 'org-done
6014 'org-not-done-regexp org-not-done-regexp
6015 'mouse-face 'highlight
6016 'keymap org-agenda-keymap
6017 'help-echo
6018 (format "mouse-2 or RET jump to org file %s"
6019 (abbreviate-file-name buffer-file-name))))
6020 (regexp (concat "[\n\r]\\*+ *\\("
6021 (if org-select-this-todo-keyword
6022 (concat "\\<\\(" org-select-this-todo-keyword
6023 "\\)\\>")
6024 org-not-done-regexp)
6025 "[^\n\r]*\\)"))
6026 marker priority category tags
6027 ee txt)
6028 (goto-char (point-min))
6029 (while (re-search-forward regexp nil t)
6030 (goto-char (match-beginning 1))
6031 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
6032 category (org-get-category)
6033 tags (org-get-tags-at (point))
6034 txt (org-format-agenda-item "" (match-string 1) category tags)
6035 priority
6036 (+ (org-get-priority txt)
6037 (if org-todo-kwd-priority-p
6038 (- org-todo-kwd-max-priority -2
6039 (length
6040 (member (match-string 2) org-todo-keywords)))
6041 1)))
6042 (org-add-props txt props
6043 'org-marker marker 'org-hd-marker marker
6044 'priority priority 'category category)
6045 (push txt ee)
6046 (goto-char (match-end 1)))
6047 (nreverse ee)))
6048
6049 (defconst org-agenda-no-heading-message
6050 "No heading for this item in buffer or region.")
6051
6052 (defun org-agenda-get-timestamps ()
6053 "Return the date stamp information for agenda display."
6054 (let* ((props (list 'face nil
6055 'org-not-done-regexp org-not-done-regexp
6056 'mouse-face 'highlight
6057 'keymap org-agenda-keymap
6058 'help-echo
6059 (format "mouse-2 or RET jump to org file %s"
6060 (abbreviate-file-name buffer-file-name))))
6061 (regexp (regexp-quote
6062 (substring
6063 (format-time-string
6064 (car org-time-stamp-formats)
6065 (apply 'encode-time ; DATE bound by calendar
6066 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6067 0 11)))
6068 marker hdmarker deadlinep scheduledp donep tmp priority category
6069 ee txt timestr tags)
6070 (goto-char (point-min))
6071 (while (re-search-forward regexp nil t)
6072 (if (not (save-match-data (org-at-date-range-p)))
6073 (progn
6074 (setq marker (org-agenda-new-marker (match-beginning 0))
6075 category (org-get-category (match-beginning 0))
6076 tmp (buffer-substring (max (point-min)
6077 (- (match-beginning 0)
6078 org-ds-keyword-length))
6079 (match-beginning 0))
6080 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6081 deadlinep (string-match org-deadline-regexp tmp)
6082 scheduledp (string-match org-scheduled-regexp tmp)
6083 donep (org-entry-is-done-p))
6084 (if (string-match ">" timestr)
6085 ;; substring should only run to end of time stamp
6086 (setq timestr (substring timestr 0 (match-end 0))))
6087 (save-excursion
6088 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6089 (progn
6090 (goto-char (match-end 1))
6091 (setq hdmarker (org-agenda-new-marker)
6092 tags (org-get-tags-at))
6093 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6094 (setq txt (org-format-agenda-item
6095 (format "%s%s"
6096 (if deadlinep "Deadline: " "")
6097 (if scheduledp "Scheduled: " ""))
6098 (match-string 1) category tags timestr)))
6099 (setq txt org-agenda-no-heading-message))
6100 (setq priority (org-get-priority txt))
6101 (org-add-props txt props
6102 'org-marker marker 'org-hd-marker hdmarker)
6103 (if deadlinep
6104 (org-add-props txt nil
6105 'face (if donep 'org-done 'org-warning)
6106 'undone-face 'org-warning 'done-face 'org-done
6107 'category category 'priority (+ 100 priority))
6108 (if scheduledp
6109 (org-add-props txt nil
6110 'face 'org-scheduled-today
6111 'undone-face 'org-scheduled-today 'done-face 'org-done
6112 'category category 'priority (+ 99 priority))
6113 (org-add-props txt nil 'priority priority 'category category)))
6114 (push txt ee))
6115 (outline-next-heading))))
6116 (nreverse ee)))
6117
6118 (defun org-agenda-get-closed ()
6119 "Return the logged TODO entries for agenda display."
6120 (let* ((props (list 'mouse-face 'highlight
6121 'org-not-done-regexp org-not-done-regexp
6122 'keymap org-agenda-keymap
6123 'help-echo
6124 (format "mouse-2 or RET jump to org file %s"
6125 (abbreviate-file-name buffer-file-name))))
6126 (regexp (concat
6127 "\\<" org-closed-string " *\\["
6128 (regexp-quote
6129 (substring
6130 (format-time-string
6131 (car org-time-stamp-formats)
6132 (apply 'encode-time ; DATE bound by calendar
6133 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6134 1 11))))
6135 marker hdmarker priority category tags
6136 ee txt timestr)
6137 (goto-char (point-min))
6138 (while (re-search-forward regexp nil t)
6139 (if (not (save-match-data (org-at-date-range-p)))
6140 (progn
6141 (setq marker (org-agenda-new-marker (match-beginning 0))
6142 category (org-get-category (match-beginning 0))
6143 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6144 ;; donep (org-entry-is-done-p)
6145 )
6146 (if (string-match "\\]" timestr)
6147 ;; substring should only run to end of time stamp
6148 (setq timestr (substring timestr 0 (match-end 0))))
6149 (save-excursion
6150 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6151 (progn
6152 (goto-char (match-end 1))
6153 (setq hdmarker (org-agenda-new-marker)
6154 tags (org-get-tags-at))
6155 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6156 (setq txt (org-format-agenda-item
6157 "Closed: "
6158 (match-string 1) category tags timestr)))
6159 (setq txt org-agenda-no-heading-message))
6160 (setq priority 100000)
6161 (org-add-props txt props
6162 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
6163 'priority priority 'category category
6164 'undone-face 'org-warning 'done-face 'org-done)
6165 (push txt ee))
6166 (outline-next-heading))))
6167 (nreverse ee)))
6168
6169 (defun org-agenda-get-deadlines ()
6170 "Return the deadline information for agenda display."
6171 (let* ((wdays org-deadline-warning-days)
6172 (props (list 'mouse-face 'highlight
6173 'org-not-done-regexp org-not-done-regexp
6174 'keymap org-agenda-keymap
6175 'help-echo
6176 (format "mouse-2 or RET jump to org file %s"
6177 (abbreviate-file-name buffer-file-name))))
6178 (regexp org-deadline-time-regexp)
6179 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6180 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6181 d2 diff pos pos1 category tags
6182 ee txt head)
6183 (goto-char (point-min))
6184 (while (re-search-forward regexp nil t)
6185 (setq pos (1- (match-beginning 1))
6186 d2 (time-to-days
6187 (org-time-string-to-time (match-string 1)))
6188 diff (- d2 d1))
6189 ;; When to show a deadline in the calendar:
6190 ;; If the expiration is within wdays warning time.
6191 ;; Past-due deadlines are only shown on the current date
6192 (if (and (< diff wdays) todayp (not (= diff 0)))
6193 (save-excursion
6194 (setq category (org-get-category))
6195 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6196 (progn
6197 (goto-char (match-end 0))
6198 (setq pos1 (match-end 1))
6199 (setq tags (org-get-tags-at pos1))
6200 (setq head (buffer-substring-no-properties
6201 (point)
6202 (progn (skip-chars-forward "^\r\n")
6203 (point))))
6204 (if (string-match org-looking-at-done-regexp head)
6205 (setq txt nil)
6206 (setq txt (org-format-agenda-item
6207 (format "In %3d d.: " diff) head category tags))))
6208 (setq txt org-agenda-no-heading-message))
6209 (when txt
6210 (org-add-props txt props
6211 'org-marker (org-agenda-new-marker pos)
6212 'org-hd-marker (org-agenda-new-marker pos1)
6213 'priority (+ (- 10 diff) (org-get-priority txt))
6214 'category category
6215 'face (cond ((<= diff 0) 'org-warning)
6216 ((<= diff 5) 'org-scheduled-previously)
6217 (t nil))
6218 'undone-face (cond
6219 ((<= diff 0) 'org-warning)
6220 ((<= diff 5) 'org-scheduled-previously)
6221 (t nil))
6222 'done-face 'org-done)
6223 (push txt ee)))))
6224 ee))
6225
6226 (defun org-agenda-get-scheduled ()
6227 "Return the scheduled information for agenda display."
6228 (let* ((props (list 'face 'org-scheduled-previously
6229 'org-not-done-regexp org-not-done-regexp
6230 'undone-face 'org-scheduled-previously
6231 'done-face 'org-done
6232 'mouse-face 'highlight
6233 'keymap org-agenda-keymap
6234 'help-echo
6235 (format "mouse-2 or RET jump to org file %s"
6236 (abbreviate-file-name buffer-file-name))))
6237 (regexp org-scheduled-time-regexp)
6238 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6239 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6240 d2 diff pos pos1 category tags
6241 ee txt head)
6242 (goto-char (point-min))
6243 (while (re-search-forward regexp nil t)
6244 (setq pos (1- (match-beginning 1))
6245 d2 (time-to-days
6246 (org-time-string-to-time (match-string 1)))
6247 diff (- d2 d1))
6248 ;; When to show a scheduled item in the calendar:
6249 ;; If it is on or past the date.
6250 (if (and (< diff 0) todayp)
6251 (save-excursion
6252 (setq category (org-get-category))
6253 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6254 (progn
6255 (goto-char (match-end 0))
6256 (setq pos1 (match-end 1))
6257 (setq tags (org-get-tags-at))
6258 (setq head (buffer-substring-no-properties
6259 (point)
6260 (progn (skip-chars-forward "^\r\n") (point))))
6261 (if (string-match org-looking-at-done-regexp head)
6262 (setq txt nil)
6263 (setq txt (org-format-agenda-item
6264 (format "Sched.%2dx: " (- 1 diff)) head
6265 category tags))))
6266 (setq txt org-agenda-no-heading-message))
6267 (when txt
6268 (org-add-props txt props
6269 'org-marker (org-agenda-new-marker pos)
6270 'org-hd-marker (org-agenda-new-marker pos1)
6271 'priority (+ (- 5 diff) (org-get-priority txt))
6272 'category category)
6273 (push txt ee)))))
6274 ee))
6275
6276 (defun org-agenda-get-blocks ()
6277 "Return the date-range information for agenda display."
6278 (let* ((props (list 'face nil
6279 'org-not-done-regexp org-not-done-regexp
6280 'mouse-face 'highlight
6281 'keymap org-agenda-keymap
6282 'help-echo
6283 (format "mouse-2 or RET jump to org file %s"
6284 (abbreviate-file-name buffer-file-name))))
6285 (regexp org-tr-regexp)
6286 (d0 (calendar-absolute-from-gregorian date))
6287 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
6288 (goto-char (point-min))
6289 (while (re-search-forward regexp nil t)
6290 (setq timestr (match-string 0)
6291 s1 (match-string 1)
6292 s2 (match-string 2)
6293 d1 (time-to-days (org-time-string-to-time s1))
6294 d2 (time-to-days (org-time-string-to-time s2)))
6295 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
6296 ;; Only allow days between the limits, because the normal
6297 ;; date stamps will catch the limits.
6298 (save-excursion
6299 (setq marker (org-agenda-new-marker (point)))
6300 (setq category (org-get-category))
6301 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6302 (progn
6303 (setq hdmarker (org-agenda-new-marker (match-end 1)))
6304 (goto-char (match-end 1))
6305 (setq tags (org-get-tags-at))
6306 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6307 (setq txt (org-format-agenda-item
6308 (format (if (= d1 d2) "" "(%d/%d): ")
6309 (1+ (- d0 d1)) (1+ (- d2 d1)))
6310 (match-string 1) category tags
6311 (if (= d0 d1) timestr))))
6312 (setq txt org-agenda-no-heading-message))
6313 (org-add-props txt props
6314 'org-marker marker 'org-hd-marker hdmarker
6315 'priority (org-get-priority txt) 'category category)
6316 (push txt ee)))
6317 (outline-next-heading))
6318 ;; Sort the entries by expiration date.
6319 (nreverse ee)))
6320
6321 (defconst org-plain-time-of-day-regexp
6322 (concat
6323 "\\(\\<[012]?[0-9]"
6324 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6325 "\\(--?"
6326 "\\(\\<[012]?[0-9]"
6327 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6328 "\\)?")
6329 "Regular expression to match a plain time or time range.
6330 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
6331 groups carry important information:
6332 0 the full match
6333 1 the first time, range or not
6334 8 the second time, if it is a range.")
6335
6336 (defconst org-stamp-time-of-day-regexp
6337 (concat
6338 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
6339 "\\([012][0-9]:[0-5][0-9]\\)>"
6340 "\\(--?"
6341 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
6342 "Regular expression to match a timestamp time or time range.
6343 After a match, the following groups carry important information:
6344 0 the full match
6345 1 date plus weekday, for backreferencing to make sure both times on same day
6346 2 the first time, range or not
6347 4 the second time, if it is a range.")
6348
6349 (defvar org-prefix-has-time nil
6350 "A flag, set by `org-compile-prefix-format'.
6351 The flag is set if the currently compiled format contains a `%t'.")
6352 (defvar org-prefix-has-tag nil
6353 "A flag, set by `org-compile-prefix-format'.
6354 The flag is set if the currently compiled format contains a `%T'.")
6355
6356 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
6357 "Format TXT to be inserted into the agenda buffer.
6358 In particular, it adds the prefix and corresponding text properties. EXTRA
6359 must be a string and replaces the `%s' specifier in the prefix format.
6360 CATEGORY (string, symbol or nil) may be used to overrule the default
6361 category taken from local variable or file name. It will replace the `%c'
6362 specifier in the format. DOTIME, when non-nil, indicates that a
6363 time-of-day should be extracted from TXT for sorting of this entry, and for
6364 the `%t' specifier in the format. When DOTIME is a string, this string is
6365 searched for a time before TXT is. NOPREFIX is a flag and indicates that
6366 only the correctly processes TXT should be returned - this is used by
6367 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
6368 (save-match-data
6369 ;; Diary entries sometimes have extra whitespace at the beginning
6370 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
6371 (let* ((category (or category
6372 org-category
6373 (if buffer-file-name
6374 (file-name-sans-extension
6375 (file-name-nondirectory buffer-file-name))
6376 "")))
6377 (tag (if tags (nth (1- (length tags)) tags) ""))
6378 time ;; needed for the eval of the prefix format
6379 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
6380 (time-of-day (and dotime (org-get-time-of-day ts)))
6381 stamp plain s0 s1 s2 rtn)
6382 (when (and dotime time-of-day org-prefix-has-time)
6383 ;; Extract starting and ending time and move them to prefix
6384 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
6385 (setq plain (string-match org-plain-time-of-day-regexp ts)))
6386 (setq s0 (match-string 0 ts)
6387 s1 (match-string (if plain 1 2) ts)
6388 s2 (match-string (if plain 8 4) ts))
6389
6390 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
6391 ;; them, we might want to remove them there to avoid duplication.
6392 ;; The user can turn this off with a variable.
6393 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
6394 (string-match (concat (regexp-quote s0) " *") txt)
6395 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
6396 (= (match-beginning 0) 0)
6397 t))
6398 (setq txt (replace-match "" nil nil txt))))
6399 ;; Normalize the time(s) to 24 hour
6400 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
6401 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
6402
6403 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
6404 (and org-agenda-remove-tags-when-in-prefix
6405 org-prefix-has-tag))
6406 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
6407 (setq txt (replace-match "" t t txt)))
6408
6409 ;; Create the final string
6410 (if noprefix
6411 (setq rtn txt)
6412 ;; Prepare the variables needed in the eval of the compiled format
6413 (setq time (cond (s2 (concat s1 "-" s2))
6414 (s1 (concat s1 "......"))
6415 (t ""))
6416 extra (or extra "")
6417 category (if (symbolp category) (symbol-name category) category))
6418 ;; Evaluate the compiled format
6419 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
6420
6421 ;; And finally add the text properties
6422 (org-add-props rtn nil
6423 'category (downcase category) 'tags tags
6424 'prefix-length (- (length rtn) (length txt))
6425 'time-of-day time-of-day
6426 'dotime dotime))))
6427
6428 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
6429 (catch 'exit
6430 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
6431 ((and todayp (member 'today (car org-agenda-time-grid))))
6432 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
6433 ((member 'weekly (car org-agenda-time-grid)))
6434 (t (throw 'exit list)))
6435 (let* ((have (delq nil (mapcar
6436 (lambda (x) (get-text-property 1 'time-of-day x))
6437 list)))
6438 (string (nth 1 org-agenda-time-grid))
6439 (gridtimes (nth 2 org-agenda-time-grid))
6440 (req (car org-agenda-time-grid))
6441 (remove (member 'remove-match req))
6442 new time)
6443 (if (and (member 'require-timed req) (not have))
6444 ;; don't show empty grid
6445 (throw 'exit list))
6446 (while (setq time (pop gridtimes))
6447 (unless (and remove (member time have))
6448 (setq time (int-to-string time))
6449 (push (org-format-agenda-item
6450 nil string "" nil
6451 (concat (substring time 0 -2) ":" (substring time -2)))
6452 new)
6453 (put-text-property
6454 1 (length (car new)) 'face 'org-time-grid (car new))))
6455 (if (member 'time-up org-agenda-sorting-strategy)
6456 (append new list)
6457 (append list new)))))
6458
6459 (defun org-compile-prefix-format (format)
6460 "Compile the prefix format into a Lisp form that can be evaluated.
6461 The resulting form is returned and stored in the variable
6462 `org-prefix-format-compiled'."
6463 (setq org-prefix-has-time nil org-prefix-has-tag nil)
6464 (let ((start 0) varform vars var (s format)e c f opt)
6465 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
6466 s start)
6467 (setq var (cdr (assoc (match-string 4 s)
6468 '(("c" . category) ("t" . time) ("s" . extra)
6469 ("T" . tag))))
6470 c (or (match-string 3 s) "")
6471 opt (match-beginning 1)
6472 start (1+ (match-beginning 0)))
6473 (if (equal var 'time) (setq org-prefix-has-time t))
6474 (if (equal var 'tag) (setq org-prefix-has-tag t))
6475 (setq f (concat "%" (match-string 2 s) "s"))
6476 (if opt
6477 (setq varform
6478 `(if (equal "" ,var)
6479 ""
6480 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
6481 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
6482 (setq s (replace-match "%s" t nil s))
6483 (push varform vars))
6484 (setq vars (nreverse vars))
6485 (setq org-prefix-format-compiled `(format ,s ,@vars))))
6486
6487 (defun org-get-time-of-day (s &optional string)
6488 "Check string S for a time of day.
6489 If found, return it as a military time number between 0 and 2400.
6490 If not found, return nil.
6491 The optional STRING argument forces conversion into a 5 character wide string
6492 HH:MM."
6493 (save-match-data
6494 (when
6495 (or
6496 (string-match
6497 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
6498 (string-match
6499 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
6500 (let* ((t0 (+ (* 100
6501 (+ (string-to-number (match-string 1 s))
6502 (if (and (match-beginning 4)
6503 (equal (downcase (match-string 4 s)) "pm"))
6504 12 0)))
6505 (if (match-beginning 3)
6506 (string-to-number (match-string 3 s))
6507 0)))
6508 (t1 (concat " "
6509 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6510 (int-to-string t0))))
6511 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6512
6513 (defun org-finalize-agenda-entries (list)
6514 "Sort and concatenate the agenda items."
6515 (setq list (mapcar 'org-agenda-highlight-todo list))
6516 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6517
6518 (defun org-agenda-highlight-todo (x)
6519 (let (re)
6520 (if (eq x 'line)
6521 (save-excursion
6522 (beginning-of-line 1)
6523 (setq re (get-text-property (point) 'org-not-done-regexp))
6524 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
6525 (and (looking-at (concat "[ \t]*" re))
6526 (add-text-properties (match-beginning 0) (match-end 0)
6527 '(face org-todo))))
6528 (setq re (get-text-property 0 'org-not-done-regexp x))
6529 (and re (string-match re x)
6530 (add-text-properties (match-beginning 0) (match-end 0)
6531 '(face org-todo) x))
6532 x)))
6533
6534 (defsubst org-cmp-priority (a b)
6535 "Compare the priorities of string A and B."
6536 (let ((pa (or (get-text-property 1 'priority a) 0))
6537 (pb (or (get-text-property 1 'priority b) 0)))
6538 (cond ((> pa pb) +1)
6539 ((< pa pb) -1)
6540 (t nil))))
6541
6542 (defsubst org-cmp-category (a b)
6543 "Compare the string values of categories of strings A and B."
6544 (let ((ca (or (get-text-property 1 'category a) ""))
6545 (cb (or (get-text-property 1 'category b) "")))
6546 (cond ((string-lessp ca cb) -1)
6547 ((string-lessp cb ca) +1)
6548 (t nil))))
6549
6550 (defsubst org-cmp-time (a b)
6551 "Compare the time-of-day values of strings A and B."
6552 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6553 (ta (or (get-text-property 1 'time-of-day a) def))
6554 (tb (or (get-text-property 1 'time-of-day b) def)))
6555 (cond ((< ta tb) -1)
6556 ((< tb ta) +1)
6557 (t nil))))
6558
6559 (defun org-entries-lessp (a b)
6560 "Predicate for sorting agenda entries."
6561 ;; The following variables will be used when the form is evaluated.
6562 (let* ((time-up (org-cmp-time a b))
6563 (time-down (if time-up (- time-up) nil))
6564 (priority-up (org-cmp-priority a b))
6565 (priority-down (if priority-up (- priority-up) nil))
6566 (category-up (org-cmp-category a b))
6567 (category-down (if category-up (- category-up) nil))
6568 (category-keep (if category-up +1 nil)))
6569 (cdr (assoc
6570 (eval (cons 'or org-agenda-sorting-strategy))
6571 '((-1 . t) (1 . nil) (nil . nil))))))
6572
6573 (defun org-agenda-show-priority ()
6574 "Show the priority of the current item.
6575 This priority is composed of the main priority given with the [#A] cookies,
6576 and by additional input from the age of a schedules or deadline entry."
6577 (interactive)
6578 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6579 (message "Priority is %d" (if pri pri -1000))))
6580
6581 (defun org-agenda-show-tags ()
6582 "Show the tags applicable to the current item."
6583 (interactive)
6584 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6585 (if tags
6586 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6587 (message "No tags associated with this line"))))
6588
6589 (defun org-agenda-goto (&optional highlight)
6590 "Go to the Org-mode file which contains the item at point."
6591 (interactive)
6592 (let* ((marker (or (get-text-property (point) 'org-marker)
6593 (org-agenda-error)))
6594 (buffer (marker-buffer marker))
6595 (pos (marker-position marker)))
6596 (switch-to-buffer-other-window buffer)
6597 (widen)
6598 (goto-char pos)
6599 (when (eq major-mode 'org-mode)
6600 (org-show-hidden-entry)
6601 (save-excursion
6602 (and (outline-next-heading)
6603 (org-flag-heading nil)))) ; show the next heading
6604 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6605
6606 (defun org-agenda-switch-to ()
6607 "Go to the Org-mode file which contains the item at point."
6608 (interactive)
6609 (let* ((marker (or (get-text-property (point) 'org-marker)
6610 (org-agenda-error)))
6611 (buffer (marker-buffer marker))
6612 (pos (marker-position marker)))
6613 (switch-to-buffer buffer)
6614 (delete-other-windows)
6615 (widen)
6616 (goto-char pos)
6617 (when (eq major-mode 'org-mode)
6618 (org-show-hidden-entry)
6619 (save-excursion
6620 (and (outline-next-heading)
6621 (org-flag-heading nil)))))) ; show the next heading
6622
6623 (defun org-agenda-goto-mouse (ev)
6624 "Go to the Org-mode file which contains the item at the mouse click."
6625 (interactive "e")
6626 (mouse-set-point ev)
6627 (org-agenda-goto))
6628
6629 (defun org-agenda-show ()
6630 "Display the Org-mode file which contains the item at point."
6631 (interactive)
6632 (let ((win (selected-window)))
6633 (org-agenda-goto t)
6634 (select-window win)))
6635
6636 (defun org-agenda-recenter (arg)
6637 "Display the Org-mode file which contains the item at point and recenter."
6638 (interactive "P")
6639 (let ((win (selected-window)))
6640 (org-agenda-goto t)
6641 (recenter arg)
6642 (select-window win)))
6643
6644 (defun org-agenda-show-mouse (ev)
6645 "Display the Org-mode file which contains the item at the mouse click."
6646 (interactive "e")
6647 (mouse-set-point ev)
6648 (org-agenda-show))
6649
6650 (defun org-agenda-check-no-diary ()
6651 "Check if the entry is a diary link and abort if yes."
6652 (if (get-text-property (point) 'org-agenda-diary-link)
6653 (org-agenda-error)))
6654
6655 (defun org-agenda-error ()
6656 (error "Command not allowed in this line"))
6657
6658 (defvar org-last-heading-marker (make-marker)
6659 "Marker pointing to the headline that last changed its TODO state
6660 by a remote command from the agenda.")
6661
6662 (defun org-agenda-todo (&optional arg)
6663 "Cycle TODO state of line at point, also in Org-mode file.
6664 This changes the line at point, all other lines in the agenda referring to
6665 the same tree node, and the headline of the tree node in the Org-mode file."
6666 (interactive "P")
6667 (org-agenda-check-no-diary)
6668 (let* ((col (current-column))
6669 (marker (or (get-text-property (point) 'org-marker)
6670 (org-agenda-error)))
6671 (buffer (marker-buffer marker))
6672 (pos (marker-position marker))
6673 (hdmarker (get-text-property (point) 'org-hd-marker))
6674 (buffer-read-only nil)
6675 newhead)
6676 (with-current-buffer buffer
6677 (widen)
6678 (goto-char pos)
6679 (org-show-hidden-entry)
6680 (save-excursion
6681 (and (outline-next-heading)
6682 (org-flag-heading nil))) ; show the next heading
6683 (org-todo arg)
6684 (and (bolp) (forward-char 1))
6685 (setq newhead (org-get-heading))
6686 (save-excursion
6687 (org-back-to-heading)
6688 (move-marker org-last-heading-marker (point))))
6689 (beginning-of-line 1)
6690 (save-excursion
6691 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6692 (move-to-column col)))
6693
6694 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6695 "Change all lines in the agenda buffer which match HDMARKER.
6696 The new content of the line will be NEWHEAD (as modified by
6697 `org-format-agenda-item'). HDMARKER is checked with
6698 `equal' against all `org-hd-marker' text properties in the file.
6699 If FIXFACE is non-nil, the face of each item is modified acording to
6700 the new TODO state."
6701 (let* (props m pl undone-face done-face finish new dotime cat tags)
6702 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6703 (save-excursion
6704 (goto-char (point-max))
6705 (beginning-of-line 1)
6706 (while (not finish)
6707 (setq finish (bobp))
6708 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6709 (equal m hdmarker))
6710 (setq props (text-properties-at (point))
6711 dotime (get-text-property (point) 'dotime)
6712 cat (get-text-property (point) 'category)
6713 tags (get-text-property (point) 'tags)
6714 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6715 pl (get-text-property (point) 'prefix-length)
6716 undone-face (get-text-property (point) 'undone-face)
6717 done-face (get-text-property (point) 'done-face))
6718 (move-to-column pl)
6719 (if (looking-at ".*")
6720 (progn
6721 (replace-match new t t)
6722 (beginning-of-line 1)
6723 (add-text-properties (point-at-bol) (point-at-eol) props)
6724 (when fixface
6725 (add-text-properties
6726 (point-at-bol) (point-at-eol)
6727 (list 'face
6728 (if org-last-todo-state-is-todo
6729 undone-face done-face)))
6730 (org-agenda-highlight-todo 'line))
6731 (beginning-of-line 1))
6732 (error "Line update did not work")))
6733 (beginning-of-line 0)))))
6734
6735 (defun org-agenda-priority-up ()
6736 "Increase the priority of line at point, also in Org-mode file."
6737 (interactive)
6738 (org-agenda-priority 'up))
6739
6740 (defun org-agenda-priority-down ()
6741 "Decrease the priority of line at point, also in Org-mode file."
6742 (interactive)
6743 (org-agenda-priority 'down))
6744
6745 (defun org-agenda-priority (&optional force-direction)
6746 "Set the priority of line at point, also in Org-mode file.
6747 This changes the line at point, all other lines in the agenda referring to
6748 the same tree node, and the headline of the tree node in the Org-mode file."
6749 (interactive)
6750 (org-agenda-check-no-diary)
6751 (let* ((marker (or (get-text-property (point) 'org-marker)
6752 (org-agenda-error)))
6753 (buffer (marker-buffer marker))
6754 (pos (marker-position marker))
6755 (hdmarker (get-text-property (point) 'org-hd-marker))
6756 (buffer-read-only nil)
6757 newhead)
6758 (with-current-buffer buffer
6759 (widen)
6760 (goto-char pos)
6761 (org-show-hidden-entry)
6762 (save-excursion
6763 (and (outline-next-heading)
6764 (org-flag-heading nil))) ; show the next heading
6765 (funcall 'org-priority force-direction)
6766 (end-of-line 1)
6767 (setq newhead (org-get-heading)))
6768 (org-agenda-change-all-lines newhead hdmarker)
6769 (beginning-of-line 1)))
6770
6771 (defun org-get-tags-at (&optional pos)
6772 "Get a list of all headline targs applicable at POS.
6773 POS defaults to point. If tags are inherited, the list contains
6774 the targets in the same sequence as the headlines appear, i.e.
6775 the tags of the current headline come last."
6776 (interactive)
6777 (let (tags)
6778 (save-excursion
6779 (goto-char (or pos (point)))
6780 (save-match-data
6781 (org-back-to-heading t)
6782 (condition-case nil
6783 (while t
6784 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6785 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6786 (or org-use-tag-inheritance (error ""))
6787 (org-up-heading-all 1))
6788 (error nil))))
6789 (message "%s" tags)
6790 tags))
6791
6792 (defun org-agenda-set-tags ()
6793 "Set tags for the current headline."
6794 (interactive)
6795 (org-agenda-check-no-diary)
6796 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6797 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6798 (org-agenda-error)))
6799 (buffer (marker-buffer hdmarker))
6800 (pos (marker-position hdmarker))
6801 (buffer-read-only nil)
6802 newhead)
6803 (with-current-buffer buffer
6804 (widen)
6805 (goto-char pos)
6806 (org-show-hidden-entry)
6807 (save-excursion
6808 (and (outline-next-heading)
6809 (org-flag-heading nil))) ; show the next heading
6810 (call-interactively 'org-set-tags)
6811 (end-of-line 1)
6812 (setq newhead (org-get-heading)))
6813 (org-agenda-change-all-lines newhead hdmarker)
6814 (beginning-of-line 1)))
6815
6816 (defun org-agenda-date-later (arg &optional what)
6817 "Change the date of this item to one day later."
6818 (interactive "p")
6819 (org-agenda-check-type t 'agenda 'timeline)
6820 (org-agenda-check-no-diary)
6821 (let* ((marker (or (get-text-property (point) 'org-marker)
6822 (org-agenda-error)))
6823 (buffer (marker-buffer marker))
6824 (pos (marker-position marker)))
6825 (with-current-buffer buffer
6826 (widen)
6827 (goto-char pos)
6828 (if (not (org-at-timestamp-p))
6829 (error "Cannot find time stamp"))
6830 (org-timestamp-change arg (or what 'day))
6831 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6832
6833 (defun org-agenda-date-earlier (arg &optional what)
6834 "Change the date of this item to one day earlier."
6835 (interactive "p")
6836 (org-agenda-date-later (- arg) what))
6837
6838 (defun org-agenda-date-prompt (arg)
6839 "Change the date of this item. Date is prompted for, with default today.
6840 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6841 be used to request time specification in the time stamp."
6842 (interactive "P")
6843 (org-agenda-check-type t 'agenda 'timeline)
6844 (org-agenda-check-no-diary)
6845 (let* ((marker (or (get-text-property (point) 'org-marker)
6846 (org-agenda-error)))
6847 (buffer (marker-buffer marker))
6848 (pos (marker-position marker)))
6849 (with-current-buffer buffer
6850 (widen)
6851 (goto-char pos)
6852 (if (not (org-at-timestamp-p))
6853 (error "Cannot find time stamp"))
6854 (org-time-stamp arg)
6855 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6856
6857 (defun org-get-heading ()
6858 "Return the heading of the current entry, without the stars."
6859 (save-excursion
6860 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6861 (if (and (re-search-backward "[\r\n]\\*" nil t)
6862 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6863 (match-string 1)
6864 "")))
6865
6866 (defun org-agenda-diary-entry ()
6867 "Make a diary entry, like the `i' command from the calendar.
6868 All the standard commands work: block, weekly etc."
6869 (interactive)
6870 (org-agenda-check-type t 'agenda 'timeline)
6871 (require 'diary-lib)
6872 (let* ((char (progn
6873 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6874 (read-char-exclusive)))
6875 (cmd (cdr (assoc char
6876 '((?d . insert-diary-entry)
6877 (?w . insert-weekly-diary-entry)
6878 (?m . insert-monthly-diary-entry)
6879 (?y . insert-yearly-diary-entry)
6880 (?a . insert-anniversary-diary-entry)
6881 (?b . insert-block-diary-entry)
6882 (?c . insert-cyclic-diary-entry)))))
6883 (oldf (symbol-function 'calendar-cursor-to-date))
6884 (point (point))
6885 (mark (or (mark t) (point))))
6886 (unless cmd
6887 (error "No command associated with <%c>" char))
6888 (unless (and (get-text-property point 'day)
6889 (or (not (equal ?b char))
6890 (get-text-property mark 'day)))
6891 (error "Don't know which date to use for diary entry"))
6892 ;; We implement this by hacking the `calendar-cursor-to-date' function
6893 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6894 (let ((calendar-mark-ring
6895 (list (calendar-gregorian-from-absolute
6896 (or (get-text-property mark 'day)
6897 (get-text-property point 'day))))))
6898 (unwind-protect
6899 (progn
6900 (fset 'calendar-cursor-to-date
6901 (lambda (&optional error)
6902 (calendar-gregorian-from-absolute
6903 (get-text-property point 'day))))
6904 (call-interactively cmd))
6905 (fset 'calendar-cursor-to-date oldf)))))
6906
6907
6908 (defun org-agenda-execute-calendar-command (cmd)
6909 "Execute a calendar command from the agenda, with the date associated to
6910 the cursor position."
6911 (org-agenda-check-type t 'agenda 'timeline)
6912 (require 'diary-lib)
6913 (unless (get-text-property (point) 'day)
6914 (error "Don't know which date to use for calendar command"))
6915 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6916 (point (point))
6917 (date (calendar-gregorian-from-absolute
6918 (get-text-property point 'day)))
6919 (displayed-day (extract-calendar-day date))
6920 (displayed-month (extract-calendar-month date))
6921 (displayed-year (extract-calendar-year date)))
6922 (unwind-protect
6923 (progn
6924 (fset 'calendar-cursor-to-date
6925 (lambda (&optional error)
6926 (calendar-gregorian-from-absolute
6927 (get-text-property point 'day))))
6928 (call-interactively cmd))
6929 (fset 'calendar-cursor-to-date oldf))))
6930
6931 (defun org-agenda-phases-of-moon ()
6932 "Display the phases of the moon for the 3 months around the cursor date."
6933 (interactive)
6934 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6935
6936 (defun org-agenda-holidays ()
6937 "Display the holidays for the 3 months around the cursor date."
6938 (interactive)
6939 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6940
6941 (defun org-agenda-sunrise-sunset (arg)
6942 "Display sunrise and sunset for the cursor date.
6943 Latitude and longitude can be specified with the variables
6944 `calendar-latitude' and `calendar-longitude'. When called with prefix
6945 argument, latitude and longitude will be prompted for."
6946 (interactive "P")
6947 (let ((calendar-longitude (if arg nil calendar-longitude))
6948 (calendar-latitude (if arg nil calendar-latitude))
6949 (calendar-location-name
6950 (if arg "the given coordinates" calendar-location-name)))
6951 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6952
6953 (defun org-agenda-goto-calendar ()
6954 "Open the Emacs calendar with the date at the cursor."
6955 (interactive)
6956 (org-agenda-check-type t 'agenda 'timeline)
6957 (let* ((day (or (get-text-property (point) 'day)
6958 (error "Don't know which date to open in calendar")))
6959 (date (calendar-gregorian-from-absolute day))
6960 (calendar-move-hook nil)
6961 (view-diary-entries-initially nil))
6962 (calendar)
6963 (calendar-goto-date date)))
6964
6965 (defun org-calendar-goto-agenda ()
6966 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6967 This is a command that has to be installed in `calendar-mode-map'."
6968 (interactive)
6969 (org-agenda-list nil (calendar-absolute-from-gregorian
6970 (calendar-cursor-to-date))
6971 nil t))
6972
6973 (defun org-agenda-convert-date ()
6974 (interactive)
6975 (org-agenda-check-type t 'agenda 'timeline)
6976 (let ((day (get-text-property (point) 'day))
6977 date s)
6978 (unless day
6979 (error "Don't know which date to convert"))
6980 (setq date (calendar-gregorian-from-absolute day))
6981 (setq s (concat
6982 "Gregorian: " (calendar-date-string date) "\n"
6983 "ISO: " (calendar-iso-date-string date) "\n"
6984 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6985 "Julian: " (calendar-julian-date-string date) "\n"
6986 "Astron. JD: " (calendar-astro-date-string date)
6987 " (Julian date number at noon UTC)\n"
6988 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6989 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6990 "French: " (calendar-french-date-string date) "\n"
6991 "Mayan: " (calendar-mayan-date-string date) "\n"
6992 "Coptic: " (calendar-coptic-date-string date) "\n"
6993 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6994 "Persian: " (calendar-persian-date-string date) "\n"
6995 "Chinese: " (calendar-chinese-date-string date) "\n"))
6996 (with-output-to-temp-buffer "*Dates*"
6997 (princ s))
6998 (if (fboundp 'fit-window-to-buffer)
6999 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
7000
7001 ;;; Tags
7002
7003 (defun org-scan-tags (action matcher &optional todo-only)
7004 "Scan headline tags with inheritance and produce output ACTION.
7005 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
7006 evaluated, testing if a given set of tags qualifies a headline for
7007 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
7008 are included in the output."
7009 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
7010 (mapconcat 'regexp-quote
7011 (nreverse (cdr (reverse org-todo-keywords)))
7012 "\\|")
7013 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
7014 (props (list 'face nil
7015 'done-face 'org-done
7016 'undone-face nil
7017 'mouse-face 'highlight
7018 'keymap org-agenda-keymap
7019 'help-echo
7020 (format "mouse-2 or RET jump to org file %s"
7021 (abbreviate-file-name buffer-file-name))))
7022 lspos
7023 tags tags-list tags-alist (llast 0) rtn level category i txt
7024 todo marker)
7025
7026 (save-excursion
7027 (goto-char (point-min))
7028 (when (eq action 'sparse-tree) (hide-sublevels 1))
7029 (while (re-search-forward re nil t)
7030 (setq todo (if (match-end 1) (match-string 2))
7031 tags (if (match-end 4) (match-string 4)))
7032 (goto-char (setq lspos (1+ (match-beginning 0))))
7033 (setq level (funcall outline-level)
7034 category (org-get-category))
7035 (setq i llast llast level)
7036 ;; remove tag lists from same and sublevels
7037 (while (>= i level)
7038 (when (setq entry (assoc i tags-alist))
7039 (setq tags-alist (delete entry tags-alist)))
7040 (setq i (1- i)))
7041 ;; add the nex tags
7042 (when tags
7043 (setq tags (mapcar 'downcase (org-split-string tags ":"))
7044 tags-alist
7045 (cons (cons level tags) tags-alist)))
7046 ;; compile tags for current headline
7047 (setq tags-list
7048 (if org-use-tag-inheritance
7049 (apply 'append (mapcar 'cdr tags-alist))
7050 tags))
7051 (when (and (or (not todo-only) todo)
7052 (eval matcher))
7053 ;; list this headline
7054 (if (eq action 'sparse-tree)
7055 (progn
7056 (org-show-hierarchy-above))
7057 (setq txt (org-format-agenda-item
7058 ""
7059 (concat
7060 (if org-tags-match-list-sublevels
7061 (make-string (1- level) ?.) "")
7062 (org-get-heading))
7063 category tags-list))
7064 (goto-char lspos)
7065 (setq marker (org-agenda-new-marker))
7066 (org-add-props txt props
7067 'org-marker marker 'org-hd-marker marker 'category category)
7068 (push txt rtn))
7069 ;; if we are to skip sublevels, jump to end of subtree
7070 (point)
7071 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
7072 (nreverse rtn)))
7073
7074 (defun org-tags-sparse-tree (&optional arg match)
7075 "Create a sparse tree according to tags search string MATCH.
7076 MATCH can contain positive and negative selection of tags, like
7077 \"+WORK+URGENT-WITHBOSS\"."
7078 (interactive "P")
7079 (let ((org-show-following-heading nil)
7080 (org-show-hierarchy-above nil))
7081 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
7082
7083 (defun org-make-tags-matcher (match)
7084 "Create the TAGS matcher form for the tags-selecting string MATCH."
7085 (unless match
7086 ;; Get a new match request, with completion
7087 (setq org-last-tags-completion-table
7088 (or (org-get-buffer-tags)
7089 org-last-tags-completion-table))
7090 (setq match (completing-read
7091 "Tags: " 'org-tags-completion-function nil nil nil
7092 'org-tags-history)))
7093 ;; parse the string and create a lisp form
7094 (let ((match0 match) minus tag mm matcher orterms term orlist)
7095 (setq orterms (org-split-string match "|"))
7096 (while (setq term (pop orterms))
7097 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
7098 (setq minus (and (match-end 1)
7099 (equal (match-string 1 term) "-"))
7100 tag (match-string 2 term)
7101 term (substring term (match-end 0))
7102 mm (list 'member (downcase tag) 'tags-list)
7103 mm (if minus (list 'not mm) mm))
7104 (push mm matcher))
7105 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
7106 orlist)
7107 (setq matcher nil))
7108 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
7109 ;; Return the string and lisp forms of the matcher
7110 (cons match0 matcher)))
7111
7112 ;;;###autoload
7113 (defun org-tags-view (&optional todo-only match keep-modes)
7114 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
7115 The prefix arg TODO-ONLY limits the search to TODO entries."
7116 (interactive "P")
7117 (org-agenda-maybe-reset-markers 'force)
7118 (org-compile-prefix-format org-agenda-prefix-format)
7119 (let* ((org-agenda-keep-modes keep-modes)
7120 (org-tags-match-list-sublevels
7121 (if todo-only t org-tags-match-list-sublevels))
7122 (win (selected-window))
7123 (completion-ignore-case t)
7124 rtn rtnall files file pos matcher
7125 buffer)
7126 (setq matcher (org-make-tags-matcher match)
7127 match (car matcher) matcher (cdr matcher))
7128 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
7129 (progn
7130 (delete-other-windows)
7131 (switch-to-buffer-other-window
7132 (get-buffer-create org-agenda-buffer-name))))
7133 (setq buffer-read-only nil)
7134 (erase-buffer)
7135 (org-agenda-mode) (setq buffer-read-only nil)
7136 (set (make-local-variable 'org-agenda-type) 'tags)
7137 (set (make-local-variable 'org-agenda-redo-command)
7138 (list 'org-tags-view (list 'quote todo-only)
7139 (list 'if 'current-prefix-arg nil match) t))
7140 (setq files (org-agenda-files)
7141 rtnall nil)
7142 (while (setq file (pop files))
7143 (catch 'nextfile
7144 (org-check-agenda-file file)
7145 (setq buffer (if (file-exists-p file)
7146 (org-get-agenda-file-buffer file)
7147 (error "No such file %s" file)))
7148 (if (not buffer)
7149 ;; If file does not exist, merror message to agenda
7150 (setq rtn (list
7151 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7152 rtnall (append rtnall rtn))
7153 (with-current-buffer buffer
7154 (unless (eq major-mode 'org-mode)
7155 (error "Agenda file %s is not in `org-mode'" file))
7156 (save-excursion
7157 (save-restriction
7158 (if org-respect-restriction
7159 (if (org-region-active-p)
7160 ;; Respect a region to restrict search
7161 (narrow-to-region (region-beginning) (region-end)))
7162 ;; If we work for the calendar or many files,
7163 ;; get rid of any restriction
7164 (widen))
7165 (setq rtn (org-scan-tags 'agenda matcher todo-only))
7166 (setq rtnall (append rtnall rtn))))))))
7167 (insert "Headlines with TAGS match: ")
7168 (add-text-properties (point-min) (1- (point))
7169 (list 'face 'org-level-3))
7170 (setq pos (point))
7171 (insert match "\n")
7172 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7173 (setq pos (point))
7174 (insert "Press `C-u r' to search again with new search string\n")
7175 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7176 (when rtnall
7177 (insert (mapconcat 'identity rtnall "\n")))
7178 (goto-char (point-min))
7179 (setq buffer-read-only t)
7180 (org-fit-agenda-window)
7181 (if (not org-select-agenda-window) (select-window win))))
7182
7183 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
7184 (defun org-set-tags (&optional arg just-align)
7185 "Set the tags for the current headline.
7186 With prefix ARG, realign all tags in headings in the current buffer."
7187 (interactive)
7188 (let* (;(inherit (org-get-inherited-tags))
7189 (re (concat "^" outline-regexp))
7190 (col (current-column))
7191 (current (org-get-tags))
7192 tags hd empty invis)
7193 (if arg
7194 (save-excursion
7195 (goto-char (point-min))
7196 (while (re-search-forward re nil t)
7197 (org-set-tags nil t))
7198 (message "All tags realigned to column %d" org-tags-column))
7199 (if just-align
7200 (setq tags current)
7201 (setq org-last-tags-completion-table
7202 (or (org-get-buffer-tags)
7203 org-last-tags-completion-table))
7204 (setq tags
7205 (let ((org-add-colon-after-tag-completion t))
7206 (completing-read "Tags: " 'org-tags-completion-function
7207 nil nil current 'org-tags-history)))
7208 (while (string-match "[-+&]+" tags)
7209 (setq tags (replace-match ":" t t tags))))
7210 ;; FIXME: still optimize this by not checking when JUST-ALIGN?
7211 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
7212 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
7213 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
7214 (if (equal current "")
7215 (progn
7216 (end-of-line 1)
7217 (or empty (insert-before-markers " ")))
7218 (beginning-of-line 1)
7219 (setq invis (org-invisible-p))
7220 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
7221 (setq hd (match-string 1))
7222 (delete-region (match-beginning 0) (match-end 0))
7223 (insert-before-markers (org-trim hd) (if empty "" " ")))
7224 (unless (equal tags "")
7225 (move-to-column (max (current-column)
7226 (if (> org-tags-column 0)
7227 org-tags-column
7228 (- (- org-tags-column) (length tags))))
7229 t)
7230 (insert-before-markers tags)
7231 (if (and (not invis) (org-invisible-p))
7232 (outline-flag-region (point-at-bol) (point) nil)))
7233 (move-to-column col))))
7234
7235 (defun org-tags-completion-function (string predicate &optional flag)
7236 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
7237 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
7238 (setq s1 (match-string 1 string)
7239 s2 (match-string 2 string))
7240 (setq s1 "" s2 string))
7241 (cond
7242 ((eq flag nil)
7243 ;; try completion
7244 (setq rtn (try-completion s2 ctable))
7245 (if (stringp rtn)
7246 (concat s1 s2 (substring rtn (length s2))
7247 (if (and org-add-colon-after-tag-completion
7248 (assoc rtn ctable))
7249 ":" "")))
7250 )
7251 ((eq flag t)
7252 ;; all-completions
7253 (all-completions s2 ctable)
7254 )
7255 ((eq flag 'lambda)
7256 ;; exact match?
7257 (assoc s2 ctable)))
7258 ))
7259
7260 (defun org-get-tags ()
7261 "Get the TAGS string in the current headline."
7262 (unless (org-on-heading-p)
7263 (error "Not on a heading"))
7264 (save-excursion
7265 (beginning-of-line 1)
7266 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
7267 (org-match-string-no-properties 1)
7268 "")))
7269
7270 (defun org-get-buffer-tags ()
7271 "Get a table of all tags used in the buffer, for completion."
7272 (let (tags)
7273 (save-excursion
7274 (goto-char (point-min))
7275 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
7276 (mapc (lambda (x) (add-to-list 'tags x))
7277 (org-split-string (org-match-string-no-properties 1) ":"))))
7278 (mapcar 'list tags)))
7279
7280 ;;; Link Stuff
7281
7282 (defun org-find-file-at-mouse (ev)
7283 "Open file link or URL at mouse."
7284 (interactive "e")
7285 (mouse-set-point ev)
7286 (org-open-at-point 'in-emacs))
7287
7288 (defun org-open-at-mouse (ev)
7289 "Open file link or URL at mouse."
7290 (interactive "e")
7291 (mouse-set-point ev)
7292 (org-open-at-point))
7293
7294 (defun org-open-at-point (&optional in-emacs)
7295 "Open link at or after point.
7296 If there is no link at point, this function will search forward up to
7297 the end of the current subtree.
7298 Normally, files will be opened by an appropriate application. If the
7299 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7300 (interactive "P")
7301 (org-remove-occur-highlights nil nil t)
7302 (if (org-at-timestamp-p)
7303 (org-agenda-list nil (time-to-days (org-time-string-to-time
7304 (substring (match-string 1) 0 10)))
7305 1)
7306 (let (type path link line search (pos (point)))
7307 (catch 'match
7308 (save-excursion
7309 (skip-chars-forward "^]\n\r")
7310 (when (and (re-search-backward "\\[\\[" nil t)
7311 (looking-at org-bracket-link-regexp)
7312 (<= (match-beginning 0) pos)
7313 (>= (match-end 0) pos))
7314 (setq link (org-link-unescape (org-match-string-no-properties 1)))
7315 (while (string-match " *\n *" link)
7316 (setq link (replace-match " " t t link)))
7317 (if (string-match org-link-re-with-space2 link)
7318 (setq type (match-string 1 link)
7319 path (match-string 2 link))
7320 (setq type "thisfile"
7321 path link))
7322 (throw 'match t)))
7323
7324 (when (get-text-property (point) 'org-linked-text)
7325 (setq type "thisfile"
7326 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7327 (1+ (point)) (point))
7328 path (buffer-substring
7329 (previous-single-property-change pos 'org-linked-text)
7330 (next-single-property-change pos 'org-linked-text)))
7331 (throw 'match t))
7332
7333 (save-excursion
7334 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
7335 (if (equal (char-before) ?<) (backward-char 1))
7336 (when (or (looking-at org-angle-link-re)
7337 (looking-at org-plain-link-re)
7338 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
7339 (re-search-forward org-plain-link-re (point-at-eol) t))
7340 (<= (match-beginning 0) pos)
7341 (>= (match-end 0) pos)))
7342 (setq type (match-string 1)
7343 path (match-string 2))
7344 (throw 'match t)))
7345 (save-excursion
7346 (skip-chars-backward "^ \t\n\r")
7347 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
7348 (setq type "tags"
7349 path (match-string 1))
7350 (while (string-match ":" path)
7351 (setq path (replace-match "+" t t path)))
7352 (throw 'match t)))
7353 (save-excursion
7354 (skip-chars-backward "a-zA-Z_")
7355 (when (and (memq 'camel org-activate-links)
7356 (looking-at org-camel-regexp))
7357 (setq type "camel" path (match-string 0))
7358 (if (equal (char-before) ?*)
7359 (setq path (concat "*" path))))
7360 (throw 'match t)))
7361 (unless path
7362 (error "No link found"))
7363 ;; Remove any trailing spaces in path
7364 (if (string-match " +\\'" path)
7365 (setq path (replace-match "" t t path)))
7366
7367 (cond
7368
7369 ((member type '("http" "https" "ftp" "mailto" "news"))
7370 (browse-url (concat type ":" path)))
7371
7372 ((string= type "tags")
7373 (org-tags-view in-emacs path))
7374 ((or (string= type "camel")
7375 (string= type "thisfile"))
7376 (org-mark-ring-push)
7377 (org-link-search
7378 path
7379 (cond ((equal in-emacs '(4)) 'occur)
7380 ((equal in-emacs '(16)) 'org-occur)
7381 (t nil))))
7382
7383 ((string= type "file")
7384 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
7385 (setq line (string-to-number (match-string 1 path))
7386 path (substring path 0 (match-beginning 0)))
7387 (if (string-match "::\\(.+\\)\\'" path)
7388 (setq search (match-string 1 path)
7389 path (substring path 0 (match-beginning 0)))))
7390 (org-open-file path in-emacs line search))
7391
7392 ((string= type "news")
7393 (org-follow-gnus-link path))
7394
7395 ((string= type "bbdb")
7396 (org-follow-bbdb-link path))
7397
7398 ((string= type "gnus")
7399 (let (group article)
7400 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7401 (error "Error in Gnus link"))
7402 (setq group (match-string 1 path)
7403 article (match-string 3 path))
7404 (org-follow-gnus-link group article)))
7405
7406 ((string= type "vm")
7407 (let (folder article)
7408 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7409 (error "Error in VM link"))
7410 (setq folder (match-string 1 path)
7411 article (match-string 3 path))
7412 ;; in-emacs is the prefix arg, will be interpreted as read-only
7413 (org-follow-vm-link folder article in-emacs)))
7414
7415 ((string= type "wl")
7416 (let (folder article)
7417 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7418 (error "Error in Wanderlust link"))
7419 (setq folder (match-string 1 path)
7420 article (match-string 3 path))
7421 (org-follow-wl-link folder article)))
7422
7423 ((string= type "mhe")
7424 (let (folder article)
7425 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7426 (error "Error in MHE link"))
7427 (setq folder (match-string 1 path)
7428 article (match-string 3 path))
7429 (org-follow-mhe-link folder article)))
7430
7431 ((string= type "rmail")
7432 (let (folder article)
7433 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7434 (error "Error in RMAIL link"))
7435 (setq folder (match-string 1 path)
7436 article (match-string 3 path))
7437 (org-follow-rmail-link folder article)))
7438
7439 ((string= type "shell")
7440 (let ((cmd path))
7441 (while (string-match "@{" cmd)
7442 (setq cmd (replace-match "<" t t cmd)))
7443 (while (string-match "@}" cmd)
7444 (setq cmd (replace-match ">" t t cmd)))
7445 (if (or (not org-confirm-shell-links)
7446 (funcall org-confirm-shell-links
7447 (format "Execute \"%s\" in shell? "
7448 (org-add-props cmd nil
7449 'face 'org-warning))))
7450 (progn
7451 (message "Executing %s..." cmd)
7452 (shell-command cmd)
7453 (message "Executing %s...done" cmd))
7454 (error "Abort"))))
7455
7456 (t
7457 (browse-url-at-point))))))
7458
7459 (defun org-link-search (s &optional type)
7460 "Search for a link search option.
7461 When S is a CamelCaseWord, search for a target, or for a sentence containing
7462 the words. If S is surrounded by forward slashes, it is interpreted as a
7463 regular expression. In org-mode files, this will create an `org-occur'
7464 sparse tree. In ordinary files, `occur' will be used to list matches.
7465 If the current buffer is in `dired-mode', grep will be used to search
7466 in all files."
7467 (let ((case-fold-search t)
7468 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7469 (pos (point))
7470 (pre "") (post "")
7471 words re0 re1 re2 re3 re4 re5 re2a reall camel)
7472 (cond ((save-excursion
7473 (goto-char (point-min))
7474 (and
7475 (re-search-forward
7476 (concat "<<" (regexp-quote s0) ">>") nil t)
7477 (setq pos (match-beginning 0))))
7478 ;; There is an exact target for this
7479 (goto-char pos))
7480 ((string-match "^/\\(.*\\)/$" s)
7481 ;; A regular expression
7482 (cond
7483 ((eq major-mode 'org-mode)
7484 (org-occur (match-string 1 s)))
7485 ;;((eq major-mode 'dired-mode)
7486 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7487 (t (org-do-occur (match-string 1 s)))))
7488 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
7489 t)
7490 ;; A camel or a normal search string
7491 (when (equal (string-to-char s) ?*)
7492 ;; Anchor on headlines, post may include tags.
7493 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
7494 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
7495 s (substring s 1)))
7496 (remove-text-properties
7497 0 (length s)
7498 '(face nil mouse-face nil keymap nil fontified nil) s)
7499 ;; Make a series of regular expressions to find a match
7500 (setq words
7501 (if camel
7502 (org-camel-to-words s)
7503 (org-split-string s "[ \n\r\t]+"))
7504 re0 (concat "<<" (regexp-quote s0) ">>")
7505 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
7506 re2a (concat "\\<" (mapconcat 'downcase words "[ \t\r\n]+") "\\>")
7507 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
7508 re1 (concat pre re2 post)
7509 re3 (concat pre re4 post)
7510 re5 (concat pre ".*" re4)
7511 re2 (concat pre re2)
7512 re2a (concat pre re2a)
7513 re4 (concat pre re4)
7514 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7515 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7516 re5 "\\)"
7517 ))
7518 (cond
7519 ((eq type 'org-occur) (org-occur reall))
7520 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7521 (t (goto-char (point-min))
7522 (if (or (org-search-not-link re0 nil t)
7523 (org-search-not-link re1 nil t)
7524 (org-search-not-link re2 nil t)
7525 (org-search-not-link re2a nil t)
7526 (org-search-not-link re3 nil t)
7527 (org-search-not-link re4 nil t)
7528 (org-search-not-link re5 nil t)
7529 )
7530 (goto-char (match-beginning 0))
7531 (goto-char pos)
7532 (error "No match")))))
7533 (t
7534 ;; Normal string-search
7535 (goto-char (point-min))
7536 (if (search-forward s nil t)
7537 (goto-char (match-beginning 0))
7538 (error "No match"))))
7539 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
7540
7541 (defun org-search-not-link (&rest args)
7542 "Execute `re-search-forward', but only accept matches that are not a link."
7543 (catch 'exit
7544 (let ((pos (point)) p1)
7545 (while (apply 're-search-forward args)
7546 (setq p1 (point))
7547 (if (not (save-match-data
7548 (and (re-search-backward "\\[\\[" nil t)
7549 (looking-at org-bracket-link-regexp)
7550 (<= (match-beginning 0) p1)
7551 (>= (match-end 0) p1))))
7552 (progn (goto-char (match-end 0))
7553 (throw 'exit (point)))
7554 (goto-char (match-end 0)))))))
7555
7556 (defun org-do-occur (regexp &optional cleanup)
7557 "Call the Emacs command `occur'.
7558 If CLEANUP is non-nil, remove the printout of the regular expression
7559 in the *Occur* buffer. This is useful if the regex is long and not useful
7560 to read."
7561 (occur regexp)
7562 (when cleanup
7563 (let ((cwin (selected-window)) win beg end)
7564 (when (setq win (get-buffer-window "*Occur*"))
7565 (select-window win))
7566 (goto-char (point-min))
7567 (when (re-search-forward "match[a-z]+" nil t)
7568 (setq beg (match-end 0))
7569 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7570 (setq end (1- (match-beginning 0)))))
7571 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
7572 (goto-char (point-min))
7573 (select-window cwin))))
7574
7575 (defvar org-mark-ring nil
7576 "Mark ring for positions before jumps in Org-mode.")
7577 (defvar org-mark-ring-last-goto nil
7578 "Last position in the mark ring used to go back.")
7579 ;; Fill and close the ring
7580 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7581 (loop for i from 1 to org-mark-ring-length do
7582 (push (make-marker) org-mark-ring))
7583 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7584 org-mark-ring)
7585
7586 (defun org-mark-ring-push (&optional pos buffer)
7587 "Put the current position or POS into the mark ring and rotate it."
7588 (interactive)
7589 (setq pos (or pos (point)))
7590 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7591 (move-marker (car org-mark-ring)
7592 (or pos (point))
7593 (or buffer (current-buffer)))
7594 (message
7595 (substitute-command-keys
7596 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7597
7598 (defun org-mark-ring-goto (&optional n)
7599 "Jump to the previous position in the mark ring.
7600 With prefix arg N, jump back that many stored positions. When
7601 called several times in succession, walk through the entire ring.
7602 Org-mode commands jumping to a different position in the current file,
7603 or to another Org-mode file, automatically push the old position
7604 onto the ring."
7605 (interactive "p")
7606 (let (p m)
7607 (if (eq last-command this-command)
7608 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7609 (setq p org-mark-ring))
7610 (setq org-mark-ring-last-goto p)
7611 (setq m (car p))
7612 (switch-to-buffer (marker-buffer m))
7613 (goto-char m)
7614 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7615
7616 (defun org-camel-to-words (s)
7617 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7618 (let ((case-fold-search nil)
7619 words)
7620 (while (string-match "[a-z][A-Z]" s)
7621 (push (substring s 0 (1+ (match-beginning 0))) words)
7622 (setq s (substring s (1+ (match-beginning 0)))))
7623 (nreverse (cons s words))))
7624
7625 (defun org-remove-angle-brackets (s)
7626 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7627 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7628 s)
7629 (defun org-add-angle-brackets (s)
7630 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7631 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7632 s)
7633
7634 (defun org-follow-bbdb-link (name)
7635 "Follow a BBDB link to NAME."
7636 (require 'bbdb)
7637 (let ((inhibit-redisplay t)
7638 (bbdb-electric-p nil))
7639 (catch 'exit
7640 ;; Exact match on name
7641 (bbdb-name (concat "\\`" name "\\'") nil)
7642 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7643 ;; Exact match on name
7644 (bbdb-company (concat "\\`" name "\\'") nil)
7645 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7646 ;; Partial match on name
7647 (bbdb-name name nil)
7648 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7649 ;; Partial match on company
7650 (bbdb-company name nil)
7651 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7652 ;; General match including network address and notes
7653 (bbdb name nil)
7654 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7655 (delete-window (get-buffer-window "*BBDB*"))
7656 (error "No matching BBDB record")))))
7657
7658 (defun org-follow-gnus-link (&optional group article)
7659 "Follow a Gnus link to GROUP and ARTICLE."
7660 (require 'gnus)
7661 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7662 (if group (gnus-fetch-group group))
7663 (if article
7664 (or (gnus-summary-goto-article article nil 'force)
7665 (if (fboundp 'gnus-summary-insert-cached-articles)
7666 (progn
7667 (gnus-summary-insert-cached-articles)
7668 (gnus-summary-goto-article article nil 'force))
7669 (message "Message could not be found.")))))
7670
7671 (defun org-follow-vm-link (&optional folder article readonly)
7672 "Follow a VM link to FOLDER and ARTICLE."
7673 (require 'vm)
7674 (setq article (org-add-angle-brackets article))
7675 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7676 ;; ange-ftp or efs or tramp access
7677 (let ((user (or (match-string 1 folder) (user-login-name)))
7678 (host (match-string 2 folder))
7679 (file (match-string 3 folder)))
7680 (cond
7681 ((featurep 'tramp)
7682 ;; use tramp to access the file
7683 (if (featurep 'xemacs)
7684 (setq folder (format "[%s@%s]%s" user host file))
7685 (setq folder (format "/%s@%s:%s" user host file))))
7686 (t
7687 ;; use ange-ftp or efs
7688 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
7689 (setq folder (format "/%s@%s:%s" user host file))))))
7690 (when folder
7691 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7692 (sit-for 0.1)
7693 (when article
7694 (vm-select-folder-buffer)
7695 (widen)
7696 (let ((case-fold-search t))
7697 (goto-char (point-min))
7698 (if (not (re-search-forward
7699 (concat "^" "message-id: *" (regexp-quote article))))
7700 (error "Could not find the specified message in this folder"))
7701 (vm-isearch-update)
7702 (vm-isearch-narrow)
7703 (vm-beginning-of-message)
7704 (vm-summarize)))))
7705
7706 (defun org-follow-wl-link (folder article)
7707 "Follow a Wanderlust link to FOLDER and ARTICLE."
7708 (setq article (org-add-angle-brackets article))
7709 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7710 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7711 (wl-summary-redisplay))
7712
7713 (defun org-follow-rmail-link (folder article)
7714 "Follow an RMAIL link to FOLDER and ARTICLE."
7715 (setq article (org-add-angle-brackets article))
7716 (let (message-number)
7717 (save-excursion
7718 (save-window-excursion
7719 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7720 (setq message-number
7721 (save-restriction
7722 (widen)
7723 (goto-char (point-max))
7724 (if (re-search-backward
7725 (concat "^Message-ID:\\s-+" (regexp-quote
7726 (or article "")))
7727 nil t)
7728 (rmail-what-message))))))
7729 (if message-number
7730 (progn
7731 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7732 (rmail-show-message message-number)
7733 message-number)
7734 (error "Message not found"))))
7735
7736 ;; mh-e integration based on planner-mode
7737 (defun org-mhe-get-message-real-folder ()
7738 "Return the name of the current message real folder, so if you use
7739 sequences, it will now work."
7740 (save-excursion
7741 (let* ((folder
7742 (if (equal major-mode 'mh-folder-mode)
7743 mh-current-folder
7744 ;; Refer to the show buffer
7745 mh-show-folder-buffer))
7746 (end-index
7747 (if (boundp 'mh-index-folder)
7748 (min (length mh-index-folder) (length folder))))
7749 )
7750 ;; a simple test on mh-index-data does not work, because
7751 ;; mh-index-data is always nil in a show buffer.
7752 (if (and (boundp 'mh-index-folder)
7753 (string= mh-index-folder (substring folder 0 end-index)))
7754 (if (equal major-mode 'mh-show-mode)
7755 (save-window-excursion
7756 (when (buffer-live-p (get-buffer folder))
7757 (progn
7758 (pop-to-buffer folder)
7759 (org-mhe-get-message-folder-from-index)
7760 )
7761 ))
7762 (org-mhe-get-message-folder-from-index)
7763 )
7764 folder
7765 )
7766 )))
7767
7768 (defun org-mhe-get-message-folder-from-index ()
7769 "Returns the name of the message folder in a index folder buffer."
7770 (save-excursion
7771 (mh-index-previous-folder)
7772 (re-search-forward "^\\(+.*\\)$" nil t)
7773 (message (match-string 1))))
7774
7775 (defun org-mhe-get-message-folder ()
7776 "Return the name of the current message folder. Be careful if you
7777 use sequences."
7778 (save-excursion
7779 (if (equal major-mode 'mh-folder-mode)
7780 mh-current-folder
7781 ;; Refer to the show buffer
7782 mh-show-folder-buffer)))
7783
7784 (defun org-mhe-get-message-num ()
7785 "Return the number of the current message. Be careful if you
7786 use sequences."
7787 (save-excursion
7788 (if (equal major-mode 'mh-folder-mode)
7789 (mh-get-msg-num nil)
7790 ;; Refer to the show buffer
7791 (mh-show-buffer-message-number))))
7792
7793 (defun org-mhe-get-header (header)
7794 "Return a header of the message in folder mode. This will create a
7795 show buffer for the corresponding message. If you have a more clever
7796 idea..."
7797 (let* ((folder (org-mhe-get-message-folder))
7798 (num (org-mhe-get-message-num))
7799 (buffer (get-buffer-create (concat "show-" folder)))
7800 (header-field))
7801 (with-current-buffer buffer
7802 (mh-display-msg num folder)
7803 (if (equal major-mode 'mh-folder-mode)
7804 (mh-header-display)
7805 (mh-show-header-display))
7806 (set-buffer buffer)
7807 (setq header-field (mh-get-header-field header))
7808 (if (equal major-mode 'mh-folder-mode)
7809 (mh-show)
7810 (mh-show-show))
7811 header-field)))
7812
7813 (defun org-follow-mhe-link (folder article)
7814 "Follow an MHE link to FOLDER and ARTICLE.
7815 If ARTICLE is nil FOLDER is shown. If the configuration variable
7816 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
7817 ARTICLE is searched in all folders. Indexed searches (swish++,
7818 namazu, and others supported by MH-E) will always search in all
7819 folders."
7820 (require 'mh-e)
7821 (require 'mh-search)
7822 (require 'mh-utils)
7823 (mh-find-path)
7824 (if (not article)
7825 (mh-visit-folder (mh-normalize-folder-name folder))
7826 (setq article (org-add-angle-brackets article))
7827 (mh-search-choose)
7828 (if (equal mh-searcher 'pick)
7829 (progn
7830 (mh-search folder (list "--message-id" article))
7831 (when (and org-mhe-search-all-folders
7832 (not (org-mhe-get-message-real-folder)))
7833 (kill-this-buffer)
7834 (mh-search "+" (list "--message-id" article))))
7835 (mh-search "+" article))
7836 (if (org-mhe-get-message-real-folder)
7837 (mh-show-msg 1)
7838 (kill-this-buffer)
7839 (error "Message not found"))))
7840
7841 (defun org-upgrade-old-links (&optional query-description)
7842 "Transfer old <...> style links to new [[...]] style links.
7843 With arg query-description, ask at each match for a description text to use
7844 for this link."
7845 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
7846 (save-excursion
7847 (goto-char (point-min))
7848 (let ((re (concat "\\([^[]\\)<\\("
7849 "\\(" (mapconcat 'identity org-link-types "\\|")
7850 "\\):"
7851 "[^" org-non-link-chars "]+\\)>"))
7852 l1 l2 (cnt 0))
7853 (while (re-search-forward re nil t)
7854 (setq cnt (1+ cnt)
7855 l1 (org-match-string-no-properties 2)
7856 l2 (save-match-data (org-link-escape l1)))
7857 (when query-description (setq l1 (read-string "Desc: " l1)))
7858 (if (equal l1 l2)
7859 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
7860 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
7861 (message "%d matches have beed treated" cnt))))
7862
7863 (defun org-open-file (path &optional in-emacs line search)
7864 "Open the file at PATH.
7865 First, this expands any special file name abbreviations. Then the
7866 configuration variable `org-file-apps' is checked if it contains an
7867 entry for this file type, and if yes, the corresponding command is launched.
7868 If no application is found, Emacs simply visits the file.
7869 With optional argument IN-EMACS, Emacs will visit the file.
7870 Optional LINE specifies a line to go to, optional SEARCH a string to
7871 search for. If LINE or SEARCH is given, the file will always be
7872 opened in Emacs.
7873 If the file does not exist, an error is thrown."
7874 (setq in-emacs (or in-emacs line search))
7875 (let* ((file (if (equal path "")
7876 buffer-file-name
7877 (convert-standard-filename (org-expand-file-name path))))
7878 (dirp (file-directory-p file))
7879 (dfile (downcase file))
7880 (old-buffer (current-buffer))
7881 (old-pos (point))
7882 (old-mode major-mode)
7883 ext cmd apps)
7884 (if (and (not (file-exists-p file))
7885 (not org-open-non-existing-files))
7886 (error "No such file: %s" file))
7887 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7888 (setq ext (match-string 1 dfile))
7889 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7890 (setq ext (match-string 1 dfile))))
7891 (setq apps (append org-file-apps (org-default-apps)))
7892 (if in-emacs
7893 (setq cmd 'emacs)
7894 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7895 (cdr (assoc ext apps))
7896 (cdr (assoc t apps)))))
7897 (when (eq cmd 'mailcap)
7898 (require 'mailcap)
7899 (mailcap-parse-mailcaps)
7900 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7901 (command (mailcap-mime-info mime-type)))
7902 (if (stringp command)
7903 (setq cmd command)
7904 (setq cmd 'emacs))))
7905 (cond
7906 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7907 ; (setq cmd (format cmd (concat "\"" file "\"")))
7908 ;; FIXME: normalize use of quotes
7909 (if (string-match "['\"]%s['\"]" cmd)
7910 (setq cmd (replace-match "'%s'" t t cmd)))
7911 (setq cmd (format cmd file))
7912 (save-window-excursion
7913 (shell-command (concat cmd " &"))))
7914 ((or (stringp cmd)
7915 (eq cmd 'emacs))
7916 (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
7917 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7918 (if line (goto-line line)
7919 (if search (org-link-search search))))
7920 ((consp cmd)
7921 (eval cmd))
7922 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7923 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7924 (or (not (equal old-buffer (current-buffer)))
7925 (not (equal old-pos (point))))
7926 (org-mark-ring-push old-pos old-buffer))))
7927
7928 (defun org-default-apps ()
7929 "Return the default applications for this operating system."
7930 (cond
7931 ((eq system-type 'darwin)
7932 org-file-apps-defaults-macosx)
7933 ((eq system-type 'windows-nt)
7934 org-file-apps-defaults-windowsnt)
7935 (t org-file-apps-defaults-gnu)))
7936
7937 (defun org-expand-file-name (path)
7938 "Replace special path abbreviations and expand the file name."
7939 (expand-file-name path))
7940
7941
7942 (defvar org-insert-link-history nil
7943 "Minibuffer history for links inserted with `org-insert-link'.")
7944
7945 (defvar org-stored-links nil
7946 "Contains the links stored with `org-store-link'.")
7947
7948 ;;;###autoload
7949 (defun org-store-link (arg)
7950 "\\<org-mode-map>Store an org-link to the current location.
7951 This link can later be inserted into an org-buffer with
7952 \\[org-insert-link].
7953 For some link types, a prefix arg is interpreted:
7954 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7955 For file links, arg negates `org-context-in-file-links'."
7956 (interactive "P")
7957 (let (link cpltxt desc txt (pos (point)))
7958 (cond
7959
7960 ((eq major-mode 'bbdb-mode)
7961 (setq cpltxt (concat
7962 "bbdb:"
7963 (or (bbdb-record-name (bbdb-current-record))
7964 (bbdb-record-company (bbdb-current-record))))
7965 link (org-make-link cpltxt)))
7966
7967 ((eq major-mode 'calendar-mode)
7968 (let ((cd (calendar-cursor-to-date)))
7969 (setq link
7970 (format-time-string
7971 (car org-time-stamp-formats)
7972 (apply 'encode-time
7973 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7974 nil nil nil))))))
7975
7976 ((or (eq major-mode 'vm-summary-mode)
7977 (eq major-mode 'vm-presentation-mode))
7978 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7979 (vm-follow-summary-cursor)
7980 (save-excursion
7981 (vm-select-folder-buffer)
7982 (let* ((message (car vm-message-pointer))
7983 (folder buffer-file-name)
7984 (subject (vm-su-subject message))
7985 (author (vm-su-full-name message))
7986 (message-id (vm-su-message-id message)))
7987 (setq message-id (org-remove-angle-brackets message-id))
7988 (setq folder (abbreviate-file-name folder))
7989 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7990 folder)
7991 (setq folder (replace-match "" t t folder)))
7992 (setq cpltxt (concat author " on: " subject))
7993 (setq link (org-make-link "vm:" folder "#" message-id)))))
7994
7995 ((eq major-mode 'wl-summary-mode)
7996 (let* ((msgnum (wl-summary-message-number))
7997 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7998 msgnum 'message-id))
7999 (wl-message-entity (elmo-msgdb-overview-get-entity
8000 msgnum (wl-summary-buffer-msgdb)))
8001 (author (wl-summary-line-from)) ; FIXME: correct?
8002 (subject "???")) ; FIXME:
8003 (setq message-id (org-remove-angle-brackets message-id))
8004 (setq cpltxt (concat author " on: " subject))
8005 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
8006 "#" message-id))))
8007
8008 ((or (equal major-mode 'mh-folder-mode)
8009 (equal major-mode 'mh-show-mode))
8010 (let ((from-header (org-mhe-get-header "From:"))
8011 (to-header (org-mhe-get-header "To:"))
8012 (subject (org-mhe-get-header "Subject:")))
8013 (setq cpltxt (concat from-header " on: " subject))
8014 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
8015 (org-remove-angle-brackets
8016 (org-mhe-get-header "Message-Id:"))))))
8017
8018 ((eq major-mode 'rmail-mode)
8019 (save-excursion
8020 (save-restriction
8021 (rmail-narrow-to-non-pruned-header)
8022 (let ((folder buffer-file-name)
8023 (message-id (mail-fetch-field "message-id"))
8024 (author (mail-fetch-field "from"))
8025 (subject (mail-fetch-field "subject")))
8026 (setq message-id (org-remove-angle-brackets message-id))
8027 (setq cpltxt (concat author " on: " subject))
8028 (setq link (org-make-link "rmail:" folder "#" message-id))))))
8029
8030 ((eq major-mode 'gnus-group-mode)
8031 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
8032 (gnus-group-group-name)) ; version
8033 ((fboundp 'gnus-group-name)
8034 (gnus-group-name))
8035 (t "???"))))
8036 (setq cpltxt (concat
8037 (if (org-xor arg org-usenet-links-prefer-google)
8038 "http://groups.google.com/groups?group="
8039 "gnus:")
8040 group)
8041 link (org-make-link cpltxt))))
8042
8043 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
8044 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
8045 (gnus-summary-beginning-of-article)
8046 (let* ((group (car gnus-article-current))
8047 (article (cdr gnus-article-current))
8048 (header (gnus-summary-article-header article))
8049 (author (mail-header-from header))
8050 (message-id (mail-header-id header))
8051 (date (mail-header-date header))
8052 (subject (gnus-summary-subject-string)))
8053 (setq cpltxt (concat author " on: " subject))
8054 (if (org-xor arg org-usenet-links-prefer-google)
8055 (setq link
8056 (concat
8057 cpltxt "\n "
8058 (format "http://groups.google.com/groups?as_umsgid=%s"
8059 (org-fixup-message-id-for-http message-id))))
8060 (setq link (org-make-link "gnus:" group
8061 "#" (number-to-string article))))))
8062
8063 ((eq major-mode 'w3-mode)
8064 (setq cpltxt (url-view-url t)
8065 link (org-make-link cpltxt)))
8066 ((eq major-mode 'w3m-mode)
8067 (setq cpltxt w3m-current-url
8068 link (org-make-link cpltxt)))
8069
8070 ((eq major-mode 'org-mode)
8071 ;; Just link to current headline
8072 (setq cpltxt (concat "file:"
8073 (abbreviate-file-name buffer-file-name)))
8074 ;; Add a context search string
8075 (when (org-xor org-context-in-file-links arg)
8076 ;; Check if we are on a target
8077 (if (save-excursion
8078 (skip-chars-forward "^>\n\r")
8079 (and (re-search-backward "<<" nil t)
8080 (looking-at "<<\\(.*?\\)>>")
8081 (<= (match-beginning 0) pos)
8082 (>= (match-end 0) pos)))
8083 (setq cpltxt (concat cpltxt "::" (match-string 1)))
8084 (setq txt (cond
8085 ((org-on-heading-p) nil)
8086 ((org-region-active-p)
8087 (buffer-substring (region-beginning) (region-end)))
8088 (t (buffer-substring (point-at-bol) (point-at-eol)))))
8089 (setq cpltxt
8090 (concat cpltxt "::"
8091 (if org-file-link-context-use-camel-case
8092 (org-make-org-heading-camel txt)
8093 (org-make-org-heading-search-string txt)))
8094 desc "NONE")))
8095 (if (string-match "::\\'" cpltxt)
8096 (setq cpltxt (substring cpltxt 0 -2)))
8097 (setq link (org-make-link cpltxt)))
8098
8099 (buffer-file-name
8100 ;; Just link to this file here.
8101 (setq cpltxt (concat "file:"
8102 (abbreviate-file-name buffer-file-name)))
8103 ;; Add a context string
8104 (when (org-xor org-context-in-file-links arg)
8105 (setq txt (if (org-region-active-p)
8106 (buffer-substring (region-beginning) (region-end))
8107 (buffer-substring (point-at-bol) (point-at-eol))))
8108 (setq cpltxt
8109 (concat cpltxt "::"
8110 (if org-file-link-context-use-camel-case
8111 (org-make-org-heading-camel txt)
8112 (org-make-org-heading-search-string txt)))
8113 desc "NONE"))
8114 (setq link (org-make-link cpltxt)))
8115
8116 ((interactive-p)
8117 (error "Cannot link to a buffer which is not visiting a file"))
8118
8119 (t (setq link nil)))
8120
8121 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8122 (setq link (or link cpltxt)
8123 desc (or desc cpltxt))
8124 (if (equal desc "NONE") (setq desc nil))
8125
8126 (if (and (interactive-p) link)
8127 (progn
8128 (setq org-stored-links
8129 (cons (list cpltxt link desc) org-stored-links))
8130 (message "Stored: %s" (or cpltxt link)))
8131 (org-make-link-string link desc))))
8132
8133 (defun org-make-org-heading-search-string (&optional string heading)
8134 "Make search string for STRING or current headline."
8135 (interactive)
8136 (let ((s (or string (org-get-heading))))
8137 (unless (and string (not heading))
8138 ;; We are using a headline, clean up garbage in there.
8139 (if (string-match org-todo-regexp s)
8140 (setq s (replace-match "" t t s)))
8141 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8142 (setq s (replace-match "" t t s)))
8143 (setq s (org-trim s))
8144 (if (string-match (concat "^\\(" org-quote-string "\\|"
8145 org-comment-string "\\)") s)
8146 (setq s (replace-match "" t t s)))
8147 (while (string-match org-ts-regexp s)
8148 (setq s (replace-match "" t t s))))
8149 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8150 (setq s (replace-match " " t t s)))
8151 (or string (setq s (concat "*" s))) ; Add * for headlines
8152 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8153
8154 (defun org-make-org-heading-camel (&optional string heading)
8155 "Make a CamelCase string for STRING or the current headline."
8156 (interactive)
8157 (let ((s (or string (org-get-heading))))
8158 (unless (and string (not heading))
8159 ;; We are using a headline, clean up garbage in there.
8160 (if (string-match org-todo-regexp s)
8161 (setq s (replace-match "" t t s)))
8162 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8163 (setq s (replace-match "" t t s)))
8164 (setq s (org-trim s))
8165 (if (string-match (concat "^\\(" org-quote-string "\\|"
8166 org-comment-string "\\)") s)
8167 (setq s (replace-match "" t t s)))
8168 (while (string-match org-ts-regexp s)
8169 (setq s (replace-match "" t t s))))
8170 (while (string-match "[^a-zA-Z_ \t]+" s)
8171 (setq s (replace-match " " t t s)))
8172 (or string (setq s (concat "*" s))) ; Add * for headlines
8173 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
8174
8175 (defun org-make-link (&rest strings)
8176 "Concatenate STRINGS, format resulting string with `org-link-format'."
8177 (format org-link-format (apply 'concat strings)))
8178
8179 (defun org-make-link-string (link &optional description)
8180 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8181 (if (eq org-link-style 'plain)
8182 (if (equal description link)
8183 link
8184 (concat description "\n" link))
8185 (when (stringp description)
8186 ;; Remove brackets from the description, they are fatal.
8187 (while (string-match "\\[\\|\\]" description)
8188 (setq description (replace-match "" t t description))))
8189 (when (equal (org-link-escape link) description)
8190 ;; No description needed, it is identical
8191 (setq description nil))
8192 (when (and (not description)
8193 (not (equal link (org-link-escape link))))
8194 (setq description link))
8195 (concat "[[" (org-link-escape link) "]"
8196 (if description (concat "[" description "]") "")
8197 "]")))
8198
8199 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
8200 "Association list of escapes for some characters problematic in links.")
8201
8202 (defun org-link-escape (text)
8203 "Escape charaters in TEXT that are problematic for links."
8204 (when text
8205 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
8206 org-link-escape-chars "\\|")))
8207 (while (string-match re text)
8208 (setq text
8209 (replace-match
8210 (cdr (assoc (match-string 0 text) org-link-escape-chars))
8211 t t text)))
8212 text)))
8213
8214 (defun org-link-unescape (text)
8215 "Reverse the action of `org-link-escape'."
8216 (when text
8217 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
8218 org-link-escape-chars "\\|")))
8219 (while (string-match re text)
8220 (setq text
8221 (replace-match
8222 (car (rassoc (match-string 0 text) org-link-escape-chars))
8223 t t text)))
8224 text)))
8225
8226 (defun org-xor (a b)
8227 "Exclusive or."
8228 (if a (not b) b))
8229
8230 (defun org-get-header (header)
8231 "Find a header field in the current buffer."
8232 (save-excursion
8233 (goto-char (point-min))
8234 (let ((case-fold-search t) s)
8235 (cond
8236 ((eq header 'from)
8237 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
8238 (setq s (match-string 1)))
8239 (while (string-match "\"" s)
8240 (setq s (replace-match "" t t s)))
8241 (if (string-match "[<(].*" s)
8242 (setq s (replace-match "" t t s))))
8243 ((eq header 'message-id)
8244 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
8245 (setq s (match-string 1))))
8246 ((eq header 'subject)
8247 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
8248 (setq s (match-string 1)))))
8249 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
8250 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
8251 s)))
8252
8253
8254 (defun org-fixup-message-id-for-http (s)
8255 "Replace special characters in a message id, so it can be used in an http query."
8256 (while (string-match "<" s)
8257 (setq s (replace-match "%3C" t t s)))
8258 (while (string-match ">" s)
8259 (setq s (replace-match "%3E" t t s)))
8260 (while (string-match "@" s)
8261 (setq s (replace-match "%40" t t s)))
8262 s)
8263
8264 (defun org-insert-link (&optional complete-file)
8265 "Insert a link. At the prompt, enter the link.
8266
8267 Completion can be used to select a link previously stored with
8268 `org-store-link'. When the empty string is entered (i.e. if you just
8269 press RET at the prompt), the link defaults to the most recently
8270 stored link. As SPC triggers completion in the minibuffer, you need to
8271 use M-SPC or C-q SPC to force the insertion of a space character.
8272
8273 You will also be prompted for a description, and if one is given, it will
8274 be displayed in the buffer instead of the link.
8275
8276 If there is already a link at point, this command will allow you to edit link
8277 and description parts.
8278
8279 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
8280 selected using completion. The path to the file will be relative to
8281 the current directory if the file is in the current directory or a
8282 subdirectory. Otherwise, the link will be the absolute path as
8283 completed in the minibuffer (i.e. normally ~/path/to/file).
8284
8285 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
8286 is in the current directory or below."
8287 (interactive "P")
8288 (let (link desc entry remove file (pos (point)))
8289 (cond
8290 ((save-excursion
8291 (skip-chars-forward "^]\n\r")
8292 (and (re-search-backward "\\[\\[" nil t)
8293 (looking-at org-bracket-link-regexp)
8294 (<= (match-beginning 0) pos)
8295 (>= (match-end 0) pos)))
8296 ;; We do have a link at point, and we are going to edit it.
8297 (setq remove (list (match-beginning 0) (match-end 0)))
8298 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8299 (setq link (read-string "Link: "
8300 (org-link-unescape
8301 (org-match-string-no-properties 1)))))
8302 (complete-file
8303 ;; Completing read for file names.
8304 (setq file (read-file-name "File: "))
8305 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8306 (pwd1 (file-name-as-directory (abbreviate-file-name
8307 (expand-file-name ".")))))
8308 (cond
8309 ((equal complete-file '(16))
8310 (setq link (org-make-link
8311 "file:"
8312 (abbreviate-file-name (expand-file-name file)))))
8313 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8314 (setq link (org-make-link "file:" (match-string 1 file))))
8315 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8316 (expand-file-name file))
8317 (setq link (org-make-link
8318 "file:" (match-string 1 (expand-file-name file)))))
8319 (t (setq link (org-make-link "file:" file))))))
8320 (t
8321 ;; Read link, with completion for stored links.
8322 (setq link (org-completing-read
8323 "Link: " org-stored-links nil nil nil
8324 org-insert-link-history
8325 (or (car (car org-stored-links)))))
8326 (setq entry (assoc link org-stored-links))
8327 (if (not org-keep-stored-link-after-insertion)
8328 (setq org-stored-links (delq (assoc link org-stored-links)
8329 org-stored-links)))
8330 (setq link (if entry (nth 1 entry) link)
8331 desc (or desc (nth 2 entry)))))
8332
8333 (if (string-match org-plain-link-re link)
8334 ;; URL-like link, normalize the use of angular brackets.
8335 (setq link (org-make-link (org-remove-angle-brackets link))))
8336
8337 ;; Check if we are linking to the current file. If yes, simplify the link.
8338 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
8339 (let* ((path (match-string 1 link))
8340 (case-fold-search nil)
8341 (search (match-string 2 link)))
8342 (when (save-match-data
8343 (equal (file-truename buffer-file-name)
8344 (file-truename path)))
8345 ;; We are linking to this same file, with a search option
8346 (setq link search))))
8347 (setq desc (read-string "Description: " desc))
8348 (unless (string-match "\\S-" desc) (setq desc nil))
8349 (if remove (apply 'delete-region remove))
8350 (insert (org-make-link-string link desc))))
8351
8352 (defun org-completing-read (&rest args)
8353 (let ((minibuffer-local-completion-map
8354 (copy-keymap minibuffer-local-completion-map)))
8355 (define-key minibuffer-local-completion-map " " 'self-insert-command)
8356 (apply 'completing-read args)))
8357
8358 ;;; Hooks for remember.el
8359
8360 (defvar org-finish-function nil)
8361
8362 ;;;###autoload
8363 (defun org-remember-annotation ()
8364 "Return a link to the current location as an annotation for remember.el.
8365 If you are using Org-mode files as target for data storage with
8366 remember.el, then the annotations should include a link compatible with the
8367 conventions in Org-mode. This function returns such a link."
8368 (org-store-link nil))
8369
8370 (defconst org-remember-help
8371 "Select a destination location for the note.
8372 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
8373 RET at beg-of-buf -> Append to file as level 2 headline
8374 RET on headline -> Store as sublevel entry to current headline
8375 <left>/<right> -> before/after current headline, same headings level")
8376
8377 ;;;###autoload
8378 (defun org-remember-apply-template ()
8379 "Initialize *remember* buffer with template, invode `org-mode'.
8380 This function should be placed into `remember-mode-hook' and in fact requires
8381 to be run from that hook to fucntion properly."
8382 (when org-remember-templates
8383 (let* ((entry (if (= (length org-remember-templates) 1)
8384 (cdar org-remember-templates)
8385 (message "Select template: %s"
8386 (mapconcat
8387 (lambda (x) (char-to-string (car x)))
8388 org-remember-templates " "))
8389 (cdr (assoc (read-char-exclusive) org-remember-templates))))
8390 (tpl (if (consp (cdr entry)) (cadr entry) (cdr entry)))
8391 (file (if (consp (cdr entry)) (nth 2 entry)))
8392 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
8393 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
8394 (v-u (concat "[" (substring v-t 1 -1) "]"))
8395 (v-U (concat "[" (substring v-T 1 -1) "]"))
8396 (v-a annotation) ; defined in `remember-mode'
8397 (v-i initial) ; defined in `remember-mode'
8398 (v-n user-full-name)
8399 )
8400 (unless tpl (setq tpl "") (message "No template") (ding))
8401 (insert tpl) (goto-char (point-min))
8402 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
8403 (when (and initial (equal (match-string 0) "%i"))
8404 (save-match-data
8405 (let* ((lead (buffer-substring
8406 (point-at-bol) (match-beginning 0))))
8407 (setq v-i (mapconcat 'identity
8408 (org-split-string initial "\n")
8409 (concat "\n" lead))))))
8410 (replace-match
8411 (or (eval (intern (concat "v-" (match-string 1)))) "")
8412 t t))
8413 (let ((org-startup-folded nil)
8414 (org-startup-with-deadline-check nil))
8415 (org-mode))
8416 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
8417 (set (make-local-variable 'org-default-notes-file) file))
8418 (goto-char (point-min))
8419 (if (re-search-forward "%\\?" nil t) (replace-match ""))
8420 (set (make-local-variable 'org-finish-function) 'remember-buffer))))
8421
8422 ;;;###autoload
8423 (defun org-remember-handler ()
8424 "Store stuff from remember.el into an org file.
8425 First prompts for an org file. If the user just presses return, the value
8426 of `org-default-notes-file' is used.
8427 Then the command offers the headings tree of the selected file in order to
8428 file the text at a specific location.
8429 You can either immediately press RET to get the note appended to the
8430 file, or you can use vertical cursor motion and visibility cycling (TAB) to
8431 find a better place. Then press RET or <left> or <right> in insert the note.
8432
8433 Key Cursor position Note gets inserted
8434 -----------------------------------------------------------------------------
8435 RET buffer-start as level 2 heading at end of file
8436 RET on headline as sublevel of the heading at cursor
8437 RET no heading at cursor position, level taken from context.
8438 Or use prefix arg to specify level manually.
8439 <left> on headline as same level, before current heading
8440 <right> on headline as same level, after current heading
8441
8442 So the fastest way to store the note is to press RET RET to append it to
8443 the default file. This way your current train of thought is not
8444 interrupted, in accordance with the principles of remember.el. But with
8445 little extra effort, you can push it directly to the correct location.
8446
8447 Before being stored away, the function ensures that the text has a
8448 headline, i.e. a first line that starts with a \"*\". If not, a headline
8449 is constructed from the current date and some additional data.
8450
8451 If the variable `org-adapt-indentation' is non-nil, the entire text is
8452 also indented so that it starts in the same column as the headline
8453 \(i.e. after the stars).
8454
8455 See also the variable `org-reverse-note-order'."
8456 (catch 'quit
8457 (let* ((txt (buffer-substring (point-min) (point-max)))
8458 (fastp current-prefix-arg)
8459 (file (if fastp org-default-notes-file (org-get-org-file)))
8460 (visiting (find-buffer-visiting file))
8461 (org-startup-with-deadline-check nil)
8462 (org-startup-folded nil)
8463 (org-startup-align-all-tables nil)
8464 spos level indent reversed)
8465 ;; Modify text so that it becomes a nice subtree which can be inserted
8466 ;; into an org tree.
8467 (let* ((lines (split-string txt "\n"))
8468 first)
8469 ;; remove empty lines at the beginning
8470 (while (and lines (string-match "^[ \t]*\n" (car lines)))
8471 (setq lines (cdr lines)))
8472 (setq first (car lines) lines (cdr lines))
8473 (if (string-match "^\\*+" first)
8474 ;; Is already a headline
8475 (setq indent nil)
8476 ;; We need to add a headline: Use time and first buffer line
8477 (setq lines (cons first lines)
8478 first (concat "* " (current-time-string)
8479 " (" (remember-buffer-desc) ")")
8480 indent " "))
8481 (if (and org-adapt-indentation indent)
8482 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
8483 (setq txt (concat first "\n"
8484 (mapconcat 'identity lines "\n"))))
8485 ;; Find the file
8486 (if (not visiting)
8487 (find-file-noselect file))
8488 (with-current-buffer (get-file-buffer file)
8489 (setq reversed (org-notes-order-reversed-p))
8490 (save-excursion
8491 (save-restriction
8492 (widen)
8493 ;; Ask the User for a location
8494 (setq spos (if fastp 1 (org-get-location
8495 (current-buffer)
8496 org-remember-help)))
8497 (if (not spos) (throw 'quit nil)) ; return nil to show we did
8498 ; not handle this note
8499 (goto-char spos)
8500 (cond ((bobp)
8501 ;; Put it at the start or end, as level 2
8502 (save-restriction
8503 (widen)
8504 (goto-char (if reversed (point-min) (point-max)))
8505 (if (not (bolp)) (newline))
8506 (org-paste-subtree 2 txt)))
8507 ((and (org-on-heading-p nil) (not current-prefix-arg))
8508 ;; Put it below this entry, at the beg/end of the subtree
8509 (org-back-to-heading)
8510 (setq level (funcall outline-level))
8511 (if reversed
8512 (outline-end-of-heading)
8513 (outline-end-of-subtree))
8514 (if (not (bolp)) (newline))
8515 (beginning-of-line 1)
8516 (org-paste-subtree (1+ level) txt))
8517 (t
8518 ;; Put it right there, with automatic level determined by
8519 ;; org-paste-subtree or from prefix arg
8520 (org-paste-subtree current-prefix-arg txt)))
8521 (when remember-save-after-remembering
8522 (save-buffer)
8523 (if (not visiting) (kill-buffer (current-buffer)))))))))
8524 t) ;; return t to indicate that we took care of this note.
8525
8526 (defun org-get-org-file ()
8527 "Read a filename, with default directory `org-directory'."
8528 (let ((default (or org-default-notes-file remember-data-file)))
8529 (read-file-name (format "File name [%s]: " default)
8530 (file-name-as-directory org-directory)
8531 default)))
8532
8533 (defun org-notes-order-reversed-p ()
8534 "Check if the current file should receive notes in reversed order."
8535 (cond
8536 ((not org-reverse-note-order) nil)
8537 ((eq t org-reverse-note-order) t)
8538 ((not (listp org-reverse-note-order)) nil)
8539 (t (catch 'exit
8540 (let ((all org-reverse-note-order)
8541 entry)
8542 (while (setq entry (pop all))
8543 (if (string-match (car entry) buffer-file-name)
8544 (throw 'exit (cdr entry))))
8545 nil)))))
8546
8547 ;;; Tables
8548
8549 ;; Watch out: Here we are talking about two different kind of tables.
8550 ;; Most of the code is for the tables created with the Org-mode table editor.
8551 ;; Sometimes, we talk about tables created and edited with the table.el
8552 ;; Emacs package. We call the former org-type tables, and the latter
8553 ;; table.el-type tables.
8554
8555
8556 (defun org-before-change-function (beg end)
8557 "Every change indicates that a table might need an update."
8558 (setq org-table-may-need-update t))
8559
8560 (defconst org-table-line-regexp "^[ \t]*|"
8561 "Detects an org-type table line.")
8562 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8563 "Detects an org-type table line.")
8564 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8565 "Detects a table line marked for automatic recalculation.")
8566 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8567 "Detects a table line marked for automatic recalculation.")
8568 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8569 "Detects a table line marked for automatic recalculation.")
8570 (defconst org-table-hline-regexp "^[ \t]*|-"
8571 "Detects an org-type table hline.")
8572 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8573 "Detects a table-type table hline.")
8574 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8575 "Detects an org-type or table-type table.")
8576 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8577 "Searching from within a table (any type) this finds the first line
8578 outside the table.")
8579 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8580 "Searching from within a table (any type) this finds the first line
8581 outside the table.")
8582
8583 (defun org-table-create-with-table.el ()
8584 "Use the table.el package to insert a new table.
8585 If there is already a table at point, convert between Org-mode tables
8586 and table.el tables."
8587 (interactive)
8588 (require 'table)
8589 (cond
8590 ((org-at-table.el-p)
8591 (if (y-or-n-p "Convert table to Org-mode table? ")
8592 (org-table-convert)))
8593 ((org-at-table-p)
8594 (if (y-or-n-p "Convert table to table.el table? ")
8595 (org-table-convert)))
8596 (t (call-interactively 'table-insert))))
8597
8598 (defun org-table-create-or-convert-from-region (arg)
8599 "Convert region to table, or create an empty table.
8600 If there is an active region, convert it to a table. If there is no such
8601 region, create an empty table."
8602 (interactive "P")
8603 (if (org-region-active-p)
8604 (org-table-convert-region (region-beginning) (region-end) arg)
8605 (org-table-create arg)))
8606
8607 (defun org-table-create (&optional size)
8608 "Query for a size and insert a table skeleton.
8609 SIZE is a string Columns x Rows like for example \"3x2\"."
8610 (interactive "P")
8611 (unless size
8612 (setq size (read-string
8613 (concat "Table size Columns x Rows [e.g. "
8614 org-table-default-size "]: ")
8615 "" nil org-table-default-size)))
8616
8617 (let* ((pos (point))
8618 (indent (make-string (current-column) ?\ ))
8619 (split (org-split-string size " *x *"))
8620 (rows (string-to-number (nth 1 split)))
8621 (columns (string-to-number (car split)))
8622 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8623 "\n")))
8624 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8625 (point-at-bol) (point)))
8626 (beginning-of-line 1)
8627 (newline))
8628 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8629 (dotimes (i rows) (insert line))
8630 (goto-char pos)
8631 (if (> rows 1)
8632 ;; Insert a hline after the first row.
8633 (progn
8634 (end-of-line 1)
8635 (insert "\n|-")
8636 (goto-char pos)))
8637 (org-table-align)))
8638
8639 (defun org-table-convert-region (beg0 end0 &optional nspace)
8640 "Convert region to a table.
8641 The region goes from BEG0 to END0, but these borders will be moved
8642 slightly, to make sure a beginning of line in the first line is included.
8643 When NSPACE is non-nil, it indicates the minimum number of spaces that
8644 separate columns (default: just one space)."
8645 (interactive "rP")
8646 (let* ((beg (min beg0 end0))
8647 (end (max beg0 end0))
8648 (tabsep t)
8649 re)
8650 (goto-char beg)
8651 (beginning-of-line 1)
8652 (setq beg (move-marker (make-marker) (point)))
8653 (goto-char end)
8654 (if (bolp) (backward-char 1) (end-of-line 1))
8655 (setq end (move-marker (make-marker) (point)))
8656 ;; Lets see if this is tab-separated material. If every nonempty line
8657 ;; contains a tab, we will assume that it is tab-separated material
8658 (if nspace
8659 (setq tabsep nil)
8660 (goto-char beg)
8661 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
8662 (if nspace (setq tabsep nil))
8663 (if tabsep
8664 (setq re "^\\|\t")
8665 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
8666 (max 1 (prefix-numeric-value nspace)))))
8667 (goto-char beg)
8668 (while (re-search-forward re end t)
8669 (replace-match "|" t t))
8670 (goto-char beg)
8671 (insert " ")
8672 (org-table-align)))
8673
8674 (defun org-table-import (file arg)
8675 "Import FILE as a table.
8676 The file is assumed to be tab-separated. Such files can be produced by most
8677 spreadsheet and database applications. If no tabs (at least one per line)
8678 are found, lines will be split on whitespace into fields."
8679 (interactive "f\nP")
8680 (or (bolp) (newline))
8681 (let ((beg (point))
8682 (pm (point-max)))
8683 (insert-file-contents file)
8684 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8685
8686 (defun org-table-export ()
8687 "Export table as a tab-separated file.
8688 Such a file can be imported into a spreadsheet program like Excel."
8689 (interactive)
8690 (let* ((beg (org-table-begin))
8691 (end (org-table-end))
8692 (table (buffer-substring beg end))
8693 (file (read-file-name "Export table to: "))
8694 buf)
8695 (unless (or (not (file-exists-p file))
8696 (y-or-n-p (format "Overwrite file %s? " file)))
8697 (error "Abort"))
8698 (with-current-buffer (find-file-noselect file)
8699 (setq buf (current-buffer))
8700 (erase-buffer)
8701 (fundamental-mode)
8702 (insert table)
8703 (goto-char (point-min))
8704 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8705 (replace-match "" t t)
8706 (end-of-line 1))
8707 (goto-char (point-min))
8708 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8709 (replace-match "" t t)
8710 (goto-char (min (1+ (point)) (point-max))))
8711 (goto-char (point-min))
8712 (while (re-search-forward "^-[-+]*$" nil t)
8713 (replace-match "")
8714 (if (looking-at "\n")
8715 (delete-char 1)))
8716 (goto-char (point-min))
8717 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8718 (replace-match "\t" t t))
8719 (save-buffer))
8720 (kill-buffer buf)))
8721
8722 (defvar org-table-aligned-begin-marker (make-marker)
8723 "Marker at the beginning of the table last aligned.
8724 Used to check if cursor still is in that table, to minimize realignment.")
8725 (defvar org-table-aligned-end-marker (make-marker)
8726 "Marker at the end of the table last aligned.
8727 Used to check if cursor still is in that table, to minimize realignment.")
8728 (defvar org-table-last-alignment nil
8729 "List of flags for flushright alignment, from the last re-alignment.
8730 This is being used to correctly align a single field after TAB or RET.")
8731 (defvar org-table-last-column-widths nil
8732 "List of max width of fields in each column.
8733 This is being used to correctly align a single field after TAB or RET.")
8734
8735 (defvar org-last-recalc-line nil)
8736 (defconst org-narrow-column-arrow "=>"
8737 "Used as display property in narrowed table columns.")
8738
8739 (defun org-table-align ()
8740 "Align the table at point by aligning all vertical bars."
8741 (interactive)
8742 (let* (
8743 ;; Limits of table
8744 (beg (org-table-begin))
8745 (end (org-table-end))
8746 ;; Current cursor position
8747 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8748 (colpos (org-table-current-column))
8749 (winstart (window-start))
8750 text lines (new "") lengths l typenums ty fields maxfields i
8751 column
8752 (indent "") cnt frac
8753 rfmt hfmt
8754 (spaces '(1 . 1))
8755 (sp1 (car spaces))
8756 (sp2 (cdr spaces))
8757 (rfmt1 (concat
8758 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8759 (hfmt1 (concat
8760 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8761 emptystrings xx links narrow fmax fmin f1 len c e)
8762 (untabify beg end)
8763 (remove-text-properties beg end '(org-cwidth t display t))
8764 ;; Check if we have links
8765 (goto-char beg)
8766 (setq links (re-search-forward org-bracket-link-regexp end t))
8767 ;; Make sure the link properties are right FIXME: Can this be optimized????
8768 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8769 ;; Check if we are narrowing any columns
8770 (goto-char beg)
8771 (setq narrow (and org-format-transports-properties-p
8772 (re-search-forward "<[0-9]+>" end t)))
8773 ;; Get the rows
8774 (setq lines (org-split-string
8775 (buffer-substring beg end) "\n"))
8776 ;; Store the indentation of the first line
8777 (if (string-match "^ *" (car lines))
8778 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8779 ;; Mark the hlines by setting the corresponding element to nil
8780 ;; At the same time, we remove trailing space.
8781 (setq lines (mapcar (lambda (l)
8782 (if (string-match "^ *|-" l)
8783 nil
8784 (if (string-match "[ \t]+$" l)
8785 (substring l 0 (match-beginning 0))
8786 l)))
8787 lines))
8788 ;; Get the data fields by splitting the lines.
8789 (setq fields (mapcar
8790 (lambda (l)
8791 (org-split-string l " *| *"))
8792 (delq nil (copy-sequence lines))))
8793 ;; How many fields in the longest line?
8794 (condition-case nil
8795 (setq maxfields (apply 'max (mapcar 'length fields)))
8796 (error
8797 (kill-region beg end)
8798 (org-table-create org-table-default-size)
8799 (error "Empty table - created default table")))
8800 ;; A list of empty string to fill any short rows on output
8801 (setq emptystrings (make-list maxfields ""))
8802 ;; Check for special formatting.
8803 (setq i -1)
8804 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8805 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8806 ;; Check if there is an explicit width specified
8807 (when (and org-table-limit-column-width narrow)
8808 (setq c column fmax nil)
8809 (while c
8810 (setq e (pop c))
8811 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8812 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8813 ;; Find fields that are wider than fmax, and shorten them
8814 (when fmax
8815 (loop for xx in column do
8816 (when (and (stringp xx)
8817 (> (org-string-width xx) fmax))
8818 (org-add-props xx nil
8819 'help-echo
8820 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8821 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8822 (unless (> f1 1)
8823 (error "Cannot narrow field starting with wide link \"%s\""
8824 (match-string 0 xx)))
8825 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8826 (add-text-properties (- f1 2) f1
8827 (list 'display org-narrow-column-arrow)
8828 xx)))))
8829 ;; Get the maximum width for each column
8830 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8831 ;; Get the fraction of numbers, to decide about alignment of the column
8832 (setq cnt 0 frac 0.0)
8833 (loop for x in column do
8834 (if (equal x "")
8835 nil
8836 (setq frac ( / (+ (* frac cnt)
8837 (if (string-match org-table-number-regexp x) 1 0))
8838 (setq cnt (1+ cnt))))))
8839 (push (>= frac org-table-number-fraction) typenums))
8840 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8841
8842 ;; Store the alignment of this table, for later editing of single fields
8843 (setq org-table-last-alignment typenums
8844 org-table-last-column-widths lengths)
8845
8846 ;; With invisible characters, `format' does not get the field width right
8847 ;; So we need to make these fields wide by hand.
8848 (when links
8849 (loop for i from 0 upto (1- maxfields) do
8850 (setq len (nth i lengths))
8851 (loop for j from 0 upto (1- (length fields)) do
8852 (setq c (nthcdr i (car (nthcdr j fields))))
8853 (if (and (stringp (car c))
8854 (string-match org-bracket-link-regexp (car c))
8855 (< (org-string-width (car c)) len))
8856 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8857
8858 ;; Compute the formats needed for output of the table
8859 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8860 (while (setq l (pop lengths))
8861 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8862 (setq rfmt (concat rfmt (format rfmt1 ty l))
8863 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8864 (setq rfmt (concat rfmt "\n")
8865 hfmt (concat (substring hfmt 0 -1) "|\n"))
8866
8867 (setq new (mapconcat
8868 (lambda (l)
8869 (if l (apply 'format rfmt
8870 (append (pop fields) emptystrings))
8871 hfmt))
8872 lines ""))
8873 ;; Replace the old one
8874 (delete-region beg end)
8875 (move-marker end nil)
8876 (move-marker org-table-aligned-begin-marker (point))
8877 (insert new)
8878 (move-marker org-table-aligned-end-marker (point))
8879 (when (and orgtbl-mode (not (eq major-mode 'org-mode)))
8880 (goto-char org-table-aligned-begin-marker)
8881 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8882 ;; Try to move to the old location (approximately)
8883 (goto-line linepos)
8884 (set-window-start (selected-window) winstart 'noforce)
8885 (org-table-goto-column colpos)
8886 (setq org-table-may-need-update nil)
8887 ))
8888
8889 (defun org-string-width (s)
8890 "Compute width of string, ignoring invisible characters.
8891 This ignores character with invisibility property `org-link', and also
8892 characters with property `org-cwidth', because these will become invisible
8893 upon the next fontification round."
8894 (let (b)
8895 (when (or (eq t buffer-invisibility-spec)
8896 (assq 'org-link buffer-invisibility-spec))
8897 (while (setq b (text-property-any 0 (length s)
8898 'invisible 'org-link s))
8899 (setq s (concat (substring s 0 b)
8900 (substring s (or (next-single-property-change
8901 b 'invisible s) (length s)))))))
8902 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8903 (setq s (concat (substring s 0 b)
8904 (substring s (or (next-single-property-change
8905 b 'org-cwidth s) (length s))))))
8906 (string-width s)))
8907
8908 (defun org-table-begin (&optional table-type)
8909 "Find the beginning of the table and return its position.
8910 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8911 (save-excursion
8912 (if (not (re-search-backward
8913 (if table-type org-table-any-border-regexp
8914 org-table-border-regexp)
8915 nil t))
8916 (error "Can't find beginning of table")
8917 (goto-char (match-beginning 0))
8918 (beginning-of-line 2)
8919 (point))))
8920
8921 (defun org-table-end (&optional table-type)
8922 "Find the end of the table and return its position.
8923 With argument TABLE-TYPE, go to the end of a table.el-type table."
8924 (save-excursion
8925 (if (not (re-search-forward
8926 (if table-type org-table-any-border-regexp
8927 org-table-border-regexp)
8928 nil t))
8929 (goto-char (point-max))
8930 (goto-char (match-beginning 0)))
8931 (point-marker)))
8932
8933 (defun org-table-justify-field-maybe (&optional new)
8934 "Justify the current field, text to left, number to right.
8935 Optional argument NEW may specify text to replace the current field content."
8936 (cond
8937 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8938 ((org-at-table-hline-p))
8939 ((and (not new)
8940 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8941 (current-buffer)))
8942 (< (point) org-table-aligned-begin-marker)
8943 (>= (point) org-table-aligned-end-marker)))
8944 ;; This is not the same table, force a full re-align
8945 (setq org-table-may-need-update t))
8946 (t ;; realign the current field, based on previous full realign
8947 (let* ((pos (point)) s
8948 (col (org-table-current-column))
8949 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8950 l f n o e)
8951 (when (> col 0)
8952 (skip-chars-backward "^|\n")
8953 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8954 (progn
8955 (setq s (match-string 1)
8956 o (match-string 0)
8957 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8958 e (not (= (match-beginning 2) (match-end 2))))
8959 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8960 l (if e "|" (setq org-table-may-need-update t) ""))
8961 n (format f s t t))
8962 (if new
8963 (if (<= (length new) l)
8964 (setq n (format f new t t)) ;; FIXME: why t t?????
8965 (setq n (concat new "|") org-table-may-need-update t)))
8966 (or (equal n o)
8967 (let (org-table-may-need-update)
8968 (replace-match n))))
8969 (setq org-table-may-need-update t))
8970 (goto-char pos))))))
8971
8972 (defun org-table-next-field ()
8973 "Go to the next field in the current table, creating new lines as needed.
8974 Before doing so, re-align the table if necessary."
8975 (interactive)
8976 (org-table-maybe-eval-formula)
8977 (org-table-maybe-recalculate-line)
8978 (if (and org-table-automatic-realign
8979 org-table-may-need-update)
8980 (org-table-align))
8981 (let ((end (org-table-end)))
8982 (if (org-at-table-hline-p)
8983 (end-of-line 1))
8984 (condition-case nil
8985 (progn
8986 (re-search-forward "|" end)
8987 (if (looking-at "[ \t]*$")
8988 (re-search-forward "|" end))
8989 (if (and (looking-at "-")
8990 org-table-tab-jumps-over-hlines
8991 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8992 (goto-char (match-beginning 1)))
8993 (if (looking-at "-")
8994 (progn
8995 (beginning-of-line 0)
8996 (org-table-insert-row 'below))
8997 (if (looking-at " ") (forward-char 1))))
8998 (error
8999 (org-table-insert-row 'below)))))
9000
9001 (defun org-table-previous-field ()
9002 "Go to the previous field in the table.
9003 Before doing so, re-align the table if necessary."
9004 (interactive)
9005 (org-table-justify-field-maybe)
9006 (org-table-maybe-recalculate-line)
9007 (if (and org-table-automatic-realign
9008 org-table-may-need-update)
9009 (org-table-align))
9010 (if (org-at-table-hline-p)
9011 (end-of-line 1))
9012 (re-search-backward "|" (org-table-begin))
9013 (re-search-backward "|" (org-table-begin))
9014 (while (looking-at "|\\(-\\|[ \t]*$\\)")
9015 (re-search-backward "|" (org-table-begin)))
9016 (if (looking-at "| ?")
9017 (goto-char (match-end 0))))
9018
9019 (defun org-table-next-row ()
9020 "Go to the next row (same column) in the current table.
9021 Before doing so, re-align the table if necessary."
9022 (interactive)
9023 (org-table-maybe-eval-formula)
9024 (org-table-maybe-recalculate-line)
9025 (if (or (looking-at "[ \t]*$")
9026 (save-excursion (skip-chars-backward " \t") (bolp)))
9027 (newline)
9028 (if (and org-table-automatic-realign
9029 org-table-may-need-update)
9030 (org-table-align))
9031 (let ((col (org-table-current-column)))
9032 (beginning-of-line 2)
9033 (if (or (not (org-at-table-p))
9034 (org-at-table-hline-p))
9035 (progn
9036 (beginning-of-line 0)
9037 (org-table-insert-row 'below)))
9038 (org-table-goto-column col)
9039 (skip-chars-backward "^|\n\r")
9040 (if (looking-at " ") (forward-char 1)))))
9041
9042 (defun org-table-copy-down (n)
9043 "Copy a field down in the current column.
9044 If the field at the cursor is empty, copy into it the content of the nearest
9045 non-empty field above. With argument N, use the Nth non-empty field.
9046 If the current field is not empty, it is copied down to the next row, and
9047 the cursor is moved with it. Therefore, repeating this command causes the
9048 column to be filled row-by-row.
9049 If the variable `org-table-copy-increment' is non-nil and the field is an
9050 integer, it will be incremented while copying."
9051 (interactive "p")
9052 (let* ((colpos (org-table-current-column))
9053 (field (org-table-get-field))
9054 (non-empty (string-match "[^ \t]" field))
9055 (beg (org-table-begin))
9056 txt)
9057 (org-table-check-inside-data-field)
9058 (if non-empty
9059 (progn
9060 (setq txt (org-trim field))
9061 (org-table-next-row)
9062 (org-table-blank-field))
9063 (save-excursion
9064 (setq txt
9065 (catch 'exit
9066 (while (progn (beginning-of-line 1)
9067 (re-search-backward org-table-dataline-regexp
9068 beg t))
9069 (org-table-goto-column colpos t)
9070 (if (and (looking-at
9071 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
9072 (= (setq n (1- n)) 0))
9073 (throw 'exit (match-string 1))))))))
9074 (if txt
9075 (progn
9076 (if (and org-table-copy-increment
9077 (string-match "^[0-9]+$" txt))
9078 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9079 (insert txt)
9080 (org-table-maybe-recalculate-line)
9081 (org-table-align))
9082 (error "No non-empty field found"))))
9083
9084 (defun org-table-check-inside-data-field ()
9085 "Is point inside a table data field?
9086 I.e. not on a hline or before the first or after the last column?
9087 This actually throws an error, so it aborts the current command."
9088 (if (or (not (org-at-table-p))
9089 (= (org-table-current-column) 0)
9090 (org-at-table-hline-p)
9091 (looking-at "[ \t]*$"))
9092 (error "Not in table data field")))
9093
9094 (defvar org-table-clip nil
9095 "Clipboard for table regions.")
9096
9097 (defun org-table-blank-field ()
9098 "Blank the current table field or active region."
9099 (interactive)
9100 (org-table-check-inside-data-field)
9101 (if (and (interactive-p) (org-region-active-p))
9102 (let (org-table-clip)
9103 (org-table-cut-region (region-beginning) (region-end)))
9104 (skip-chars-backward "^|")
9105 (backward-char 1)
9106 (if (looking-at "|[^|\n]+")
9107 (let* ((pos (match-beginning 0))
9108 (match (match-string 0))
9109 (len (org-string-width match)))
9110 (replace-match (concat "|" (make-string (1- len) ?\ )))
9111 (goto-char (+ 2 pos))
9112 (substring match 1)))))
9113
9114 (defun org-table-get-field (&optional n replace)
9115 "Return the value of the field in column N of current row.
9116 N defaults to current field.
9117 If REPLACE is a string, replace field with this value. The return value
9118 is always the old value."
9119 (and n (org-table-goto-column n))
9120 (skip-chars-backward "^|\n")
9121 (backward-char 1)
9122 (if (looking-at "|[^|\r\n]*")
9123 (let* ((pos (match-beginning 0))
9124 (val (buffer-substring (1+ pos) (match-end 0))))
9125 (if replace
9126 (replace-match (concat "|" replace)))
9127 (goto-char (min (point-at-eol) (+ 2 pos)))
9128 val)
9129 (forward-char 1) ""))
9130
9131 (defun org-table-current-column ()
9132 "Find out which column we are in.
9133 When called interactively, column is also displayed in echo area."
9134 (interactive)
9135 (if (interactive-p) (org-table-check-inside-data-field))
9136 (save-excursion
9137 (let ((cnt 0) (pos (point)))
9138 (beginning-of-line 1)
9139 (while (search-forward "|" pos t)
9140 (setq cnt (1+ cnt)))
9141 (if (interactive-p) (message "This is table column %d" cnt))
9142 cnt)))
9143
9144 (defun org-table-goto-column (n &optional on-delim force)
9145 "Move the cursor to the Nth column in the current table line.
9146 With optional argument ON-DELIM, stop with point before the left delimiter
9147 of the field.
9148 If there are less than N fields, just go to after the last delimiter.
9149 However, when FORCE is non-nil, create new columns if necessary."
9150 (interactive "p")
9151 (let ((pos (point-at-eol)))
9152 (beginning-of-line 1)
9153 (when (> n 0)
9154 (while (and (> (setq n (1- n)) -1)
9155 (or (search-forward "|" pos t)
9156 (and force
9157 (progn (end-of-line 1)
9158 (skip-chars-backward "^|")
9159 (insert " | "))))))
9160 ; (backward-char 2) t)))))
9161 (when (and force (not (looking-at ".*|")))
9162 (save-excursion (end-of-line 1) (insert " | ")))
9163 (if on-delim
9164 (backward-char 1)
9165 (if (looking-at " ") (forward-char 1))))))
9166
9167 (defun org-at-table-p (&optional table-type)
9168 "Return t if the cursor is inside an org-type table.
9169 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9170 (if org-enable-table-editor
9171 (save-excursion
9172 (beginning-of-line 1)
9173 (looking-at (if table-type org-table-any-line-regexp
9174 org-table-line-regexp)))
9175 nil))
9176
9177 (defun org-at-table.el-p ()
9178 "Return t if and only if we are at a table.el table."
9179 (and (org-at-table-p 'any)
9180 (save-excursion
9181 (goto-char (org-table-begin 'any))
9182 (looking-at org-table1-hline-regexp))))
9183
9184 (defun org-table-recognize-table.el ()
9185 "If there is a table.el table nearby, recognize it and move into it."
9186 (if org-table-tab-recognizes-table.el
9187 (if (org-at-table.el-p)
9188 (progn
9189 (beginning-of-line 1)
9190 (if (looking-at org-table-dataline-regexp)
9191 nil
9192 (if (looking-at org-table1-hline-regexp)
9193 (progn
9194 (beginning-of-line 2)
9195 (if (looking-at org-table-any-border-regexp)
9196 (beginning-of-line -1)))))
9197 (if (re-search-forward "|" (org-table-end t) t)
9198 (progn
9199 (require 'table)
9200 (if (table--at-cell-p (point))
9201 t
9202 (message "recognizing table.el table...")
9203 (table-recognize-table)
9204 (message "recognizing table.el table...done")))
9205 (error "This should not happen..."))
9206 t)
9207 nil)
9208 nil))
9209
9210 (defun org-at-table-hline-p ()
9211 "Return t if the cursor is inside a hline in a table."
9212 (if org-enable-table-editor
9213 (save-excursion
9214 (beginning-of-line 1)
9215 (looking-at org-table-hline-regexp))
9216 nil))
9217
9218 (defun org-table-insert-column ()
9219 "Insert a new column into the table."
9220 (interactive)
9221 (if (not (org-at-table-p))
9222 (error "Not at a table"))
9223 (org-table-find-dataline)
9224 (let* ((col (max 1 (org-table-current-column)))
9225 (beg (org-table-begin))
9226 (end (org-table-end))
9227 ;; Current cursor position
9228 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9229 (colpos col))
9230 (goto-char beg)
9231 (while (< (point) end)
9232 (if (org-at-table-hline-p)
9233 nil
9234 (org-table-goto-column col t)
9235 (insert "| "))
9236 (beginning-of-line 2))
9237 (move-marker end nil)
9238 (goto-line linepos)
9239 (org-table-goto-column colpos)
9240 (org-table-align)
9241 (org-table-modify-formulas 'insert col)))
9242
9243 (defun org-table-find-dataline ()
9244 "Find a dataline in the current table, which is needed for column commands."
9245 (if (and (org-at-table-p)
9246 (not (org-at-table-hline-p)))
9247 t
9248 (let ((col (current-column))
9249 (end (org-table-end)))
9250 (move-to-column col)
9251 (while (and (< (point) end)
9252 (or (not (= (current-column) col))
9253 (org-at-table-hline-p)))
9254 (beginning-of-line 2)
9255 (move-to-column col))
9256 (if (and (org-at-table-p)
9257 (not (org-at-table-hline-p)))
9258 t
9259 (error
9260 "Please position cursor in a data line for column operations")))))
9261
9262 (defun org-table-delete-column ()
9263 "Delete a column into the table."
9264 (interactive)
9265 (if (not (org-at-table-p))
9266 (error "Not at a table"))
9267 (org-table-find-dataline)
9268 (org-table-check-inside-data-field)
9269 (let* ((col (org-table-current-column))
9270 (beg (org-table-begin))
9271 (end (org-table-end))
9272 ;; Current cursor position
9273 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9274 (colpos col))
9275 (goto-char beg)
9276 (while (< (point) end)
9277 (if (org-at-table-hline-p)
9278 nil
9279 (org-table-goto-column col t)
9280 (and (looking-at "|[^|\n]+|")
9281 (replace-match "|")))
9282 (beginning-of-line 2))
9283 (move-marker end nil)
9284 (goto-line linepos)
9285 (org-table-goto-column colpos)
9286 (org-table-align)
9287 (org-table-modify-formulas 'remove col)))
9288
9289 (defun org-table-move-column-right ()
9290 "Move column to the right."
9291 (interactive)
9292 (org-table-move-column nil))
9293 (defun org-table-move-column-left ()
9294 "Move column to the left."
9295 (interactive)
9296 (org-table-move-column 'left))
9297
9298 (defun org-table-move-column (&optional left)
9299 "Move the current column to the right. With arg LEFT, move to the left."
9300 (interactive "P")
9301 (if (not (org-at-table-p))
9302 (error "Not at a table"))
9303 (org-table-find-dataline)
9304 (org-table-check-inside-data-field)
9305 (let* ((col (org-table-current-column))
9306 (col1 (if left (1- col) col))
9307 (beg (org-table-begin))
9308 (end (org-table-end))
9309 ;; Current cursor position
9310 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9311 (colpos (if left (1- col) (1+ col))))
9312 (if (and left (= col 1))
9313 (error "Cannot move column further left"))
9314 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9315 (error "Cannot move column further right"))
9316 (goto-char beg)
9317 (while (< (point) end)
9318 (if (org-at-table-hline-p)
9319 nil
9320 (org-table-goto-column col1 t)
9321 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9322 (replace-match "|\\2|\\1|")))
9323 (beginning-of-line 2))
9324 (move-marker end nil)
9325 (goto-line linepos)
9326 (org-table-goto-column colpos)
9327 (org-table-align)
9328 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
9329
9330 (defun org-table-move-row-down ()
9331 "Move table row down."
9332 (interactive)
9333 (org-table-move-row nil))
9334 (defun org-table-move-row-up ()
9335 "Move table row up."
9336 (interactive)
9337 (org-table-move-row 'up))
9338
9339 (defun org-table-move-row (&optional up)
9340 "Move the current table line down. With arg UP, move it up."
9341 (interactive "P")
9342 (let ((col (current-column))
9343 (pos (point))
9344 (tonew (if up 0 2))
9345 txt)
9346 (beginning-of-line tonew)
9347 (if (not (org-at-table-p))
9348 (progn
9349 (goto-char pos)
9350 (error "Cannot move row further")))
9351 (goto-char pos)
9352 (beginning-of-line 1)
9353 (setq pos (point))
9354 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9355 (delete-region (point) (1+ (point-at-eol)))
9356 (beginning-of-line tonew)
9357 (insert txt)
9358 (beginning-of-line 0)
9359 (move-to-column col)))
9360
9361 (defun org-table-insert-row (&optional arg)
9362 "Insert a new row above the current line into the table.
9363 With prefix ARG, insert below the current line."
9364 (interactive "P")
9365 (if (not (org-at-table-p))
9366 (error "Not at a table"))
9367 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9368 (new (org-table-clean-line line)))
9369 ;; Fix the first field if necessary
9370 (if (string-match "^[ \t]*| *[#$] *|" line)
9371 (setq new (replace-match (match-string 0 line) t t new)))
9372 (beginning-of-line (if arg 2 1))
9373 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9374 (beginning-of-line 0)
9375 (re-search-forward "| ?" (point-at-eol) t)
9376 (and org-table-may-need-update (org-table-align))))
9377
9378 (defun org-table-insert-hline (&optional arg)
9379 "Insert a horizontal-line below the current line into the table.
9380 With prefix ARG, insert above the current line."
9381 (interactive "P")
9382 (if (not (org-at-table-p))
9383 (error "Not at a table"))
9384 (let ((line (org-table-clean-line
9385 (buffer-substring (point-at-bol) (point-at-eol))))
9386 (col (current-column)))
9387 (while (string-match "|\\( +\\)|" line)
9388 (setq line (replace-match
9389 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9390 ?-) "|") t t line)))
9391 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9392 (beginning-of-line (if arg 1 2))
9393 (insert line "\n")
9394 (beginning-of-line (if arg 1 -1))
9395 (move-to-column col)))
9396
9397 (defun org-table-clean-line (s)
9398 "Convert a table line S into a string with only \"|\" and space.
9399 In particular, this does handle wide and invisible characters."
9400 (if (string-match "^[ \t]*|-" s)
9401 ;; It's a hline, just map the characters
9402 (setq s (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) s))
9403 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9404 (setq s (replace-match
9405 (concat "|" (make-string (org-string-width (match-string 1 s))
9406 ?\ ) "|")
9407 t t s)))
9408 s))
9409
9410 (defun org-table-kill-row ()
9411 "Delete the current row or horizontal line from the table."
9412 (interactive)
9413 (if (not (org-at-table-p))
9414 (error "Not at a table"))
9415 (let ((col (current-column)))
9416 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9417 (if (not (org-at-table-p)) (beginning-of-line 0))
9418 (move-to-column col)))
9419
9420 (defun org-table-sort-lines (beg end numericp)
9421 "Sort table lines in region.
9422 Point and mark define the first and last line to include. Both point and
9423 mark should be in the column that is used for sorting. For example, to
9424 sort according to column 3, put the mark in the first line to sort, in
9425 table column 3. Put point into the last line to be included in the sorting,
9426 also in table column 3. The command will prompt for the sorting method
9427 \(n for numerical, a for alphanumeric)."
9428 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
9429 (setq numericp (string-match "[nN]" numericp))
9430 (org-table-align) ;; Just to be safe
9431 (let* (bcol ecol cmp column lns)
9432 (goto-char beg)
9433 (org-table-check-inside-data-field)
9434 (setq column (org-table-current-column)
9435 beg (move-marker (make-marker) (point-at-bol)))
9436 (goto-char end)
9437 (org-table-check-inside-data-field)
9438 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
9439 (untabify beg end)
9440 (goto-char beg)
9441 (org-table-goto-column column)
9442 (skip-chars-backward "^|")
9443 (setq bcol (current-column))
9444 (org-table-goto-column (1+ column))
9445 (skip-chars-backward "^|")
9446 (setq ecol (1- (current-column)))
9447 (setq cmp (if numericp
9448 (lambda (a b) (< (car a) (car b)))
9449 (lambda (a b) (string< (car a) (car b)))))
9450 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
9451 (split-string (buffer-substring beg end) "\n")))
9452 (if numericp
9453 (setq lns (mapcar (lambda(x)
9454 (cons (string-to-number (car x)) (cdr x)))
9455 lns)))
9456 (delete-region beg end)
9457 (move-marker beg nil)
9458 (move-marker end nil)
9459 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
9460 (message "%d lines sorted %s based on column %d"
9461 (length lns)
9462 (if numericp "numerically" "alphabetically") column)))
9463
9464 (defun org-table-cut-region (beg end)
9465 "Copy region in table to the clipboard and blank all relevant fields."
9466 (interactive "r")
9467 (org-table-copy-region beg end 'cut))
9468
9469 (defun org-table-copy-region (beg end &optional cut)
9470 "Copy rectangular region in table to clipboard.
9471 A special clipboard is used which can only be accessed
9472 with `org-table-paste-rectangle'."
9473 (interactive "rP")
9474 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9475 region cols
9476 (rpl (if cut " " nil)))
9477 (goto-char beg)
9478 (org-table-check-inside-data-field)
9479 (setq l01 (count-lines (point-min) (point))
9480 c01 (org-table-current-column))
9481 (goto-char end)
9482 (org-table-check-inside-data-field)
9483 (setq l02 (count-lines (point-min) (point))
9484 c02 (org-table-current-column))
9485 (setq l1 (min l01 l02) l2 (max l01 l02)
9486 c1 (min c01 c02) c2 (max c01 c02))
9487 (catch 'exit
9488 (while t
9489 (catch 'nextline
9490 (if (> l1 l2) (throw 'exit t))
9491 (goto-line l1)
9492 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9493 (setq cols nil ic1 c1 ic2 c2)
9494 (while (< ic1 (1+ ic2))
9495 (push (org-table-get-field ic1 rpl) cols)
9496 (setq ic1 (1+ ic1)))
9497 (push (nreverse cols) region)
9498 (setq l1 (1+ l1)))))
9499 (setq org-table-clip (nreverse region))
9500 (if cut (org-table-align))
9501 org-table-clip))
9502
9503 (defun org-table-paste-rectangle ()
9504 "Paste a rectangular region into a table.
9505 The upper right corner ends up in the current field. All involved fields
9506 will be overwritten. If the rectangle does not fit into the present table,
9507 the table is enlarged as needed. The process ignores horizontal separator
9508 lines."
9509 (interactive)
9510 (unless (and org-table-clip (listp org-table-clip))
9511 (error "First cut/copy a region to paste!"))
9512 (org-table-check-inside-data-field)
9513 (let* ((clip org-table-clip)
9514 (line (count-lines (point-min) (point)))
9515 (col (org-table-current-column))
9516 (org-enable-table-editor t)
9517 (org-table-automatic-realign nil)
9518 c cols field)
9519 (while (setq cols (pop clip))
9520 (while (org-at-table-hline-p) (beginning-of-line 2))
9521 (if (not (org-at-table-p))
9522 (progn (end-of-line 0) (org-table-next-field)))
9523 (setq c col)
9524 (while (setq field (pop cols))
9525 (org-table-goto-column c nil 'force)
9526 (org-table-get-field nil field)
9527 (setq c (1+ c)))
9528 (beginning-of-line 2))
9529 (goto-line line)
9530 (org-table-goto-column col)
9531 (org-table-align)))
9532
9533 (defun org-table-convert ()
9534 "Convert from `org-mode' table to table.el and back.
9535 Obviously, this only works within limits. When an Org-mode table is
9536 converted to table.el, all horizontal separator lines get lost, because
9537 table.el uses these as cell boundaries and has no notion of horizontal lines.
9538 A table.el table can be converted to an Org-mode table only if it does not
9539 do row or column spanning. Multiline cells will become multiple cells.
9540 Beware, Org-mode does not test if the table can be successfully converted - it
9541 blindly applies a recipe that works for simple tables."
9542 (interactive)
9543 (require 'table)
9544 (if (org-at-table.el-p)
9545 ;; convert to Org-mode table
9546 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9547 (end (move-marker (make-marker) (org-table-end t))))
9548 (table-unrecognize-region beg end)
9549 (goto-char beg)
9550 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9551 (replace-match ""))
9552 (goto-char beg))
9553 (if (org-at-table-p)
9554 ;; convert to table.el table
9555 (let ((beg (move-marker (make-marker) (org-table-begin)))
9556 (end (move-marker (make-marker) (org-table-end))))
9557 ;; first, get rid of all horizontal lines
9558 (goto-char beg)
9559 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9560 (replace-match ""))
9561 ;; insert a hline before first
9562 (goto-char beg)
9563 (org-table-insert-hline 'above)
9564 (beginning-of-line -1)
9565 ;; insert a hline after each line
9566 (while (progn (beginning-of-line 3) (< (point) end))
9567 (org-table-insert-hline))
9568 (goto-char beg)
9569 (setq end (move-marker end (org-table-end)))
9570 ;; replace "+" at beginning and ending of hlines
9571 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9572 (replace-match "\\1+-"))
9573 (goto-char beg)
9574 (while (re-search-forward "-|[ \t]*$" end t)
9575 (replace-match "-+"))
9576 (goto-char beg)))))
9577
9578 (defun org-table-wrap-region (arg)
9579 "Wrap several fields in a column like a paragraph.
9580 This is useful if you'd like to spread the contents of a field over several
9581 lines, in order to keep the table compact.
9582
9583 If there is an active region, and both point and mark are in the same column,
9584 the text in the column is wrapped to minimum width for the given number of
9585 lines. Generally, this makes the table more compact. A prefix ARG may be
9586 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9587 formats the selected text to two lines. If the region was longer than two
9588 lines, the remaining lines remain empty. A negative prefix argument reduces
9589 the current number of lines by that amount. The wrapped text is pasted back
9590 into the table. If you formatted it to more lines than it was before, fields
9591 further down in the table get overwritten - so you might need to make space in
9592 the table first.
9593
9594 If there is no region, the current field is split at the cursor position and
9595 the text fragment to the right of the cursor is prepended to the field one
9596 line down.
9597
9598 If there is no region, but you specify a prefix ARG, the current field gets
9599 blank, and the content is appended to the field above."
9600 (interactive "P")
9601 (org-table-check-inside-data-field)
9602 (if (org-region-active-p)
9603 ;; There is a region: fill as a paragraph
9604 (let ((beg (region-beginning))
9605 nlines)
9606 (org-table-cut-region (region-beginning) (region-end))
9607 (if (> (length (car org-table-clip)) 1)
9608 (error "Region must be limited to single column"))
9609 (setq nlines (if arg
9610 (if (< arg 1)
9611 (+ (length org-table-clip) arg)
9612 arg)
9613 (length org-table-clip)))
9614 (setq org-table-clip
9615 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9616 nil nlines)))
9617 (goto-char beg)
9618 (org-table-paste-rectangle))
9619 ;; No region, split the current field at point
9620 (if arg
9621 ;; combine with field above
9622 (let ((s (org-table-blank-field))
9623 (col (org-table-current-column)))
9624 (beginning-of-line 0)
9625 (while (org-at-table-hline-p) (beginning-of-line 0))
9626 (org-table-goto-column col)
9627 (skip-chars-forward "^|")
9628 (skip-chars-backward " ")
9629 (insert " " (org-trim s))
9630 (org-table-align))
9631 ;; split field
9632 (when (looking-at "\\([^|]+\\)+|")
9633 (let ((s (match-string 1)))
9634 (replace-match " |")
9635 (goto-char (match-beginning 0))
9636 (org-table-next-row)
9637 (insert (org-trim s) " ")
9638 (org-table-align))))))
9639
9640 (defvar org-field-marker nil)
9641
9642 (defun org-table-edit-field (arg)
9643 "Edit table field in a different window.
9644 This is mainly useful for fields that contain hidden parts.
9645 When called with a \\[universal-argument] prefix, just make the full field visible so that
9646 it can be edited in place."
9647 (interactive "P")
9648 (if arg
9649 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9650 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9651 (remove-text-properties b e '(org-cwidth t invisible t
9652 display t intangible t))
9653 (if (and (boundp 'font-lock-mode) font-lock-mode)
9654 (font-lock-fontify-block)))
9655 (let ((pos (move-marker (make-marker) (point)))
9656 (field (org-table-get-field))
9657 (cw (current-window-configuration))
9658 p)
9659 (switch-to-buffer-other-window "*Org tmp*")
9660 (erase-buffer)
9661 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9662 (org-mode)
9663 (goto-char (setq p (point-max)))
9664 (insert (org-trim field))
9665 (remove-text-properties p (point-max)
9666 '(invisible t org-cwidth t display t
9667 intangible t))
9668 (goto-char p)
9669 (set (make-local-variable 'org-finish-function)
9670 'org-table-finish-edit-field)
9671 (set (make-local-variable 'org-window-configuration) cw)
9672 (set (make-local-variable 'org-field-marker) pos)
9673 (message "Edit and finish with C-c C-c"))))
9674
9675 (defun org-table-finish-edit-field ()
9676 "Finish editing a table data field.
9677 Remove all newline characters, insert the result into the table, realign
9678 the table and kill the editing buffer."
9679 (let ((pos org-field-marker)
9680 (cw org-window-configuration)
9681 (cb (current-buffer))
9682 text)
9683 (goto-char (point-min))
9684 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9685 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9686 (replace-match " "))
9687 (setq text (org-trim (buffer-string)))
9688 (set-window-configuration cw)
9689 (kill-buffer cb)
9690 (select-window (get-buffer-window (marker-buffer pos)))
9691 (goto-char pos)
9692 (move-marker pos nil)
9693 (org-table-check-inside-data-field)
9694 (org-table-get-field nil text)
9695 (org-table-align)
9696 (message "New field value inserted")))
9697
9698 (defun org-trim (s)
9699 "Remove whitespace at beginning and end of string."
9700 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
9701 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
9702 s)
9703
9704 (defun org-wrap (string &optional width lines)
9705 "Wrap string to either a number of lines, or a width in characters.
9706 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9707 that costs. If there is a word longer than WIDTH, the text is actually
9708 wrapped to the length of that word.
9709 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9710 many lines, whatever width that takes.
9711 The return value is a list of lines, without newlines at the end."
9712 (let* ((words (org-split-string string "[ \t\n]+"))
9713 (maxword (apply 'max (mapcar 'org-string-width words)))
9714 w ll)
9715 (cond (width
9716 (org-do-wrap words (max maxword width)))
9717 (lines
9718 (setq w maxword)
9719 (setq ll (org-do-wrap words maxword))
9720 (if (<= (length ll) lines)
9721 ll
9722 (setq ll words)
9723 (while (> (length ll) lines)
9724 (setq w (1+ w))
9725 (setq ll (org-do-wrap words w)))
9726 ll))
9727 (t (error "Cannot wrap this")))))
9728
9729
9730 (defun org-do-wrap (words width)
9731 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9732 (let (lines line)
9733 (while words
9734 (setq line (pop words))
9735 (while (and words (< (+ (length line) (length (car words))) width))
9736 (setq line (concat line " " (pop words))))
9737 (setq lines (push line lines)))
9738 (nreverse lines)))
9739
9740 (defun org-split-string (string &optional separators)
9741 "Splits STRING into substrings at SEPARATORS.
9742 No empty strings are returned if there are matches at the beginning
9743 and end of string."
9744 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9745 (start 0)
9746 notfirst
9747 (list nil))
9748 (while (and (string-match rexp string
9749 (if (and notfirst
9750 (= start (match-beginning 0))
9751 (< start (length string)))
9752 (1+ start) start))
9753 (< (match-beginning 0) (length string)))
9754 (setq notfirst t)
9755 (or (eq (match-beginning 0) 0)
9756 (and (eq (match-beginning 0) (match-end 0))
9757 (eq (match-beginning 0) start))
9758 (setq list
9759 (cons (substring string start (match-beginning 0))
9760 list)))
9761 (setq start (match-end 0)))
9762 (or (eq start (length string))
9763 (setq list
9764 (cons (substring string start)
9765 list)))
9766 (nreverse list)))
9767
9768 (defun org-table-map-tables (function)
9769 "Apply FUNCTION to the start of all tables in the buffer."
9770 (save-excursion
9771 (save-restriction
9772 (widen)
9773 (goto-char (point-min))
9774 (while (re-search-forward org-table-any-line-regexp nil t)
9775 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9776 (beginning-of-line 1)
9777 (if (looking-at org-table-line-regexp)
9778 (save-excursion (funcall function)))
9779 (re-search-forward org-table-any-border-regexp nil 1))))
9780 (message "Mapping tables: done"))
9781
9782 (defun org-table-sum (&optional beg end nlast)
9783 "Sum numbers in region of current table column.
9784 The result will be displayed in the echo area, and will be available
9785 as kill to be inserted with \\[yank].
9786
9787 If there is an active region, it is interpreted as a rectangle and all
9788 numbers in that rectangle will be summed. If there is no active
9789 region and point is located in a table column, sum all numbers in that
9790 column.
9791
9792 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9793 numbers are assumed to be times as well (in decimal hours) and the
9794 numbers are added as such.
9795
9796 If NLAST is a number, only the NLAST fields will actually be summed."
9797 (interactive)
9798 (save-excursion
9799 (let (col (timecnt 0) diff h m s org-table-clip)
9800 (cond
9801 ((and beg end)) ; beg and end given explicitly
9802 ((org-region-active-p)
9803 (setq beg (region-beginning) end (region-end)))
9804 (t
9805 (setq col (org-table-current-column))
9806 (goto-char (org-table-begin))
9807 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9808 (error "No table data"))
9809 (org-table-goto-column col)
9810 ;not needed? (skip-chars-backward "^|")
9811 (setq beg (point))
9812 (goto-char (org-table-end))
9813 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9814 (error "No table data"))
9815 (org-table-goto-column col)
9816 ;not needed? (skip-chars-forward "^|")
9817 (setq end (point))))
9818 (let* ((items (apply 'append (org-table-copy-region beg end)))
9819 (items1 (cond ((not nlast) items)
9820 ((>= nlast (length items)) items)
9821 (t (setq items (reverse items))
9822 (setcdr (nthcdr (1- nlast) items) nil)
9823 (nreverse items))))
9824 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9825 items1)))
9826 (res (apply '+ numbers))
9827 (sres (if (= timecnt 0)
9828 (format "%g" res)
9829 (setq diff (* 3600 res)
9830 h (floor (/ diff 3600)) diff (mod diff 3600)
9831 m (floor (/ diff 60)) diff (mod diff 60)
9832 s diff)
9833 (format "%d:%02d:%02d" h m s))))
9834 (kill-new sres)
9835 (if (interactive-p)
9836 (message "%s"
9837 (substitute-command-keys
9838 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9839 (length numbers) sres))))
9840 sres))))
9841
9842 (defun org-table-get-number-for-summing (s)
9843 (let (n)
9844 (if (string-match "^ *|? *" s)
9845 (setq s (replace-match "" nil nil s)))
9846 (if (string-match " *|? *$" s)
9847 (setq s (replace-match "" nil nil s)))
9848 (setq n (string-to-number s))
9849 (cond
9850 ((and (string-match "0" s)
9851 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9852 ((string-match "\\`[ \t]+\\'" s) nil)
9853 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9854 (let ((h (string-to-number (or (match-string 1 s) "0")))
9855 (m (string-to-number (or (match-string 2 s) "0")))
9856 (s (string-to-number (or (match-string 4 s) "0"))))
9857 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9858 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9859 ((equal n 0) nil)
9860 (t n))))
9861
9862 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9863 "Get a calc vector from a column, accorting to descriptor DESC.
9864 Optional arguments TBEG and COL can give the beginning of the table and
9865 the current column, to avoid unnecessary parsing."
9866 (save-excursion
9867 (or tbeg (setq tbeg (org-table-begin)))
9868 (or col (setq col (org-table-current-column)))
9869 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9870 (cond
9871 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9872 (setq n1 (- (match-end 1) (match-beginning 1)))
9873 (if (match-beginning 3)
9874 (setq n2 (- (match-end 2) (match-beginning 3))))
9875 (setq n (if n2 (max n1 n2) n1))
9876 (setq n1 (if n2 (min n1 n2)))
9877 (setq nn n)
9878 (while (and (> nn 0)
9879 (re-search-backward org-table-hline-regexp tbeg t))
9880 (push (org-current-line) hline-list)
9881 (setq nn (1- nn)))
9882 (setq hline-list (nreverse hline-list))
9883 (goto-line (nth (1- n) hline-list))
9884 (when (re-search-forward org-table-dataline-regexp)
9885 (org-table-goto-column col)
9886 (setq beg (point)))
9887 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9888 (when (re-search-backward org-table-dataline-regexp)
9889 (org-table-goto-column col)
9890 (setq end (point)))
9891 (setq l (apply 'append (org-table-copy-region beg end)))
9892 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9893 (if (equal x "") "0" x))
9894 l ",") "]"))
9895 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9896 (setq n1 (string-to-number (match-string 1 desc))
9897 n2 (string-to-number (match-string 2 desc)))
9898 (beginning-of-line 1)
9899 (save-excursion
9900 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9901 (org-table-goto-column col)
9902 (setq beg (point))))
9903 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9904 (org-table-goto-column col)
9905 (setq end (point)))
9906 (setq l (apply 'append (org-table-copy-region beg end)))
9907 (concat "[" (mapconcat
9908 (lambda (x) (setq x (org-trim x))
9909 (if (equal x "") "0" x))
9910 l ",") "]"))
9911 ((string-match "\\([0-9]+\\)" desc)
9912 (beginning-of-line 1)
9913 (when (re-search-backward org-table-dataline-regexp tbeg t
9914 (string-to-number (match-string 0 desc)))
9915 (org-table-goto-column col)
9916 (org-trim (org-table-get-field))))))))
9917
9918 (defvar org-table-formula-history nil)
9919
9920 (defvar org-table-column-names nil
9921 "Alist with column names, derived from the `!' line.")
9922 (defvar org-table-column-name-regexp nil
9923 "Regular expression matching the current column names.")
9924 (defvar org-table-local-parameters nil
9925 "Alist with parameter names, derived from the `$' line.")
9926 (defvar org-table-named-field-locations nil
9927 "Alist with locations of named fields.")
9928
9929 (defun org-table-get-formula (&optional equation named)
9930 "Read a formula from the minibuffer, offer stored formula as default."
9931 (let* ((name (car (rassoc (list (org-current-line)
9932 (org-table-current-column))
9933 org-table-named-field-locations)))
9934 (scol (if named
9935 (if name name
9936 (error "Not in a named field"))
9937 (int-to-string (org-table-current-column))))
9938 (dummy (and name (not named)
9939 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9940 (error "Abort")))
9941 (org-table-may-need-update nil)
9942 (stored-list (org-table-get-stored-formulas))
9943 (stored (cdr (assoc scol stored-list)))
9944 (eq (cond
9945 ((and stored equation (string-match "^ *=? *$" equation))
9946 stored)
9947 ((stringp equation)
9948 equation)
9949 (t (read-string
9950 (format "%s formula $%s=" (if named "Field" "Column") scol)
9951 (or stored "") 'org-table-formula-history
9952 ;stored
9953 ))))
9954 mustsave)
9955 (when (not (string-match "\\S-" eq))
9956 ;; remove formula
9957 (setq stored-list (delq (assoc scol stored-list) stored-list))
9958 (org-table-store-formulas stored-list)
9959 (error "Formula removed"))
9960 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9961 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9962 (if (and name (not named))
9963 ;; We set the column equation, delete the named one.
9964 (setq stored-list (delq (assoc name stored-list) stored-list)
9965 mustsave t))
9966 (if stored
9967 (setcdr (assoc scol stored-list) eq)
9968 (setq stored-list (cons (cons scol eq) stored-list)))
9969 (if (or mustsave (not (equal stored eq)))
9970 (org-table-store-formulas stored-list))
9971 eq))
9972
9973 (defun org-table-store-formulas (alist)
9974 "Store the list of formulas below the current table."
9975 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9976 (save-excursion
9977 (goto-char (org-table-end))
9978 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9979 (delete-region (point) (match-end 0)))
9980 (insert "#+TBLFM: "
9981 (mapconcat (lambda (x)
9982 (concat "$" (car x) "=" (cdr x)))
9983 alist "::")
9984 "\n")))
9985
9986 (defun org-table-get-stored-formulas ()
9987 "Return an alist with the t=stored formulas directly after current table."
9988 (interactive)
9989 (let (scol eq eq-alist strings string seen)
9990 (save-excursion
9991 (goto-char (org-table-end))
9992 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9993 (setq strings (org-split-string (match-string 2) " *:: *"))
9994 (while (setq string (pop strings))
9995 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9996 (setq scol (match-string 1 string)
9997 eq (match-string 2 string)
9998 eq-alist (cons (cons scol eq) eq-alist))
9999 (if (member scol seen)
10000 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
10001 (push scol seen))))))
10002 (nreverse eq-alist)))
10003
10004 (defun org-table-modify-formulas (action &rest columns)
10005 "Modify the formulas stored below the current table.
10006 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
10007 expected, for the other actions only a single column number is needed."
10008 (let ((list (org-table-get-stored-formulas))
10009 (nmax (length (org-split-string
10010 (buffer-substring (point-at-bol) (point-at-eol))
10011 "|")))
10012 col col1 col2 scol si sc1 sc2)
10013 (cond
10014 ((null list)) ; No action needed if there are no stored formulas
10015 ((eq action 'remove)
10016 (setq col (car columns)
10017 scol (int-to-string col))
10018 (org-table-replace-in-formulas list scol "INVALID")
10019 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
10020 (loop for i from (1+ col) upto nmax by 1 do
10021 (setq si (int-to-string i))
10022 (org-table-replace-in-formulas list si (int-to-string (1- i)))
10023 (if (assoc si list) (setcar (assoc si list)
10024 (int-to-string (1- i))))))
10025 ((eq action 'insert)
10026 (setq col (car columns))
10027 (loop for i from nmax downto col by 1 do
10028 (setq si (int-to-string i))
10029 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
10030 (if (assoc si list) (setcar (assoc si list)
10031 (int-to-string (1+ i))))))
10032 ((eq action 'swap)
10033 (setq col1 (car columns) col2 (nth 1 columns)
10034 sc1 (int-to-string col1) sc2 (int-to-string col2))
10035 ;; Hopefully, ZqZtZ will never be a name in a table
10036 (org-table-replace-in-formulas list sc1 "ZqZtZ")
10037 (org-table-replace-in-formulas list sc2 sc1)
10038 (org-table-replace-in-formulas list "ZqZtZ" sc2)
10039 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
10040 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
10041 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
10042 (t (error "Invalid action in `org-table-modify-formulas'")))
10043 (if list (org-table-store-formulas list))))
10044
10045 (defun org-table-replace-in-formulas (list s1 s2)
10046 (let (elt re s)
10047 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
10048 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
10049 re (concat (regexp-quote s1) "\\>"))
10050 (while (setq elt (pop list))
10051 (setq s (cdr elt))
10052 (while (string-match re s)
10053 (setq s (replace-match s2 t t s)))
10054 (setcdr elt s))))
10055
10056 (defun org-table-get-specials ()
10057 "Get the column names and local parameters for this table."
10058 (save-excursion
10059 (let ((beg (org-table-begin)) (end (org-table-end))
10060 names name fields fields1 field cnt c v line col)
10061 (setq org-table-column-names nil
10062 org-table-local-parameters nil
10063 org-table-named-field-locations nil)
10064 (goto-char beg)
10065 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10066 (setq names (org-split-string (match-string 1) " *| *")
10067 cnt 1)
10068 (while (setq name (pop names))
10069 (setq cnt (1+ cnt))
10070 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10071 (push (cons name (int-to-string cnt)) org-table-column-names))))
10072 (setq org-table-column-names (nreverse org-table-column-names))
10073 (setq org-table-column-name-regexp
10074 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10075 (goto-char beg)
10076 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10077 (setq fields (org-split-string (match-string 1) " *| *"))
10078 (while (setq field (pop fields))
10079 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10080 (push (cons (match-string 1 field) (match-string 2 field))
10081 org-table-local-parameters))))
10082 (goto-char beg)
10083 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10084 (setq c (match-string 1)
10085 fields (org-split-string (match-string 2) " *| *"))
10086 (save-excursion
10087 (beginning-of-line (if (equal c "_") 2 0))
10088 (setq line (org-current-line) col 1)
10089 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10090 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10091 (while (and fields1 (setq field (pop fields)))
10092 (setq v (pop fields1) col (1+ col))
10093 (when (and (stringp field) (stringp v)
10094 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10095 (push (cons field v) org-table-local-parameters)
10096 (push (list field line col) org-table-named-field-locations)))))))
10097
10098 (defun org-this-word ()
10099 ;; Get the current word
10100 (save-excursion
10101 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
10102 (end (progn (skip-chars-forward "^ \t\n") (point))))
10103 (buffer-substring-no-properties beg end))))
10104
10105 (defun org-table-maybe-eval-formula ()
10106 "Check if the current field starts with \"=\" or \":=\".
10107 If yes, store the formula and apply it."
10108 ;; We already know we are in a table. Get field will only return a formula
10109 ;; when appropriate. It might return a separator line, but no problem.
10110 (when org-table-formula-evaluate-inline
10111 (let* ((field (org-trim (or (org-table-get-field) "")))
10112 named eq)
10113 (when (string-match "^:?=\\(.*\\)" field)
10114 (setq named (equal (string-to-char field) ?:)
10115 eq (match-string 1 field))
10116 (if (fboundp 'calc-eval)
10117 (org-table-eval-formula (if named '(4) nil) eq))))))
10118
10119 (defvar org-recalc-commands nil
10120 "List of commands triggering the recalculation of a line.
10121 Will be filled automatically during use.")
10122
10123 (defvar org-recalc-marks
10124 '((" " . "Unmarked: no special line, no automatic recalculation")
10125 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10126 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10127 ("!" . "Column name definition line. Reference in formula as $name.")
10128 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10129 ("_" . "Names for values in row below this one.")
10130 ("^" . "Names for values in row above this one.")))
10131
10132 (defun org-table-rotate-recalc-marks (&optional newchar)
10133 "Rotate the recalculation mark in the first column.
10134 If in any row, the first field is not consistent with a mark,
10135 insert a new column for the markers.
10136 When there is an active region, change all the lines in the region,
10137 after prompting for the marking character.
10138 After each change, a message will be displayed indicating the meaning
10139 of the new mark."
10140 (interactive)
10141 (unless (org-at-table-p) (error "Not at a table"))
10142 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10143 (beg (org-table-begin))
10144 (end (org-table-end))
10145 (l (org-current-line))
10146 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10147 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10148 (have-col
10149 (save-excursion
10150 (goto-char beg)
10151 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10152 (col (org-table-current-column))
10153 (forcenew (car (assoc newchar org-recalc-marks)))
10154 epos new)
10155 (when l1
10156 (message "Change region to what mark? Type # * ! $ or SPC: ")
10157 (setq newchar (char-to-string (read-char-exclusive))
10158 forcenew (car (assoc newchar org-recalc-marks))))
10159 (if (and newchar (not forcenew))
10160 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10161 newchar))
10162 (if l1 (goto-line l1))
10163 (save-excursion
10164 (beginning-of-line 1)
10165 (unless (looking-at org-table-dataline-regexp)
10166 (error "Not at a table data line")))
10167 (unless have-col
10168 (org-table-goto-column 1)
10169 (org-table-insert-column)
10170 (org-table-goto-column (1+ col)))
10171 (setq epos (point-at-eol))
10172 (save-excursion
10173 (beginning-of-line 1)
10174 (org-table-get-field
10175 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10176 (concat " "
10177 (setq new (or forcenew
10178 (cadr (member (match-string 1) marks))))
10179 " ")
10180 " # ")))
10181 (if (and l1 l2)
10182 (progn
10183 (goto-line l1)
10184 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10185 (and (looking-at org-table-dataline-regexp)
10186 (org-table-get-field 1 (concat " " new " "))))
10187 (goto-line l1)))
10188 (if (not (= epos (point-at-eol))) (org-table-align))
10189 (goto-line l)
10190 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
10191
10192 (defun org-table-maybe-recalculate-line ()
10193 "Recompute the current line if marked for it, and if we haven't just done it."
10194 (interactive)
10195 (and org-table-allow-automatic-line-recalculation
10196 (not (and (memq last-command org-recalc-commands)
10197 (equal org-last-recalc-line (org-current-line))))
10198 (save-excursion (beginning-of-line 1)
10199 (looking-at org-table-auto-recalculate-regexp))
10200 (fboundp 'calc-eval)
10201 (org-table-recalculate) t))
10202
10203 (defvar org-table-formula-debug nil
10204 "Non-nil means, debug table formulas.
10205 When nil, simply write \"#ERROR\" in corrupted fields.")
10206
10207 (defvar modes)
10208 (defsubst org-set-calc-mode (var &optional value)
10209 (if (stringp var)
10210 (setq var (assoc var '(("D" calc-angle-mode deg)
10211 ("R" calc-angle-mode rad)
10212 ("F" calc-prefer-frac t)
10213 ("S" calc-symbolic-mode t)))
10214 value (nth 2 var) var (nth 1 var)))
10215 (if (memq var modes)
10216 (setcar (cdr (memq var modes)) value)
10217 (cons var (cons value modes)))
10218 modes)
10219
10220 (defun org-table-eval-formula (&optional arg equation
10221 suppress-align suppress-const
10222 suppress-store)
10223 "Replace the table field value at the cursor by the result of a calculation.
10224
10225 This function makes use of Dave Gillespie's Calc package, in my view the
10226 most exciting program ever written for GNU Emacs. So you need to have Calc
10227 installed in order to use this function.
10228
10229 In a table, this command replaces the value in the current field with the
10230 result of a formula. It also installs the formula as the \"current\" column
10231 formula, by storing it in a special line below the table. When called
10232 with a `C-u' prefix, the current field must ba a named field, and the
10233 formula is installed as valid in only this specific field.
10234
10235 When called, the command first prompts for a formula, which is read in
10236 the minibuffer. Previously entered formulas are available through the
10237 history list, and the last used formula is offered as a default.
10238 These stored formulas are adapted correctly when moving, inserting, or
10239 deleting columns with the corresponding commands.
10240
10241 The formula can be any algebraic expression understood by the Calc package.
10242 For details, see the Org-mode manual.
10243
10244 This function can also be called from Lisp programs and offers
10245 additional arguments: EQUATION can be the formula to apply. If this
10246 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10247 used to speed-up recursive calls by by-passing unnecessary aligns.
10248 SUPPRESS-CONST suppresses the interpretation of constants in the
10249 formula, assuming that this has been done already outside the function.
10250 SUPPRESS-STORE means the formula should not be stored, either because
10251 it is already stored, or because it is a modified equation that should
10252 not overwrite the stored one."
10253 (interactive "P")
10254 (require 'calc)
10255 (org-table-check-inside-data-field)
10256 (org-table-get-specials)
10257 (let* (fields
10258 (ndown (if (integerp arg) arg 1))
10259 (org-table-automatic-realign nil)
10260 (case-fold-search nil)
10261 (down (> ndown 1))
10262 (formula (if (and equation suppress-store)
10263 equation
10264 (org-table-get-formula equation (equal arg '(4)))))
10265 (n0 (org-table-current-column))
10266 (modes (copy-sequence org-calc-default-modes))
10267 n form fmt x ev orig c)
10268 ;; Parse the format string. Since we have a lot of modes, this is
10269 ;; a lot of work. However, I think calc still uses most of the time.
10270 (if (string-match ";" formula)
10271 (let ((tmp (org-split-string formula ";")))
10272 (setq formula (car tmp)
10273 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10274 (nth 1 tmp)))
10275 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
10276 (setq c (string-to-char (match-string 1 fmt))
10277 n (string-to-number (or (match-string 1 fmt) "")))
10278 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
10279 (setq modes (org-set-calc-mode
10280 'calc-float-format
10281 (list (cdr (assoc c '((?n . float) (?f . fix)
10282 (?s . sci) (?e . eng))))
10283 n))))
10284 (setq fmt (replace-match "" t t fmt)))
10285 (while (string-match "[DRFS]" fmt)
10286 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10287 (setq fmt (replace-match "" t t fmt)))
10288 (unless (string-match "\\S-" fmt)
10289 (setq fmt nil))))
10290 (if (and (not suppress-const) org-table-formula-use-constants)
10291 (setq formula (org-table-formula-substitute-names formula)))
10292 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10293 (while (> ndown 0)
10294 (setq fields (org-split-string
10295 (buffer-substring
10296 (point-at-bol) (point-at-eol)) " *| *"))
10297 (if org-table-formula-numbers-only
10298 (setq fields (mapcar
10299 (lambda (x) (number-to-string (string-to-number x)))
10300 fields)))
10301 (setq ndown (1- ndown))
10302 (setq form (copy-sequence formula))
10303 ;; Insert the references to fields in same row
10304 (while (string-match "\\$\\([0-9]+\\)?" form)
10305 (setq n (if (match-beginning 1)
10306 (string-to-number (match-string 1 form))
10307 n0)
10308 x (nth (1- n) fields))
10309 (unless x (error "Invalid field specifier \"%s\""
10310 (match-string 0 form)))
10311 (if (equal x "") (setq x "0"))
10312 (setq form (replace-match (concat "(" x ")") t t form)))
10313 ;; Insert ranges in current column
10314 (while (string-match "\\&[-I0-9]+" form)
10315 (setq form (replace-match
10316 (save-match-data
10317 (org-table-get-vertical-vector (match-string 0 form)
10318 nil n0))
10319 t t form)))
10320 (setq ev (calc-eval (cons form modes)
10321 (if org-table-formula-numbers-only 'num)))
10322
10323 (when org-table-formula-debug
10324 (with-output-to-temp-buffer "*Help*"
10325 (princ (format "Substitution history of formula
10326 Orig: %s
10327 $xyz-> %s
10328 $1-> %s\n" orig formula form))
10329 (if (listp ev)
10330 (princ (format " %s^\nError: %s"
10331 (make-string (car ev) ?\-) (nth 1 ev)))
10332 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10333 ev (or fmt "NONE")
10334 (if fmt (format fmt (string-to-number ev)) ev)))))
10335 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
10336 (unless (and (interactive-p) (not ndown))
10337 (unless (let (inhibit-redisplay)
10338 (y-or-n-p "Debugging Formula. Continue to next? "))
10339 (org-table-align)
10340 (error "Abort"))
10341 (delete-window (get-buffer-window "*Help*"))
10342 (message "")))
10343 (if (listp ev) (setq fmt nil ev "#ERROR"))
10344 (org-table-justify-field-maybe
10345 (if fmt (format fmt (string-to-number ev)) ev))
10346 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10347 (call-interactively 'org-return)
10348 (setq ndown 0)))
10349 (and down (org-table-maybe-recalculate-line))
10350 (or suppress-align (and org-table-may-need-update
10351 (org-table-align)))))
10352
10353 (defun org-table-recalculate (&optional all noalign)
10354 "Recalculate the current table line by applying all stored formulas.
10355 With prefix arg ALL, do this for all lines in the table."
10356 (interactive "P")
10357 (or (memq this-command org-recalc-commands)
10358 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10359 (unless (org-at-table-p) (error "Not at a table"))
10360 (org-table-get-specials)
10361 (let* ((eqlist (sort (org-table-get-stored-formulas)
10362 (lambda (a b) (string< (car a) (car b)))))
10363 (inhibit-redisplay t)
10364 (line-re org-table-dataline-regexp)
10365 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10366 (thiscol (org-table-current-column))
10367 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
10368 ;; Insert constants in all formulas
10369 (setq eqlist
10370 (mapcar (lambda (x)
10371 (setcdr x (org-table-formula-substitute-names (cdr x)))
10372 x)
10373 eqlist))
10374 ;; Split the equation list
10375 (while (setq eq (pop eqlist))
10376 (if (<= (string-to-char (car eq)) ?9)
10377 (push eq eqlnum)
10378 (push eq eqlname)))
10379 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10380 (if all
10381 (progn
10382 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10383 (goto-char (setq beg (org-table-begin)))
10384 (if (re-search-forward org-table-calculate-mark-regexp end t)
10385 ;; This is a table with marked lines, only compute selected lines
10386 (setq line-re org-table-recalculate-regexp)
10387 ;; Move forward to the first non-header line
10388 (if (and (re-search-forward org-table-dataline-regexp end t)
10389 (re-search-forward org-table-hline-regexp end t)
10390 (re-search-forward org-table-dataline-regexp end t))
10391 (setq beg (match-beginning 0))
10392 nil))) ;; just leave beg where it is
10393 (setq beg (point-at-bol)
10394 end (move-marker (make-marker) (1+ (point-at-eol)))))
10395 (goto-char beg)
10396 (and all (message "Re-applying formulas to full table..."))
10397 (while (re-search-forward line-re end t)
10398 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
10399 ;; Unprotected line, recalculate
10400 (and all (message "Re-applying formulas to full table...(line %d)"
10401 (setq cnt (1+ cnt))))
10402 (setq org-last-recalc-line (org-current-line))
10403 (setq eql eqlnum)
10404 (while (setq entry (pop eql))
10405 (goto-line org-last-recalc-line)
10406 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10407 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
10408 (goto-line thisline)
10409 (org-table-goto-column thiscol)
10410 (or noalign (and org-table-may-need-update (org-table-align))
10411 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10412 ;; Now do the names fields
10413 (while (setq eq (pop eqlname))
10414 (setq name (car eq)
10415 a (assoc name org-table-named-field-locations))
10416 (when a
10417 (message "Re-applying formula to named field: %s" name)
10418 (goto-line (nth 1 a))
10419 (org-table-goto-column (nth 2 a))
10420 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
10421 ;; back to initial position
10422 (goto-line thisline)
10423 (org-table-goto-column thiscol)
10424 (or noalign (and org-table-may-need-update (org-table-align))
10425 (and all (message "Re-applying formulas...done")))))
10426
10427 (defun org-table-formula-substitute-names (f)
10428 "Replace $const with values in string F."
10429 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
10430 ;; First, check for column names
10431 (while (setq start (string-match org-table-column-name-regexp f start))
10432 (setq start (1+ start))
10433 (setq a (assoc (match-string 1 f) org-table-column-names))
10434 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10435 ;; Expand ranges to vectors
10436 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
10437 (setq n1 (string-to-number (match-string 1 f))
10438 n2 (string-to-number (match-string 2 f))
10439 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
10440 s (concat "[($" (number-to-string (1- nn1)) ")"))
10441 (loop for i from nn1 upto nn2 do
10442 (setq s (concat s ",($" (int-to-string i) ")")))
10443 (setq s (concat s "]"))
10444 (if (< n2 n1) (setq s (concat "rev(" s ")")))
10445 (setq f (replace-match s t t f)))
10446 ;; Parameters and constants
10447 (setq start 0)
10448 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
10449 (setq start (1+ start))
10450 (if (setq a (save-match-data
10451 (org-table-get-constant (match-string 1 f))))
10452 (setq f (replace-match (concat "(" a ")") t t f))))
10453 (if org-table-formula-debug
10454 (put-text-property 0 (length f) :orig-formula f1 f))
10455 f))
10456
10457 (defun org-table-get-constant (const)
10458 "Find the value for a parameter or constant in a formula.
10459 Parameters get priority."
10460 (or (cdr (assoc const org-table-local-parameters))
10461 (cdr (assoc const org-table-formula-constants))
10462 (and (fboundp 'constants-get) (constants-get const))
10463 "#UNDEFINED_NAME"))
10464
10465 (defvar org-edit-formulas-map (make-sparse-keymap))
10466 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
10467 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
10468 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
10469
10470 (defvar org-pos)
10471
10472 (defun org-table-edit-formulas ()
10473 "Edit the formulas of the current table in a separate buffer."
10474 (interactive)
10475 (unless (org-at-table-p)
10476 (error "Not at a table"))
10477 (org-table-get-specials)
10478 (let ((eql (org-table-get-stored-formulas))
10479 (pos (move-marker (make-marker) (point)))
10480 (wc (current-window-configuration))
10481 entry loc s)
10482 (switch-to-buffer-other-window "*Edit Formulas*")
10483 (erase-buffer)
10484 (fundamental-mode)
10485 (set (make-local-variable 'org-pos) pos)
10486 (set (make-local-variable 'org-window-configuration) wc)
10487 (use-local-map org-edit-formulas-map)
10488 (setq s "# Edit formulas and finish with `C-c C-c'.
10489 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
10490 # Use `C-c ?' to get information about $name at point.
10491 # To cancel editing, press `C-c C-q'.\n")
10492 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10493 (insert s)
10494 (while (setq entry (pop eql))
10495 (when (setq loc (assoc (car entry) org-table-named-field-locations))
10496 (setq s (format "# Named formula, referring to column %d in line %d\n"
10497 (nth 2 loc) (nth 1 loc)))
10498 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10499 (insert s))
10500 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
10501 (remove-text-properties 0 (length s) '(face nil) s)
10502 (insert s))
10503 (goto-char (point-min))
10504 (message "Edit formulas and finish with `C-c C-c'.")))
10505
10506 (defun org-show-variable ()
10507 "Show the location/value of the $ expression at point."
10508 (interactive)
10509 (let (var (pos org-pos) (win (selected-window)) e)
10510 (save-excursion
10511 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
10512 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
10513 (setq var (match-string 1))
10514 (error "No variable at point")))
10515 (cond
10516 ((setq e (assoc var org-table-named-field-locations))
10517 (switch-to-buffer-other-window (marker-buffer pos))
10518 (goto-line (nth 1 e))
10519 (org-table-goto-column (nth 2 e))
10520 (select-window win)
10521 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10522 ((setq e (assoc var org-table-column-names))
10523 (switch-to-buffer-other-window (marker-buffer pos))
10524 (goto-char pos)
10525 (goto-char (org-table-begin))
10526 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10527 (org-table-end) t)
10528 (progn
10529 (goto-char (match-beginning 1))
10530 (message "Named column (column %s)" (cdr e)))
10531 (error "Column name not found"))
10532 (select-window win))
10533 ((string-match "^[0-9]$" var)
10534 ;; column number
10535 (switch-to-buffer-other-window (marker-buffer pos))
10536 (goto-char pos)
10537 (goto-char (org-table-begin))
10538 (recenter 1)
10539 (if (re-search-forward org-table-dataline-regexp
10540 (org-table-end) t)
10541 (progn
10542 (goto-char (match-beginning 0))
10543 (org-table-goto-column (string-to-number var))
10544 (message "Column %s" var))
10545 (error "Column name not found"))
10546 (select-window win))
10547 ((setq e (assoc var org-table-local-parameters))
10548 (switch-to-buffer-other-window (marker-buffer pos))
10549 (goto-char pos)
10550 (goto-char (org-table-begin))
10551 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10552 (progn
10553 (goto-char (match-beginning 1))
10554 (message "Local parameter."))
10555 (error "Parameter not found"))
10556 (select-window win))
10557 (t
10558 (cond
10559 ((setq e (assoc var org-table-formula-constants))
10560 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
10561 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10562 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
10563 (t (error "Undefined name $%s" var)))))))
10564
10565 (defun org-finish-edit-formulas (&optional arg)
10566 "Parse the buffer for formula definitions and install them.
10567 With prefix ARG, apply the new formulas to the table."
10568 (interactive "P")
10569 (let ((pos org-pos) eql)
10570 (goto-char (point-min))
10571 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
10572 (push (cons (match-string 1) (match-string 2)) eql))
10573 (set-window-configuration org-window-configuration)
10574 (select-window (get-buffer-window (marker-buffer pos)))
10575 (goto-char pos)
10576 (unless (org-at-table-p)
10577 (error "Lost table position - cannot install formulae"))
10578 (org-table-store-formulas eql)
10579 (move-marker pos nil)
10580 (kill-buffer "*Edit Formulas*")
10581 (if arg
10582 (org-table-recalculate 'all)
10583 (message "New formulas installed - press C-u C-c C-c to apply."))))
10584
10585 (defun org-abort-edit-formulas ()
10586 "Abort editing formulas, without installing the changes."
10587 (interactive)
10588 (let ((pos org-pos))
10589 (set-window-configuration org-window-configuration)
10590 (select-window (get-buffer-window (marker-buffer pos)))
10591 (goto-char pos)
10592 (message "Formula editing aborted without installing changes")))
10593
10594 ;;; The orgtbl minor mode
10595
10596 ;; Define a minor mode which can be used in other modes in order to
10597 ;; integrate the org-mode table editor.
10598
10599 ;; This is really a hack, because the org-mode table editor uses several
10600 ;; keys which normally belong to the major mode, for example the TAB and
10601 ;; RET keys. Here is how it works: The minor mode defines all the keys
10602 ;; necessary to operate the table editor, but wraps the commands into a
10603 ;; function which tests if the cursor is currently inside a table. If that
10604 ;; is the case, the table editor command is executed. However, when any of
10605 ;; those keys is used outside a table, the function uses `key-binding' to
10606 ;; look up if the key has an associated command in another currently active
10607 ;; keymap (minor modes, major mode, global), and executes that command.
10608 ;; There might be problems if any of the keys used by the table editor is
10609 ;; otherwise used as a prefix key.
10610
10611 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10612 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10613 ;; addresses this by checking explicitly for both bindings.
10614
10615 ;; The optimized version (see variable `orgtbl-optimized') takes over
10616 ;; all keys which are bound to `self-insert-command' in the *global map*.
10617 ;; Some modes bind other commands to simple characters, for example
10618 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10619 ;; active, this binding is ignored inside tables and replaced with a
10620 ;; modified self-insert.
10621
10622 (defvar orgtbl-mode nil
10623 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10624 table editor in arbitrary modes.")
10625 (make-variable-buffer-local 'orgtbl-mode)
10626
10627 (defvar orgtbl-mode-map (make-keymap)
10628 "Keymap for `orgtbl-mode'.")
10629
10630 ;;;###autoload
10631 (defun turn-on-orgtbl ()
10632 "Unconditionally turn on `orgtbl-mode'."
10633 (orgtbl-mode 1))
10634
10635 ;;;###autoload
10636 (defun orgtbl-mode (&optional arg)
10637 "The `org-mode' table editor as a minor mode for use in other modes."
10638 (interactive)
10639 (if (eq major-mode 'org-mode)
10640 ;; Exit without error, in case some hook functions calls this
10641 ;; by accident in org-mode.
10642 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10643 (setq orgtbl-mode
10644 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10645 (if orgtbl-mode
10646 (progn
10647 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10648 ;; Make sure we are first in minor-mode-map-alist
10649 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10650 (and c (setq minor-mode-map-alist
10651 (cons c (delq c minor-mode-map-alist)))))
10652 (set (make-local-variable (quote org-table-may-need-update)) t)
10653 (org-add-hook 'before-change-functions 'org-before-change-function
10654 nil 'local)
10655 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
10656 auto-fill-inhibit-regexp)
10657 (set (make-local-variable 'auto-fill-inhibit-regexp)
10658 (if auto-fill-inhibit-regexp
10659 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
10660 "[ \t]*|"))
10661 (org-add-to-invisibility-spec '(org-cwidth))
10662 (easy-menu-add orgtbl-mode-menu)
10663 (run-hooks 'orgtbl-mode-hook))
10664 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10665 (org-cleanup-narrow-column-properties)
10666 (org-remove-from-invisibility-spec '(org-cwidth))
10667 (remove-hook 'before-change-functions 'org-before-change-function t)
10668 (easy-menu-remove orgtbl-mode-menu)
10669 (force-mode-line-update 'all))))
10670
10671 (defun org-cleanup-narrow-column-properties ()
10672 "Remove all properties related to narrow-column invisibility."
10673 (let ((s 1))
10674 (while (setq s (text-property-any s (point-max)
10675 'display org-narrow-column-arrow))
10676 (remove-text-properties s (1+ s) '(display t)))
10677 (setq s 1)
10678 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10679 (remove-text-properties s (1+ s) '(org-cwidth t)))
10680 (setq s 1)
10681 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10682 (remove-text-properties s (1+ s) '(invisible t)))))
10683
10684 ;; Install it as a minor mode.
10685 (put 'orgtbl-mode :included t)
10686 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10687 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10688
10689 (defun orgtbl-make-binding (fun n &rest keys)
10690 "Create a function for binding in the table minor mode.
10691 FUN is the command to call inside a table. N is used to create a unique
10692 command name. KEYS are keys that should be checked in for a command
10693 to execute outside of tables."
10694 (eval
10695 (list 'defun
10696 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10697 '(arg)
10698 (concat "In tables, run `" (symbol-name fun) "'.\n"
10699 "Outside of tables, run the binding of `"
10700 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10701 "'.")
10702 '(interactive "p")
10703 (list 'if
10704 '(org-at-table-p)
10705 (list 'call-interactively (list 'quote fun))
10706 (list 'let '(orgtbl-mode)
10707 (list 'call-interactively
10708 (append '(or)
10709 (mapcar (lambda (k)
10710 (list 'key-binding k))
10711 keys)
10712 '('orgtbl-error))))))))
10713
10714 (defun orgtbl-error ()
10715 "Error when there is no default binding for a table key."
10716 (interactive)
10717 (error "This key is has no function outside tables"))
10718
10719 (defun orgtbl-setup ()
10720 "Setup orgtbl keymaps."
10721 (let ((nfunc 0)
10722 (bindings
10723 (list
10724 '([(meta shift left)] org-table-delete-column)
10725 '([(meta left)] org-table-move-column-left)
10726 '([(meta right)] org-table-move-column-right)
10727 '([(meta shift right)] org-table-insert-column)
10728 '([(meta shift up)] org-table-kill-row)
10729 '([(meta shift down)] org-table-insert-row)
10730 '([(meta up)] org-table-move-row-up)
10731 '([(meta down)] org-table-move-row-down)
10732 '("\C-c\C-w" org-table-cut-region)
10733 '("\C-c\M-w" org-table-copy-region)
10734 '("\C-c\C-y" org-table-paste-rectangle)
10735 '("\C-c-" org-table-insert-hline)
10736 ; '([(shift tab)] org-table-previous-field)
10737 '("\C-m" org-table-next-row)
10738 (list (org-key 'S-return) 'org-table-copy-down)
10739 '([(meta return)] org-table-wrap-region)
10740 '("\C-c\C-q" org-table-wrap-region)
10741 '("\C-c?" org-table-current-column)
10742 '("\C-c " org-table-blank-field)
10743 '("\C-c+" org-table-sum)
10744 '("\C-c=" org-table-eval-formula)
10745 '("\C-c'" org-table-edit-formulas)
10746 '("\C-c`" org-table-edit-field)
10747 '("\C-c*" org-table-recalculate)
10748 '("\C-c|" org-table-create-or-convert-from-region)
10749 '("\C-c^" org-table-sort-lines)
10750 '([(control ?#)] org-table-rotate-recalc-marks)))
10751 elt key fun cmd)
10752 (while (setq elt (pop bindings))
10753 (setq nfunc (1+ nfunc))
10754 (setq key (car elt)
10755 fun (nth 1 elt)
10756 cmd (orgtbl-make-binding fun nfunc key))
10757 (define-key orgtbl-mode-map key cmd))
10758 ;; Special treatment needed for TAB and RET
10759 (define-key orgtbl-mode-map [(return)]
10760 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10761 (define-key orgtbl-mode-map "\C-m"
10762 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10763 (define-key orgtbl-mode-map [(tab)]
10764 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10765 (define-key orgtbl-mode-map "\C-i"
10766 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
10767 (define-key orgtbl-mode-map "\C-i"
10768 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
10769 (define-key orgtbl-mode-map "\C-c\C-c"
10770 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
10771 (when orgtbl-optimized
10772 ;; If the user wants maximum table support, we need to hijack
10773 ;; some standard editing functions
10774 (org-remap orgtbl-mode-map
10775 'self-insert-command 'orgtbl-self-insert-command
10776 'delete-char 'org-delete-char
10777 'delete-backward-char 'org-delete-backward-char)
10778 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
10779 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10780 '("OrgTbl"
10781 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10782 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10783 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10784 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10785 "--"
10786 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10787 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10788 ["Copy Field from Above"
10789 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10790 "--"
10791 ("Column"
10792 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10793 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10794 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10795 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
10796 "--"
10797 ["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])
10798 ("Row"
10799 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10800 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10801 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10802 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10803 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10804 "--"
10805 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10806 ("Rectangle"
10807 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10808 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10809 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10810 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10811 "--"
10812 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10813 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10814 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10815 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10816 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10817 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10818 ["Sum Column/Rectangle" org-table-sum
10819 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10820 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10821 ["Debug Formulas"
10822 (setq org-table-formula-debug (not org-table-formula-debug))
10823 :style toggle :selected org-table-formula-debug]
10824 ))
10825 t)
10826
10827 (defun orgtbl-tab (arg)
10828 "Justification and field motion for `orgtbl-mode'."
10829 (interactive "P")
10830 (if arg (org-table-edit-field t)
10831 (org-table-justify-field-maybe)
10832 (org-table-next-field)))
10833
10834 (defun orgtbl-ret ()
10835 "Justification and field motion for `orgtbl-mode'."
10836 (interactive)
10837 (org-table-justify-field-maybe)
10838 (org-table-next-row))
10839
10840 (defun orgtbl-self-insert-command (N)
10841 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10842 If the cursor is in a table looking at whitespace, the whitespace is
10843 overwritten, and the table is not marked as requiring realignment."
10844 (interactive "p")
10845 (if (and (org-at-table-p)
10846 (or
10847 (and org-table-auto-blank-field
10848 (member last-command
10849 '(orgtbl-hijacker-command-100
10850 orgtbl-hijacker-command-101
10851 orgtbl-hijacker-command-102
10852 orgtbl-hijacker-command-103
10853 orgtbl-hijacker-command-104
10854 orgtbl-hijacker-command-105))
10855 (org-table-blank-field))
10856 t)
10857 (eq N 1)
10858 (looking-at "[^|\n]* +|"))
10859 (let (org-table-may-need-update)
10860 (goto-char (1- (match-end 0)))
10861 (delete-backward-char 1)
10862 (goto-char (match-beginning 0))
10863 (self-insert-command N))
10864 (setq org-table-may-need-update t)
10865 (let (orgtbl-mode)
10866 (call-interactively (key-binding (vector last-input-event))))))
10867
10868 (defun org-force-self-insert (N)
10869 "Needed to enforce self-insert under remapping."
10870 (interactive "p")
10871 (self-insert-command N))
10872
10873 ;;; Exporting
10874
10875 (defconst org-level-max 20)
10876
10877 (defun org-export-find-first-heading-line (list)
10878 "Remove all lines from LIST which are before the first headline."
10879 (let ((orig-list list)
10880 (re (concat "^" outline-regexp)))
10881 (while (and list
10882 (not (string-match re (car list))))
10883 (pop list))
10884 (or list orig-list)))
10885
10886 (defun org-skip-comments (lines)
10887 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10888 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10889 (re2 "^\\(\\*+\\)[ \t\n\r]")
10890 rtn line level)
10891 (while (setq line (pop lines))
10892 (cond
10893 ((and (string-match re1 line)
10894 (setq level (- (match-end 1) (match-beginning 1))))
10895 ;; Beginning of a COMMENT subtree. Skip it.
10896 (while (and (setq line (pop lines))
10897 (or (not (string-match re2 line))
10898 (> (- (match-end 1) (match-beginning 1)) level))))
10899 (setq lines (cons line lines)))
10900 ((string-match "^#" line)
10901 ;; an ordinary comment line
10902 )
10903 ((and org-export-table-remove-special-lines
10904 (string-match "^[ \t]*| *[!_^] *|" line))
10905 ;; a special table line that should be removed
10906 )
10907 (t (setq rtn (cons line rtn)))))
10908 (nreverse rtn)))
10909
10910 ;; ASCII
10911
10912 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10913 "Characters for underlining headings in ASCII export.")
10914
10915 (defconst org-html-entities
10916 '(("nbsp")
10917 ("iexcl")
10918 ("cent")
10919 ("pound")
10920 ("curren")
10921 ("yen")
10922 ("brvbar")
10923 ("sect")
10924 ("uml")
10925 ("copy")
10926 ("ordf")
10927 ("laquo")
10928 ("not")
10929 ("shy")
10930 ("reg")
10931 ("macr")
10932 ("deg")
10933 ("plusmn")
10934 ("sup2")
10935 ("sup3")
10936 ("acute")
10937 ("micro")
10938 ("para")
10939 ("middot")
10940 ("odot"."o")
10941 ("star"."*")
10942 ("cedil")
10943 ("sup1")
10944 ("ordm")
10945 ("raquo")
10946 ("frac14")
10947 ("frac12")
10948 ("frac34")
10949 ("iquest")
10950 ("Agrave")
10951 ("Aacute")
10952 ("Acirc")
10953 ("Atilde")
10954 ("Auml")
10955 ("Aring") ("AA"."&Aring;")
10956 ("AElig")
10957 ("Ccedil")
10958 ("Egrave")
10959 ("Eacute")
10960 ("Ecirc")
10961 ("Euml")
10962 ("Igrave")
10963 ("Iacute")
10964 ("Icirc")
10965 ("Iuml")
10966 ("ETH")
10967 ("Ntilde")
10968 ("Ograve")
10969 ("Oacute")
10970 ("Ocirc")
10971 ("Otilde")
10972 ("Ouml")
10973 ("times")
10974 ("Oslash")
10975 ("Ugrave")
10976 ("Uacute")
10977 ("Ucirc")
10978 ("Uuml")
10979 ("Yacute")
10980 ("THORN")
10981 ("szlig")
10982 ("agrave")
10983 ("aacute")
10984 ("acirc")
10985 ("atilde")
10986 ("auml")
10987 ("aring")
10988 ("aelig")
10989 ("ccedil")
10990 ("egrave")
10991 ("eacute")
10992 ("ecirc")
10993 ("euml")
10994 ("igrave")
10995 ("iacute")
10996 ("icirc")
10997 ("iuml")
10998 ("eth")
10999 ("ntilde")
11000 ("ograve")
11001 ("oacute")
11002 ("ocirc")
11003 ("otilde")
11004 ("ouml")
11005 ("divide")
11006 ("oslash")
11007 ("ugrave")
11008 ("uacute")
11009 ("ucirc")
11010 ("uuml")
11011 ("yacute")
11012 ("thorn")
11013 ("yuml")
11014 ("fnof")
11015 ("Alpha")
11016 ("Beta")
11017 ("Gamma")
11018 ("Delta")
11019 ("Epsilon")
11020 ("Zeta")
11021 ("Eta")
11022 ("Theta")
11023 ("Iota")
11024 ("Kappa")
11025 ("Lambda")
11026 ("Mu")
11027 ("Nu")
11028 ("Xi")
11029 ("Omicron")
11030 ("Pi")
11031 ("Rho")
11032 ("Sigma")
11033 ("Tau")
11034 ("Upsilon")
11035 ("Phi")
11036 ("Chi")
11037 ("Psi")
11038 ("Omega")
11039 ("alpha")
11040 ("beta")
11041 ("gamma")
11042 ("delta")
11043 ("epsilon")
11044 ("varepsilon"."&epsilon;")
11045 ("zeta")
11046 ("eta")
11047 ("theta")
11048 ("iota")
11049 ("kappa")
11050 ("lambda")
11051 ("mu")
11052 ("nu")
11053 ("xi")
11054 ("omicron")
11055 ("pi")
11056 ("rho")
11057 ("sigmaf") ("varsigma"."&sigmaf;")
11058 ("sigma")
11059 ("tau")
11060 ("upsilon")
11061 ("phi")
11062 ("chi")
11063 ("psi")
11064 ("omega")
11065 ("thetasym") ("vartheta"."&thetasym;")
11066 ("upsih")
11067 ("piv")
11068 ("bull") ("bullet"."&bull;")
11069 ("hellip") ("dots"."&hellip;")
11070 ("prime")
11071 ("Prime")
11072 ("oline")
11073 ("frasl")
11074 ("weierp")
11075 ("image")
11076 ("real")
11077 ("trade")
11078 ("alefsym")
11079 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
11080 ("uarr") ("uparrow"."&uarr;")
11081 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
11082 ("darr")("downarrow"."&darr;")
11083 ("harr") ("leftrightarrow"."&harr;")
11084 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
11085 ("lArr") ("Leftarrow"."&lArr;")
11086 ("uArr") ("Uparrow"."&uArr;")
11087 ("rArr") ("Rightarrow"."&rArr;")
11088 ("dArr") ("Downarrow"."&dArr;")
11089 ("hArr") ("Leftrightarrow"."&hArr;")
11090 ("forall")
11091 ("part") ("partial"."&part;")
11092 ("exist") ("exists"."&exist;")
11093 ("empty") ("emptyset"."&empty;")
11094 ("nabla")
11095 ("isin") ("in"."&isin;")
11096 ("notin")
11097 ("ni")
11098 ("prod")
11099 ("sum")
11100 ("minus")
11101 ("lowast") ("ast"."&lowast;")
11102 ("radic")
11103 ("prop") ("proptp"."&prop;")
11104 ("infin") ("infty"."&infin;")
11105 ("ang") ("angle"."&ang;")
11106 ("and") ("vee"."&and;")
11107 ("or") ("wedge"."&or;")
11108 ("cap")
11109 ("cup")
11110 ("int")
11111 ("there4")
11112 ("sim")
11113 ("cong") ("simeq"."&cong;")
11114 ("asymp")("approx"."&asymp;")
11115 ("ne") ("neq"."&ne;")
11116 ("equiv")
11117 ("le")
11118 ("ge")
11119 ("sub") ("subset"."&sub;")
11120 ("sup") ("supset"."&sup;")
11121 ("nsub")
11122 ("sube")
11123 ("supe")
11124 ("oplus")
11125 ("otimes")
11126 ("perp")
11127 ("sdot") ("cdot"."&sdot;")
11128 ("lceil")
11129 ("rceil")
11130 ("lfloor")
11131 ("rfloor")
11132 ("lang")
11133 ("rang")
11134 ("loz") ("Diamond"."&loz;")
11135 ("spades") ("spadesuit"."&spades;")
11136 ("clubs") ("clubsuit"."&clubs;")
11137 ("hearts") ("diamondsuit"."&hearts;")
11138 ("diams") ("diamondsuit"."&diams;")
11139 ("quot")
11140 ("amp")
11141 ("lt")
11142 ("gt")
11143 ("OElig")
11144 ("oelig")
11145 ("Scaron")
11146 ("scaron")
11147 ("Yuml")
11148 ("circ")
11149 ("tilde")
11150 ("ensp")
11151 ("emsp")
11152 ("thinsp")
11153 ("zwnj")
11154 ("zwj")
11155 ("lrm")
11156 ("rlm")
11157 ("ndash")
11158 ("mdash")
11159 ("lsquo")
11160 ("rsquo")
11161 ("sbquo")
11162 ("ldquo")
11163 ("rdquo")
11164 ("bdquo")
11165 ("dagger")
11166 ("Dagger")
11167 ("permil")
11168 ("lsaquo")
11169 ("rsaquo")
11170 ("euro")
11171
11172 ("arccos"."arccos")
11173 ("arcsin"."arcsin")
11174 ("arctan"."arctan")
11175 ("arg"."arg")
11176 ("cos"."cos")
11177 ("cosh"."cosh")
11178 ("cot"."cot")
11179 ("coth"."coth")
11180 ("csc"."csc")
11181 ("deg"."deg")
11182 ("det"."det")
11183 ("dim"."dim")
11184 ("exp"."exp")
11185 ("gcd"."gcd")
11186 ("hom"."hom")
11187 ("inf"."inf")
11188 ("ker"."ker")
11189 ("lg"."lg")
11190 ("lim"."lim")
11191 ("liminf"."liminf")
11192 ("limsup"."limsup")
11193 ("ln"."ln")
11194 ("log"."log")
11195 ("max"."max")
11196 ("min"."min")
11197 ("Pr"."Pr")
11198 ("sec"."sec")
11199 ("sin"."sin")
11200 ("sinh"."sinh")
11201 ("sup"."sup")
11202 ("tan"."tan")
11203 ("tanh"."tanh")
11204 )
11205 "Entities for TeX->HTML translation.
11206 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
11207 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
11208 In that case, \"\\ent\" will be translated to \"&other;\".
11209 The list contains HTML entities for Latin-1, Greek and other symbols.
11210 It is supplemented by a number of commonly used TeX macros with appropriate
11211 translations. There is currently no way for users to extend this.")
11212
11213 (defun org-cleaned-string-for-export (string)
11214 "Cleanup a buffer substring so that links can be created safely."
11215 (interactive)
11216 (let* ((cb (current-buffer))
11217 (re-radio (and org-target-link-regexp
11218 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
11219 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
11220 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
11221 rtn)
11222 (save-excursion
11223 (set-buffer (get-buffer-create " org-mode-tmp"))
11224 (erase-buffer)
11225 (insert string)
11226 (org-mode)
11227 ;; Find targets in comments and move them out of comments,
11228 ;; but mark them as targets that should be invisible
11229 (goto-char (point-min))
11230 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
11231 (replace-match "\\1(INVISIBLE)"))
11232 ;; Find matches for radio targets and turn them into internal links
11233 (goto-char (point-min))
11234 (when re-radio
11235 (while (re-search-forward re-radio nil t)
11236 (replace-match "\\1[[\\2]]")))
11237 ;; Find all links that contain a newline and put them into a single line
11238 (goto-char (point-min))
11239 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
11240 (replace-match "\\1 \\3")
11241 (goto-char (match-beginning 0)))
11242 ;; Normalize links: Convert angle and plain links into bracket links
11243 (goto-char (point-min))
11244 (while (re-search-forward re-plain-link nil t)
11245 (replace-match
11246 (concat
11247 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11248 t t))
11249 (goto-char (point-min))
11250 (while (re-search-forward re-angle-link nil t)
11251 (replace-match
11252 (concat
11253 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11254 t t))
11255
11256 ;; Remove comments
11257 (goto-char (point-min))
11258 (while (re-search-forward "^#.*\n?" nil t)
11259 (replace-match ""))
11260 (setq rtn (buffer-string)))
11261 (kill-buffer " org-mode-tmp")
11262 rtn))
11263
11264 (defun org-solidify-link-text (s &optional alist)
11265 "Take link text and make a safe target out of it."
11266 (save-match-data
11267 (let* ((rtn
11268 (mapconcat
11269 'identity
11270 (org-split-string s "[ \t\r\n]+") "--"))
11271 (a (assoc rtn alist)))
11272 (or (cdr a) rtn))))
11273
11274 (defun org-convert-to-odd-levels ()
11275 "Convert an org-mode file with all levels allowed to one with odd levels.
11276 This will leave level 1 alone, convert level 2 to level 3, level 3 to
11277 level 5 etc."
11278 (interactive)
11279 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
11280 (let ((org-odd-levels-only nil) n)
11281 (save-excursion
11282 (goto-char (point-min))
11283 (while (re-search-forward "^\\*\\*+" nil t)
11284 (setq n (1- (length (match-string 0))))
11285 (while (>= (setq n (1- n)) 0)
11286 (org-demote))
11287 (end-of-line 1))))))
11288
11289
11290 (defun org-convert-to-oddeven-levels ()
11291 "Convert an org-mode file with only odd levels to one with odd and even levels.
11292 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
11293 section with an even level, conversion would destroy the structure of the file. An error
11294 is signaled in this case."
11295 (interactive)
11296 (goto-char (point-min))
11297 ;; First check if there are no even levels
11298 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
11299 (org-show-hierarchy-above)
11300 (error "Not all levels are odd in this file. Conversion not possible."))
11301 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
11302 (let ((org-odd-levels-only nil) n)
11303 (save-excursion
11304 (goto-char (point-min))
11305 (while (re-search-forward "^\\*\\*+" nil t)
11306 (setq n (/ (length (match-string 0)) 2))
11307 (while (>= (setq n (1- n)) 0)
11308 (org-promote))
11309 (end-of-line 1))))))
11310
11311 (defun org-tr-level (n)
11312 "Make N odd if required."
11313 (if org-odd-levels-only (1+ (/ n 2)) n))
11314
11315 (defvar org-last-level nil) ; dynamically scoped variable
11316
11317 (defun org-export-as-ascii (arg)
11318 "Export the outline as a pretty ASCII file.
11319 If there is an active region, export only the region.
11320 The prefix ARG specifies how many levels of the outline should become
11321 underlined headlines. The default is 3."
11322 (interactive "P")
11323 (setq-default org-todo-line-regexp org-todo-line-regexp)
11324 (let* ((region
11325 (buffer-substring
11326 (if (org-region-active-p) (region-beginning) (point-min))
11327 (if (org-region-active-p) (region-end) (point-max))))
11328 (lines (org-export-find-first-heading-line
11329 (org-skip-comments
11330 (org-split-string
11331 (org-cleaned-string-for-export region)
11332 "[\r\n]"))))
11333 (org-startup-with-deadline-check nil)
11334 (level 0) line txt
11335 (umax nil)
11336 (case-fold-search nil)
11337 (filename (concat (file-name-sans-extension buffer-file-name)
11338 ".txt"))
11339 (buffer (find-file-noselect filename))
11340 (levels-open (make-vector org-level-max nil))
11341 (date (format-time-string "%Y/%m/%d" (current-time)))
11342 (time (format-time-string "%X" (org-current-time)))
11343 (author user-full-name)
11344 (title (buffer-name))
11345 (options nil)
11346 (email user-mail-address)
11347 (language org-export-default-language)
11348 (text nil)
11349 (todo nil)
11350 (lang-words nil))
11351
11352 (setq org-last-level 1)
11353 (org-init-section-numbers)
11354
11355 (find-file-noselect filename)
11356
11357 ;; Search for the export key lines
11358 (org-parse-key-lines)
11359
11360 (setq lang-words (or (assoc language org-export-language-setup)
11361 (assoc "en" org-export-language-setup)))
11362 (if org-export-ascii-show-new-buffer
11363 (switch-to-buffer-other-window buffer)
11364 (set-buffer buffer))
11365 (erase-buffer)
11366 (fundamental-mode)
11367 (if options (org-parse-export-options options))
11368 (setq umax (if arg (prefix-numeric-value arg)
11369 org-export-headline-levels))
11370
11371 ;; File header
11372 (if title (org-insert-centered title ?=))
11373 (insert "\n")
11374 (if (or author email)
11375 (insert (concat (nth 1 lang-words) ": " (or author "")
11376 (if email (concat " <" email ">") "")
11377 "\n")))
11378 (if (and date time)
11379 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
11380 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
11381
11382 (insert "\n\n")
11383
11384 (if org-export-with-toc
11385 (progn
11386 (insert (nth 3 lang-words) "\n"
11387 (make-string (length (nth 3 lang-words)) ?=) "\n")
11388 (mapcar '(lambda (line)
11389 (if (string-match org-todo-line-regexp
11390 line)
11391 ;; This is a headline
11392 (progn
11393 (setq level (- (match-end 1) (match-beginning 1))
11394 level (org-tr-level level)
11395 txt (match-string 3 line)
11396 todo
11397 (or (and (match-beginning 2)
11398 (not (equal (match-string 2 line)
11399 org-done-string)))
11400 ; TODO, not DONE
11401 (and org-export-mark-todo-in-toc
11402 (= level umax)
11403 (org-search-todo-below
11404 line lines level))))
11405 (setq txt (org-html-expand-for-ascii txt))
11406
11407 (if org-export-with-section-numbers
11408 (setq txt (concat (org-section-number level)
11409 " " txt)))
11410 (if (<= level umax)
11411 (progn
11412 (insert
11413 (make-string (* (1- level) 4) ?\ )
11414 (format (if todo "%s (*)\n" "%s\n") txt))
11415 (setq org-last-level level))
11416 ))))
11417 lines)))
11418
11419 (org-init-section-numbers)
11420 (while (setq line (pop lines))
11421 ;; Remove the quoted HTML tags.
11422 (setq line (org-html-expand-for-ascii line))
11423 ;; Remove targets
11424 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
11425 (setq line (replace-match "" t t line)))
11426 ;; Replace internal links
11427 (while (string-match org-bracket-link-regexp line)
11428 (setq line (replace-match
11429 (if (match-end 3) "[\\3]" "[\\1]")
11430 t nil line)))
11431 (cond
11432 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11433 ;; a Headline
11434 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11435 txt (match-string 2 line))
11436 (org-ascii-level-start level txt umax))
11437 (t (insert line "\n"))))
11438 (normal-mode)
11439 (save-buffer)
11440 (goto-char (point-min))))
11441
11442 (defun org-search-todo-below (line lines level)
11443 "Search the subtree below LINE for any TODO entries."
11444 (let ((rest (cdr (memq line lines)))
11445 (re org-todo-line-regexp)
11446 line lv todo)
11447 (catch 'exit
11448 (while (setq line (pop rest))
11449 (if (string-match re line)
11450 (progn
11451 (setq lv (- (match-end 1) (match-beginning 1))
11452 todo (and (match-beginning 2)
11453 (not (equal (match-string 2 line)
11454 org-done-string))))
11455 ; TODO, not DONE
11456 (if (<= lv level) (throw 'exit nil))
11457 (if todo (throw 'exit t))))))))
11458
11459 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
11460 ;; We could also implement *bold*,/italic/ and _underline_ for ASCII export
11461 (defun org-html-expand-for-ascii (line)
11462 "Handle quoted HTML for ASCII export."
11463 (if org-export-html-expand
11464 (while (string-match "@<[^<>\n]*>" line)
11465 ;; We just remove the tags for now.
11466 (setq line (replace-match "" nil nil line))))
11467 line)
11468
11469 (defun org-insert-centered (s &optional underline)
11470 "Insert the string S centered and underline it with character UNDERLINE."
11471 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
11472 (insert (make-string ind ?\ ) s "\n")
11473 (if underline
11474 (insert (make-string ind ?\ )
11475 (make-string (string-width s) underline)
11476 "\n"))))
11477
11478 (defun org-ascii-level-start (level title umax)
11479 "Insert a new level in ASCII export."
11480 (let (char)
11481 (if (> level umax)
11482 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
11483 (if (or (not (equal (char-before) ?\n))
11484 (not (equal (char-before (1- (point))) ?\n)))
11485 (insert "\n"))
11486 (setq char (nth (- umax level) (reverse org-ascii-underline)))
11487 (if org-export-with-section-numbers
11488 (setq title (concat (org-section-number level) " " title)))
11489 (insert title "\n" (make-string (string-width title) char) "\n"))))
11490
11491 (defun org-export-copy-visible ()
11492 "Copy the visible part of the buffer to another buffer, for printing.
11493 Also removes the first line of the buffer if it specifies a mode,
11494 and all options lines."
11495 (interactive)
11496 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
11497 ".txt"))
11498 (buffer (find-file-noselect filename))
11499 (ore (concat
11500 (org-make-options-regexp
11501 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
11502 "STARTUP" "ARCHIVE"
11503 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
11504 (if org-noutline-p "\\(\n\\|$\\)" "")))
11505 s e)
11506 (with-current-buffer buffer
11507 (erase-buffer)
11508 (text-mode))
11509 (save-excursion
11510 (setq s (goto-char (point-min)))
11511 (while (not (= (point) (point-max)))
11512 (goto-char (org-find-invisible))
11513 (append-to-buffer buffer s (point))
11514 (setq s (goto-char (org-find-visible)))))
11515 (switch-to-buffer-other-window buffer)
11516 (newline)
11517 (goto-char (point-min))
11518 (if (looking-at ".*-\\*- mode:.*\n")
11519 (replace-match ""))
11520 (while (re-search-forward ore nil t)
11521 (replace-match ""))
11522 (goto-char (point-min))))
11523
11524 (defun org-find-visible ()
11525 (if (featurep 'noutline)
11526 (let ((s (point)))
11527 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11528 (get-char-property s 'invisible)))
11529 s)
11530 (skip-chars-forward "^\n")
11531 (point)))
11532 (defun org-find-invisible ()
11533 (if (featurep 'noutline)
11534 (let ((s (point)))
11535 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11536 (not (get-char-property s 'invisible))))
11537 s)
11538 (skip-chars-forward "^\r")
11539 (point)))
11540
11541 ;; HTML
11542
11543 (defun org-get-current-options ()
11544 "Return a string with current options as keyword options.
11545 Does include HTML export options as well as TODO and CATEGORY stuff."
11546 (format
11547 "#+TITLE: %s
11548 #+AUTHOR: %s
11549 #+EMAIL: %s
11550 #+LANGUAGE: %s
11551 #+TEXT: Some descriptive text to be emitted. Several lines OK.
11552 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
11553 #+CATEGORY: %s
11554 #+SEQ_TODO: %s
11555 #+TYP_TODO: %s
11556 #+STARTUP: %s %s %s %s %s
11557 #+ARCHIVE: %s
11558 "
11559 (buffer-name) (user-full-name) user-mail-address org-export-default-language
11560 org-export-headline-levels
11561 org-export-with-section-numbers
11562 org-export-with-toc
11563 org-export-preserve-breaks
11564 org-export-html-expand
11565 org-export-with-fixed-width
11566 org-export-with-tables
11567 org-export-with-sub-superscripts
11568 org-export-with-emphasize
11569 org-export-with-TeX-macros
11570 (file-name-nondirectory buffer-file-name)
11571 (if (equal org-todo-interpretation 'sequence)
11572 (mapconcat 'identity org-todo-keywords " ")
11573 "TODO FEEDBACK VERIFY DONE")
11574 (if (equal org-todo-interpretation 'type)
11575 (mapconcat 'identity org-todo-keywords " ")
11576 "Me Jason Marie DONE")
11577 (cdr (assoc org-startup-folded
11578 '((nil . "showall") (t . "overview") (content . "content"))))
11579 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
11580 (if org-odd-levels-only "odd" "oddeven")
11581 (if org-hide-leading-stars "hidestars" "showstars")
11582 (if org-startup-align-all-tables "align" "noalign")
11583 org-archive-location
11584 ))
11585
11586 (defun org-insert-export-options-template ()
11587 "Insert into the buffer a template with information for exporting."
11588 (interactive)
11589 (if (not (bolp)) (newline))
11590 (let ((s (org-get-current-options)))
11591 (and (string-match "#\\+CATEGORY" s)
11592 (setq s (substring s 0 (match-beginning 0))))
11593 (insert s)))
11594
11595 (defun org-toggle-fixed-width-section (arg)
11596 "Toggle the fixed-width export.
11597 If there is no active region, the QUOTE keyword at the current headline is
11598 inserted or removed. When present, it causes the text between this headline
11599 and the next to be exported as fixed-width text, and unmodified.
11600 If there is an active region, this command adds or removes a colon as the
11601 first character of this line. If the first character of a line is a colon,
11602 this line is also exported in fixed-width font."
11603 (interactive "P")
11604 (let* ((cc 0)
11605 (regionp (org-region-active-p))
11606 (beg (if regionp (region-beginning) (point)))
11607 (end (if regionp (region-end)))
11608 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
11609 (re "[ \t]*\\(:\\)")
11610 off)
11611 (if regionp
11612 (save-excursion
11613 (goto-char beg)
11614 (setq cc (current-column))
11615 (beginning-of-line 1)
11616 (setq off (looking-at re))
11617 (while (> nlines 0)
11618 (setq nlines (1- nlines))
11619 (beginning-of-line 1)
11620 (cond
11621 (arg
11622 (move-to-column cc t)
11623 (insert ":\n")
11624 (forward-line -1))
11625 ((and off (looking-at re))
11626 (replace-match "" t t nil 1))
11627 ((not off) (move-to-column cc t) (insert ":")))
11628 (forward-line 1)))
11629 (save-excursion
11630 (org-back-to-heading)
11631 (if (looking-at (concat outline-regexp
11632 "\\( +\\<" org-quote-string "\\>\\)"))
11633 (replace-match "" t t nil 1)
11634 (if (looking-at outline-regexp)
11635 (progn
11636 (goto-char (match-end 0))
11637 (insert " " org-quote-string))))))))
11638
11639 (defun org-export-as-html-and-open (arg)
11640 "Export the outline as HTML and immediately open it with a browser.
11641 If there is an active region, export only the region.
11642 The prefix ARG specifies how many levels of the outline should become
11643 headlines. The default is 3. Lower levels will become bulleted lists."
11644 (interactive "P")
11645 (org-export-as-html arg 'hidden)
11646 (org-open-file buffer-file-name))
11647
11648 (defun org-export-as-html-batch ()
11649 "Call `org-export-as-html', may be used in batch processing as
11650 emacs --batch
11651 --load=$HOME/lib/emacs/org.el
11652 --eval \"(setq org-export-headline-levels 2)\"
11653 --visit=MyFile --funcall org-export-as-html-batch"
11654 (org-export-as-html org-export-headline-levels 'hidden))
11655
11656 (defun org-export-as-html (arg &optional hidden)
11657 "Export the outline as a pretty HTML file.
11658 If there is an active region, export only the region.
11659 The prefix ARG specifies how many levels of the outline should become
11660 headlines. The default is 3. Lower levels will become bulleted lists."
11661 (interactive "P")
11662 (setq-default org-todo-line-regexp org-todo-line-regexp)
11663 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
11664 (setq-default org-done-string org-done-string)
11665 (let* ((style org-export-html-style)
11666 (odd org-odd-levels-only)
11667 (region-p (org-region-active-p))
11668 (region
11669 (buffer-substring
11670 (if region-p (region-beginning) (point-min))
11671 (if region-p (region-end) (point-max))))
11672 (all_lines
11673 (org-skip-comments (org-split-string
11674 (org-cleaned-string-for-export region)
11675 "[\r\n]")))
11676 (lines (org-export-find-first-heading-line all_lines))
11677 (level 0) (line "") (origline "") txt todo
11678 (umax nil)
11679 (filename (concat (file-name-sans-extension buffer-file-name)
11680 ".html"))
11681 (buffer (find-file-noselect filename))
11682 (levels-open (make-vector org-level-max nil))
11683 (date (format-time-string "%Y/%m/%d" (current-time)))
11684 (time (format-time-string "%X" (org-current-time)))
11685 (author user-full-name)
11686 (title (buffer-name))
11687 (options nil)
11688 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
11689 (inquote nil)
11690 (infixed nil)
11691 (in-local-list nil)
11692 (local-list-num nil)
11693 (local-list-indent nil)
11694 (llt org-plain-list-ordered-item-terminator)
11695 (email user-mail-address)
11696 (language org-export-default-language)
11697 (text nil)
11698 (lang-words nil)
11699 (target-alist nil) tg
11700 (head-count 0) cnt
11701 (start 0)
11702 ;; FIXME: The following returns always nil under XEmacs
11703 (coding-system (and (fboundp 'coding-system-get)
11704 (boundp 'buffer-file-coding-system)
11705 buffer-file-coding-system))
11706 (coding-system-for-write (or coding-system coding-system-for-write))
11707 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
11708 (charset (and coding-system
11709 (coding-system-get coding-system 'mime-charset)))
11710 table-open type
11711 table-buffer table-orig-buffer
11712 ind start-is-num starter
11713 rpl path desc desc1 desc2 link
11714 )
11715 (message "Exporting...")
11716
11717 (setq org-last-level 1)
11718 (org-init-section-numbers)
11719
11720 ;; Search for the export key lines
11721 (org-parse-key-lines)
11722 (setq lang-words (or (assoc language org-export-language-setup)
11723 (assoc "en" org-export-language-setup)))
11724
11725 ;; Switch to the output buffer
11726 (if (or hidden (not org-export-html-show-new-buffer))
11727 (set-buffer buffer)
11728 (switch-to-buffer-other-window buffer))
11729 (erase-buffer)
11730 (fundamental-mode)
11731 (let ((case-fold-search nil)
11732 (org-odd-levels-only odd))
11733 (if options (org-parse-export-options options))
11734 (setq umax (if arg (prefix-numeric-value arg)
11735 org-export-headline-levels))
11736
11737 ;; File header
11738 (insert (format
11739 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
11740 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
11741 <html lang=\"%s\"><head>
11742 <title>%s</title>
11743 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
11744 <meta name=generator content=\"Org-mode\">
11745 <meta name=generated content=\"%s %s\">
11746 <meta name=author content=\"%s\">
11747 %s
11748 </head><body>
11749 "
11750 language (org-html-expand title) (or charset "iso-8859-1")
11751 date time author style))
11752 (if title (insert (concat "<H1 class=\"title\">"
11753 (org-html-expand title) "</H1>\n")))
11754 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
11755 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
11756 email "&gt;</a>\n")))
11757 (if (or author email) (insert "<br>\n"))
11758 (if (and date time) (insert (concat (nth 2 lang-words) ": "
11759 date " " time "<br>\n")))
11760 (if text (insert (concat "<p>\n" (org-html-expand text))))
11761 (if org-export-with-toc
11762 (progn
11763 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
11764 (insert "<ul>\n")
11765 (setq lines
11766 (mapcar '(lambda (line)
11767 (if (string-match org-todo-line-regexp line)
11768 ;; This is a headline
11769 (progn
11770 (setq level (- (match-end 1) (match-beginning 1))
11771 level (org-tr-level level)
11772 txt (save-match-data
11773 (org-html-expand
11774 (match-string 3 line)))
11775 todo
11776 (or (and (match-beginning 2)
11777 (not (equal (match-string 2 line)
11778 org-done-string)))
11779 ; TODO, not DONE
11780 (and org-export-mark-todo-in-toc
11781 (= level umax)
11782 (org-search-todo-below
11783 line lines level))))
11784 (if org-export-with-section-numbers
11785 (setq txt (concat (org-section-number level)
11786 " " txt)))
11787 (if (<= level umax)
11788 (progn
11789 (setq head-count (+ head-count 1))
11790 (if (> level org-last-level)
11791 (progn
11792 (setq cnt (- level org-last-level))
11793 (while (>= (setq cnt (1- cnt)) 0)
11794 (insert "<ul>"))
11795 (insert "\n")))
11796 (if (< level org-last-level)
11797 (progn
11798 (setq cnt (- org-last-level level))
11799 (while (>= (setq cnt (1- cnt)) 0)
11800 (insert "</ul>"))
11801 (insert "\n")))
11802 ;; Check for targets
11803 (while (string-match org-target-regexp line)
11804 (setq tg (match-string 1 line)
11805 line (replace-match
11806 (concat "@<span class=\"target\">" tg "@</span> ")
11807 t t line))
11808 (push (cons (org-solidify-link-text tg)
11809 (format "sec-%d" head-count))
11810 target-alist))
11811 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
11812 (setq txt (replace-match "" t t txt)))
11813 (insert
11814 (format
11815 (if todo
11816 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
11817 "<li><a href=\"#sec-%d\">%s</a>\n")
11818 head-count txt))
11819
11820 (setq org-last-level level))
11821 )))
11822 line)
11823 lines))
11824 (while (> org-last-level 0)
11825 (setq org-last-level (1- org-last-level))
11826 (insert "</ul>\n"))
11827 ))
11828 (setq head-count 0)
11829 (org-init-section-numbers)
11830
11831 (while (setq line (pop lines) origline line)
11832 (catch 'nextline
11833
11834 ;; end of quote section?
11835 (when (and inquote (string-match "^\\*+" line))
11836 (insert "</pre>\n")
11837 (setq inquote nil))
11838 ;; inside a quote section?
11839 (when inquote
11840 (insert (org-html-protect line) "\n")
11841 (throw 'nextline nil))
11842
11843 ;; verbatim lines
11844 (when (and org-export-with-fixed-width
11845 (string-match "^[ \t]*:\\(.*\\)" line))
11846 (when (not infixed)
11847 (setq infixed t)
11848 (insert "<pre>\n"))
11849 (insert (org-html-protect (match-string 1 line)) "\n")
11850 (when (and lines
11851 (not (string-match "^[ \t]*\\(:.*\\)"
11852 (car lines))))
11853 (setq infixed nil)
11854 (insert "</pre>\n"))
11855 (throw 'nextline nil))
11856
11857
11858 ;; make targets to anchors
11859 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
11860 (cond
11861 ((match-end 2)
11862 (setq line (replace-match
11863 (concat "@<a name=\""
11864 (org-solidify-link-text (match-string 1 line))
11865 "\">\\nbsp@</a>")
11866 t t line)))
11867 ((and org-export-with-toc (equal (string-to-char line) ?*))
11868 (setq line (replace-match
11869 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
11870 ; (concat "@<i>" (match-string 1 line) "@</i> ")
11871 t t line)))
11872 (t
11873 (setq line (replace-match
11874 (concat "@<a name=\""
11875 (org-solidify-link-text (match-string 1 line))
11876 "\" class=\"target\">" (match-string 1 line) "@</a> ")
11877 t t line)))))
11878
11879 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
11880 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
11881 (setq line (org-html-expand line))
11882
11883 ;; Format the links
11884 (setq start 0)
11885 (while (string-match org-bracket-link-analytic-regexp line start)
11886 (setq start (match-beginning 0))
11887 (setq type (if (match-end 2) (match-string 2 line) "internal"))
11888 (setq path (match-string 3 line))
11889 (setq desc1 (if (match-end 5) (match-string 5 line))
11890 desc2 (if (match-end 2) (concat type ":" path) path)
11891 desc (or desc1 desc2))
11892 (cond
11893 ((equal type "internal")
11894 (setq rpl
11895 (concat
11896 "<a href=\"#"
11897 (org-solidify-link-text path target-alist)
11898 "\">" desc "</a>")))
11899 ((member type '("http" "https" "ftp" "mailto" "news"))
11900 ;; standard URL
11901 (setq link (concat type ":" path))
11902 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
11903 ((string= type "file")
11904 ;; FILE link
11905 (let* ((filename path)
11906 (abs-p (file-name-absolute-p filename))
11907 thefile file-is-image-p search)
11908 (save-match-data
11909 (if (string-match "::\\(.*\\)" filename)
11910 (setq search (match-string 1 filename)
11911 filename (replace-match "" nil nil filename)))
11912 (setq file-is-image-p
11913 (string-match (org-image-file-name-regexp) filename))
11914 (setq thefile (if abs-p (expand-file-name filename) filename))
11915 (when (and org-export-html-link-org-files-as-html
11916 (string-match "\\.org$" thefile))
11917 (setq thefile (concat (substring thefile 0
11918 (match-beginning 0))
11919 ".html"))
11920 (if (and search
11921 ;; make sure this is can be used as target search
11922 (not (string-match "^[0-9]*$" search))
11923 (not (string-match "^\\*" search))
11924 (not (string-match "^/.*/$" search)))
11925 (setq thefile (concat thefile "#"
11926 (org-solidify-link-text
11927 (org-link-unescape search)))))))
11928 (setq rpl (if (and org-export-html-inline-images
11929 file-is-image-p)
11930 (concat "<img src=\"" thefile "\"/>")
11931 (concat "<a href=\"" thefile "\">" desc "</a>")))))
11932 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11933 (setq rpl (concat "<i>&lt;" type ":"
11934 (save-match-data (org-link-unescape path))
11935 "&gt;</i>"))))
11936 (setq line (replace-match rpl t t line)
11937 start (+ start (length rpl))))
11938 ;; TODO items
11939 (if (and (string-match org-todo-line-regexp line)
11940 (match-beginning 2))
11941 (if (equal (match-string 2 line) org-done-string)
11942 (setq line (replace-match
11943 "<span class=\"done\">\\2</span>"
11944 nil nil line 2))
11945 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11946 nil nil line 2))))
11947
11948 ;; DEADLINES
11949 (if (string-match org-deadline-line-regexp line)
11950 (progn
11951 (if (save-match-data
11952 (string-match "<a href"
11953 (substring line 0 (match-beginning 0))))
11954 nil ; Don't do the replacement - it is inside a link
11955 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11956 nil nil line 1)))))
11957 (cond
11958 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11959 ;; This is a headline
11960 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11961 txt (match-string 2 line))
11962 (if (<= level umax) (setq head-count (+ head-count 1)))
11963 (when in-local-list
11964 ;; Close any local lists before inserting a new header line
11965 (while local-list-num
11966 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11967 (pop local-list-num))
11968 (setq local-list-indent nil
11969 in-local-list nil))
11970 (org-html-level-start level txt umax
11971 (and org-export-with-toc (<= level umax))
11972 head-count)
11973 ;; QUOTES
11974 (when (string-match quote-re line)
11975 (insert "<pre>")
11976 (setq inquote t)))
11977
11978 ((and org-export-with-tables
11979 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11980 (if (not table-open)
11981 ;; New table starts
11982 (setq table-open t table-buffer nil table-orig-buffer nil))
11983 ;; Accumulate lines
11984 (setq table-buffer (cons line table-buffer)
11985 table-orig-buffer (cons origline table-orig-buffer))
11986 (when (or (not lines)
11987 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11988 (car lines))))
11989 (setq table-open nil
11990 table-buffer (nreverse table-buffer)
11991 table-orig-buffer (nreverse table-orig-buffer))
11992 (insert (org-format-table-html table-buffer table-orig-buffer))))
11993 (t
11994 ;; Normal lines
11995 (when (and (string-match
11996 (cond
11997 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11998 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11999 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
12000 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
12001 line))
12002 (setq ind (org-get-string-indentation line)
12003 start-is-num (match-beginning 4)
12004 starter (if (match-beginning 2) (match-string 2 line))
12005 line (substring line (match-beginning 5)))
12006 (unless (string-match "[^ \t]" line)
12007 ;; empty line. Pretend indentation is large.
12008 (setq ind (1+ (or (car local-list-indent) 1))))
12009 (while (and in-local-list
12010 (or (and (= ind (car local-list-indent))
12011 (not starter))
12012 (< ind (car local-list-indent))))
12013 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
12014 (pop local-list-num) (pop local-list-indent)
12015 (setq in-local-list local-list-indent))
12016 (cond
12017 ((and starter
12018 (or (not in-local-list)
12019 (> ind (car local-list-indent))))
12020 ;; Start new (level of ) list
12021 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
12022 (push start-is-num local-list-num)
12023 (push ind local-list-indent)
12024 (setq in-local-list t))
12025 (starter
12026 ;; continue current list
12027 (insert "<li>\n"))))
12028 ;; Empty lines start a new paragraph. If hand-formatted lists
12029 ;; are not fully interpreted, lines starting with "-", "+", "*"
12030 ;; also start a new paragraph.
12031 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
12032 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
12033 ))
12034 (if org-export-html-with-timestamp
12035 (insert org-export-html-html-helper-timestamp))
12036 (insert "</body>\n</html>\n")
12037 (normal-mode)
12038 (save-buffer)
12039 (goto-char (point-min)))))
12040
12041 (defun org-format-table-html (lines olines)
12042 "Find out which HTML converter to use and return the HTML code."
12043 (if (string-match "^[ \t]*|" (car lines))
12044 ;; A normal org table
12045 (org-format-org-table-html lines)
12046 ;; Table made by table.el - test for spanning
12047 (let* ((hlines (delq nil (mapcar
12048 (lambda (x)
12049 (if (string-match "^[ \t]*\\+-" x) x
12050 nil))
12051 lines)))
12052 (first (car hlines))
12053 (ll (and (string-match "\\S-+" first)
12054 (match-string 0 first)))
12055 (re (concat "^[ \t]*" (regexp-quote ll)))
12056 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
12057 hlines))))
12058 (if (and (not spanning)
12059 (not org-export-prefer-native-exporter-for-tables))
12060 ;; We can use my own converter with HTML conversions
12061 (org-format-table-table-html lines)
12062 ;; Need to use the code generator in table.el, with the original text.
12063 (org-format-table-table-html-using-table-generate-source olines)))))
12064
12065 (defun org-format-org-table-html (lines)
12066 "Format a table into HTML."
12067 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
12068 (setq lines (nreverse lines))
12069 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
12070 (setq lines (nreverse lines))
12071 (when org-export-table-remove-special-lines
12072 ;; Check if the table has a marking column. If yes remove the
12073 ;; column and the special lines
12074 (let* ((special
12075 (not
12076 (memq nil
12077 (mapcar
12078 (lambda (x)
12079 (or (string-match "^[ \t]*|-" x)
12080 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
12081 lines)))))
12082 (if special
12083 (setq lines
12084 (delq nil
12085 (mapcar
12086 (lambda (x)
12087 (if (string-match "^[ \t]*| *[!_^] *|" x)
12088 nil ; ignore this line
12089 (and (or (string-match "^[ \t]*|-+\\+" x)
12090 (string-match "^[ \t]*|[^|]*|" x))
12091 (replace-match "|" t t x))))
12092 lines))))))
12093
12094 (let ((head (and org-export-highlight-first-table-line
12095 (delq nil (mapcar
12096 (lambda (x) (string-match "^[ \t]*|-" x))
12097 (cdr lines)))))
12098 line fields html)
12099 (setq html (concat org-export-html-table-tag "\n"))
12100 (while (setq line (pop lines))
12101 (catch 'next-line
12102 (if (string-match "^[ \t]*|-" line)
12103 (progn
12104 (setq head nil) ;; head ends here, first time around
12105 ;; ignore this line
12106 (throw 'next-line t)))
12107 ;; Break the line into fields
12108 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
12109 (setq html (concat
12110 html
12111 "<tr>"
12112 (mapconcat (lambda (x)
12113 (if head
12114 (concat "<th>" x "</th>")
12115 (concat "<td>" x "</td>")))
12116 fields "")
12117 "</tr>\n"))))
12118 (setq html (concat html "</table>\n"))
12119 html))
12120
12121 (defun org-fake-empty-table-line (line)
12122 "Replace everything except \"|\" with spaces."
12123 (let ((i (length line))
12124 (newstr (copy-sequence line)))
12125 (while (> i 0)
12126 (setq i (1- i))
12127 (if (not (eq (aref newstr i) ?|))
12128 (aset newstr i ?\ )))
12129 newstr))
12130
12131 (defun org-format-table-table-html (lines)
12132 "Format a table generated by table.el into HTML.
12133 This conversion does *not* use `table-generate-source' from table.el.
12134 This has the advantage that Org-mode's HTML conversions can be used.
12135 But it has the disadvantage, that no cell- or row-spanning is allowed."
12136 (let (line field-buffer
12137 (head org-export-highlight-first-table-line)
12138 fields html empty)
12139 (setq html (concat org-export-html-table-tag "\n"))
12140 (while (setq line (pop lines))
12141 (setq empty "&nbsp")
12142 (catch 'next-line
12143 (if (string-match "^[ \t]*\\+-" line)
12144 (progn
12145 (if field-buffer
12146 (progn
12147 (setq html (concat
12148 html
12149 "<tr>"
12150 (mapconcat
12151 (lambda (x)
12152 (if (equal x "") (setq x empty))
12153 (if head
12154 (concat "<th>" x "</th>\n")
12155 (concat "<td>" x "</td>\n")))
12156 field-buffer "\n")
12157 "</tr>\n"))
12158 (setq head nil)
12159 (setq field-buffer nil)))
12160 ;; Ignore this line
12161 (throw 'next-line t)))
12162 ;; Break the line into fields and store the fields
12163 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
12164 (if field-buffer
12165 (setq field-buffer (mapcar
12166 (lambda (x)
12167 (concat x "<br>" (pop fields)))
12168 field-buffer))
12169 (setq field-buffer fields))))
12170 (setq html (concat html "</table>\n"))
12171 html))
12172
12173 (defun org-format-table-table-html-using-table-generate-source (lines)
12174 "Format a table into html, using `table-generate-source' from table.el.
12175 This has the advantage that cell- or row-spanning is allowed.
12176 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
12177 (require 'table)
12178 (with-current-buffer (get-buffer-create " org-tmp1 ")
12179 (erase-buffer)
12180 (insert (mapconcat 'identity lines "\n"))
12181 (goto-char (point-min))
12182 (if (not (re-search-forward "|[^+]" nil t))
12183 (error "Error processing table"))
12184 (table-recognize-table)
12185 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
12186 (table-generate-source 'html " org-tmp2 ")
12187 (set-buffer " org-tmp2 ")
12188 (buffer-substring (point-min) (point-max))))
12189
12190 (defun org-html-protect (s)
12191 ;; convert & to &amp;, < to &lt; and > to &gt;
12192 (let ((start 0))
12193 (while (string-match "&" s start)
12194 (setq s (replace-match "&amp;" t t s)
12195 start (1+ (match-beginning 0))))
12196 (while (string-match "<" s)
12197 (setq s (replace-match "&lt;" t t s)))
12198 (while (string-match ">" s)
12199 (setq s (replace-match "&gt;" t t s))))
12200 s)
12201
12202 (defun org-html-expand (string)
12203 "Prepare STRING for HTML export. Applies all active conversions.
12204 If there are links in the string, don't modify these."
12205 (let* (m s l res)
12206 (while (setq m (string-match org-bracket-link-regexp string))
12207 (setq s (substring string 0 m)
12208 l (match-string 0 string)
12209 string (substring string (match-end 0)))
12210 (push (org-html-do-expand s) res)
12211 (push l res))
12212 (push (org-html-do-expand string) res)
12213 (apply 'concat (nreverse res))))
12214
12215 (defun org-html-do-expand (s)
12216 "Apply all active conversions to translate special ASCII to HTML."
12217 (setq s (org-html-protect s))
12218 (if org-export-html-expand
12219 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
12220 (setq s (replace-match "<\\1>" nil nil s))))
12221 (if org-export-with-emphasize
12222 (setq s (org-export-html-convert-emphasize s)))
12223 (if org-export-with-sub-superscripts
12224 (setq s (org-export-html-convert-sub-super s)))
12225 (if org-export-with-TeX-macros
12226 (let ((start 0) wd ass)
12227 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
12228 (setq wd (match-string 1 s))
12229 (if (setq ass (assoc wd org-html-entities))
12230 (setq s (replace-match (or (cdr ass)
12231 (concat "&" (car ass) ";"))
12232 t t s))
12233 (setq start (+ start (length wd)))))))
12234 s)
12235
12236 (defun org-create-multibrace-regexp (left right n)
12237 "Create a regular expression which will match a balanced sexp.
12238 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
12239 as single character strings.
12240 The regexp returned will match the entire expression including the
12241 delimiters. It will also define a single group which contains the
12242 match except for the outermost delimiters. The maximum depth of
12243 stacked delimiters is N. Escaping delimiters is not possible."
12244 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
12245 (or "\\|")
12246 (re nothing)
12247 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
12248 (while (> n 1)
12249 (setq n (1- n)
12250 re (concat re or next)
12251 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
12252 (concat left "\\(" re "\\)" right)))
12253
12254 (defvar org-match-substring-regexp
12255 (concat
12256 "\\([^\\]\\)\\([_^]\\)\\("
12257 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
12258 "\\|"
12259 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
12260 "\\|"
12261 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
12262 "The regular expression matching a sub- or superscript.")
12263
12264 (defun org-export-html-convert-sub-super (string)
12265 "Convert sub- and superscripts in STRING to HTML."
12266 (let (key c)
12267 (while (string-match org-match-substring-regexp string)
12268 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
12269 (setq c (or (match-string 8 string)
12270 (match-string 6 string)
12271 (match-string 5 string)))
12272 (setq string (replace-match
12273 (concat (match-string 1 string)
12274 "<" key ">" c "</" key ">")
12275 t t string)))
12276 (while (string-match "\\\\\\([_^]\\)" string)
12277 (setq string (replace-match (match-string 1 string) t t string))))
12278 string)
12279
12280 ;(defun org-export-html-convert-emphasize (string)
12281 ; (let (c (s 0))
12282 ; (while (string-match "\\(\\W\\|^\\)\\([*/_]\\)\\(\\w+\\)\\2\\(\\W\\|$\\)" string s)
12283 ; (setq c (cdr (assoc (match-string 2 string)
12284 ; '(("*" . "b") ("/" . "i") ("_" . "u"))))
12285 ; s (+ (match-end 0) 3)
12286 ; string (replace-match
12287 ; (concat "\\1<" c ">\\3</" c ">\\4") t nil string)))
12288 ; string))
12289
12290 (defun org-export-html-convert-emphasize (string)
12291 (while (string-match org-italic-re string)
12292 (setq string (replace-match "\\1<i>\\3</i>\\4" t nil string)))
12293 (while (string-match org-bold-re string)
12294 (setq string (replace-match "\\1<b>\\3</b>\\4" t nil string)))
12295 (while (string-match org-underline-re string)
12296 (setq string (replace-match "\\1<u>\\3</u>\\4" t nil string)))
12297 string)
12298
12299 (defun org-parse-key-lines ()
12300 "Find the special key lines with the information for exporters."
12301 (save-excursion
12302 (goto-char 0)
12303 (let ((re (org-make-options-regexp
12304 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12305 key)
12306 (while (re-search-forward re nil t)
12307 (setq key (match-string 1))
12308 (cond ((string-equal key "TITLE")
12309 (setq title (match-string 2)))
12310 ((string-equal key "AUTHOR")
12311 (setq author (match-string 2)))
12312 ((string-equal key "EMAIL")
12313 (setq email (match-string 2)))
12314 ((string-equal key "LANGUAGE")
12315 (setq language (match-string 2)))
12316 ((string-equal key "TEXT")
12317 (setq text (concat text "\n" (match-string 2))))
12318 ((string-equal key "OPTIONS")
12319 (setq options (match-string 2))))))))
12320
12321 (defun org-parse-export-options (s)
12322 "Parse the export options line."
12323 (let ((op '(("H" . org-export-headline-levels)
12324 ("num" . org-export-with-section-numbers)
12325 ("toc" . org-export-with-toc)
12326 ("\\n" . org-export-preserve-breaks)
12327 ("@" . org-export-html-expand)
12328 (":" . org-export-with-fixed-width)
12329 ("|" . org-export-with-tables)
12330 ("^" . org-export-with-sub-superscripts)
12331 ("*" . org-export-with-emphasize)
12332 ("TeX" . org-export-with-TeX-macros)))
12333 o)
12334 (while (setq o (pop op))
12335 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
12336 s)
12337 (set (make-local-variable (cdr o))
12338 (car (read-from-string (match-string 1 s))))))))
12339
12340 (defun org-html-level-start (level title umax with-toc head-count)
12341 "Insert a new level in HTML export."
12342 (let ((l (1+ (max level umax))))
12343 (while (<= l org-level-max)
12344 (if (aref levels-open (1- l))
12345 (progn
12346 (org-html-level-close l)
12347 (aset levels-open (1- l) nil)))
12348 (setq l (1+ l)))
12349 (if (> level umax)
12350 (progn
12351 (if (aref levels-open (1- level))
12352 (insert "<li>" title "<p>\n")
12353 (aset levels-open (1- level) t)
12354 (insert "<ul><li>" title "<p>\n")))
12355 (if org-export-with-section-numbers
12356 (setq title (concat (org-section-number level) " " title)))
12357 (setq level (+ level 1))
12358 (if with-toc
12359 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
12360 level head-count title level))
12361 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
12362
12363 (defun org-html-level-close (&rest args)
12364 "Terminate one level in HTML export."
12365 (insert "</ul>"))
12366
12367 ;; Variable holding the vector with section numbers
12368 (defvar org-section-numbers (make-vector org-level-max 0))
12369
12370 (defun org-init-section-numbers ()
12371 "Initialize the vector for the section numbers."
12372 (let* ((level -1)
12373 (numbers (nreverse (org-split-string "" "\\.")))
12374 (depth (1- (length org-section-numbers)))
12375 (i depth) number-string)
12376 (while (>= i 0)
12377 (if (> i level)
12378 (aset org-section-numbers i 0)
12379 (setq number-string (or (car numbers) "0"))
12380 (if (string-match "\\`[A-Z]\\'" number-string)
12381 (aset org-section-numbers i
12382 (- (string-to-char number-string) ?A -1))
12383 (aset org-section-numbers i (string-to-number number-string)))
12384 (pop numbers))
12385 (setq i (1- i)))))
12386
12387 (defun org-section-number (&optional level)
12388 "Return a string with the current section number.
12389 When LEVEL is non-nil, increase section numbers on that level."
12390 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
12391 (when level
12392 (when (> level -1)
12393 (aset org-section-numbers
12394 level (1+ (aref org-section-numbers level))))
12395 (setq idx (1+ level))
12396 (while (<= idx depth)
12397 (if (not (= idx 1))
12398 (aset org-section-numbers idx 0))
12399 (setq idx (1+ idx))))
12400 (setq idx 0)
12401 (while (<= idx depth)
12402 (setq n (aref org-section-numbers idx))
12403 (setq string (concat string (if (not (string= string "")) "." "")
12404 (int-to-string n)))
12405 (setq idx (1+ idx)))
12406 (save-match-data
12407 (if (string-match "\\`\\([@0]\\.\\)+" string)
12408 (setq string (replace-match "" nil nil string)))
12409 (if (string-match "\\(\\.0\\)+\\'" string)
12410 (setq string (replace-match "" nil nil string))))
12411 string))
12412
12413
12414 (defun org-export-icalendar-this-file ()
12415 "Export current file as an iCalendar file.
12416 The iCalendar file will be located in the same directory as the Org-mode
12417 file, but with extension `.ics'."
12418 (interactive)
12419 (org-export-icalendar nil buffer-file-name))
12420
12421 (defun org-export-as-xml ()
12422 "Export current buffer as XOXO XML buffer."
12423 (interactive)
12424 (cond ((eq org-export-xml-type 'xoxo)
12425 (org-export-as-xoxo (current-buffer)))))
12426
12427 (defun org-export-as-xoxo-insert-into (buffer &rest output)
12428 (with-current-buffer buffer
12429 (apply 'insert output)))
12430
12431 (defun org-export-as-xoxo (&optional buffer)
12432 "Export the org buffer as XOXO.
12433 The XOXO buffer is named *xoxo-<source buffer name>*"
12434 (interactive (list (current-buffer)))
12435 ;; A quickie abstraction
12436
12437 ;; Output everything as XOXO
12438 (with-current-buffer (get-buffer buffer)
12439 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
12440 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
12441 ".xml"))
12442 (out (find-file-noselect filename))
12443 (last-level 1)
12444 (hanging-li nil))
12445 ;; Check the output buffer is empty.
12446 (with-current-buffer out (erase-buffer))
12447 ;; Kick off the output
12448 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
12449 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
12450 (let* ((hd (match-string-no-properties 1))
12451 (level (length hd))
12452 (text (concat
12453 (match-string-no-properties 2)
12454 (save-excursion
12455 (goto-char (match-end 0))
12456 (let ((str ""))
12457 (catch 'loop
12458 (while 't
12459 (forward-line)
12460 (if (looking-at "^[ \t]\\(.*\\)")
12461 (setq str (concat str (match-string-no-properties 1)))
12462 (throw 'loop str)))))))))
12463
12464 ;; Handle level rendering
12465 (cond
12466 ((> level last-level)
12467 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
12468
12469 ((< level last-level)
12470 (dotimes (- (- last-level level) 1)
12471 (if hanging-li
12472 (org-export-as-xoxo-insert-into out "</li>\n"))
12473 (org-export-as-xoxo-insert-into out "</ol>\n"))
12474 (when hanging-li
12475 (org-export-as-xoxo-insert-into out "</li>\n")
12476 (setq hanging-li nil)))
12477
12478 ((equal level last-level)
12479 (if hanging-li
12480 (org-export-as-xoxo-insert-into out "</li>\n")))
12481 )
12482
12483 (setq last-level level)
12484
12485 ;; And output the new li
12486 (setq hanging-li 't)
12487 (if (equal ?+ (elt text 0))
12488 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
12489 (org-export-as-xoxo-insert-into out "<li>" text))))
12490
12491 ;; Finally finish off the ol
12492 (dotimes (- last-level 1)
12493 (if hanging-li
12494 (org-export-as-xoxo-insert-into out "</li>\n"))
12495 (org-export-as-xoxo-insert-into out "</ol>\n"))
12496
12497 ;; Finish the buffer off and clean it up.
12498 (switch-to-buffer-other-window out)
12499 (indent-region (point-min) (point-max))
12500 (save-buffer)
12501 (goto-char (point-min))
12502 )))
12503
12504 ;;;###autoload
12505 (defun org-export-icalendar-all-agenda-files ()
12506 "Export all files in `org-agenda-files' to iCalendar .ics files.
12507 Each iCalendar file will be located in the same directory as the Org-mode
12508 file, but with extension `.ics'."
12509 (interactive)
12510 (apply 'org-export-icalendar nil (org-agenda-files t)))
12511
12512 ;;;###autoload
12513 (defun org-export-icalendar-combine-agenda-files ()
12514 "Export all files in `org-agenda-files' to a single combined iCalendar file.
12515 The file is stored under the name `org-combined-agenda-icalendar-file'."
12516 (interactive)
12517 (apply 'org-export-icalendar t (org-agenda-files t)))
12518
12519 (defun org-export-icalendar (combine &rest files)
12520 "Create iCalendar files for all elements of FILES.
12521 If COMBINE is non-nil, combine all calendar entries into a single large
12522 file and store it under the name `org-combined-agenda-icalendar-file'."
12523 (save-excursion
12524 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
12525 (when combine
12526 (setq ical-file org-combined-agenda-icalendar-file
12527 ical-buffer (org-get-agenda-file-buffer ical-file))
12528 (set-buffer ical-buffer) (erase-buffer))
12529 (while (setq file (pop files))
12530 (catch 'nextfile
12531 (org-check-agenda-file file)
12532 (unless combine
12533 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
12534 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
12535 (set-buffer ical-buffer) (erase-buffer))
12536 (set-buffer (org-get-agenda-file-buffer file))
12537 (setq category (or org-category
12538 (file-name-sans-extension
12539 (file-name-nondirectory buffer-file-name))))
12540 (if (symbolp category) (setq category (symbol-name category)))
12541 (let ((standard-output ical-buffer))
12542 (if combine
12543 (and (not started) (setq started t)
12544 (org-start-icalendar-file org-icalendar-combined-name))
12545 (org-start-icalendar-file category))
12546 (org-print-icalendar-entries combine category)
12547 (when (or (and combine (not files)) (not combine))
12548 (org-finish-icalendar-file)
12549 (set-buffer ical-buffer)
12550 (save-buffer)
12551 (run-hooks 'org-after-save-iCalendar-file-hook)))))
12552 (org-release-buffers org-agenda-new-buffers))))
12553
12554 (defvar org-after-save-iCalendar-file-hook nil
12555 "Hook run after an iCalendar file has been saved.
12556 The iCalendar buffer is still current when this hook is run.
12557 A good way to use this is to tell a desktop calenndar application to re-read
12558 the iCalendar file.")
12559
12560 (defun org-print-icalendar-entries (&optional combine category)
12561 "Print iCalendar entries for the current Org-mode file to `standard-output'.
12562 When COMBINE is non nil, add the category to each line."
12563 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
12564 (dts (org-ical-ts-to-string
12565 (format-time-string (cdr org-time-stamp-formats) (current-time))
12566 "DTSTART"))
12567 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
12568 (save-excursion
12569 (goto-char (point-min))
12570 (while (re-search-forward org-ts-regexp nil t)
12571 (setq pos (match-beginning 0)
12572 ts (match-string 0)
12573 inc t
12574 hd (org-get-heading))
12575 (if (looking-at re2)
12576 (progn
12577 (goto-char (match-end 0))
12578 (setq ts2 (match-string 1) inc nil))
12579 (setq ts2 ts
12580 tmp (buffer-substring (max (point-min)
12581 (- pos org-ds-keyword-length))
12582 pos)
12583 deadlinep (string-match org-deadline-regexp tmp)
12584 scheduledp (string-match org-scheduled-regexp tmp)
12585 ;; donep (org-entry-is-done-p)
12586 ))
12587 (if (or (string-match org-tr-regexp hd)
12588 (string-match org-ts-regexp hd))
12589 (setq hd (replace-match "" t t hd)))
12590 (if combine
12591 (setq hd (concat hd " (category " category ")")))
12592 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
12593 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
12594 (princ (format "BEGIN:VEVENT
12595 %s
12596 %s
12597 SUMMARY:%s
12598 END:VEVENT\n"
12599 (org-ical-ts-to-string ts "DTSTART")
12600 (org-ical-ts-to-string ts2 "DTEND" inc)
12601 hd)))
12602 (when org-icalendar-include-todo
12603 (goto-char (point-min))
12604 (while (re-search-forward org-todo-line-regexp nil t)
12605 (setq state (match-string 1))
12606 (unless (equal state org-done-string)
12607 (setq hd (match-string 3))
12608 (if (string-match org-priority-regexp hd)
12609 (setq pri (string-to-char (match-string 2 hd))
12610 hd (concat (substring hd 0 (match-beginning 1))
12611 (substring hd (- (match-end 1)))))
12612 (setq pri org-default-priority))
12613 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
12614 (- org-lowest-priority ?A))))))
12615
12616 (princ (format "BEGIN:VTODO
12617 %s
12618 SUMMARY:%s
12619 SEQUENCE:1
12620 PRIORITY:%d
12621 END:VTODO\n"
12622 dts hd pri))))))))
12623
12624 (defun org-start-icalendar-file (name)
12625 "Start an iCalendar file by inserting the header."
12626 (let ((user user-full-name)
12627 (name (or name "unknown"))
12628 (timezone (cadr (current-time-zone))))
12629 (princ
12630 (format "BEGIN:VCALENDAR
12631 VERSION:2.0
12632 X-WR-CALNAME:%s
12633 PRODID:-//%s//Emacs with Org-mode//EN
12634 X-WR-TIMEZONE:%s
12635 CALSCALE:GREGORIAN\n" name user timezone))))
12636
12637 (defun org-finish-icalendar-file ()
12638 "Finish an iCalendar file by inserting the END statement."
12639 (princ "END:VCALENDAR\n"))
12640
12641 (defun org-ical-ts-to-string (s keyword &optional inc)
12642 "Take a time string S and convert it to iCalendar format.
12643 KEYWORD is added in front, to make a complete line like DTSTART....
12644 When INC is non-nil, increase the hour by two (if time string contains
12645 a time), or the day by one (if it does not contain a time)."
12646 (let ((t1 (org-parse-time-string s 'nodefault))
12647 t2 fmt have-time time)
12648 (if (and (car t1) (nth 1 t1) (nth 2 t1))
12649 (setq t2 t1 have-time t)
12650 (setq t2 (org-parse-time-string s)))
12651 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
12652 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
12653 (when inc
12654 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
12655 (setq time (encode-time s mi h d m y)))
12656 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
12657 (concat keyword (format-time-string fmt time))))
12658
12659
12660 ;;; Key bindings
12661
12662 ;; - Bindings in Org-mode map are currently
12663 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
12664 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
12665 ;; e (?) useful from outline-mode
12666 ;; i k @ expendable from outline-mode
12667 ;; 0123456789 % & ()_{} " ` free
12668
12669 ;; Make `C-c C-x' a prefix key
12670 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
12671
12672 ;; TAB key with modifiers
12673 (define-key org-mode-map "\C-i" 'org-cycle)
12674 (define-key org-mode-map [(tab)] 'org-cycle)
12675 (define-key org-mode-map [(meta tab)] 'org-complete)
12676 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
12677 ;; The following line is necessary under Suse GNU/Linux
12678 (unless (featurep 'xemacs)
12679 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
12680 (define-key org-mode-map [(shift tab)] 'org-shifttab)
12681
12682 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
12683 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
12684 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12685 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
12686 (define-key org-mode-map [(meta return)] 'org-meta-return)
12687 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
12688 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
12689
12690 ;; Cursor keys with modifiers
12691 (define-key org-mode-map [(meta left)] 'org-metaleft)
12692 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
12693 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
12694 (define-key org-mode-map [(meta right)] 'org-metaright)
12695 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
12696 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
12697 (define-key org-mode-map [(meta up)] 'org-metaup)
12698 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
12699 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
12700 (define-key org-mode-map [(meta down)] 'org-metadown)
12701 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
12702 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
12703
12704 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12705 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
12706 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
12707 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
12708 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
12709 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
12710 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
12711 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
12712 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
12713 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
12714 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
12715 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
12716 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
12717 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
12718 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
12719 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
12720
12721 ;; All the other keys
12722 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
12723 (define-key org-mode-map "\C-c\C-j" 'org-goto)
12724 (define-key org-mode-map "\C-c\C-t" 'org-todo)
12725 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
12726 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
12727 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
12728 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12729 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
12730 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
12731 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12732 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
12733 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
12734 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
12735 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
12736 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
12737 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
12738 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
12739 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12740 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12741 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12742 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12743 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
12744 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
12745 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12746 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
12747 (define-key org-mode-map "\C-c]" 'org-remove-file)
12748 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
12749 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
12750 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
12751 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12752 (define-key org-mode-map "\C-m" 'org-return)
12753 (define-key org-mode-map "\C-c?" 'org-table-current-column)
12754 (define-key org-mode-map "\C-c " 'org-table-blank-field)
12755 (define-key org-mode-map "\C-c+" 'org-table-sum)
12756 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
12757 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
12758 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
12759 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12760 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
12761 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12762 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
12763 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12764 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
12765 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
12766 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
12767 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
12768 ;; OPML support is only an option for the future
12769 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
12770 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
12771 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
12772 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
12773 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
12774 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
12775 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
12776 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12777 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
12778 (define-key org-mode-map "\C-c\C-xx" 'org-export-as-xml)
12779 (define-key org-mode-map "\C-c\C-x\C-x" 'org-export-as-xml)
12780 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
12781 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
12782
12783 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12784 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12785 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12786 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12787
12788 (defsubst org-table-p () (org-at-table-p))
12789
12790 (defun org-self-insert-command (N)
12791 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12792 If the cursor is in a table looking at whitespace, the whitespace is
12793 overwritten, and the table is not marked as requiring realignment."
12794 (interactive "p")
12795 (if (and (org-table-p)
12796 (progn
12797 ;; check if we blank the field, and if that triggers align
12798 (and org-table-auto-blank-field
12799 (member last-command
12800 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12801 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12802 ;; got extra space, this field does not determine column width
12803 (let (org-table-may-need-update) (org-table-blank-field))
12804 ;; no extra space, this field may determine column width
12805 (org-table-blank-field)))
12806 t)
12807 (eq N 1)
12808 (looking-at "[^|\n]* |"))
12809 (let (org-table-may-need-update)
12810 (goto-char (1- (match-end 0)))
12811 (delete-backward-char 1)
12812 (goto-char (match-beginning 0))
12813 (self-insert-command N))
12814 (setq org-table-may-need-update t)
12815 (self-insert-command N)))
12816
12817 (defun org-delete-backward-char (N)
12818 "Like `delete-backward-char', insert whitespace at field end in tables.
12819 When deleting backwards, in tables this function will insert whitespace in
12820 front of the next \"|\" separator, to keep the table aligned. The table will
12821 still be marked for re-alignment if the field did fill the entire column,
12822 because, in this case the deletion might narrow the column."
12823 (interactive "p")
12824 (if (and (org-table-p)
12825 (eq N 1)
12826 (string-match "|" (buffer-substring (point-at-bol) (point)))
12827 (looking-at ".*?|"))
12828 (let ((pos (point))
12829 (noalign (looking-at "[^|\n\r]* |"))
12830 (c org-table-may-need-update))
12831 (backward-delete-char N)
12832 (skip-chars-forward "^|")
12833 (insert " ")
12834 (goto-char (1- pos))
12835 ;; noalign: if there were two spaces at the end, this field
12836 ;; does not determine the width of the column.
12837 (if noalign (setq org-table-may-need-update c)))
12838 (backward-delete-char N)))
12839
12840 (defun org-delete-char (N)
12841 "Like `delete-char', but insert whitespace at field end in tables.
12842 When deleting characters, in tables this function will insert whitespace in
12843 front of the next \"|\" separator, to keep the table aligned. The table will
12844 still be marked for re-alignment if the field did fill the entire column,
12845 because, in this case the deletion might narrow the column."
12846 (interactive "p")
12847 (if (and (org-table-p)
12848 (not (bolp))
12849 (not (= (char-after) ?|))
12850 (eq N 1))
12851 (if (looking-at ".*?|")
12852 (let ((pos (point))
12853 (noalign (looking-at "[^|\n\r]* |"))
12854 (c org-table-may-need-update))
12855 (replace-match (concat
12856 (substring (match-string 0) 1 -1)
12857 " |"))
12858 (goto-char pos)
12859 ;; noalign: if there were two spaces at the end, this field
12860 ;; does not determine the width of the column.
12861 (if noalign (setq org-table-may-need-update c))))
12862 (delete-char N)))
12863
12864 ;; How to do this: Measure non-white length of current string
12865 ;; If equal to column width, we should realign.
12866
12867 (defun org-remap (map &rest commands)
12868 "In MAP, remap the functions given in COMMANDS.
12869 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12870 (let (new old)
12871 (while commands
12872 (setq old (pop commands) new (pop commands))
12873 (if (fboundp 'command-remapping)
12874 (define-key map (vector 'remap old) new)
12875 (substitute-key-definition old new map global-map)))))
12876
12877 (when (eq org-enable-table-editor 'optimized)
12878 ;; If the user wants maximum table support, we need to hijack
12879 ;; some standard editing functions
12880 (org-remap org-mode-map
12881 'self-insert-command 'org-self-insert-command
12882 'delete-char 'org-delete-char
12883 'delete-backward-char 'org-delete-backward-char)
12884 (define-key org-mode-map "|" 'org-force-self-insert))
12885
12886 (defun org-shiftcursor-error ()
12887 "Throw an error because Shift-Cursor command was applied in wrong context."
12888 (error "This command is active in special context like tables, headlines or timestamps"))
12889
12890 (defun org-shifttab ()
12891 "Global visibility cycling or move to previous table field.
12892 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
12893 See the individual commands for more information."
12894 (interactive)
12895 (cond
12896 ((org-at-table-p) (org-table-previous-field))
12897 (t (org-cycle '(4)))))
12898
12899 (defun org-shiftmetaleft ()
12900 "Promote subtree or delete table column.
12901 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
12902 See the individual commands for more information."
12903 (interactive)
12904 (cond
12905 ((org-at-table-p) (org-table-delete-column))
12906 ((org-on-heading-p) (org-promote-subtree))
12907 ((org-at-item-p) (call-interactively 'org-outdent-item))
12908 (t (org-shiftcursor-error))))
12909
12910 (defun org-shiftmetaright ()
12911 "Demote subtree or insert table column.
12912 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
12913 See the individual commands for more information."
12914 (interactive)
12915 (cond
12916 ((org-at-table-p) (org-table-insert-column))
12917 ((org-on-heading-p) (org-demote-subtree))
12918 ((org-at-item-p) (call-interactively 'org-indent-item))
12919 (t (org-shiftcursor-error))))
12920
12921 (defun org-shiftmetaup (&optional arg)
12922 "Move subtree up or kill table row.
12923 Calls `org-move-subtree-up' or `org-table-kill-row' or
12924 `org-move-item-up' depending on context. See the individual commands
12925 for more information."
12926 (interactive "P")
12927 (cond
12928 ((org-at-table-p) (org-table-kill-row))
12929 ((org-on-heading-p) (org-move-subtree-up arg))
12930 ((org-at-item-p) (org-move-item-up arg))
12931 (t (org-shiftcursor-error))))
12932 (defun org-shiftmetadown (&optional arg)
12933 "Move subtree down or insert table row.
12934 Calls `org-move-subtree-down' or `org-table-insert-row' or
12935 `org-move-item-down', depending on context. See the individual
12936 commands for more information."
12937 (interactive "P")
12938 (cond
12939 ((org-at-table-p) (org-table-insert-row arg))
12940 ((org-on-heading-p) (org-move-subtree-down arg))
12941 ((org-at-item-p) (org-move-item-down arg))
12942 (t (org-shiftcursor-error))))
12943
12944 (defun org-metaleft (&optional arg)
12945 "Promote heading or move table column to left.
12946 Calls `org-do-promote' or `org-table-move-column', depending on context.
12947 With no specific context, calls the Emacs default `backward-word'.
12948 See the individual commands for more information."
12949 (interactive "P")
12950 (cond
12951 ((org-at-table-p) (org-table-move-column 'left))
12952 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
12953 (t (backward-word (prefix-numeric-value arg)))))
12954
12955 (defun org-metaright (&optional arg)
12956 "Demote subtree or move table column to right.
12957 Calls `org-do-demote' or `org-table-move-column', depending on context.
12958 With no specific context, calls the Emacs default `forward-word'.
12959 See the individual commands for more information."
12960 (interactive "P")
12961 (cond
12962 ((org-at-table-p) (org-table-move-column nil))
12963 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
12964 (t (forward-word (prefix-numeric-value arg)))))
12965
12966 (defun org-metaup (&optional arg)
12967 "Move subtree up or move table row up.
12968 Calls `org-move-subtree-up' or `org-table-move-row' or
12969 `org-move-item-up', depending on context. See the individual commands
12970 for more information."
12971 (interactive "P")
12972 (cond
12973 ((org-at-table-p) (org-table-move-row 'up))
12974 ((org-on-heading-p) (org-move-subtree-up arg))
12975 ((org-at-item-p) (org-move-item-up arg))
12976 (t (org-shiftcursor-error))))
12977
12978 (defun org-metadown (&optional arg)
12979 "Move subtree down or move table row down.
12980 Calls `org-move-subtree-down' or `org-table-move-row' or
12981 `org-move-item-down', depending on context. See the individual
12982 commands for more information."
12983 (interactive "P")
12984 (cond
12985 ((org-at-table-p) (org-table-move-row nil))
12986 ((org-on-heading-p) (org-move-subtree-down arg))
12987 ((org-at-item-p) (org-move-item-down arg))
12988 (t (org-shiftcursor-error))))
12989
12990 (defun org-shiftup (&optional arg)
12991 "Increase item in timestamp or increase priority of current item.
12992 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12993 See the individual commands for more information."
12994 (interactive "P")
12995 (cond
12996 ((org-at-timestamp-p) (org-timestamp-up arg))
12997 (t (org-priority-up))))
12998
12999 (defun org-shiftdown (&optional arg)
13000 "Decrease item in timestamp or decrease priority of current item.
13001 Calls `org-timestamp-down' or `org-priority-down', depending on context.
13002 See the individual commands for more information."
13003 (interactive "P")
13004 (cond
13005 ((org-at-timestamp-p) (org-timestamp-down arg))
13006 (t (org-priority-down))))
13007
13008 (defun org-shiftright ()
13009 "Next TODO keyword or timestamp one day later, depending on context."
13010 (interactive)
13011 (cond
13012 ((org-at-timestamp-p) (org-timestamp-up-day))
13013 ((org-on-heading-p) (org-todo 'right))
13014 (t (org-shiftcursor-error))))
13015
13016 (defun org-shiftleft ()
13017 "Previous TODO keyword or timestamp one day earlier, depending on context."
13018 (interactive)
13019 (cond
13020 ((org-at-timestamp-p) (org-timestamp-down-day))
13021 ((org-on-heading-p) (org-todo 'left))
13022 (t (org-shiftcursor-error))))
13023
13024 (defun org-copy-special ()
13025 "Copy region in table or copy current subtree.
13026 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13027 See the individual commands for more information."
13028 (interactive)
13029 (call-interactively
13030 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13031
13032 (defun org-cut-special ()
13033 "Cut region in table or cut current subtree.
13034 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13035 See the individual commands for more information."
13036 (interactive)
13037 (call-interactively
13038 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13039
13040 (defun org-paste-special (arg)
13041 "Paste rectangular region into table, or past subtree relative to level.
13042 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13043 See the individual commands for more information."
13044 (interactive "P")
13045 (if (org-at-table-p)
13046 (org-table-paste-rectangle)
13047 (org-paste-subtree arg)))
13048
13049 (defun org-ctrl-c-ctrl-c (&optional arg)
13050 "Set tags in headline, or update according to changed information at point.
13051
13052 This command does many different things, depending on context:
13053
13054 - If the cursor is in a headline, prompt for tags and insert them
13055 into the current line, aligned to `org-tags-column'. When called
13056 with prefix arg, realign all tags in the current buffer.
13057
13058 - If the cursor is in one of the special #+KEYWORD lines, this
13059 triggers scanning the buffer for these lines and updating the
13060 information.
13061
13062 - If the cursor is inside a table, realign the table. This command
13063 works even if the automatic table editor has been turned off.
13064
13065 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13066 the entire table.
13067
13068 - If the cursor is inside a table created by the table.el package,
13069 activate that table.
13070
13071 - If the current buffer is a remember buffer, close note and file it.
13072 with a prefix argument, file it without further interaction to the default
13073 location.
13074
13075 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13076 links in this buffer.
13077
13078 - If the cursor is on a numbered item in a plain list, renumber the
13079 ordered list."
13080 (interactive "P")
13081 (let ((org-enable-table-editor t))
13082 (cond
13083 ((and (local-variable-p 'org-finish-function (current-buffer))
13084 (fboundp org-finish-function))
13085 (funcall org-finish-function))
13086 ((org-on-target-p) (org-update-radio-target-regexp))
13087 ((org-on-heading-p) (org-set-tags arg))
13088 ((org-at-table.el-p)
13089 (require 'table)
13090 (beginning-of-line 1)
13091 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13092 (table-recognize-table))
13093 ((org-at-table-p)
13094 (org-table-maybe-eval-formula)
13095 (if arg
13096 (org-table-recalculate t)
13097 (org-table-maybe-recalculate-line))
13098 (org-table-align))
13099 ((org-at-item-p)
13100 (org-renumber-ordered-list (prefix-numeric-value arg)))
13101 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13102 (cond
13103 ((equal (match-string 1) "TBLFM")
13104 ;; Recalculate the table before this line
13105 (save-excursion
13106 (beginning-of-line 1)
13107 (skip-chars-backward " \r\n\t")
13108 (if (org-at-table-p) (org-table-recalculate t))))
13109 (t
13110 (org-mode-restart))))
13111 (t (error "C-c C-c can do nothing useful at this location.")))))
13112
13113 (defun org-mode-restart ()
13114 "Restart Org-mode, to scan again for special lines.
13115 Also updates the keyword regular expressions."
13116 (interactive)
13117 (let ((org-inhibit-startup t)) (org-mode))
13118 (message "Org-mode restarted to refresh keyword and special line setup"))
13119
13120 (defun org-return ()
13121 "Goto next table row or insert a newline.
13122 Calls `org-table-next-row' or `newline', depending on context.
13123 See the individual commands for more information."
13124 (interactive)
13125 (cond
13126 ((org-at-table-p)
13127 (org-table-justify-field-maybe)
13128 (org-table-next-row))
13129 (t (newline))))
13130
13131 (defun org-meta-return (&optional arg)
13132 "Insert a new heading or wrap a region in a table.
13133 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13134 See the individual commands for more information."
13135 (interactive "P")
13136 (cond
13137 ((org-at-table-p)
13138 (org-table-wrap-region arg))
13139 (t (org-insert-heading arg))))
13140
13141 ;;; Menu entries
13142
13143 ;; Define the Org-mode menus
13144 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13145 '("Tbl"
13146 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
13147 ["Next Field" org-cycle (org-at-table-p)]
13148 ["Previous Field" org-shifttab (org-at-table-p)]
13149 ["Next Row" org-return (org-at-table-p)]
13150 "--"
13151 ["Blank Field" org-table-blank-field (org-at-table-p)]
13152 ["Edit Field" org-table-edit-field (org-at-table-p)]
13153 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13154 "--"
13155 ("Column"
13156 ["Move Column Left" org-metaleft (org-at-table-p)]
13157 ["Move Column Right" org-metaright (org-at-table-p)]
13158 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13159 ["Insert Column" org-shiftmetaright (org-at-table-p)]
13160 "--"
13161 ["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])
13162 ("Row"
13163 ["Move Row Up" org-metaup (org-at-table-p)]
13164 ["Move Row Down" org-metadown (org-at-table-p)]
13165 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13166 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13167 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13168 "--"
13169 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
13170 ("Rectangle"
13171 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13172 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13173 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13174 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13175 "--"
13176 ("Calculate"
13177 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13178 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13179 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
13180 "--"
13181 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13182 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13183 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13184 "--"
13185 ["Sum Column/Rectangle" org-table-sum
13186 (or (org-at-table-p) (org-region-active-p))]
13187 ["Which Column?" org-table-current-column (org-at-table-p)])
13188 ["Debug Formulas"
13189 (setq org-table-formula-debug (not org-table-formula-debug))
13190 :style toggle :selected org-table-formula-debug]
13191 "--"
13192 ["Create" org-table-create (and (not (org-at-table-p))
13193 org-enable-table-editor)]
13194 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13195 ["Import from File" org-table-import (not (org-at-table-p))]
13196 ["Export to File" org-table-export (org-at-table-p)]
13197 "--"
13198 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13199
13200 (easy-menu-define org-org-menu org-mode-map "Org menu"
13201 '("Org"
13202 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
13203 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
13204 ["Sparse Tree" org-occur t]
13205 ["Show All" show-all t]
13206 "--"
13207 ["New Heading" org-insert-heading t]
13208 ("Navigate Headings"
13209 ["Up" outline-up-heading t]
13210 ["Next" outline-next-visible-heading t]
13211 ["Previous" outline-previous-visible-heading t]
13212 ["Next Same Level" outline-forward-same-level t]
13213 ["Previous Same Level" outline-backward-same-level t]
13214 "--"
13215 ["Jump" org-goto t])
13216 ("Edit Structure"
13217 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13218 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13219 "--"
13220 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13221 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13222 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13223 "--"
13224 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13225 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13226 ["Demote Heading" org-metaright (not (org-at-table-p))]
13227 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13228 "--"
13229 ["Archive Subtree" org-archive-subtree t]
13230 "--"
13231 ["Convert to odd levels" org-convert-to-odd-levels t]
13232 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13233 "--"
13234 ("TODO Lists"
13235 ["TODO/DONE/-" org-todo t]
13236 ["Show TODO Tree" org-show-todo-tree t]
13237 ["Global TODO list" org-todo-list t]
13238 "--"
13239 ["Set Priority" org-priority t]
13240 ["Priority Up" org-shiftup t]
13241 ["Priority Down" org-shiftdown t])
13242 ("Dates and Scheduling"
13243 ["Timestamp" org-time-stamp t]
13244 ["Timestamp (inactive)" org-time-stamp-inactive t]
13245 ("Change Date"
13246 ["1 Day Later" org-timestamp-up-day t]
13247 ["1 Day Earlier" org-timestamp-down-day t]
13248 ["1 ... Later" org-shiftup t]
13249 ["1 ... Earlier" org-shiftdown t])
13250 ["Compute Time Range" org-evaluate-time-range t]
13251 ["Schedule Item" org-schedule t]
13252 ["Deadline" org-deadline t]
13253 "--"
13254 ["Goto Calendar" org-goto-calendar t]
13255 ["Date from Calendar" org-date-from-calendar t])
13256 "--"
13257 ["Agenda Command" org-agenda t]
13258 ("File List for Agenda")
13259 ("Special views current file"
13260 ["TODO Tree" org-show-todo-tree t]
13261 ["Check Deadlines" org-check-deadlines t]
13262 ["Timeline" org-timeline t]
13263 ["Tags Tree" org-tags-sparse-tree t])
13264 "--"
13265 ("Hyperlinks"
13266 ["Store Link (Global)" org-store-link t]
13267 ["Insert Link" org-insert-link t]
13268 ["Follow Link" org-open-at-point t]
13269 "--"
13270 ["Descriptive Links"
13271 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13272 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
13273 ["Literal Links"
13274 (progn
13275 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13276 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
13277 "--"
13278 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
13279 (save-excursion (goto-char (point-min))
13280 (re-search-forward "<[a-z]+:" nil t))])
13281 "--"
13282 ("Export"
13283 ["ASCII" org-export-as-ascii t]
13284 ["Extract Visible Text" org-export-copy-visible t]
13285 ["HTML" org-export-as-html t]
13286 ["HTML and Open" org-export-as-html-and-open t]
13287 ["XML (XOXO)" org-export-as-xml t]
13288 "--"
13289 ["iCalendar this file" org-export-icalendar-this-file t]
13290 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
13291 :active t :keys "C-c C-x C-i"]
13292 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
13293 "--"
13294 ["Option Template" org-insert-export-options-template t]
13295 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
13296 "--"
13297 ("Documentation"
13298 ["Show Version" org-version t]
13299 ["Info Documentation" org-info t])
13300 ("Customize"
13301 ["Browse Org Group" org-customize t]
13302 "--"
13303 ["Expand This Menu" org-create-customize-menu
13304 (fboundp 'customize-menu-create)])
13305 "--"
13306 ["Refresh setup" org-mode-restart t]
13307 ))
13308
13309 (defun org-info (&optional node)
13310 "Read documentation for Org-mode in the info system.
13311 With optional NODE, go directly to that node."
13312 (interactive)
13313 (require 'info)
13314 (Info-goto-node (format "(org)%s" (or node ""))))
13315
13316 (defun org-install-agenda-files-menu ()
13317 (let ((bl (buffer-list)))
13318 (save-excursion
13319 (while bl
13320 (set-buffer (pop bl))
13321 (if (eq major-mode 'org-mode) (setq bl nil)))
13322 (when (eq major-mode 'org-mode)
13323 (easy-menu-change
13324 '("Org") "File List for Agenda"
13325 (append
13326 (list
13327 ["Edit File List" (org-edit-agenda-file-list) t]
13328 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13329 ["Remove Current File from List" org-remove-file t]
13330 ["Cycle through agenda files" org-cycle-agenda-files t]
13331 "--")
13332 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13333
13334 ;;; Documentation
13335
13336 (defun org-customize ()
13337 "Call the customize function with org as argument."
13338 (interactive)
13339 (customize-browse 'org))
13340
13341 (defun org-create-customize-menu ()
13342 "Create a full customization menu for Org-mode, insert it into the menu."
13343 (interactive)
13344 (if (fboundp 'customize-menu-create)
13345 (progn
13346 (easy-menu-change
13347 '("Org") "Customize"
13348 `(["Browse Org group" org-customize t]
13349 "--"
13350 ,(customize-menu-create 'org)
13351 ["Set" Custom-set t]
13352 ["Save" Custom-save t]
13353 ["Reset to Current" Custom-reset-current t]
13354 ["Reset to Saved" Custom-reset-saved t]
13355 ["Reset to Standard Settings" Custom-reset-standard t]))
13356 (message "\"Org\"-menu now contains full customization menu"))
13357 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13358
13359 ;;; Miscellaneous stuff
13360
13361 (defun org-move-line-down (arg)
13362 "Move the current line down. With prefix argument, move it past ARG lines."
13363 (interactive "p")
13364 (let ((col (current-column))
13365 beg end pos)
13366 (beginning-of-line 1) (setq beg (point))
13367 (beginning-of-line 2) (setq end (point))
13368 (beginning-of-line (+ 1 arg))
13369 (setq pos (move-marker (make-marker) (point)))
13370 (insert (delete-and-extract-region beg end))
13371 (goto-char pos)
13372 (move-to-column col)))
13373
13374 (defun org-move-line-up (arg)
13375 "Move the current line up. With prefix argument, move it past ARG lines."
13376 (interactive "p")
13377 (let ((col (current-column))
13378 beg end pos)
13379 (beginning-of-line 1) (setq beg (point))
13380 (beginning-of-line 2) (setq end (point))
13381 (beginning-of-line (- arg))
13382 (setq pos (move-marker (make-marker) (point)))
13383 (insert (delete-and-extract-region beg end))
13384 (goto-char pos)
13385 (move-to-column col)))
13386
13387 ;; Paragraph filling stuff.
13388 ;; We want this to be just right, so use the full arsenal.
13389 ;; FIXME: This very likely does not work correctly for XEmacs, because the
13390 ;; filladapt package works slightly differently.
13391
13392 (defun org-set-autofill-regexps ()
13393 (interactive)
13394 ;; In the paragraph separator we include headlines, because filling
13395 ;; text in a line directly attached to a headline would otherwise
13396 ;; fill the headline as well.
13397 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
13398 ;; The paragraph starter includes hand-formatted lists.
13399 (set (make-local-variable 'paragraph-start)
13400 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13401 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13402 ;; But only if the user has not turned off tables or fixed-width regions
13403 (set (make-local-variable 'auto-fill-inhibit-regexp)
13404 (concat "\\*\\|#"
13405 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13406 (concat
13407 "\\|[ \t]*["
13408 (if org-enable-table-editor "|" "")
13409 (if org-enable-fixed-width-editor ":" "")
13410 "]"))))
13411 ;; We use our own fill-paragraph function, to make sure that tables
13412 ;; and fixed-width regions are not wrapped. That function will pass
13413 ;; through to `fill-paragraph' when appropriate.
13414 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
13415 ;; Adaptive filling: To get full control, first make sure that
13416 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13417 (set (make-local-variable 'adaptive-fill-regexp) "\000")
13418 (set (make-local-variable 'adaptive-fill-function)
13419 'org-adaptive-fill-function))
13420
13421 (defun org-fill-paragraph (&optional justify)
13422 "Re-align a table, pass through to fill-paragraph if no table."
13423 (let ((table-p (org-at-table-p))
13424 (table.el-p (org-at-table.el-p)))
13425 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
13426 (table.el-p t) ; skip table.el tables
13427 (table-p (org-table-align) t) ; align org-mode tables
13428 (t nil)))) ; call paragraph-fill
13429
13430 ;; For reference, this is the default value of adaptive-fill-regexp
13431 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13432
13433 (defun org-adaptive-fill-function ()
13434 "Return a fill prefix for org-mode files.
13435 In particular, this makes sure hanging paragraphs for hand-formatted lists
13436 work correctly."
13437 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
13438 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
13439
13440 ;; Functions needed for Emacs/XEmacs region compatibility
13441
13442 (defun org-add-hook (hook function &optional append local)
13443 "Add-hook, compatible with both Emacsen."
13444 (if (and local (featurep 'xemacs))
13445 (add-local-hook hook function append)
13446 (add-hook hook function append local)))
13447
13448 (defun org-region-active-p ()
13449 "Is `transient-mark-mode' on and the region active?
13450 Works on both Emacs and XEmacs."
13451 (if org-ignore-region
13452 nil
13453 (if (featurep 'xemacs)
13454 (and zmacs-regions (region-active-p))
13455 (and transient-mark-mode mark-active))))
13456
13457 (defun org-add-to-invisibility-spec (arg)
13458 "Add elements to `buffer-invisibility-spec'.
13459 See documentation for `buffer-invisibility-spec' for the kind of elements
13460 that can be added."
13461 (cond
13462 ((fboundp 'add-to-invisibility-spec)
13463 (add-to-invisibility-spec arg))
13464 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
13465 (setq buffer-invisibility-spec (list arg)))
13466 (t
13467 (setq buffer-invisibility-spec
13468 (cons arg buffer-invisibility-spec)))))
13469
13470 (defun org-remove-from-invisibility-spec (arg)
13471 "Remove elements from `buffer-invisibility-spec'."
13472 (if (fboundp 'remove-from-invisibility-spec)
13473 (remove-from-invisibility-spec arg)
13474 (if (consp buffer-invisibility-spec)
13475 (setq buffer-invisibility-spec
13476 (delete arg buffer-invisibility-spec)))))
13477
13478 (defun org-in-invisibility-spec-p (arg)
13479 "Is ARG a member of `buffer-invisibility-spec'?"
13480 (if (consp buffer-invisibility-spec)
13481 (member arg buffer-invisibility-spec)
13482 nil))
13483
13484 (defun org-image-file-name-regexp ()
13485 "Return regexp matching the file names of images."
13486 (if (fboundp 'image-file-name-regexp)
13487 (image-file-name-regexp)
13488 (let ((image-file-name-extensions
13489 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13490 "xbm" "xpm" "pbm" "pgm" "ppm")))
13491 (concat "\\."
13492 (regexp-opt (nconc (mapcar 'upcase
13493 image-file-name-extensions)
13494 image-file-name-extensions)
13495 t)
13496 "\\'"))))
13497
13498 ;; Functions needed for compatibility with old outline.el.
13499
13500 ;; Programming for the old outline.el (that uses selective display
13501 ;; instead of `invisible' text properties) is a nightmare, mostly
13502 ;; because regular expressions can no longer be anchored at
13503 ;; beginning/end of line. Therefore a number of function need special
13504 ;; treatment when the old outline.el is being used.
13505
13506 ;; The following functions capture almost the entire compatibility code
13507 ;; between the different versions of outline-mode. The only other
13508 ;; places where this is important are the font-lock-keywords, and in
13509 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
13510
13511 ;; C-a should go to the beginning of a *visible* line, also in the
13512 ;; new outline.el. I guess this should be patched into Emacs?
13513 (defun org-beginning-of-line ()
13514 "Go to the beginning of the current line. If that is invisible, continue
13515 to a visible line beginning. This makes the function of C-a more intuitive."
13516 (interactive)
13517 (beginning-of-line 1)
13518 (if (bobp)
13519 nil
13520 (backward-char 1)
13521 (if (org-invisible-p)
13522 (while (and (not (bobp)) (org-invisible-p))
13523 (backward-char 1)
13524 (beginning-of-line 1))
13525 (forward-char 1))))
13526
13527 (when org-noutline-p
13528 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
13529 ;; FIXME: should I use substitute-key-definition to reach other bindings
13530 ;; of beginning-of-line?
13531
13532 (defun org-invisible-p ()
13533 "Check if point is at a character currently not visible."
13534 (if org-noutline-p
13535 ;; Early versions of noutline don't have `outline-invisible-p'.
13536 (if (fboundp 'outline-invisible-p)
13537 (outline-invisible-p)
13538 (get-char-property (point) 'invisible))
13539 (save-excursion
13540 (skip-chars-backward "^\r\n")
13541 (equal (char-before) ?\r))))
13542
13543 (defun org-invisible-p2 ()
13544 "Check if point is at a character currently not visible."
13545 (save-excursion
13546 (if org-noutline-p
13547 (progn
13548 (if (and (eolp) (not (bobp))) (backward-char 1))
13549 ;; Early versions of noutline don't have `outline-invisible-p'.
13550 (if (fboundp 'outline-invisible-p)
13551 (outline-invisible-p)
13552 (get-char-property (point) 'invisible)))
13553 (skip-chars-backward "^\r\n")
13554 (equal (char-before) ?\r))))
13555
13556 (defun org-back-to-heading (&optional invisible-ok)
13557 "Move to previous heading line, or beg of this line if it's a heading.
13558 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
13559 (if org-noutline-p
13560 (outline-back-to-heading invisible-ok)
13561 (if (and (memq (char-before) '(?\n ?\r))
13562 (looking-at outline-regexp))
13563 t
13564 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
13565 outline-regexp)
13566 nil t)
13567 (if invisible-ok
13568 (progn (goto-char (match-end 1))
13569 (looking-at outline-regexp)))
13570 (error "Before first heading")))))
13571
13572 (defun org-on-heading-p (&optional invisible-ok)
13573 "Return t if point is on a (visible) heading line.
13574 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
13575 (if org-noutline-p
13576 (outline-on-heading-p 'invisible-ok)
13577 (save-excursion
13578 (skip-chars-backward "^\n\r")
13579 (and (looking-at outline-regexp)
13580 (or invisible-ok
13581 (bobp)
13582 (equal (char-before) ?\n))))))
13583
13584 (defun org-on-target-p ()
13585 (let ((pos (point)))
13586 (save-excursion
13587 (skip-chars-forward "<")
13588 (and (re-search-backward "<<" nil t)
13589 (or (looking-at org-radio-target-regexp)
13590 (looking-at org-target-regexp))
13591 (<= (match-beginning 0) pos)
13592 (>= (1+ (match-end 0)) pos)))))
13593
13594 (defun org-up-heading-all (arg)
13595 "Move to the heading line of which the present line is a subheading.
13596 This function considers both visible and invisible heading lines.
13597 With argument, move up ARG levels."
13598 (if org-noutline-p
13599 (if (fboundp 'outline-up-heading-all)
13600 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13601 (outline-up-heading arg t)) ; emacs 22 version of outline.el
13602 (org-back-to-heading t)
13603 (looking-at outline-regexp)
13604 (if (<= (- (match-end 0) (match-beginning 0)) arg)
13605 (error "Cannot move up %d levels" arg)
13606 (re-search-backward
13607 (concat "[\n\r]" (regexp-quote
13608 (make-string (- (match-end 0) (match-beginning 0) arg)
13609 ?*))
13610 "[^*]"))
13611 (forward-char 1))))
13612
13613 (defun org-show-hidden-entry ()
13614 "Show an entry where even the heading is hidden."
13615 (save-excursion
13616 (if (not org-noutline-p)
13617 (progn
13618 (org-back-to-heading t)
13619 (org-flag-heading nil)))
13620 (org-show-entry)))
13621
13622 (defun org-check-occur-regexp (regexp)
13623 "If REGEXP starts with \"^\", modify it to check for \\r as well.
13624 Of course, only for the old outline mode."
13625 (if org-noutline-p
13626 regexp
13627 (if (string-match "^\\^" regexp)
13628 (concat "[\n\r]" (substring regexp 1))
13629 regexp)))
13630
13631 (defun org-flag-heading (flag &optional entry)
13632 "Flag the current heading. FLAG non-nil means make invisible.
13633 When ENTRY is non-nil, show the entire entry."
13634 (save-excursion
13635 (org-back-to-heading t)
13636 (if (not org-noutline-p)
13637 ;; Make the current headline visible
13638 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
13639 ;; Check if we should show the entire entry
13640 (if entry
13641 (progn
13642 (org-show-entry)
13643 (save-excursion ;; FIXME: Is this the fix for points in the -|
13644 ;; middle of text? |
13645 (and (outline-next-heading) ;; |
13646 (org-flag-heading nil)))) ; show the next heading _|
13647 (outline-flag-region (max 1 (1- (point)))
13648 (save-excursion (outline-end-of-heading) (point))
13649 (if org-noutline-p
13650 flag
13651 (if flag ?\r ?\n))))))
13652
13653 (defun org-end-of-subtree (&optional invisible-OK)
13654 ;; This is an exact copy of the original function, but it uses
13655 ;; `org-back-to-heading', to make it work also in invisible
13656 ;; trees. And is uses an invisible-OK argument.
13657 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13658 (org-back-to-heading invisible-OK)
13659 (let ((first t)
13660 (level (funcall outline-level)))
13661 (while (and (not (eobp))
13662 (or first (> (funcall outline-level) level)))
13663 (setq first nil)
13664 (outline-next-heading))
13665 (if (memq (preceding-char) '(?\n ?\^M))
13666 (progn
13667 ;; Go to end of line before heading
13668 (forward-char -1)
13669 (if (memq (preceding-char) '(?\n ?\^M))
13670 ;; leave blank line before heading
13671 (forward-char -1))))))
13672
13673 (defun org-show-subtree ()
13674 "Show everything after this heading at deeper levels."
13675 (outline-flag-region
13676 (point)
13677 (save-excursion
13678 (outline-end-of-subtree) (outline-next-heading) (point))
13679 (if org-noutline-p nil ?\n)))
13680
13681 (defun org-show-entry ()
13682 "Show the body directly following this heading.
13683 Show the heading too, if it is currently invisible."
13684 (interactive)
13685 (save-excursion
13686 (org-back-to-heading t)
13687 (outline-flag-region
13688 (1- (point))
13689 (save-excursion
13690 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13691 (or (match-beginning 1) (point-max)))
13692 (if org-noutline-p nil ?\n))))
13693
13694 (defun org-make-options-regexp (kwds)
13695 "Make a regular expression for keyword lines."
13696 (concat
13697 (if org-noutline-p "^" "[\n\r]")
13698 "#?[ \t]*\\+\\("
13699 (mapconcat 'regexp-quote kwds "\\|")
13700 "\\):[ \t]*"
13701 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
13702
13703 ;; Make `bookmark-jump' show the jump location if it was hidden.
13704 (eval-after-load "bookmark"
13705 '(if (boundp 'bookmark-after-jump-hook)
13706 ;; We can use the hook
13707 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13708 ;; Hook not available, use advice
13709 (defadvice bookmark-jump (after org-make-visible activate)
13710 "Make the position visible."
13711 (org-bookmark-jump-unhide))))
13712
13713 (defun org-bookmark-jump-unhide ()
13714 "Unhide the current position, to show the bookmark location."
13715 (and (eq major-mode 'org-mode)
13716 (or (org-invisible-p)
13717 (save-excursion (goto-char (max (point-min) (1- (point))))
13718 (org-invisible-p)))
13719 (org-show-hierarchy-above)))
13720
13721 ;;; Finish up
13722
13723 (provide 'org)
13724
13725 (run-hooks 'org-load-hook)
13726
13727 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13728 ;;; org.el ends here
13729