]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-open-at-point): Use renamed variable
[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.33
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 ;; Furthermore you need to activate font-lock-mode in org-mode buffers.
56 ;; either of the following two lins will do the trick:
57 ;;
58 ;; (global-font-lock-mode 1) ; for all buffers
59 ;; (add-hook 'org-mode-hook 'turn-on-font-lock) ; org-mode buffers only
60 ;;
61 ;; If you have downloaded Org-mode from the Web, you have to take additional
62 ;; action: Byte-compile org.el and org-publish.el and put them together with
63 ;; org-install.el on your load path. Then also add to your .emacs file:
64 ;;
65 ;; (require 'org-install)
66 ;;
67 ;; This setup will put all files with extension ".org" into Org-mode. As
68 ;; an alternative, make the first line of a file look like this:
69 ;;
70 ;; MY PROJECTS -*- mode: org; -*-
71 ;;
72 ;; which will select Org-mode for this buffer no matter what the file's
73 ;; name is.
74 ;;
75 ;; Documentation
76 ;; -------------
77 ;; The documentation of Org-mode can be found in the TeXInfo file. The
78 ;; distribution also contains a PDF version of it. At the homepage of
79 ;; Org-mode, you can read the same text online as HTML. There is also an
80 ;; excellent reference card made by Philip Rooke. This card can be found
81 ;; in the etc/ directory of Emacs 22.
82 ;;
83 ;; Changes since version 4.10:
84 ;; ---------------------------
85 ;; Version 4.33
86 ;; - New commands to move through plain lists: S-up and S-down.
87 ;; - Bug fixes and documentation update.
88 ;;
89 ;; Version 4.32
90 ;; - Fast (single-key-per-tag) interface for setting TAGS.
91 ;; - The list of legal tags can be configured globally and locally.
92 ;; - Elisp and Info links (thanks to Todd Neal).
93 ;; - `org-export-publishing-directory' can be an alist, with different
94 ;; directories for different export types.
95 ;; - All context-sensitive commands use `call-interactively' to dispatch.
96 ;; - `org-confirm-shell-links' renamed to `org-confirm-shell-link-function'.
97 ;; - Bug fixes.
98 ;;
99 ;; Version 4.31
100 ;; - Bug fixes.
101 ;;
102 ;; Version 4.30
103 ;; - Modified installation: Autoloads have been collected in org-install.el.
104 ;; - Logging (org-log-done) is now a #+STARTUP option.
105 ;; - Checkboxes in plain list items, following up on Frank Ruell's idea.
106 ;; - File links inserted with C-c C-l will use relative paths if the linked
107 ;; file is in the current directory or a subdirectory of it.
108 ;; - New variable `org-link-file-path-type' to specify preference for
109 ;; relative and absolute paths.
110 ;; - New CSS classes for tags, timestamps, timestamp keywords.
111 ;; - Bug and typo fixes.
112 ;;
113 ;; Version 4.29
114 ;; - Inlining images in HTML export now depends on wheather the link
115 ;; contains a description or not.
116 ;; - TODO items can be scheduled from the global TODO list using C-c C-s.
117 ;; - TODO items already scheduled can be made to disappear from the global
118 ;; todo list, see `org-agenda-todo-ignore-scheduled'.
119 ;; - In Tables, formulas may also be Lisp forms.
120 ;; - Exporting the visible part of an outline with `C-c C-x v' works now
121 ;; for all available exporters.
122 ;; - Bug fixes, lots of them :-(
123 ;;
124 ;; Version 4.28
125 ;; - Bug fixes.
126 ;;
127 ;; Version 4.27
128 ;; - HTML exporter generalized to receive external options.
129 ;; As part of the process, author, email and date have been moved to the
130 ;; end of the HTML file.
131 ;; - Support for customizable file search in file links.
132 ;; - BibTeX database links as first application of the above.
133 ;; - New option `org-agenda-todo-list-sublevels' to turn off listing TODO
134 ;; entries that are sublevels of another TODO entry.
135 ;;
136 ;; Version 4.26
137 ;; - Bug fixes.
138 ;;
139 ;; Version 4.25
140 ;; - Revision of the font-lock faces section, with better tty support.
141 ;; - TODO keywords in Agenda buffer are fontified.
142 ;; - Export converts links between .org files to links between .html files.
143 ;; - Better support for bold/italic/underline emphasis.
144 ;;
145 ;; Version 4.24
146 ;; - Bug fixes.
147 ;;
148 ;; Version 4.23
149 ;; - Bug fixes.
150 ;;
151 ;; Version 4.22
152 ;; - Bug fixes.
153 ;; - In agenda buffer, mouse-1 no longer follows link.
154 ;; See `org-agenda-mouse-1-follows-link' and `org-mouse-1-follows-link'.
155 ;;
156 ;; Version 4.20
157 ;; - Links use now the [[link][description]] format by default.
158 ;; When inserting links, the user is prompted for a description.
159 ;; - If a link has a description, only the description is displayed
160 ;; the link part is hidden. Use C-c C-l to edit the link part.
161 ;; - TAGS are now bold, but in the same color as the headline.
162 ;; - The width of a table column can be limited by using a field "<N>".
163 ;; - New structure for the customization tree.
164 ;; - Bug fixes.
165 ;;
166 ;; Version 4.13
167 ;; - The list of agenda files can be maintainted in an external file.
168 ;; - Bug fixes.
169 ;;
170 ;; Version 4.12
171 ;; - Templates for remember buffer. Note that the remember setup changes.
172 ;; To set up templates, see `org-remember-templates'.
173 ;; - The time in new time stamps can be rounded, see new option
174 ;; `org-time-stamp-rounding-minutes'.
175 ;; - Bug fixes (there are *always* more bugs).
176 ;;
177 ;;; Code:
178
179 (eval-when-compile
180 (require 'cl)
181 (require 'calendar))
182 (require 'outline)
183 (require 'time-date)
184 (require 'easymenu)
185
186 (defvar calc-embedded-close-formula) ; defined by the calc package
187 (defvar calc-embedded-open-formula) ; defined by the calc package
188 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
189
190 ;;; Customization variables
191
192 (defvar org-version "4.33"
193 "The version number of the file org.el.")
194 (defun org-version ()
195 (interactive)
196 (message "Org-mode version %s" org-version))
197
198 ;; The following constant is for compatibility with different versions
199 ;; of outline.el.
200 (defconst org-noutline-p (featurep 'noutline)
201 "Are we using the new outline mode?")
202 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
203 (defconst org-format-transports-properties-p
204 (let ((x "a"))
205 (add-text-properties 0 1 '(test t) x)
206 (get-text-property 0 'test (format "%s" x)))
207 "Does format transport text properties?")
208
209 (defgroup org nil
210 "Outline-based notes management and organizer."
211 :tag "Org"
212 :group 'outlines
213 :group 'hypermedia
214 :group 'calendar)
215
216 (defgroup org-startup nil
217 "Options concerning startup of Org-mode."
218 :tag "Org Startup"
219 :group 'org)
220
221 (defcustom org-startup-folded t
222 "Non-nil means, entering Org-mode will switch to OVERVIEW.
223 This can also be configured on a per-file basis by adding one of
224 the following lines anywhere in the buffer:
225
226 #+STARTUP: fold
227 #+STARTUP: nofold
228 #+STARTUP: content"
229 :group 'org-startup
230 :type '(choice
231 (const :tag "nofold: show all" nil)
232 (const :tag "fold: overview" t)
233 (const :tag "content: all headlines" content)))
234
235 (defcustom org-startup-truncated t
236 "Non-nil means, entering Org-mode will set `truncate-lines'.
237 This is useful since some lines containing links can be very long and
238 uninteresting. Also tables look terrible when wrapped."
239 :group 'org-startup
240 :type 'boolean)
241
242 (defcustom org-startup-align-all-tables nil
243 "Non-nil means, align all tables when visiting a file.
244 This is useful when the column width in tables is forced with <N> cookies
245 in table fields. Such tables will look correct only after the first re-align.
246 This can also be configured on a per-file basis by adding one of
247 the following lines anywhere in the buffer:
248 #+STARTUP: align
249 #+STARTUP: noalign"
250 :group 'org-startup
251 :type 'boolean)
252
253 (defcustom org-startup-with-deadline-check nil
254 "Non-nil means, entering Org-mode will run the deadline check.
255 This means, if you start editing an org file, you will get an
256 immediate reminder of any due deadlines.
257 This can also be configured on a per-file basis by adding one of
258 the following lines anywhere in the buffer:
259 #+STARTUP: dlcheck
260 #+STARTUP: nodlcheck"
261 :group 'org-startup
262 :type 'boolean)
263
264 (defcustom org-insert-mode-line-in-empty-file nil
265 "Non-nil means insert the first line setting Org-mode in empty files.
266 When the function `org-mode' is called interactively in an empty file, this
267 normally means that the file name does not automatically trigger Org-mode.
268 To ensure that the file will always be in Org-mode in the future, a
269 line enforcing Org-mode will be inserted into the buffer, if this option
270 has been set."
271 :group 'org-startup
272 :type 'boolean)
273
274 (defcustom org-CUA-compatible nil
275 "Non-nil means use alternative key bindings for S-<cursor movement>.
276 Org-mode used S-<cursor movement> for changing timestamps and priorities.
277 S-<cursor movement> is also used for example by `CUA-mode' to select text.
278 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
279 alternative bindings. Setting this variable to t will replace the following
280 keys both in Org-mode and in the Org-agenda buffer.
281
282 S-RET -> C-S-RET
283 S-up -> M-p
284 S-down -> M-n
285 S-left -> M--
286 S-right -> M-+
287
288 If you do not like the alternative keys, take a look at the variable
289 `org-disputed-keys'.
290
291 This option is only relevant at load-time of Org-mode. Changing it requires
292 a restart of Emacs to become effective."
293 :group 'org-startup
294 :type 'boolean)
295
296 (defvar org-disputed-keys
297 '((S-up [(shift up)] [(meta ?p)])
298 (S-down [(shift down)] [(meta ?n)])
299 (S-left [(shift left)] [(meta ?-)])
300 (S-right [(shift right)] [(meta ?+)])
301 (S-return [(shift return)] [(control shift return)]))
302 "Keys for which Org-mode and other modes compete.
303 This is an alist, cars are symbols for lookup, 1st element is the default key,
304 second element will be used when `org-CUA-compatible' is t.")
305
306 (defun org-key (key)
307 "Select a key according to `org-CUA-compatible'."
308 (nth (if org-CUA-compatible 2 1)
309 (or (assq key org-disputed-keys)
310 (error "Invalid Key %s in `org-key'" key))))
311
312 (defcustom org-ellipsis nil
313 "The ellipsis to use in the Org-mode outline.
314 When nil, just use the standard three dots. When a string, use that instead,
315 and just in Org-mode (which will then use its own display table).
316 Changing this requires executing `M-x org-mode' in a buffer to become
317 effective."
318 :group 'org-startup
319 :type '(choice (const :tag "Default" nil)
320 (string :tag "String" :value "...#")))
321
322 (defvar org-display-table nil
323 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
324
325 (defgroup org-keywords nil
326 "Keywords in Org-mode."
327 :tag "Org Keywords"
328 :group 'org)
329
330 (defcustom org-deadline-string "DEADLINE:"
331 "String to mark deadline entries.
332 A deadline is this string, followed by a time stamp. Should be a word,
333 terminated by a colon. You can insert a schedule keyword and
334 a timestamp with \\[org-deadline].
335 Changes become only effective after restarting Emacs."
336 :group 'org-keywords
337 :type 'string)
338
339 (defcustom org-scheduled-string "SCHEDULED:"
340 "String to mark scheduled TODO entries.
341 A schedule is this string, followed by a time stamp. Should be a word,
342 terminated by a colon. You can insert a schedule keyword and
343 a timestamp with \\[org-schedule].
344 Changes become only effective after restarting Emacs."
345 :group 'org-keywords
346 :type 'string)
347
348 (defcustom org-closed-string "CLOSED:"
349 "String used as the prefix for timestamps logging closing a TODO entry."
350 :group 'org-keywords
351 :type 'string)
352
353 (defcustom org-comment-string "COMMENT"
354 "Entries starting with this keyword will never be exported.
355 An entry can be toggled between COMMENT and normal with
356 \\[org-toggle-comment].
357 Changes become only effective after restarting Emacs."
358 :group 'org-keywords
359 :type 'string)
360
361 (defcustom org-quote-string "QUOTE"
362 "Entries starting with this keyword will be exported in fixed-width font.
363 Quoting applies only to the text in the entry following the headline, and does
364 not extend beyond the next headline, even if that is lower level.
365 An entry can be toggled between QUOTE and normal with
366 \\[org-toggle-fixed-width-section]."
367 :group 'org-keywords
368 :type 'string)
369
370 (defgroup org-structure nil
371 "Options concerning the general structure of Org-mode files."
372 :tag "Org Structure"
373 :group 'org)
374
375 (defgroup org-cycle nil
376 "Options concerning visibility cycling in Org-mode."
377 :tag "Org Cycle"
378 :group 'org-structure)
379
380 (defcustom org-cycle-global-at-bob t
381 "Cycle globally if cursor is at beginning of buffer and not at a headline.
382 This makes it possible to do global cycling without having to use S-TAB or
383 C-u TAB. For this special case to work, the first line of the buffer
384 must not be a headline - it may be empty ot some other text. When used in
385 this way, `org-cycle-hook' is disables temporarily, to make sure the
386 cursor stays at the beginning of the buffer.
387 When this option is nil, don't do anything special at the beginning
388 of the buffer."
389 :group 'org-cycle
390 :type 'boolean)
391
392 (defcustom org-cycle-emulate-tab t
393 "Where should `org-cycle' emulate TAB.
394 nil Never
395 white Only in completely white lines
396 t Everywhere except in headlines"
397 :group 'org-cycle
398 :type '(choice (const :tag "Never" nil)
399 (const :tag "Only in completely white lines" white)
400 (const :tag "Everywhere except in headlines" t)
401 ))
402
403 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
404 "Hook that is run after `org-cycle' has changed the buffer visibility.
405 The function(s) in this hook must accept a single argument which indicates
406 the new state that was set by the most recent `org-cycle' command. The
407 argument is a symbol. After a global state change, it can have the values
408 `overview', `content', or `all'. After a local state change, it can have
409 the values `folded', `children', or `subtree'."
410 :group 'org-cycle
411 :type 'hook)
412
413 (defgroup org-edit-structure nil
414 "Options concerning structure editing in Org-mode."
415 :tag "Org Edit Structure"
416 :group 'org-structure)
417
418 (defcustom org-odd-levels-only nil
419 "Non-nil means, skip even levels and only use odd levels for the outline.
420 This has the effect that two stars are being added/taken away in
421 promotion/demotion commands. It also influences how levels are
422 handled by the exporters.
423 Changing it requires restart of `font-lock-mode' to become effective
424 for fontification also in regions already fontified.
425 You may also set this on a per-file basis by adding one of the following
426 lines to the buffer:
427
428 #+STARTUP: odd
429 #+STARTUP: oddeven"
430 :group 'org-edit-structure
431 :group 'org-font-lock
432 :type 'boolean)
433
434 (defcustom org-adapt-indentation t
435 "Non-nil means, adapt indentation when promoting and demoting.
436 When this is set and the *entire* text in an entry is indented, the
437 indentation is increased by one space in a demotion command, and
438 decreased by one in a promotion command. If any line in the entry
439 body starts at column 0, indentation is not changed at all."
440 :group 'org-edit-structure
441 :type 'boolean)
442
443 (defcustom org-insert-heading-hook nil
444 "Hook being run after inserting a new heading."
445 :group 'org-edit-structure
446 :type 'boolean)
447
448 (defcustom org-enable-fixed-width-editor t
449 "Non-nil means, lines starting with \":\" are treated as fixed-width.
450 This currently only means, they are never auto-wrapped.
451 When nil, such lines will be treated like ordinary lines.
452 See also the QUOTE keyword."
453 :group 'org-edit-structure
454 :type 'boolean)
455
456 (defgroup org-sparse-trees nil
457 "Options concerning sparse trees in Org-mode."
458 :tag "Org Sparse Trees"
459 :group 'org-structure)
460
461 (defcustom org-highlight-sparse-tree-matches t
462 "Non-nil means, highlight all matches that define a sparse tree.
463 The highlights will automatically disappear the next time the buffer is
464 changed by an edit command."
465 :group 'org-sparse-trees
466 :type 'boolean)
467
468 (defcustom org-show-hierarchy-above t
469 "Non-nil means, show full hierarchy when showing a spot in the tree.
470 Turning this off makes sparse trees more compact, but also less clear."
471 :group 'org-sparse-trees
472 :type 'boolean)
473
474 (defcustom org-show-following-heading t
475 "Non-nil means, show heading following match in `org-occur'.
476 When doing an `org-occur' it is useful to show the headline which
477 follows the match, even if they do not match the regexp. This makes it
478 easier to edit directly inside the sparse tree. However, if you use
479 `org-occur' mainly as an overview, the following headlines are
480 unnecessary clutter."
481 :group 'org-sparse-trees
482 :type 'boolean)
483
484 (defcustom org-occur-hook '(org-first-headline-recenter)
485 "Hook that is run after `org-occur' has constructed a sparse tree.
486 This can be used to recenter the window to show as much of the structure
487 as possible."
488 :group 'org-sparse-trees
489 :type 'hook)
490
491 (defgroup org-plain-lists nil
492 "Options concerning plain lists in Org-mode."
493 :tag "Org Plain lists"
494 :group 'org-structure)
495
496 (defcustom org-cycle-include-plain-lists nil
497 "Non-nil means, include plain lists into visibility cycling.
498 This means that during cycling, plain list items will *temporarily* be
499 interpreted as outline headlines with a level given by 1000+i where i is the
500 indentation of the bullet. In all other operations, plain list items are
501 not seen as headlines. For example, you cannot assign a TODO keyword to
502 such an item."
503 :group 'org-plain-lists
504 :type 'boolean)
505
506
507 (defcustom org-plain-list-ordered-item-terminator t
508 "The character that makes a line with leading number an ordered list item.
509 Valid values are ?. and ?\). To get both terminators, use t. While
510 ?. may look nicer, it creates the danger that a line with leading
511 number may be incorrectly interpreted as an item. ?\) therefore is
512 the safe choice."
513 :group 'org-plain-lists
514 :type '(choice (const :tag "dot like in \"2.\"" ?.)
515 (const :tag "paren like in \"2)\"" ?\))
516 (const :tab "both" t)))
517
518 (defcustom org-auto-renumber-ordered-lists t
519 "Non-nil means, automatically renumber ordered plain lists.
520 Renumbering happens when the sequence have been changed with
521 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
522 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
523 :group 'org-plain-lists
524 :type 'boolean)
525
526 (defgroup org-archive nil
527 "Options concerning archiving in Org-mode."
528 :tag "Org Archive"
529 :group 'org-structure)
530
531 (defcustom org-archive-location "%s_archive::"
532 "The location where subtrees should be archived.
533 This string consists of two parts, separated by a double-colon.
534
535 The first part is a file name - when omitted, archiving happens in the same
536 file. %s will be replaced by the current file name (without directory part).
537 Archiving to a different file is useful to keep archived entries from
538 contributing to the Org-mode Agenda.
539
540 The part after the double colon is a headline. The archived entries will be
541 filed under that headline. When omitted, the subtrees are simply filed away
542 at the end of the file, as top-level entries.
543
544 Here are a few examples:
545 \"%s_archive::\"
546 If the current file is Projects.org, archive in file
547 Projects.org_archive, as top-level trees. This is the default.
548
549 \"::* Archived Tasks\"
550 Archive in the current file, under the top-level headline
551 \"* Archived Tasks\".
552
553 \"~/org/archive.org::\"
554 Archive in file ~/org/archive.org (absolute path), as top-level trees.
555
556 \"basement::** Finished Tasks\"
557 Archive in file ./basement (relative path), as level 3 trees
558 below the level 2 heading \"** Finished Tasks\".
559
560 You may set this option on a per-file basis by adding to the buffer a
561 line like
562
563 #+ARCHIVE: basement::** Finished Tasks"
564 :group 'org-archive
565 :type 'string)
566
567 (defcustom org-archive-mark-done t
568 "Non-nil means, mark archived entries as DONE."
569 :group 'org-archive
570 :type 'boolean)
571
572 (defcustom org-archive-stamp-time t
573 "Non-nil means, add a time stamp to archived entries.
574 The time stamp will be added directly after the TODO state keyword in the
575 first line, so it is probably best to use this in combinations with
576 `org-archive-mark-done'."
577 :group 'org-archive
578 :type 'boolean)
579
580 (defgroup org-table nil
581 "Options concerning tables in Org-mode."
582 :tag "Org Table"
583 :group 'org)
584
585 (defcustom org-enable-table-editor 'optimized
586 "Non-nil means, lines starting with \"|\" are handled by the table editor.
587 When nil, such lines will be treated like ordinary lines.
588
589 When equal to the symbol `optimized', the table editor will be optimized to
590 do the following:
591 - Use automatic overwrite mode in front of whitespace in table fields.
592 This make the structure of the table stay in tact as long as the edited
593 field does not exceed the column width.
594 - Minimize the number of realigns. Normally, the table is aligned each time
595 TAB or RET are pressed to move to another field. With optimization this
596 happens only if changes to a field might have changed the column width.
597 Optimization requires replacing the functions `self-insert-command',
598 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
599 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
600 very good at guessing when a re-align will be necessary, but you can always
601 force one with \\[org-ctrl-c-ctrl-c].
602
603 If you would like to use the optimized version in Org-mode, but the
604 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
605
606 This variable can be used to turn on and off the table editor during a session,
607 but in order to toggle optimization, a restart is required.
608
609 See also the variable `org-table-auto-blank-field'."
610 :group 'org-table
611 :type '(choice
612 (const :tag "off" nil)
613 (const :tag "on" t)
614 (const :tag "on, optimized" optimized)))
615
616 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
617 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
618 In the optimized version, the table editor takes over all simple keys that
619 normally just insert a character. In tables, the characters are inserted
620 in a way to minimize disturbing the table structure (i.e. in overwrite mode
621 for empty fields). Outside tables, the correct binding of the keys is
622 restored.
623
624 The default for this option is t if the optimized version is also used in
625 Org-mode. See the variable `org-enable-table-editor' for details. Changing
626 this variable requires a restart of Emacs to become effective."
627 :group 'org-table
628 :type 'boolean)
629
630 (defgroup org-table-settings nil
631 "Settings for tables in Org-mode."
632 :tag "Org Table Settings"
633 :group 'org-table)
634
635 (defcustom org-table-default-size "5x2"
636 "The default size for newly created tables, Columns x Rows."
637 :group 'org-table-settings
638 :type 'string)
639
640 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
641 "Regular expression for recognizing numbers in table columns.
642 If a table column contains mostly numbers, it will be aligned to the
643 right. If not, it will be aligned to the left.
644
645 The default value of this option is a regular expression which allows
646 anything which looks remotely like a number as used in scientific
647 context. For example, all of the following will be considered a
648 number:
649 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
650
651 Other options offered by the customize interface are more restrictive."
652 :group 'org-table-settings
653 :type '(choice
654 (const :tag "Positive Integers"
655 "^[0-9]+$")
656 (const :tag "Integers"
657 "^[-+]?[0-9]+$")
658 (const :tag "Floating Point Numbers"
659 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
660 (const :tag "Floating Point Number or Integer"
661 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
662 (const :tag "Exponential, Floating point, Integer"
663 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
664 (const :tag "Very General Number-Like"
665 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
666 (string :tag "Regexp:")))
667
668 (defcustom org-table-number-fraction 0.5
669 "Fraction of numbers in a column required to make the column align right.
670 In a column all non-white fields are considered. If at least this
671 fraction of fields is matched by `org-table-number-fraction',
672 alignment to the right border applies."
673 :group 'org-table-settings
674 :type 'number)
675
676 (defgroup org-table-editing nil
677 "Bahavior of tables during editing in Org-mode."
678 :tag "Org Table Editing"
679 :group 'org-table)
680
681 (defcustom org-table-automatic-realign t
682 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
683 When nil, aligning is only done with \\[org-table-align], or after column
684 removal/insertion."
685 :group 'org-table-editing
686 :type 'boolean)
687
688 (defcustom org-table-limit-column-width t ;kw
689 "Non-nil means, allow to limit the width of table columns with <N> fields."
690 :group 'org-table-editing
691 :type 'boolean)
692
693 (defcustom org-table-auto-blank-field t
694 "Non-nil means, automatically blank table field when starting to type into it.
695 This only happens when typing immediately after a field motion
696 command (TAB, S-TAB or RET).
697 Only relevant when `org-enable-table-editor' is equal to `optimized'."
698 :group 'org-table-editing
699 :type 'boolean)
700
701 (defcustom org-table-tab-jumps-over-hlines t
702 "Non-nil means, tab in the last column of a table with jump over a hline.
703 If a horizontal separator line is following the current line,
704 `org-table-next-field' can either create a new row before that line, or jump
705 over the line. When this option is nil, a new line will be created before
706 this line."
707 :group 'org-table-editing
708 :type 'boolean)
709
710 (defcustom org-table-tab-recognizes-table.el t
711 "Non-nil means, TAB will automatically notice a table.el table.
712 When it sees such a table, it moves point into it and - if necessary -
713 calls `table-recognize-table'."
714 :group 'org-table-editing
715 :type 'boolean)
716
717 (defgroup org-table-calculation nil
718 "Options concerning tables in Org-mode."
719 :tag "Org Table Calculation"
720 :group 'org-table)
721
722 (defcustom org-table-copy-increment t
723 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
724 :group 'org-table-calculation
725 :type 'boolean)
726
727 (defcustom org-calc-default-modes
728 '(calc-internal-prec 12
729 calc-float-format (float 5)
730 calc-angle-mode deg
731 calc-prefer-frac nil
732 calc-symbolic-mode nil
733 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
734 calc-display-working-message t
735 )
736 "List with Calc mode settings for use in calc-eval for table formulas.
737 The list must contain alternating symbols (Calc modes variables and values).
738 Don't remove any of the default settings, just change the values. Org-mode
739 relies on the variables to be present in the list."
740 :group 'org-table-calculation
741 :type 'plist)
742
743 (defcustom org-table-formula-evaluate-inline t
744 "Non-nil means, TAB and RET evaluate a formula in current table field.
745 If the current field starts with an equal sign, it is assumed to be a formula
746 which should be evaluated as described in the manual and in the documentation
747 string of the command `org-table-eval-formula'. This feature requires the
748 Emacs calc package.
749 When this variable is nil, formula calculation is only available through
750 the command \\[org-table-eval-formula]."
751 :group 'org-table-calculation
752 :type 'boolean)
753
754
755 (defcustom org-table-formula-use-constants t
756 "Non-nil means, interpret constants in formulas in tables.
757 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
758 by the value given in `org-table-formula-constants', or by a value obtained
759 from the `constants.el' package."
760 :group 'org-table-calculation
761 :type 'boolean)
762
763 (defcustom org-table-formula-constants nil
764 "Alist with constant names and values, for use in table formulas.
765 The car of each element is a name of a constant, without the `$' before it.
766 The cdr is the value as a string. For example, if you'd like to use the
767 speed of light in a formula, you would configure
768
769 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
770
771 and then use it in an equation like `$1*$c'."
772 :group 'org-table-calculation
773 :type '(repeat
774 (cons (string :tag "name")
775 (string :tag "value"))))
776
777 (defcustom org-table-formula-numbers-only nil
778 "Non-nil means, calculate only with numbers in table formulas.
779 Then all input fields will be converted to a number, and the result
780 must also be a number. When nil, calc's full potential is available
781 in table calculations, including symbolics etc."
782 :group 'org-table-calculation
783 :type 'boolean)
784
785 (defcustom org-table-allow-automatic-line-recalculation t
786 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
787 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
788 :group 'org-table-calculation
789 :type 'boolean)
790
791 (defgroup org-link nil
792 "Options concerning links in Org-mode."
793 :tag "Org Link"
794 :group 'org)
795
796 (defcustom org-descriptive-links t
797 "Non-nil means, hide link part and only show description of bracket links.
798 Bracket links are like [[link][descritpion]]. This variable sets the initial
799 state in new org-mode buffers. The setting can then be toggled on a
800 per-buffer basis from the Org->Hyperlinks menu."
801 :group 'org-link
802 :type 'boolean)
803
804 (defcustom org-link-style 'bracket
805 "The style of links to be inserted with \\[org-insert-link].
806 Possible values are:
807 bracket [[link][description]]. This is recommended
808 plain Description \\n link. The old way, no longer recommended."
809 :group 'org-link
810 :type '(choice
811 (const :tag "Bracket (recommended)" bracket)
812 (const :tag "Plain (no longer recommended)" plain)))
813
814 (defcustom org-link-format "%s"
815 "Default format for external, URL-like linkes in the buffer.
816 This is a format string for printf, %s will be replaced by the link text.
817 The recommended value is just \"%s\", since links will be protected by
818 enclosing them in double brackets. If you prefer plain links (see variable
819 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
820 additional URL: prefix, so the format would be \"<URL:%s>\"."
821 :group 'org-link
822 :type '(choice
823 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
824 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
825 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
826 (string :tag "Other" :value "<%s>")))
827
828 (defcustom org-link-file-path-type 'adaptive
829 "How the path name in file links should be stored.
830 Valid values are:
831
832 relative relative to the current directory, i.e. the directory of the file
833 into which the link is being inserted.
834 absolute absolute path, if possible with ~ for home directory.
835 noabbrev absolute path, no abbreviation of home directory.
836 adaptive Use relative path for files in the current directory and sub-
837 directories of it. For other files, use an absolute path."
838 :group 'org-link
839 :type '(choice
840 (const relative)
841 (const absolute)
842 (const noabbrev)
843 (const adaptive)))
844
845 (defcustom org-activate-links '(bracket angle plain radio tag date)
846 "Types of links that should be activated in Org-mode files.
847 This is a list of symbols, each leading to the activation of a certain link
848 type. In principle, it does not hurt to turn on most link types - there may
849 be a small gain when turning off unused link types. The types are:
850
851 bracket The recommended [[link][description]] or [[link]] links with hiding.
852 angular Links in angular brackes that may contain whitespace like
853 <bbdb:Carsten Dominik>.
854 plain Plain links in normal text, no whitespace, like http://google.com.
855 radio Text that is matched by a radio target, see manual for details.
856 tag Tag settings in a headline (link to tag search).
857 date Time stamps (link to calendar).
858 camel CamelCase words defining text searches.
859
860 Changing this variable requires a restart of Emacs to become effective."
861 :group 'org-link
862 :type '(set (const :tag "Double bracket links (new style)" bracket)
863 (const :tag "Angular bracket links (old style)" angular)
864 (const :tag "plain text links" plain)
865 (const :tag "Radio target matches" radio)
866 (const :tag "Tags" tag)
867 (const :tag "Timestamps" date)
868 (const :tag "CamelCase words" camel)))
869
870 (defgroup org-link-store nil
871 "Options concerning storing links in Org-mode"
872 :tag "Org Store Link"
873 :group 'org-link)
874
875 (defcustom org-context-in-file-links t
876 "Non-nil means, file links from `org-store-link' contain context.
877 A search string will be added to the file name with :: as separator and
878 used to find the context when the link is activated by the command
879 `org-open-at-point'.
880 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
881 negates this setting for the duration of the command."
882 :group 'org-link-store
883 :type 'boolean)
884
885 (defcustom org-file-link-context-use-camel-case nil
886 "Non-nil means, use CamelCase to store a search context in a file link.
887 When nil, the search string simply consists of the words of the string.
888 CamelCase is deprecated, and support for it may be dropped in the future."
889 :group 'org-link-store
890 :type 'boolean)
891
892 (defcustom org-keep-stored-link-after-insertion nil
893 "Non-nil means, keep link in list for entire session.
894
895 The command `org-store-link' adds a link pointing to the current
896 location to an internal list. These links accumulate during a session.
897 The command `org-insert-link' can be used to insert links into any
898 Org-mode file (offering completion for all stored links). When this
899 option is nil, every link which has been inserted once using \\[org-insert-link]
900 will be removed from the list, to make completing the unused links
901 more efficient."
902 :group 'org-link-store
903 :type 'boolean)
904
905 (defcustom org-usenet-links-prefer-google nil
906 "Non-nil means, `org-store-link' will create web links to Google groups.
907 When nil, Gnus will be used for such links.
908 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
909 negates this setting for the duration of the command."
910 :group 'org-link-store
911 :type 'boolean)
912
913 (defgroup org-link-follow nil
914 "Options concerning following links in Org-mode"
915 :tag "Org Follow Link"
916 :group 'org-link)
917
918 (defcustom org-tab-follows-link nil
919 "Non-nil means, on links TAB will follow the link.
920 Needs to be set before org.el is loaded."
921 :group 'org-link-follow
922 :type 'boolean)
923
924 (defcustom org-return-follows-link nil
925 "Non-nil means, on links RET will follow the link.
926 Needs to be set before org.el is loaded."
927 :group 'org-link-follow
928 :type 'boolean)
929
930 (defcustom org-mouse-1-follows-link t
931 "Non-nil means, mouse-1 on a link will follow the link.
932 A longer mouse click will still set point. Does not wortk on XEmacs.
933 Needs to be set before org.el is loaded."
934 :group 'org-link-follow
935 :type 'boolean)
936
937 (defcustom org-mark-ring-length 4
938 "Number of different positions to be recorded in the ring
939 Changing this requires a restart of Emacs to work correctly."
940 :group 'org-link-follow
941 :type 'interger)
942
943 (defcustom org-link-frame-setup
944 '((vm . vm-visit-folder-other-frame)
945 (gnus . gnus-other-frame)
946 (file . find-file-other-window))
947 "Setup the frame configuration for following links.
948 When following a link with Emacs, it may often be useful to display
949 this link in another window or frame. This variable can be used to
950 set this up for the different types of links.
951 For VM, use any of
952 `vm-visit-folder'
953 `vm-visit-folder-other-frame'
954 For Gnus, use any of
955 `gnus'
956 `gnus-other-frame'
957 For FILE, use any of
958 `find-file'
959 `find-file-other-window'
960 `find-file-other-frame'
961 For the calendar, use the variable `calendar-setup'.
962 For BBDB, it is currently only possible to display the matches in
963 another window."
964 :group 'org-link-follow
965 :type '(list
966 (cons (const vm)
967 (choice
968 (const vm-visit-folder)
969 (const vm-visit-folder-other-window)
970 (const vm-visit-folder-other-frame)))
971 (cons (const gnus)
972 (choice
973 (const gnus)
974 (const gnus-other-frame)))
975 (cons (const file)
976 (choice
977 (const find-file)
978 (const find-file-other-window)
979 (const find-file-other-frame)))))
980
981 (defcustom org-open-non-existing-files nil
982 "Non-nil means, `org-open-file' will open non-existing file.
983 When nil, an error will be generated."
984 :group 'org-link-follow
985 :type 'boolean)
986
987 (defcustom org-confirm-shell-link-function 'yes-or-no-p
988 "Non-nil means, ask for confirmation before executing shell links.
989 Shell links can be dangerous, just thing about a link
990
991 [[shell:rm -rf ~/*][Google Search]]
992
993 This link would show up in your Org-mode document as \"Google Search\"
994 but really it would remove your entire home directory.
995 Therefore I *definitely* advise against setting this variable to nil.
996 Just change it to `y-or-n-p' of you want to confirm with a single key press
997 rather than having to type \"yes\"."
998 :group 'org-link-follow
999 :type '(choice
1000 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1001 (const :tag "with y-or-n (faster)" y-or-n-p)
1002 (const :tag "no confirmation (dangerous)" nil)))
1003
1004 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1005 "Non-nil means, ask for confirmation before executing elisp links.
1006 Elisp links can be dangerous, just thing about a link
1007
1008 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1009
1010 This link would show up in your Org-mode document as \"Google Search\"
1011 but really it would remove your entire home directory.
1012 Therefore I *definitely* advise against setting this variable to nil.
1013 Just change it to `y-or-n-p' of you want to confirm with a single key press
1014 rather than having to type \"yes\"."
1015 :group 'org-link-follow
1016 :type '(choice
1017 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1018 (const :tag "with y-or-n (faster)" y-or-n-p)
1019 (const :tag "no confirmation (dangerous)" nil)))
1020
1021 (defconst org-file-apps-defaults-gnu
1022 '((t . mailcap))
1023 "Default file applications on a UNIX or GNU/Linux system.
1024 See `org-file-apps'.")
1025
1026 (defconst org-file-apps-defaults-macosx
1027 '((t . "open %s")
1028 ("ps" . "gv %s")
1029 ("ps.gz" . "gv %s")
1030 ("eps" . "gv %s")
1031 ("eps.gz" . "gv %s")
1032 ("dvi" . "xdvi %s")
1033 ("fig" . "xfig %s"))
1034 "Default file applications on a MacOS X system.
1035 The system \"open\" is known as a default, but we use X11 applications
1036 for some files for which the OS does not have a good default.
1037 See `org-file-apps'.")
1038
1039 (defconst org-file-apps-defaults-windowsnt
1040 (list (cons t
1041 (list (if (featurep 'xemacs)
1042 'mswindows-shell-execute
1043 'w32-shell-execute)
1044 "open" 'file)))
1045 "Default file applications on a Windows NT system.
1046 The system \"open\" is used for most files.
1047 See `org-file-apps'.")
1048
1049 (defcustom org-file-apps
1050 '(
1051 ("txt" . emacs)
1052 ("tex" . emacs)
1053 ("ltx" . emacs)
1054 ("org" . emacs)
1055 ("el" . emacs)
1056 ("bib" . emacs)
1057 )
1058 "External applications for opening `file:path' items in a document.
1059 Org-mode uses system defaults for different file types, but
1060 you can use this variable to set the application for a given file
1061 extension. The entries in this list are cons cells where the car identifies
1062 files and the cdr the corresponding command. Possible values for the
1063 file identifier are
1064 \"ext\" A string identifying an extension
1065 `directory' Matches a directory
1066 t Default for all remaining files
1067
1068 Possible values for the command are:
1069 `emacs' The file will be visited by the current Emacs process.
1070 `default' Use the default application for this file type.
1071 string A command to be executed by a shell; %s will be replaced
1072 by the path to the file.
1073 sexp A Lisp form which will be evaluated. The file path will
1074 be available in the Lisp variable `file'.
1075 For more examples, see the system specific constants
1076 `org-file-apps-defaults-macosx'
1077 `org-file-apps-defaults-windowsnt'
1078 `org-file-apps-defaults-gnu'."
1079 :group 'org-link-follow
1080 :type '(repeat
1081 (cons (choice :value ""
1082 (string :tag "Extension")
1083 (const :tag "Default for unrecognized files" t)
1084 (const :tag "Links to a directory" directory))
1085 (choice :value ""
1086 (const :tag "Visit with Emacs" emacs)
1087 (const :tag "Use system default" default)
1088 (string :tag "Command")
1089 (sexp :tag "Lisp form")))))
1090
1091 (defcustom org-mhe-search-all-folders nil
1092 "Non-nil means, that the search for the mh-message will be extended to
1093 all folders if the message cannot be found in the folder given in the link.
1094 Searching all folders is very effective with one of the search engines
1095 supported by MH-E, but will be slow with pick."
1096 :group 'org-link-follow
1097 :type 'boolean)
1098
1099 (defgroup org-remember nil
1100 "Options concerning interaction with remember.el."
1101 :tag "Org Remember"
1102 :group 'org)
1103
1104 (defcustom org-directory "~/org"
1105 "Directory with org files.
1106 This directory will be used as default to prompt for org files.
1107 Used by the hooks for remember.el."
1108 :group 'org-remember
1109 :type 'directory)
1110
1111 (defcustom org-default-notes-file "~/.notes"
1112 "Default target for storing notes.
1113 Used by the hooks for remember.el. This can be a string, or nil to mean
1114 the value of `remember-data-file'."
1115 :group 'org-remember
1116 :type '(choice
1117 (const :tag "Default from remember-data-file" nil)
1118 file))
1119
1120 (defcustom org-remember-templates nil
1121 "Templates for the creation of remember buffers.
1122 When nil, just let remember make the buffer.
1123 When not nil, this is a list of 3-element lists. In each entry, the first
1124 element is a character, a unique key to select this template.
1125 The second element is the template. The third element is optional and can
1126 specify a destination file for remember items created with this template.
1127 The default file is given by `org-default-notes-file'.
1128
1129 The template specifies the structure of the remember buffer. It should have
1130 a first line starting with a star, to act as the org-mode headline.
1131 Furthermore, the following %-escapes will be replaced with content:
1132 %t time stamp, date only
1133 %T time stamp with date and time
1134 %u inactive time stamp, date only
1135 %U inactive time stamp with date and time
1136 %n user name
1137 %a annotation, normally the link created with org-store-link
1138 %i initial content, the region when remember is called with C-u.
1139 If %i is indented, the entire inserted text will be indented as well.
1140 %? This will be removed, and the cursor placed at this position."
1141 :group 'org-remember
1142 :type '(repeat :tag "enabled"
1143 (list :value (?a "\n" nil)
1144 (character :tag "Selection Key")
1145 (string :tag "Template")
1146 (file :tag "Destination file (optional)"))))
1147
1148 (defcustom org-reverse-note-order nil
1149 "Non-nil means, store new notes at the beginning of a file or entry.
1150 When nil, new notes will be filed to the end of a file or entry."
1151 :group 'org-remember
1152 :type '(choice
1153 (const :tag "Reverse always" t)
1154 (const :tag "Reverse never" nil)
1155 (repeat :tag "By file name regexp"
1156 (cons regexp boolean))))
1157
1158 (defgroup org-todo nil
1159 "Options concerning TODO items in Org-mode."
1160 :tag "Org TODO"
1161 :group 'org)
1162
1163 (defcustom org-todo-keywords '("TODO" "DONE")
1164 "List of TODO entry keywords.
1165 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1166 considered to mean that the entry is \"done\". All the other mean that
1167 action is required, and will make the entry show up in todo lists, diaries
1168 etc.
1169 The command \\[org-todo] cycles an entry through these states, and an
1170 additional state where no keyword is present. For details about this
1171 cycling, see also the variable `org-todo-interpretation'
1172 Changes become only effective after restarting Emacs."
1173 :group 'org-todo
1174 :group 'org-keywords
1175 :type '(repeat (string :tag "Keyword")))
1176
1177 (defcustom org-todo-interpretation 'sequence
1178 "Controls how TODO keywords are interpreted.
1179 This variable is only relevant if `org-todo-keywords' contains more than two
1180 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1181
1182 When `sequence', \\[org-todo] will always switch to the next state in the
1183 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1184 to state when executed several times in direct succession. Otherwise, it
1185 switches directly to DONE from any state.
1186 See the manual for more information."
1187 :group 'org-todo
1188 :group 'org-keywords
1189 :type '(choice (const sequence)
1190 (const type)))
1191
1192 (defcustom org-after-todo-state-change-hook nil
1193 "Hook which is run after the state of a TODO item was changed.
1194 The new state (a string with a TODO keyword, or nil) is available in the
1195 Lisp variable `state'."
1196 :group 'org-todo
1197 :type 'hook)
1198
1199 (defcustom org-log-done nil
1200 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1201 When the state of an entry is changed from nothing to TODO, remove a previous
1202 closing date.
1203 This can also be configured on a per-file basis by adding one of
1204 the following lines anywhere in the buffer:
1205
1206 #+STARTUP: logging
1207 #+STARTUP: nologging"
1208 :group 'org-todo
1209 :type 'boolean)
1210
1211 (defgroup org-priorities nil
1212 "Priorities in Org-mode."
1213 :tag "Org Priorities"
1214 :group 'org-todo)
1215
1216 (defcustom org-default-priority ?B
1217 "The default priority of TODO items.
1218 This is the priority an item get if no explicit priority is given."
1219 :group 'org-priorities
1220 :type 'character)
1221
1222 (defcustom org-lowest-priority ?C
1223 "The lowest priority of TODO items. A character like ?A, ?B etc."
1224 :group 'org-priorities
1225 :type 'character)
1226
1227 (defgroup org-time nil
1228 "Options concerning time stamps and deadlines in Org-mode."
1229 :tag "Org Time"
1230 :group 'org)
1231
1232 (defcustom org-insert-labeled-timestamps-at-point nil
1233 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1234 When nil, these labeled time stamps are forces into the second line of an
1235 entry, just after the headline. When scheduling from the global TODO list,
1236 the time stamp will always be forced into the second line."
1237 :group 'org-time
1238 :type 'boolean)
1239
1240 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1241 "Formats for `format-time-string' which are used for time stamps.
1242 It is not recommended to change this constant.")
1243
1244 (defcustom org-time-stamp-rounding-minutes 0
1245 "Number of minutes to round time stamps to upon insertion.
1246 When zero, insert the time unmodified. Useful rounding numbers
1247 should be factors of 60, so for example 5, 10, 15.
1248 When this is not zero, you can still force an exact time-stamp by using
1249 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1250 :group 'org-time
1251 :type 'integer)
1252
1253 (defcustom org-deadline-warning-days 30
1254 "No. of days before expiration during which a deadline becomes active.
1255 This variable governs the display in the org file."
1256 :group 'org-time
1257 :type 'number)
1258
1259 (defcustom org-popup-calendar-for-date-prompt t
1260 "Non-nil means, pop up a calendar when prompting for a date.
1261 In the calendar, the date can be selected with mouse-1. However, the
1262 minibuffer will also be active, and you can simply enter the date as well.
1263 When nil, only the minibuffer will be available."
1264 :group 'org-time
1265 :type 'boolean)
1266
1267 (defcustom org-calendar-follow-timestamp-change t
1268 "Non-nil means, make the calendar window follow timestamp changes.
1269 When a timestamp is modified and the calendar window is visible, it will be
1270 moved to the new date."
1271 :group 'org-time
1272 :type 'boolean)
1273
1274 (defgroup org-tags nil
1275 "Options concerning tags in Org-mode."
1276 :tag "Org Tags"
1277 :group 'org)
1278
1279 (defcustom org-tag-alist nil
1280 "List of tags allowed in Org-mode files.
1281 When this list is nil, Org-mode will base TAG input on what is already in the
1282 buffer.
1283 The value of this variable is an alist, the car may be (and should) be a
1284 character that is used to select that tag through the fast-tag-selection
1285 interface. See the manual for details."
1286 :group 'org-tags
1287 :type '(repeat
1288 (cons (character) (string :tag "Tag"))))
1289
1290 (defcustom org-use-fast-tag-selection 'auto
1291 "Non-nil means, use fast tag selection scheme.
1292 This is a special interface to select and deselect tags with single keys.
1293 When nil, fast selection is never used.
1294 When the symbol `auto', fast selection is used if and only if selection
1295 characters for tags have been configured, either through the variable
1296 `org-tag-alist' or through a #+TAGS line in the buffer.
1297 When t, fast selection is always used and selection keys are assigned
1298 automatically if necessary."
1299 :group 'org-tags
1300 :type '(choice
1301 (const :tag "Always" t)
1302 (const :tag "Never" nil)
1303 (const :tag "When selection characters are configured" 'auto)))
1304
1305 (defcustom org-tags-column 48
1306 "The column to which tags should be indented in a headline.
1307 If this number is positive, it specifies the column. If it is negative,
1308 it means that the tags should be flushright to that column. For example,
1309 -79 works well for a normal 80 character screen."
1310 :group 'org-tags
1311 :type 'integer)
1312
1313 (defcustom org-auto-align-tags t
1314 "Non-nil means, realign tags after pro/demotion of TODO state change.
1315 These operations change the length of a headline and therefore shift
1316 the tags around. With this options turned on, after each such operation
1317 the tags are again aligned to `org-tags-column'."
1318 :group 'org-tags
1319 :type 'boolean)
1320
1321 (defcustom org-use-tag-inheritance t
1322 "Non-nil means, tags in levels apply also for sublevels.
1323 When nil, only the tags directly given in a specific line apply there.
1324 If you turn off this option, you very likely want to turn on the
1325 companion option `org-tags-match-list-sublevels'."
1326 :group 'org-tags
1327 :type 'boolean)
1328
1329 (defcustom org-tags-match-list-sublevels nil
1330 "Non-nil means list also sublevels of headlines matching tag search.
1331 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1332 the sublevels of a headline matching a tag search often also match
1333 the same search. Listing all of them can create very long lists.
1334 Setting this variable to nil causes subtrees of a match to be skipped.
1335 This option is off by default, because inheritance in on. If you turn
1336 inheritance off, you very likely want to turn this option on.
1337
1338 As a special case, if the tag search is restricted to TODO items, the
1339 value of this variable is ignored and sublevels are always checked, to
1340 make sure all corresponding TODO items find their way into the list."
1341 :group 'org-tags
1342 :type 'boolean)
1343
1344 (defvar org-tags-history nil
1345 "History of minibuffer reads for tags.")
1346 (defvar org-last-tags-completion-table nil
1347 "The last used completion table for tags.")
1348
1349 (defgroup org-agenda nil
1350 "Options concerning agenda display Org-mode."
1351 :tag "Org Agenda"
1352 :group 'org)
1353
1354 (defvar org-category nil
1355 "Variable used by org files to set a category for agenda display.
1356 Such files should use a file variable to set it, for example
1357
1358 -*- mode: org; org-category: \"ELisp\"
1359
1360 or contain a special line
1361
1362 #+CATEGORY: ELisp
1363
1364 If the file does not specify a category, then file's base name
1365 is used instead.")
1366 (make-variable-buffer-local 'org-category)
1367
1368 (defcustom org-agenda-files nil
1369 "The files to be used for agenda display.
1370 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1371 \\[org-remove-file]. You can also use customize to edit the list.
1372
1373 If the value of the variable is not a list but a single file name, then
1374 the list of agenda files is actually stored and maintained in that file, one
1375 agenda file per line."
1376 :group 'org-agenda
1377 :type '(choice
1378 (repeat :tag "List of files" file)
1379 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1380
1381 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1382 "Custom commands for the agenda.
1383 These commands will be offered on the splash screen displayed by the
1384 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1385
1386 key The key (a single char as a string) to be associated with the command.
1387 type The command type, any of the following symbols:
1388 todo Entries with a specific TODO keyword, in all agenda files.
1389 tags Tags match in all agenda files.
1390 tags-todo Tags match in all agenda files, TODO entries only.
1391 todo-tree Sparse tree of specific TODO keyword in *current* file.
1392 tags-tree Sparse tree with all tags matches in *current* file.
1393 occur-tree Occur sparse tree for current file.
1394 match What to search for:
1395 - a single keyword for TODO keyword searches
1396 - a tags match expression for tags searches
1397 - a regular expression for occur searches"
1398 :group 'org-agenda
1399 :type '(repeat
1400 (list (string :tag "Key")
1401 (choice :tag "Type"
1402 (const :tag "Tags search in all agenda files" tags)
1403 (const :tag "Tags search of TODO entries, all agenda files" tags-todo)
1404 (const :tag "TODO keyword search in all agenda files" todo)
1405 (const :tag "Tags sparse tree in current buffer" tags-tree)
1406 (const :tag "TODO keyword tree in current buffer" todo-tree)
1407 (const :tag "Occur tree in current buffer" occur-tree))
1408 (string :tag "Match"))))
1409
1410 ;; FIXME: Need a toggle for this variable, maybe a mode in the agenda buffer?
1411 (defcustom org-agenda-todo-list-sublevels t
1412 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1413 When nil, the sublevels of a TODO entry are not checked, resulting in
1414 potentially much shorter TODO lists."
1415 :group 'org-agenda
1416 :group 'org-todo
1417 :type 'boolean)
1418
1419 (defcustom org-agenda-todo-ignore-scheduled nil
1420 "Non-nil means, don't show scheduled entries in the global todo list.
1421 The idea behind this is that by scheduling it, you have already taken care
1422 of this item."
1423 :group 'org-agenda
1424 :group 'org-todo
1425 :type 'boolean)
1426
1427 (defcustom org-agenda-include-all-todo nil
1428 "Non-nil means, the agenda will always contain all TODO entries.
1429 When nil, date-less entries will only be shown if `org-agenda' is called
1430 with a prefix argument.
1431 When non-nil, the TODO entries will be listed at the top of the agenda, before
1432 the entries for specific days."
1433 :group 'org-agenda
1434 :type 'boolean)
1435
1436 (defcustom org-agenda-include-diary nil
1437 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1438 :group 'org-agenda
1439 :type 'boolean)
1440
1441 (defcustom org-calendar-to-agenda-key [?c]
1442 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1443 The command `org-calendar-goto-agenda' will be bound to this key. The
1444 default is the character `c' because then `c' can be used to switch back and
1445 forth between agenda and calendar."
1446 :group 'org-agenda
1447 :type 'sexp)
1448
1449 (defgroup org-agenda-setup nil
1450 "Options concerning setting up the Agenda window in Org Mode."
1451 :tag "Org Agenda Window Setup"
1452 :group 'org-agenda)
1453
1454 (defcustom org-agenda-mouse-1-follows-link nil
1455 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1456 A longer mouse click will still set point. Does not wortk on XEmacs.
1457 Needs to be set before org.el is loaded."
1458 :group 'org-agenda-setup
1459 :type 'boolean)
1460
1461 (defcustom org-agenda-start-with-follow-mode nil
1462 "The initial value of follwo-mode in a newly created agenda window."
1463 :group 'org-agenda-setup
1464 :type 'boolean)
1465
1466 (defcustom org-select-timeline-window t
1467 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1468 When nil, cursor will remain in the current window."
1469 :group 'org-agenda-setup
1470 :type 'boolean)
1471
1472 (defcustom org-select-agenda-window t
1473 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1474 When nil, cursor will remain in the current window."
1475 :group 'org-agenda-setup
1476 :type 'boolean)
1477
1478 (defcustom org-fit-agenda-window t
1479 "Non-nil means, change window size of agenda to fit content."
1480 :group 'org-agenda-setup
1481 :type 'boolean)
1482
1483 (defgroup org-agenda-display nil
1484 "Options concerning what to display initially in Agenda."
1485 :tag "Org Agenda Display"
1486 :group 'org-agenda)
1487
1488 (defcustom org-agenda-show-all-dates t
1489 "Non-nil means, `org-agenda' shows every day in the selected range.
1490 When nil, only the days which actually have entries are shown."
1491 :group 'org-agenda-display
1492 :type 'boolean)
1493
1494 (defcustom org-agenda-start-on-weekday 1
1495 "Non-nil means, start the overview always on the specified weekday.
1496 0 denotes Sunday, 1 denotes Monday etc.
1497 When nil, always start on the current day."
1498 :group 'org-agenda-display
1499 :type '(choice (const :tag "Today" nil)
1500 (number :tag "Weekday No.")))
1501
1502 (defcustom org-agenda-ndays 7
1503 "Number of days to include in overview display.
1504 Should be 1 or 7."
1505 :group 'org-agenda-display
1506 :type 'number)
1507
1508 (defcustom org-agenda-use-time-grid t
1509 "Non-nil means, show a time grid in the agenda schedule.
1510 A time grid is a set of lines for specific times (like every two hours between
1511 8:00 and 20:00). The items scheduled for a day at specific times are
1512 sorted in between these lines.
1513 For details about when the grid will be shown, and what it will look like, see
1514 the variable `org-agenda-time-grid'."
1515 :group 'org-agenda-display
1516 :type 'boolean)
1517
1518 (defcustom org-agenda-time-grid
1519 '((daily today require-timed)
1520 "----------------"
1521 (800 1000 1200 1400 1600 1800 2000))
1522
1523 "The settings for time grid for agenda display.
1524 This is a list of three items. The first item is again a list. It contains
1525 symbols specifying conditions when the grid should be displayed:
1526
1527 daily if the agenda shows a single day
1528 weekly if the agenda shows an entire week
1529 today show grid on current date, independent of daily/weekly display
1530 require-timed show grid only if at least on item has a time specification
1531
1532 The second item is a string which will be places behing the grid time.
1533
1534 The third item is a list of integers, indicating the times that should have
1535 a grid line."
1536 :group 'org-agenda-display
1537 :type
1538 '(list
1539 (set :greedy t :tag "Grid Display Options"
1540 (const :tag "Show grid in single day agenda display" daily)
1541 (const :tag "Show grid in weekly agenda display" weekly)
1542 (const :tag "Always show grid for today" today)
1543 (const :tag "Show grid only if any timed entries are present"
1544 require-timed)
1545 (const :tag "Skip grid times already present in an entry"
1546 remove-match))
1547 (string :tag "Grid String")
1548 (repeat :tag "Grid Times" (integer :tag "Time"))))
1549
1550 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1551 "Sorting structure for the agenda items of a single day.
1552 This is a list of symbols which will be used in sequence to determine
1553 if an entry should be listed before another entry. The following
1554 symbols are recognized:
1555
1556 time-up Put entries with time-of-day indications first, early first
1557 time-down Put entries with time-of-day indications first, late first
1558 category-keep Keep the default order of categories, corresponding to the
1559 sequence in `org-agenda-files'.
1560 category-up Sort alphabetically by category, A-Z.
1561 category-down Sort alphabetically by category, Z-A.
1562 priority-up Sort numerically by priority, high priority last.
1563 priority-down Sort numerically by priority, high priority first.
1564
1565 The different possibilities will be tried in sequence, and testing stops
1566 if one comparison returns a \"not-equal\". For example, the default
1567 '(time-up category-keep priority-down)
1568 means: Pull out all entries having a specified time of day and sort them,
1569 in order to make a time schedule for the current day the first thing in the
1570 agenda listing for the day. Of the entries without a time indication, keep
1571 the grouped in categories, don't sort the categories, but keep them in
1572 the sequence given in `org-agenda-files'. Within each category sort by
1573 priority.
1574
1575 Leaving out `category-keep' would mean that items will be sorted across
1576 categories by priority."
1577 :group 'org-agenda-display
1578 :type '(repeat
1579 (choice
1580 (const time-up)
1581 (const time-down)
1582 (const category-keep)
1583 (const category-up)
1584 (const category-down)
1585 (const priority-up)
1586 (const priority-down))))
1587
1588 (defcustom org-sort-agenda-notime-is-late t
1589 "Non-nil means, items without time are considered late.
1590 This is only relevant for sorting. When t, items which have no explicit
1591 time like 15:30 will be considered as 24:01, i.e. later than any items which
1592 do have a time. When nil, the default time is before 0:00. You can use this
1593 option to decide if the schedule for today should come before or after timeless
1594 agenda entries."
1595 :group 'org-agenda-display
1596 :type 'boolean)
1597
1598
1599 (defgroup org-agenda-prefix nil
1600 "Options concerning the entry prefix in the Org-mode agenda display."
1601 :tag "Org Agenda Prefix"
1602 :group 'org-agenda)
1603
1604 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1605 "Format specification for the prefix of items in the agenda buffer.
1606 This format works similar to a printf format, with the following meaning:
1607
1608 %c the category of the item, \"Diary\" for entries from the diary, or
1609 as given by the CATEGORY keyword or derived from the file name.
1610 %T the first tag of the item.
1611 %t the time-of-day specification if one applies to the entry, in the
1612 format HH:MM
1613 %s Scheduling/Deadline information, a short string
1614
1615 All specifiers work basically like the standard `%s' of printf, but may
1616 contain two additional characters: A question mark just after the `%' and
1617 a whitespace/punctuation character just before the final letter.
1618
1619 If the first character after `%' is a question mark, the entire field
1620 will only be included if the corresponding value applies to the
1621 current entry. This is useful for fields which should have fixed
1622 width when present, but zero width when absent. For example,
1623 \"%?-12t\" will result in a 12 character time field if a time of the
1624 day is specified, but will completely disappear in entries which do
1625 not contain a time.
1626
1627 If there is punctuation or whitespace character just before the final
1628 format letter, this character will be appended to the field value if
1629 the value is not empty. For example, the format \"%-12:c\" leads to
1630 \"Diary: \" if the category is \"Diary\". If the category were be
1631 empty, no additional colon would be interted.
1632
1633 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1634 - Indent the line with two space characters
1635 - Give the category in a 12 chars wide field, padded with whitespace on
1636 the right (because of `-'). Append a colon if there is a category
1637 (because of `:').
1638 - If there is a time-of-day, put it into a 12 chars wide field. If no
1639 time, don't put in an empty field, just skip it (because of '?').
1640 - Finally, put the scheduling information and append a whitespace.
1641
1642 As another example, if you don't want the time-of-day of entries in
1643 the prefix, you could use:
1644
1645 (setq org-agenda-prefix-format \" %-11:c% s\")
1646
1647 See also the variables `org-agenda-remove-times-when-in-prefix' and
1648 `org-agenda-remove-tags-when-in-prefix'."
1649 :type 'string
1650 :group 'org-agenda-prefix)
1651
1652 (defcustom org-timeline-prefix-format " % s"
1653 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1654 :type 'string
1655 :group 'org-agenda-prefix)
1656
1657 (defvar org-prefix-format-compiled nil
1658 "The compiled version of the most recently used prefix format.
1659 Depending on which command was used last, this may be the compiled version
1660 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1661
1662 ;; FIXME: There seem to be situations where this does not work.
1663 (defcustom org-agenda-remove-times-when-in-prefix t
1664 "Non-nil means, remove duplicate time specifications in agenda items.
1665 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1666 time-of-day specification in a headline or diary entry is extracted and
1667 placed into the prefix. If this option is non-nil, the original specification
1668 \(a timestamp or -range, or just a plain time(range) specification like
1669 11:30-4pm) will be removed for agenda display. This makes the agenda less
1670 cluttered.
1671 The option can be t or nil. It may also be the symbol `beg', indicating
1672 that the time should only be removed what it is located at the beginning of
1673 the headline/diary entry."
1674 :group 'org-agenda-prefix
1675 :type '(choice
1676 (const :tag "Always" t)
1677 (const :tag "Never" nil)
1678 (const :tag "When at beginning of entry" beg)))
1679
1680 (defcustom org-agenda-remove-tags-when-in-prefix nil
1681 "Non-nil means, remove the tags from the headline copy in the agenda.
1682 When this is the symbol `prefix', only remove tags when
1683 `org-agenda-prefix-format' contains a `%T' specifier."
1684 :group 'org-agenda-prefix
1685 :type '(choice
1686 (const :tag "Always" t)
1687 (const :tag "Never" nil)
1688 (const :tag "When prefix format contains %T" prefix)))
1689
1690 (defgroup org-export nil
1691 "Options for exporting org-listings."
1692 :tag "Org Export"
1693 :group 'org)
1694
1695 (defgroup org-export-general nil
1696 "General options for exporting Org-mode files."
1697 :tag "Org Export General"
1698 :group 'org-export)
1699
1700 (defcustom org-export-publishing-directory "."
1701 "Path to the location where exported files should be located.
1702 This path may be relative to the directory where the Org-mode file lives.
1703 The default is to put them into the same directory as the Org-mode file.
1704 The variable may also be an alist with export types `:html', `:ascii',
1705 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
1706 is relative, it is interpreted relative to the directory where the exported
1707 Org-mode files lives."
1708 :group 'org-export-general
1709 :type '(choice
1710 (directory)
1711 (repeat
1712 (cons
1713 (choice :tag "Type"
1714 (const :html) (const :ascii) (const :ical) (const :xoxo))
1715 (directory)))))
1716
1717 (defcustom org-export-language-setup
1718 '(("en" "Author" "Date" "Table of Contents")
1719 ("da" "Ophavsmand" "Dato" "Indhold")
1720 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1721 ("es" "Autor" "Fecha" "\xccndice")
1722 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1723 ("it" "Autore" "Data" "Indice")
1724 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1725 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1726 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1727 "Terms used in export text, translated to different languages.
1728 Use the variable `org-export-default-language' to set the language,
1729 or use the +OPTION lines for a per-file setting."
1730 :group 'org-export-general
1731 :type '(repeat
1732 (list
1733 (string :tag "HTML language tag")
1734 (string :tag "Author")
1735 (string :tag "Date")
1736 (string :tag "Table of Contents"))))
1737
1738 (defcustom org-export-default-language "en"
1739 "The default language of HTML export, as a string.
1740 This should have an association in `org-export-language-setup'."
1741 :group 'org-export-general
1742 :type 'string)
1743
1744 (defcustom org-export-headline-levels 3
1745 "The last level which is still exported as a headline.
1746 Inferior levels will produce itemize lists when exported.
1747 Note that a numeric prefix argument to an exporter function overrides
1748 this setting.
1749
1750 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1751 :group 'org-export-general
1752 :type 'number)
1753
1754 (defcustom org-export-with-section-numbers t
1755 "Non-nil means, add section numbers to headlines when exporting.
1756
1757 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1758 :group 'org-export-general
1759 :type 'boolean)
1760
1761 (defcustom org-export-with-toc t
1762 "Non-nil means, create a table of contents in exported files.
1763 The TOC contains headlines with levels up to`org-export-headline-levels'.
1764
1765 Headlines which contain any TODO items will be marked with \"(*)\" in
1766 ASCII export, and with red color in HTML output.
1767
1768 In HTML output, the TOC will be clickable.
1769
1770 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1771 :group 'org-export-general
1772 :type 'boolean)
1773
1774 (defcustom org-export-mark-todo-in-toc nil
1775 "Non-nil means, mark TOC lines that contain any open TODO items."
1776 :group 'org-export-general
1777 :type 'boolean)
1778
1779 (defcustom org-export-preserve-breaks nil
1780 "Non-nil means, preserve all line breaks when exporting.
1781 Normally, in HTML output paragraphs will be reformatted. In ASCII
1782 export, line breaks will always be preserved, regardless of this variable.
1783
1784 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1785 :group 'org-export-general
1786 :type 'boolean)
1787
1788 (defcustom org-export-with-timestamps t
1789 "Nil means, do not export time stamps and associated keywords."
1790 :group 'org-export
1791 :type 'boolean)
1792
1793 (defcustom org-export-with-tags t
1794 "Nil means, do not export tags, just remove them from headlines."
1795 :group 'org-export-general
1796 :type 'boolean)
1797
1798 (defcustom org-export-with-timestamps t
1799 "Nil means, do not export timestamps and associated keywords."
1800 :group 'org-export-general
1801 :type 'boolean)
1802
1803 (defgroup org-export-translation nil
1804 "Options for translating special ascii sequences for the export backends."
1805 :tag "Org Export Translation"
1806 :group 'org-export)
1807
1808 (defcustom org-export-with-emphasize t
1809 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1810 If the export target supports emphasizing text, the word will be
1811 typeset in bold, italic, or underlined, respectively. Works only for
1812 single words, but you can say: I *really* *mean* *this*.
1813 Not all export backends support this.
1814
1815 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1816 :group 'org-export-translation
1817 :type 'boolean)
1818
1819 (defcustom org-export-with-sub-superscripts t
1820 "Non-nil means, interpret \"_\" and \"^\" for export.
1821 When this option is turned on, you can use TeX-like syntax for sub- and
1822 superscripts. Several characters after \"_\" or \"^\" will be
1823 considered as a single item - so grouping with {} is normally not
1824 needed. For example, the following things will be parsed as single
1825 sub- or superscripts.
1826
1827 10^24 or 10^tau several digits will be considered 1 item.
1828 10^-12 or 10^-tau a leading sign with digits or a word
1829 x^2-y^3 will be read as x^2 - y^3, because items are
1830 terminated by almost any nonword/nondigit char.
1831 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1832
1833 Still, ambiguity is possible - so when in doubt use {} to enclose the
1834 sub/superscript.
1835 Not all export backends support this, but HTML does.
1836
1837 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1838 :group 'org-export-translation
1839 :type 'boolean)
1840
1841 (defcustom org-export-with-TeX-macros t
1842 "Non-nil means, interpret simple TeX-like macros when exporting.
1843 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1844 No only real TeX macros will work here, but the standard HTML entities
1845 for math can be used as macro names as well. For a list of supported
1846 names in HTML export, see the constant `org-html-entities'.
1847 Not all export backends support this.
1848
1849 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1850 :group 'org-export-translation
1851 :type 'boolean)
1852
1853 (defcustom org-export-with-fixed-width t
1854 "Non-nil means, lines starting with \":\" will be in fixed width font.
1855 This can be used to have pre-formatted text, fragments of code etc. For
1856 example:
1857 : ;; Some Lisp examples
1858 : (while (defc cnt)
1859 : (ding))
1860 will be looking just like this in also HTML. See also the QUOTE keyword.
1861 Not all export backends support this.
1862
1863 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1864 :group 'org-export-translation
1865 :type 'boolean)
1866
1867 (defcustom org-match-sexp-depth 3
1868 "Number of stacked braces for sub/superscript matching.
1869 This has to be set before loading org.el to be effective."
1870 :group 'org-export-translation
1871 :type 'integer)
1872
1873 (defgroup org-export-tables nil
1874 "Options for exporting tables in Org-mode."
1875 :tag "Org Export Tables"
1876 :group 'org-export)
1877
1878 (defcustom org-export-with-tables t
1879 "If non-nil, lines starting with \"|\" define a table.
1880 For example:
1881
1882 | Name | Address | Birthday |
1883 |-------------+----------+-----------|
1884 | Arthur Dent | England | 29.2.2100 |
1885
1886 Not all export backends support this.
1887
1888 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1889 :group 'org-export-tables
1890 :type 'boolean)
1891
1892 (defcustom org-export-highlight-first-table-line t
1893 "Non-nil means, highlight the first table line.
1894 In HTML export, this means use <th> instead of <td>.
1895 In tables created with table.el, this applies to the first table line.
1896 In Org-mode tables, all lines before the first horizontal separator
1897 line will be formatted with <th> tags."
1898 :group 'org-export-tables
1899 :type 'boolean)
1900
1901 (defcustom org-export-table-remove-special-lines t
1902 "Remove special lines and marking characters in calculating tables.
1903 This removes the special marking character column from tables that are set
1904 up for spreadsheet calculations. It also removes the entire lines
1905 marked with `!', `_', or `^'. The lines with `$' are kept, because
1906 the values of constants may be useful to have."
1907 :group 'org-export-tables
1908 :type 'boolean)
1909
1910 (defcustom org-export-prefer-native-exporter-for-tables nil
1911 "Non-nil means, always export tables created with table.el natively.
1912 Natively means, use the HTML code generator in table.el.
1913 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1914 the table does not use row- or column-spanning). This has the
1915 advantage, that the automatic HTML conversions for math symbols and
1916 sub/superscripts can be applied. Org-mode's HTML generator is also
1917 much faster."
1918 :group 'org-export-tables
1919 :type 'boolean)
1920
1921 (defgroup org-export-ascii nil
1922 "Options specific for ASCII export of Org-mode files."
1923 :tag "Org Export ASCII"
1924 :group 'org-export)
1925
1926 (defcustom org-export-ascii-show-new-buffer t
1927 "Non-nil means, popup buffer containing the exported ASCII text.
1928 Otherwise the buffer will just be saved to a file and stay hidden."
1929 :group 'org-export-ascii
1930 :type 'boolean)
1931
1932 (defgroup org-export-xml nil
1933 "Options specific for XML export of Org-mode files."
1934 :tag "Org Export XML"
1935 :group 'org-export)
1936
1937 ;; FIXME: I am told XOXO is not XML, it is semantic-only HTML.
1938 (defcustom org-export-xml-type 'xoxo
1939 "The kind of XML to be produced by the XML exporter.
1940 Allowed values are:
1941 xoxo The XOXO exporter."
1942 :group 'org-export-xml
1943 :type '(choice
1944 (const :tag "XOXO" xoxo)))
1945
1946 (defgroup org-export-html nil
1947 "Options specific for HTML export of Org-mode files."
1948 :tag "Org Export HTML"
1949 :group 'org-export)
1950
1951 (defcustom org-export-html-style
1952 "<style type=\"text/css\">
1953 html {
1954 font-family: Times, serif;
1955 font-size: 12pt;
1956 }
1957 .title { text-align: center; }
1958 .todo { color: red; }
1959 .done { color: green; }
1960 .timestamp { color: grey }
1961 .timestamp-kwd { color: CadetBlue }
1962 .tag { background-color:lightblue; font-weight:normal }
1963 .target { background-color: lavender; }
1964 pre {
1965 border: 1pt solid #AEBDCC;
1966 background-color: #F3F5F7;
1967 padding: 5pt;
1968 font-family: courier, monospace;
1969 }
1970 table { border-collapse: collapse; }
1971 td, th {
1972 vertical-align: top;
1973 border: 1pt solid #ADB9CC;
1974 }
1975 </style>"
1976 "The default style specification for exported HTML files.
1977 Since there are different ways of setting style information, this variable
1978 needs to contain the full HTML structure to provide a style, including the
1979 surrounding HTML tags. The style specifications should include definitions
1980 for new classes todo, done, title, and deadline. For example, legal values
1981 would be:
1982
1983 <style type=\"text/css\">
1984 p { font-weight: normal; color: gray; }
1985 h1 { color: black; }
1986 .title { text-align: center; }
1987 .todo, .deadline { color: red; }
1988 .done { color: green; }
1989 </style>
1990
1991 or, if you want to keep the style in a file,
1992
1993 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1994
1995 As the value of this option simply gets inserted into the HTML <head> header,
1996 you can \"misuse\" it to add arbitrary text to the header."
1997 :group 'org-export-html
1998 :type 'string)
1999
2000 (defcustom org-export-html-link-org-files-as-html t
2001 "Non-nil means, make file links to `file.org' point to `file.html'.
2002 When org-mode is exporting an org-mode file to HTML, links to
2003 non-html files are directly put into a href tag in HTML.
2004 However, links to other Org-mode files (recognized by the
2005 extension `.org.) should become links to the corresponding html
2006 file, assuming that the linked org-mode file will also be
2007 converted to HTML.
2008 When nil, the links still point to the plain `.org' file."
2009 :group 'org-export-html
2010 :type 'boolean)
2011
2012 (defcustom org-export-html-inline-images 'maybe
2013 "Non-nil means, inline images into exported HTML pages.
2014 This is done using an <img> tag. When nil, an anchor with href is used to
2015 link to the image. If this option is `maybe', then images in links with
2016 an empty description will be inlined, while images with a description will
2017 be linked only."
2018 :group 'org-export-html
2019 :type '(choice (const :tag "Never" nil)
2020 (const :tag "Always" t)
2021 (const :tag "When there is no description" maybe)))
2022
2023 (defcustom org-export-html-expand t
2024 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2025 When nil, these tags will be exported as plain text and therefore
2026 not be interpreted by a browser.
2027
2028 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2029 :group 'org-export-html
2030 :type 'boolean)
2031
2032 (defcustom org-export-html-table-tag
2033 "<table border=1 cellspacing=0 cellpadding=6>"
2034 "The HTML tag used to start a table.
2035 This must be a <table> tag, but you may change the options like
2036 borders and spacing."
2037 :group 'org-export-html
2038 :type 'string)
2039
2040 (defcustom org-export-html-with-timestamp nil
2041 "If non-nil, write `org-export-html-html-helper-timestamp'
2042 into the exported HTML text. Otherwise, the buffer will just be saved
2043 to a file."
2044 :group 'org-export-html
2045 :type 'boolean)
2046
2047 (defcustom org-export-html-html-helper-timestamp
2048 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
2049 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2050 :group 'org-export-html
2051 :type 'string)
2052
2053 (defcustom org-export-html-show-new-buffer nil
2054 "Non-nil means, popup buffer containing the exported html text.
2055 Otherwise, the buffer will just be saved to a file and stay hidden."
2056 :group 'org-export-html
2057 :type 'boolean)
2058
2059 (defgroup org-export-icalendar nil
2060 "Options specific for iCalendar export of Org-mode files."
2061 :tag "Org Export iCalendar"
2062 :group 'org-export)
2063
2064 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2065 "The file name for the iCalendar file covering all agenda files.
2066 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2067 The file name should be absolute."
2068 :group 'org-export-icalendar
2069 :type 'file)
2070
2071 (defcustom org-icalendar-include-todo nil
2072 "Non-nil means, export to iCalendar files should also cover TODO items."
2073 :group 'org-export-icalendar
2074 :type 'boolean)
2075
2076 (defcustom org-icalendar-combined-name "OrgMode"
2077 "Calendar name for the combined iCalendar representing all agenda files."
2078 :group 'org-export-icalendar
2079 :type 'string)
2080
2081 (defgroup org-font-lock nil
2082 "Font-lock settings for highlighting in Org-mode."
2083 :tag "Org Font Lock"
2084 :group 'org)
2085
2086 (defcustom org-level-color-stars-only nil
2087 "Non-nil means fontify only the stars in each headline.
2088 When nil, the entire headline is fontified.
2089 Changing it requires restart of `font-lock-mode' to become effective
2090 also in regions already fontified."
2091 :group 'org-font-lock
2092 :type 'boolean)
2093
2094 (defcustom org-hide-leading-stars nil
2095 "Non-nil means, hide the first N-1 stars in a headline.
2096 This works by using the face `org-hide' for these stars. This
2097 face is white for a light background, and black for a dark
2098 background. You may have to customize the face `org-hide' to
2099 make this work.
2100 Changing it requires restart of `font-lock-mode' to become effective
2101 also in regions already fontified.
2102 You may also set this on a per-file basis by adding one of the following
2103 lines to the buffer:
2104
2105 #+STARTUP: hidestars
2106 #+STARTUP: showstars"
2107 :group 'org-font-lock
2108 :type 'boolean)
2109
2110 (defcustom org-fontify-done-headline nil
2111 "Non-nil means, change the face of a headline if it is marked DONE.
2112 Normally, only the TODO/DONE keyword indicates the state of a headline.
2113 When this is non-nil, the headline after the keyword is set to the
2114 `org-headline-done' as an additional indication."
2115 :group 'org-font-lock
2116 :type 'boolean)
2117
2118 (defcustom org-fontify-emphasized-text t
2119 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2120 Changing this variable requires a restart of Emacs to take effect."
2121 :group 'org-font-lock
2122 :type 'boolean)
2123
2124 (defgroup org-faces nil
2125 "Faces in Org-mode."
2126 :tag "Org Faces"
2127 :group 'org-font-lock)
2128
2129 (defun org-compatible-face (specs)
2130 "Make a compatible face specification.
2131 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2132 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2133 to the top of the list. The `min-colors' attribute will be removed from
2134 any other entries, and any resulting duplicates will be removed entirely."
2135 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2136 (let (r e a)
2137 (while (setq e (pop specs))
2138 (cond
2139 ((memq (car e) '(t default)) (push e r))
2140 ((setq a (member '(min-colors 8) (car e)))
2141 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2142 (cdr e)))))
2143 ((setq a (assq 'min-colors (car e)))
2144 (setq e (cons (delq a (car e)) (cdr e)))
2145 (or (assoc (car e) r) (push e r)))
2146 (t (or (assoc (car e) r) (push e r)))))
2147 (nreverse r))
2148 specs))
2149
2150 (defface org-hide
2151 '((((background light)) (:foreground "white"))
2152 (((background dark)) (:foreground "black")))
2153 "Face used to hide leading stars in headlines.
2154 The forground color of this face should be equal to the background
2155 color of the frame."
2156 :group 'org-faces)
2157
2158 (defface org-level-1 ;; font-lock-function-name-face
2159 (org-compatible-face
2160 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2161 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2162 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2163 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2164 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2165 (t (:bold t))))
2166 "Face used for level 1 headlines."
2167 :group 'org-faces)
2168
2169 (defface org-level-2 ;; font-lock-variable-name-face
2170 (org-compatible-face
2171 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2172 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2173 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2174 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2175 (t (:bold t))))
2176 "Face used for level 2 headlines."
2177 :group 'org-faces)
2178
2179 (defface org-level-3 ;; font-lock-keyword-face
2180 (org-compatible-face
2181 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2182 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2183 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2184 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2185 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2186 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2187 (t (:bold t))))
2188 "Face used for level 3 headlines."
2189 :group 'org-faces)
2190
2191 (defface org-level-4 ;; font-lock-comment-face
2192 (org-compatible-face
2193 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2194 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2195 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2196 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2197 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2198 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2199 (t (:bold t))))
2200 "Face used for level 4 headlines."
2201 :group 'org-faces)
2202
2203 (defface org-level-5 ;; font-lock-type-face
2204 (org-compatible-face
2205 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2206 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2207 (((class color) (min-colors 8)) (:foreground "green"))))
2208 "Face used for level 5 headlines."
2209 :group 'org-faces)
2210
2211 (defface org-level-6 ;; font-lock-constant-face
2212 (org-compatible-face
2213 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2214 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2215 (((class color) (min-colors 8)) (:foreground "magenta"))))
2216 "Face used for level 6 headlines."
2217 :group 'org-faces)
2218
2219 (defface org-level-7 ;; font-lock-builtin-face
2220 (org-compatible-face
2221 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2222 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2223 (((class color) (min-colors 8)) (:foreground "blue"))))
2224 "Face used for level 7 headlines."
2225 :group 'org-faces)
2226
2227 (defface org-level-8 ;; font-lock-string-face
2228 (org-compatible-face
2229 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2230 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2231 (((class color) (min-colors 8)) (:foreground "green"))))
2232 "Face used for level 8 headlines."
2233 :group 'org-faces)
2234
2235 (defface org-special-keyword ;; font-lock-string-face
2236 (org-compatible-face
2237 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2238 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2239 (t (:italic t))))
2240 "Face used for special keywords."
2241 :group 'org-faces)
2242
2243 (defface org-warning ;; font-lock-warning-face
2244 (org-compatible-face
2245 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2246 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2247 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2248 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2249 (t (:bold t))))
2250 "Face for deadlines and TODO keywords."
2251 :group 'org-faces)
2252
2253 (defface org-headline-done ;; font-lock-string-face
2254 (org-compatible-face
2255 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2256 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2257 (((class color) (min-colors 8) (background light)) (:bold nil))))
2258 "Face used to indicate that a headline is DONE.
2259 This face is only used if `org-fontify-done-headline' is set."
2260 :group 'org-faces)
2261
2262 (defface org-link
2263 '((((class color) (background light)) (:foreground "Purple" :underline t))
2264 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2265 (t (:underline t)))
2266 "Face for links."
2267 :group 'org-faces)
2268
2269 (defface org-date
2270 '((((class color) (background light)) (:foreground "Purple" :underline t))
2271 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2272 (t (:underline t)))
2273 "Face for links."
2274 :group 'org-faces)
2275
2276 (defface org-tag
2277 '((t (:bold t)))
2278 "Face for tags."
2279 :group 'org-faces)
2280
2281 (defface org-todo ;; font-lock-warning-face
2282 (org-compatible-face
2283 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2284 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2285 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2286 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2287 (t (:inverse-video t :bold t))))
2288 "Face for TODO keywords."
2289 :group 'org-faces)
2290
2291 (defface org-done ;; font-lock-type-face
2292 (org-compatible-face
2293 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2294 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2295 (((class color) (min-colors 8)) (:foreground "green"))
2296 (t (:bold t))))
2297 "Face used for DONE."
2298 :group 'org-faces)
2299
2300 (defface org-table ;; font-lock-function-name-face
2301 (org-compatible-face
2302 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2303 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2304 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2305 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2306 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2307 (((class color) (min-colors 8) (background dark)))))
2308 "Face used for tables."
2309 :group 'org-faces)
2310
2311 (defface org-formula
2312 (org-compatible-face
2313 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2314 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2315 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2316 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2317 (t (:bold t :italic t))))
2318 "Face for formulas."
2319 :group 'org-faces)
2320
2321 (defface org-scheduled-today
2322 (org-compatible-face
2323 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2324 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2325 (((class color) (min-colors 8)) (:foreground "green"))
2326 (t (:bold t :italic t))))
2327 "Face for items scheduled for a certain day."
2328 :group 'org-faces)
2329
2330 (defface org-scheduled-previously
2331 (org-compatible-face
2332 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2333 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2334 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2335 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2336 (t (:bold t))))
2337 "Face for items scheduled previously, and not yet done."
2338 :group 'org-faces)
2339
2340 (defface org-time-grid ;; font-lock-variable-name-face
2341 (org-compatible-face
2342 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2343 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2344 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2345 "Face used for time grids."
2346 :group 'org-faces)
2347
2348 (defconst org-level-faces
2349 '(org-level-1 org-level-2 org-level-3 org-level-4
2350 org-level-5 org-level-6 org-level-7 org-level-8
2351 ))
2352 (defconst org-n-levels (length org-level-faces))
2353
2354 (defconst org-bold-re
2355 (if (featurep 'xemacs)
2356 "\\([ ]\\|^\\)\\(\\*\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)\\*\\)\\([ ,.]\\|$\\)"
2357 "\\([ ]\\|^\\)\\(\\*\\(\\w[[:word:] -_]*?\\w\\)\\*\\)\\([ ,.]\\|$\\)")
2358 "Regular expression for bold emphasis.")
2359 (defconst org-italic-re
2360 (if (featurep 'xemacs)
2361 "\\([ ]\\|^\\)\\(/\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)/\\)\\([ ,.]\\|$\\)"
2362 "\\([ ]\\|^\\)\\(/\\(\\w[[:word:] -_]*?\\w\\)/\\)\\([ ,.]\\|$\\)")
2363 "Regular expression for italic emphasis.")
2364 (defconst org-underline-re
2365 (if (featurep 'xemacs)
2366 "\\([ ]\\|^\\)\\(_\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)_\\)\\([ ,.]\\|$\\)"
2367 "\\([ ]\\|^\\)\\(_\\(\\w[[:word:] -_]*?\\w\\)_\\)\\([ ,.]\\|$\\)")
2368 "Regular expression for underline emphasis.")
2369
2370 ;; Variables for pre-computed regular expressions, all buffer local
2371 (defvar org-done-string nil
2372 "The last string in `org-todo-keywords', indicating an item is DONE.")
2373 (make-variable-buffer-local 'org-done-string)
2374 (defvar org-todo-regexp nil
2375 "Matches any of the TODO state keywords.")
2376 (make-variable-buffer-local 'org-todo-regexp)
2377 (defvar org-not-done-regexp nil
2378 "Matches any of the TODO state keywords except the last one.")
2379 (make-variable-buffer-local 'org-not-done-regexp)
2380 (defvar org-todo-line-regexp nil
2381 "Matches a headline and puts TODO state into group 2 if present.")
2382 (make-variable-buffer-local 'org-todo-line-regexp)
2383 (defvar org-nl-done-regexp nil
2384 "Matches newline followed by a headline with the DONE keyword.")
2385 (make-variable-buffer-local 'org-nl-done-regexp)
2386 (defvar org-looking-at-done-regexp nil
2387 "Matches the DONE keyword a point.")
2388 (make-variable-buffer-local 'org-looking-at-done-regexp)
2389 (defvar org-todo-kwd-priority-p nil
2390 "Do TODO items have priorities?")
2391 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2392 (defvar org-todo-kwd-max-priority nil
2393 "Maximum priority of TODO items.")
2394 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2395 (defvar org-ds-keyword-length 12
2396 "Maximum length of the Deadline and SCHEDULED keywords.")
2397 (make-variable-buffer-local 'org-ds-keyword-length)
2398 (defvar org-deadline-regexp nil
2399 "Matches the DEADLINE keyword.")
2400 (make-variable-buffer-local 'org-deadline-regexp)
2401 (defvar org-deadline-time-regexp nil
2402 "Matches the DEADLINE keyword together with a time stamp.")
2403 (make-variable-buffer-local 'org-deadline-time-regexp)
2404 (defvar org-deadline-line-regexp nil
2405 "Matches the DEADLINE keyword and the rest of the line.")
2406 (make-variable-buffer-local 'org-deadline-line-regexp)
2407 (defvar org-scheduled-regexp nil
2408 "Matches the SCHEDULED keyword.")
2409 (make-variable-buffer-local 'org-scheduled-regexp)
2410 (defvar org-scheduled-time-regexp nil
2411 "Matches the SCHEDULED keyword together with a time stamp.")
2412 (make-variable-buffer-local 'org-scheduled-time-regexp)
2413 (defvar org-closed-time-regexp nil
2414 "Matches the CLOSED keyword together with a time stamp.")
2415 (make-variable-buffer-local 'org-closed-time-regexp)
2416
2417 (defvar org-keyword-time-regexp nil
2418 "Matches any of the 3 keywords, together with the time stamp.")
2419 (make-variable-buffer-local 'org-keyword-time-regexp)
2420 (defvar org-maybe-keyword-time-regexp nil
2421 "Matches a timestamp, possibly preceeded by a keyword.")
2422 (make-variable-buffer-local 'org-keyword-time-regexp)
2423
2424 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2425 mouse-map t)
2426 "Properties to remove when a string without properties is wanted.")
2427
2428 (defsubst org-match-string-no-properties (num &optional string)
2429 (if (featurep 'xemacs)
2430 (let ((s (match-string num string)))
2431 (remove-text-properties 0 (length s) org-rm-props s)
2432 s)
2433 (match-string-no-properties num string)))
2434
2435 (defsubst org-no-properties (s)
2436 (remove-text-properties 0 (length s) org-rm-props s)
2437 s)
2438
2439 (defun org-set-regexps-and-options ()
2440 "Precompute regular expressions for current buffer."
2441 (when (eq major-mode 'org-mode)
2442 (let ((re (org-make-options-regexp
2443 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2444 "STARTUP" "ARCHIVE" "TAGS")))
2445 (splitre "[ \t]+")
2446 kwds int key value cat arch tags)
2447 (save-excursion
2448 (save-restriction
2449 (widen)
2450 (goto-char (point-min))
2451 (while (re-search-forward re nil t)
2452 (setq key (match-string 1) value (org-match-string-no-properties 2))
2453 (cond
2454 ((equal key "CATEGORY")
2455 (if (string-match "[ \t]+$" value)
2456 (setq value (replace-match "" t t value)))
2457 (setq cat (intern value)))
2458 ((equal key "SEQ_TODO")
2459 (setq int 'sequence
2460 kwds (append kwds (org-split-string value splitre))))
2461 ((equal key "PRI_TODO")
2462 (setq int 'priority
2463 kwds (append kwds (org-split-string value splitre))))
2464 ((equal key "TYP_TODO")
2465 (setq int 'type
2466 kwds (append kwds (org-split-string value splitre))))
2467 ((equal key "TAGS")
2468 (setq tags (append tags (org-split-string value splitre))))
2469 ((equal key "STARTUP")
2470 (let ((opts (org-split-string value splitre))
2471 (set '(("fold" org-startup-folded t)
2472 ("overview" org-startup-folded t)
2473 ("nofold" org-startup-folded nil)
2474 ("showall" org-startup-folded nil)
2475 ("content" org-startup-folded content)
2476 ("hidestars" org-hide-leading-stars t)
2477 ("showstars" org-hide-leading-stars nil)
2478 ("odd" org-odd-levels-only t)
2479 ("oddeven" org-odd-levels-only nil)
2480 ("align" org-startup-align-all-tables t)
2481 ("noalign" org-startup-align-all-tables nil)
2482 ("logging" org-log-done t)
2483 ("nologging" org-log-done nil)
2484 ("dlcheck" org-startup-with-deadline-check t)
2485 ("nodlcheck" org-startup-with-deadline-check nil)))
2486 l var val)
2487 (while (setq l (assoc (pop opts) set))
2488 (setq var (nth 1 l) val (nth 2 l))
2489 (set (make-local-variable var) val))))
2490 ((equal key "ARCHIVE")
2491 (string-match " *$" value)
2492 (setq arch (replace-match "" t t value))
2493 (remove-text-properties 0 (length arch)
2494 '(face t fontified t) arch)))
2495 )))
2496 (and cat (set (make-local-variable 'org-category) cat))
2497 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2498 (and arch (set (make-local-variable 'org-archive-location) arch))
2499 (and int (set (make-local-variable 'org-todo-interpretation) int))
2500 (when tags
2501 (let (e tg c tgs)
2502 (while (setq e (pop tags))
2503 (if (string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
2504 (push (cons (match-string 1 e)
2505 (string-to-char (match-string 2 e)))
2506 tgs)
2507 (push (list e) tgs)))
2508 (set (make-local-variable 'org-tag-alist) nil)
2509 (while (setq e (pop tgs))
2510 (or (assoc (car e) org-tag-alist)
2511 (push e org-tag-alist))))))
2512
2513 ;; Compute the regular expressions and other local variables
2514 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2515 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2516 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2517 (length org-scheduled-string)))
2518 org-done-string
2519 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2520 org-todo-regexp
2521 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2522 "\\|") "\\)\\>")
2523 org-not-done-regexp
2524 (concat "\\<\\("
2525 (mapconcat 'regexp-quote
2526 (nreverse (cdr (reverse org-todo-keywords)))
2527 "\\|")
2528 "\\)\\>")
2529 org-todo-line-regexp
2530 (concat "^\\(\\*+\\)[ \t]*\\("
2531 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2532 "\\)? *\\(.*\\)")
2533 org-nl-done-regexp
2534 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2535 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2536 org-deadline-regexp (concat "\\<" org-deadline-string)
2537 org-deadline-time-regexp
2538 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2539 org-deadline-line-regexp
2540 (concat "\\<\\(" org-deadline-string "\\).*")
2541 org-scheduled-regexp
2542 (concat "\\<" org-scheduled-string)
2543 org-scheduled-time-regexp
2544 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2545 org-closed-time-regexp
2546 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2547 org-keyword-time-regexp
2548 (concat "\\<\\(" org-scheduled-string
2549 "\\|" org-deadline-string
2550 "\\|" org-closed-string "\\)"
2551 " *[[<]\\([^]>]+\\)[]>]") ;; FIXME: is this correct?
2552 org-maybe-keyword-time-regexp
2553 (concat "\\(\\<\\(" org-scheduled-string
2554 "\\|" org-deadline-string
2555 "\\|" org-closed-string "\\)\\)?"
2556 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)")) ;; FIXME: is this correct?
2557
2558 (org-set-font-lock-defaults)))
2559
2560 ;; Tell the compiler about dynamically scoped variables,
2561 ;; and variables from other packages
2562 (defvar zmacs-regions) ; XEmacs regions
2563 (defvar original-date) ; dynamically scoped in calendar
2564 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2565 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2566 (defvar org-html-entities) ; defined later in this file
2567 (defvar org-goto-start-pos) ; dynamically scoped parameter
2568 (defvar org-time-was-given) ; dynamically scoped parameter
2569 (defvar org-ts-what) ; dynamically scoped parameter
2570 (defvar mark-active) ; Emacs only, not available in XEmacs.
2571 (defvar timecnt) ; dynamically scoped parameter
2572 (defvar levels-open) ; dynamically scoped parameter
2573 (defvar entry) ; dynamically scoped parameter
2574 (defvar date) ; dynamically scoped parameter
2575 (defvar description) ; dynamically scoped parameter
2576 (defvar ans1) ; dynamically scoped parameter
2577 (defvar ans2) ; dynamically scoped parameter
2578 (defvar starting-day) ; local variable
2579 (defvar include-all-loc) ; local variable
2580 (defvar vm-message-pointer) ; from vm
2581 (defvar vm-folder-directory) ; from vm
2582 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2583 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2584 (defvar gnus-group-name) ; from gnus
2585 (defvar gnus-article-current) ; from gnus
2586 (defvar w3m-current-url) ; from w3m
2587 (defvar mh-progs) ; from MH-E
2588 (defvar mh-current-folder) ; from MH-E
2589 (defvar mh-show-folder-buffer) ; from MH-E
2590 (defvar mh-index-folder) ; from MH-E
2591 (defvar mh-searcher) ; from MH-E
2592 (defvar org-selected-point) ; dynamically scoped parameter
2593 (defvar calendar-mode-map) ; from calendar.el
2594 (defvar last-arg) ; local variable
2595 (defvar remember-save-after-remembering) ; from remember.el
2596 (defvar remember-data-file) ; from remember.el
2597 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2598 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2599 (defvar orgtbl-mode) ; defined later in this file
2600 (defvar Info-current-file) ; from info.el
2601 (defvar Info-current-node) ; from info.el
2602
2603 ;;; Define the mode
2604
2605 (defvar org-mode-map
2606 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2607 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or ugrade to newer allout, for example by switching to Emacs 22.")
2608 (copy-keymap outline-mode-map))
2609 "Keymap for Org-mode.")
2610
2611 (defvar org-struct-menu) ; defined later in this file
2612 (defvar org-org-menu) ; defined later in this file
2613 (defvar org-tbl-menu) ; defined later in this file
2614
2615 ;; We use a before-change function to check if a table might need
2616 ;; an update.
2617 (defvar org-table-may-need-update t
2618 "Indicates that a table might need an update.
2619 This variable is set by `org-before-change-function'.
2620 `org-table-align' sets it back to nil.")
2621 (defvar org-mode-hook nil)
2622 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2623 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2624
2625
2626 ;;;###autoload
2627 (define-derived-mode org-mode outline-mode "Org"
2628 "Outline-based notes management and organizer, alias
2629 \"Carsten's outline-mode for keeping track of everything.\"
2630
2631 Org-mode develops organizational tasks around a NOTES file which
2632 contains information about projects as plain text. Org-mode is
2633 implemented on top of outline-mode, which is ideal to keep the content
2634 of large files well structured. It supports ToDo items, deadlines and
2635 time stamps, which magically appear in the diary listing of the Emacs
2636 calendar. Tables are easily created with a built-in table editor.
2637 Plain text URL-like links connect to websites, emails (VM), Usenet
2638 messages (Gnus), BBDB entries, and any files related to the project.
2639 For printing and sharing of notes, an Org-mode file (or a part of it)
2640 can be exported as a structured ASCII or HTML file.
2641
2642 The following commands are available:
2643
2644 \\{org-mode-map}"
2645
2646 ;; Get rid of Outline menus, they are not needed
2647 ;; Need to do this here because define-derived-mode sets up
2648 ;; the keymap so late.
2649 (if (featurep 'xemacs)
2650 (if org-noutline-p
2651 (progn
2652 (easy-menu-remove outline-mode-menu-heading)
2653 (easy-menu-remove outline-mode-menu-show)
2654 (easy-menu-remove outline-mode-menu-hide))
2655 (delete-menu-item '("Headings"))
2656 (delete-menu-item '("Show"))
2657 (delete-menu-item '("Hide"))
2658 (set-menubar-dirty-flag))
2659 (define-key org-mode-map [menu-bar headings] 'undefined)
2660 (define-key org-mode-map [menu-bar hide] 'undefined)
2661 (define-key org-mode-map [menu-bar show] 'undefined))
2662
2663 (easy-menu-add org-org-menu)
2664 (easy-menu-add org-tbl-menu)
2665 (org-install-agenda-files-menu)
2666 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2667 (org-add-to-invisibility-spec '(org-cwidth))
2668 (when (featurep 'xemacs)
2669 (set (make-local-variable 'line-move-ignore-invisible) t))
2670 (setq outline-regexp "\\*+")
2671 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2672 (setq outline-level 'org-outline-level)
2673 (when (and org-ellipsis (stringp org-ellipsis))
2674 (unless org-display-table
2675 (setq org-display-table (make-display-table)))
2676 (set-display-table-slot org-display-table
2677 4 (string-to-vector org-ellipsis))
2678 (setq buffer-display-table org-display-table))
2679 (org-set-regexps-and-options)
2680 (if org-startup-truncated (setq truncate-lines t))
2681 (set (make-local-variable 'font-lock-unfontify-region-function)
2682 'org-unfontify-region)
2683 ;; Activate before-change-function
2684 (set (make-local-variable 'org-table-may-need-update) t)
2685 (org-add-hook 'before-change-functions 'org-before-change-function nil
2686 'local)
2687 ;; Paragraphs and auto-filling
2688 (org-set-autofill-regexps)
2689 (org-update-radio-target-regexp)
2690 ;; Settings for Calc embedded mode
2691 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2692 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2693 (if (and org-insert-mode-line-in-empty-file
2694 (interactive-p)
2695 (= (point-min) (point-max)))
2696 (insert " -*- mode: org -*-\n\n"))
2697
2698 (unless org-inhibit-startup
2699 (if org-startup-align-all-tables
2700 (org-table-map-tables 'org-table-align))
2701 (if org-startup-with-deadline-check
2702 (call-interactively 'org-check-deadlines)
2703 (cond
2704 ((eq org-startup-folded t)
2705 (org-cycle '(4)))
2706 ((eq org-startup-folded 'content)
2707 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2708 (org-cycle '(4)) (org-cycle '(4))))))))
2709
2710 (defsubst org-call-with-arg (command arg)
2711 "Call COMMAND interactively, but pretend prefix are was ARG."
2712 (let ((current-prefix-arg arg)) (call-interactively command)))
2713
2714 (defsubst org-current-line (&optional pos)
2715 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2716
2717 (defun org-current-time ()
2718 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2719 (if (> org-time-stamp-rounding-minutes 0)
2720 (let ((r org-time-stamp-rounding-minutes)
2721 (time (decode-time)))
2722 (apply 'encode-time
2723 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2724 (nthcdr 2 time))))
2725 (current-time)))
2726
2727 (defun org-add-props (string plist &rest props)
2728 "Add text properties to entire string, from beginning to end.
2729 PLIST may be a list of properties, PROPS are individual properties and values
2730 that will be added to PLIST. Returns the string that was modified."
2731 (add-text-properties
2732 0 (length string) (if props (append plist props) plist) string)
2733 string)
2734 (put 'org-add-props 'lisp-indent-function 2)
2735
2736
2737 ;;; Font-Lock stuff
2738
2739 (defvar org-mouse-map (make-sparse-keymap))
2740 (define-key org-mouse-map
2741 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
2742 (define-key org-mouse-map
2743 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
2744 (when org-mouse-1-follows-link
2745 (define-key org-mouse-map [follow-link] 'mouse-face))
2746 (when org-tab-follows-link
2747 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2748 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2749 (when org-return-follows-link
2750 (define-key org-mouse-map [(return)] 'org-open-at-point)
2751 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2752
2753 (require 'font-lock)
2754
2755 (defconst org-non-link-chars "]\t\n\r<>")
2756 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
2757 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
2758 (defconst org-link-re-with-space
2759 (concat
2760 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2761 "\\([^" org-non-link-chars " ]"
2762 "[^" org-non-link-chars "]*"
2763 "[^" org-non-link-chars " ]\\)>?")
2764 "Matches a link with spaces, optional angular brackets around it.")
2765
2766 (defconst org-link-re-with-space2
2767 (concat
2768 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2769 "\\([^" org-non-link-chars " ]"
2770 "[^]\t\n\r]*"
2771 "[^" org-non-link-chars " ]\\)>?")
2772 "Matches a link with spaces, optional angular brackets around it.")
2773
2774 (defconst org-angle-link-re
2775 (concat
2776 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2777 "\\([^" org-non-link-chars " ]"
2778 "[^" org-non-link-chars "]*"
2779 "\\)>")
2780 "Matches link with angular brackets, spaces are allowed.")
2781 (defconst org-plain-link-re
2782 (concat
2783 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2784 "\\([^]\t\n\r<>,;() ]+\\)")
2785 "Matches plain link, without spaces.")
2786
2787 (defconst org-bracket-link-regexp
2788 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2789 "Matches a link in double brackets.")
2790
2791 (defconst org-bracket-link-analytic-regexp
2792 (concat
2793 "\\[\\["
2794 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
2795 "\\([^]]+\\)"
2796 "\\]"
2797 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
2798 "\\]"))
2799 ; 1: http:
2800 ; 2: http
2801 ; 3: path
2802 ; 4: [desc]
2803 ; 5: desc
2804
2805
2806 (defconst org-ts-lengths
2807 (cons (length (format-time-string (car org-time-stamp-formats)))
2808 (length (format-time-string (cdr org-time-stamp-formats))))
2809 "This holds the lengths of the two different time formats.")
2810 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2811 "Regular expression for fast time stamp matching.")
2812 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2813 "Regular expression for fast time stamp matching.")
2814 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2815 "Regular expression matching time strings for analysis.")
2816 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2817 "Regular expression matching time stamps, with groups.")
2818 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2819 "Regular expression matching a time stamp range.")
2820 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2821 org-ts-regexp "\\)?")
2822 "Regular expression matching a time stamp or time stamp range.")
2823
2824 (defun org-activate-plain-links (limit)
2825 "Run through the buffer and add overlays to links."
2826 (if (re-search-forward org-plain-link-re limit t)
2827 (progn
2828 (add-text-properties (match-beginning 0) (match-end 0)
2829 (list 'mouse-face 'highlight
2830 'keymap org-mouse-map
2831 ))
2832 t)))
2833
2834 (defun org-activate-angle-links (limit)
2835 "Run through the buffer and add overlays to links."
2836 (if (re-search-forward org-angle-link-re limit t)
2837 (progn
2838 (add-text-properties (match-beginning 0) (match-end 0)
2839 (list 'mouse-face 'highlight
2840 'keymap org-mouse-map
2841 ))
2842 t)))
2843
2844 (defun org-activate-bracket-links (limit)
2845 "Run through the buffer and add overlays to bracketed links."
2846 (if (re-search-forward org-bracket-link-regexp limit t)
2847 (let* ((help (concat "LINK: "
2848 (org-match-string-no-properties 1)))
2849 ;; FIXME: above we should remove the escapes.
2850 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
2851 'keymap org-mouse-map 'mouse-face 'highlight
2852 'help-echo help))
2853 (vp (list 'rear-nonsticky t
2854 'keymap org-mouse-map 'mouse-face 'highlight
2855 'help-echo help)))
2856 ;; We need to remove the invisible property here. Table narrowing
2857 ;; may have made some of this invisible.
2858 (remove-text-properties (match-beginning 0) (match-end 0)
2859 '(invisible nil))
2860 (if (match-end 3)
2861 (progn
2862 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
2863 (add-text-properties (match-beginning 3) (match-end 3) vp)
2864 (add-text-properties (match-end 3) (match-end 0) ip))
2865 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
2866 (add-text-properties (match-beginning 1) (match-end 1) vp)
2867 (add-text-properties (match-end 1) (match-end 0) ip))
2868 t)))
2869
2870 (defun org-activate-dates (limit)
2871 "Run through the buffer and add overlays to dates."
2872 (if (re-search-forward org-tsr-regexp limit t)
2873 (progn
2874 (add-text-properties (match-beginning 0) (match-end 0)
2875 (list 'mouse-face 'highlight
2876 'keymap org-mouse-map))
2877 t)))
2878
2879 (defvar org-target-link-regexp nil
2880 "Regular expression matching radio targets in plain text.")
2881 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2882 "Regular expression matching a link target.")
2883 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2884 "Regular expression matching a link target.")
2885
2886 (defun org-activate-target-links (limit)
2887 "Run through the buffer and add overlays to target matches."
2888 (when org-target-link-regexp
2889 (let ((case-fold-search t))
2890 (if (re-search-forward org-target-link-regexp limit t)
2891 (progn
2892 (add-text-properties (match-beginning 0) (match-end 0)
2893 (list 'mouse-face 'highlight
2894 'keymap org-mouse-map
2895 'help-echo "Radio target link"
2896 'org-linked-text t))
2897 t)))))
2898
2899 (defun org-update-radio-target-regexp ()
2900 "Find all radio targets in this file and update the regular expression."
2901 (interactive)
2902 (when (memq 'radio org-activate-links)
2903 (setq org-target-link-regexp
2904 (org-make-target-link-regexp (org-all-targets 'radio)))
2905 (org-restart-font-lock)))
2906
2907 (defun org-hide-wide-columns (limit)
2908 (let (s e)
2909 (setq s (text-property-any (point) (or limit (point-max))
2910 'org-cwidth t))
2911 (when s
2912 (setq e (next-single-property-change s 'org-cwidth))
2913 (add-text-properties s e '(invisible org-cwidth intangible t))
2914 (goto-char e)
2915 t)))
2916
2917 (defun org-restart-font-lock ()
2918 "Restart font-lock-mode, to force refontification."
2919 (when (and (boundp 'font-lock-mode) font-lock-mode)
2920 (font-lock-mode -1)
2921 (font-lock-mode 1)))
2922
2923 (defun org-all-targets (&optional radio)
2924 "Return a list of all targets in this file.
2925 With optional argument RADIO, only find radio targets."
2926 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2927 rtn)
2928 (save-excursion
2929 (goto-char (point-min))
2930 (while (re-search-forward re nil t)
2931 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
2932 rtn)))
2933
2934 (defun org-make-target-link-regexp (targets)
2935 "Make regular expression matching all strings in TARGETS.
2936 The regular expression finds the targets also if there is a line break
2937 between words."
2938 (and targets
2939 (concat
2940 "\\<\\("
2941 (mapconcat
2942 (lambda (x)
2943 (while (string-match " +" x)
2944 (setq x (replace-match "\\s-+" t t x)))
2945 x)
2946 targets
2947 "\\|")
2948 "\\)\\>")))
2949
2950 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2951 "Matches CamelCase words, possibly with a star before it.")
2952
2953 (defun org-activate-camels (limit)
2954 "Run through the buffer and add overlays to dates."
2955 (if (re-search-forward org-camel-regexp limit t)
2956 (progn
2957 (add-text-properties (match-beginning 0) (match-end 0)
2958 (list 'mouse-face 'highlight
2959 'keymap org-mouse-map))
2960 t)))
2961
2962 (defun org-activate-tags (limit)
2963 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2964 (progn
2965 (add-text-properties (match-beginning 1) (match-end 1)
2966 (list 'mouse-face 'highlight
2967 'keymap org-mouse-map))
2968 t)))
2969
2970 (defun org-font-lock-level ()
2971 (save-excursion
2972 (org-back-to-heading t)
2973 (- (match-end 0) (match-beginning 0))))
2974
2975 (defun org-outline-level ()
2976 (save-excursion
2977 (looking-at outline-regexp)
2978 (if (match-beginning 1)
2979 (+ (org-get-string-indentation (match-string 1)) 1000)
2980 (- (match-end 0) (match-beginning 0)))))
2981
2982 (defvar org-font-lock-keywords nil)
2983
2984 (defun org-set-font-lock-defaults ()
2985 (let* ((em org-fontify-emphasized-text)
2986 (lk org-activate-links)
2987 (org-font-lock-extra-keywords
2988 ;; Headlines
2989 (list
2990 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
2991 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
2992 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2993 (1 'org-table))
2994 ;; Links
2995 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
2996 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
2997 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
2998 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
2999 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3000 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3001 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3002 (if org-table-limit-column-width
3003 '(org-hide-wide-columns (0 nil append)))
3004 ;; TODO lines
3005 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3006 '(1 'org-todo t))
3007 ;; Priorities
3008 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3009 ;; Special keywords
3010 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3011 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3012 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3013 ;; Emphasis
3014 (if em (list org-bold-re 2 ''bold 'prepend))
3015 (if em (list org-italic-re 2 ''italic 'prepend))
3016 (if em (list org-underline-re 2 ''underline 'prepend))
3017 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3018 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3019 2 'bold prepend)
3020 ;; COMMENT
3021 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3022 "\\|" org-quote-string "\\)\\>")
3023 '(1 'org-special-keyword t))
3024 '("^#.*" (0 'font-lock-comment-face t))
3025 ;; DONE
3026 (if org-fontify-done-headline
3027 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3028 '(1 'org-done t) '(2 'org-headline-done t))
3029 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3030 '(1 'org-done t)))
3031 ;; Table stuff
3032 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3033 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3034 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3035 (if org-format-transports-properties-p
3036 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3037 )))
3038 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3039 ;; Now set the full font-lock-keywords
3040 (set (make-local-variable 'org-font-lock-keywords)
3041 org-font-lock-extra-keywords)
3042 (set (make-local-variable 'font-lock-defaults)
3043 '(org-font-lock-keywords t nil nil backward-paragraph))
3044 (kill-local-variable 'font-lock-keywords) nil))
3045
3046 (defvar org-m nil)
3047 (defvar org-l nil)
3048 (defvar org-f nil)
3049 (defun org-get-level-face (n)
3050 "Get the right face for match N in font-lock matching of healdines."
3051 (setq org-l (- (match-end 2) (match-beginning 1)))
3052 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3053 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3054 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3055 (cond
3056 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3057 ((eq n 2) org-f)
3058 (t (if org-level-color-stars-only nil org-f))))
3059
3060 (defun org-unfontify-region (beg end &optional maybe_loudly)
3061 "Remove fontification and activation overlays from links."
3062 (font-lock-default-unfontify-region beg end)
3063 (let* ((buffer-undo-list t)
3064 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3065 (inhibit-modification-hooks t)
3066 deactivate-mark buffer-file-name buffer-file-truename)
3067 (remove-text-properties beg end
3068 '(mouse-face nil keymap nil org-linked-text nil
3069 invisible nil intangible nil))))
3070 ;;; Visibility cycling
3071
3072 (defvar org-cycle-global-status nil)
3073 (make-variable-buffer-local 'org-cycle-global-status)
3074 (defvar org-cycle-subtree-status nil)
3075 (make-variable-buffer-local 'org-cycle-subtree-status)
3076
3077 ;;;###autoload
3078 (defun org-cycle (&optional arg)
3079 "Visibility cycling for Org-mode.
3080
3081 - When this function is called with a prefix argument, rotate the entire
3082 buffer through 3 states (global cycling)
3083 1. OVERVIEW: Show only top-level headlines.
3084 2. CONTENTS: Show all headlines of all levels, but no body text.
3085 3. SHOW ALL: Show everything.
3086
3087 - When point is at the beginning of a headline, rotate the subtree started
3088 by this line through 3 different states (local cycling)
3089 1. FOLDED: Only the main headline is shown.
3090 2. CHILDREN: The main headline and the direct children are shown.
3091 From this state, you can move to one of the children
3092 and zoom in further.
3093 3. SUBTREE: Show the entire subtree, including body text.
3094
3095 - When there is a numeric prefix, go up to a heading with level ARG, do
3096 a `show-subtree' and return to the previous cursor position. If ARG
3097 is negative, go up that many levels.
3098
3099 - When point is not at the beginning of a headline, execute
3100 `indent-relative', like TAB normally does. See the option
3101 `org-cycle-emulate-tab' for details.
3102
3103 - Special case: if point is the the beginning of the buffer and there is
3104 no headline in line 1, this function will act as if called with prefix arg."
3105 (interactive "P")
3106
3107 (let* ((outline-regexp
3108 (if org-cycle-include-plain-lists
3109 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
3110 outline-regexp))
3111 (bob-special (and org-cycle-global-at-bob (bobp)
3112 (not (looking-at outline-regexp))))
3113 (org-cycle-hook (if bob-special nil org-cycle-hook)))
3114
3115 (if (or bob-special (equal arg '(4)))
3116 ;; special case: use global cycling
3117 (setq arg t))
3118
3119 (cond
3120
3121 ((org-at-table-p 'any)
3122 ;; Enter the table or move to the next field in the table
3123 (or (org-table-recognize-table.el)
3124 (progn
3125 (if arg (org-table-edit-field t)
3126 (org-table-justify-field-maybe)
3127 (call-interactively 'org-table-next-field)))))
3128
3129 ((eq arg t) ;; Global cycling
3130
3131 (cond
3132 ((and (eq last-command this-command)
3133 (eq org-cycle-global-status 'overview))
3134 ;; We just created the overview - now do table of contents
3135 ;; This can be slow in very large buffers, so indicate action
3136 (message "CONTENTS...")
3137 (org-content)
3138 (message "CONTENTS...done")
3139 (setq org-cycle-global-status 'contents)
3140 (run-hook-with-args 'org-cycle-hook 'contents))
3141
3142 ((and (eq last-command this-command)
3143 (eq org-cycle-global-status 'contents))
3144 ;; We just showed the table of contents - now show everything
3145 (show-all)
3146 (message "SHOW ALL")
3147 (setq org-cycle-global-status 'all)
3148 (run-hook-with-args 'org-cycle-hook 'all))
3149
3150 (t
3151 ;; Default action: go to overview
3152 (org-overview)
3153 (message "OVERVIEW")
3154 (setq org-cycle-global-status 'overview)
3155 (run-hook-with-args 'org-cycle-hook 'overview))))
3156
3157 ((integerp arg)
3158 ;; Show-subtree, ARG levels up from here.
3159 (save-excursion
3160 (org-back-to-heading)
3161 (outline-up-heading (if (< arg 0) (- arg)
3162 (- (funcall outline-level) arg)))
3163 (org-show-subtree)))
3164
3165 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3166 ;; At a heading: rotate between three different views
3167 (org-back-to-heading)
3168 (let ((goal-column 0) eoh eol eos)
3169 ;; First, some boundaries
3170 (save-excursion
3171 (org-back-to-heading)
3172 (save-excursion
3173 (beginning-of-line 2)
3174 (while (and (not (eobp)) ;; this is like `next-line'
3175 (get-char-property (1- (point)) 'invisible))
3176 (beginning-of-line 2)) (setq eol (point)))
3177 (outline-end-of-heading) (setq eoh (point))
3178 (org-end-of-subtree t) (setq eos (point))
3179 (outline-next-heading))
3180 ;; Find out what to do next and set `this-command'
3181 (cond
3182 ((and (= eos eoh)
3183 ;; Nothing is hidden behind this heading
3184 (message "EMPTY ENTRY")
3185 (setq org-cycle-subtree-status nil)))
3186 ((>= eol eos)
3187 ;; Entire subtree is hidden in one line: open it
3188 (org-show-entry)
3189 (show-children)
3190 (message "CHILDREN")
3191 (setq org-cycle-subtree-status 'children)
3192 (run-hook-with-args 'org-cycle-hook 'children))
3193 ((and (eq last-command this-command)
3194 (eq org-cycle-subtree-status 'children))
3195 ;; We just showed the children, now show everything.
3196 (org-show-subtree)
3197 (message "SUBTREE")
3198 (setq org-cycle-subtree-status 'subtree)
3199 (run-hook-with-args 'org-cycle-hook 'subtree))
3200 (t
3201 ;; Default action: hide the subtree.
3202 (hide-subtree)
3203 (message "FOLDED")
3204 (setq org-cycle-subtree-status 'folded)
3205 (run-hook-with-args 'org-cycle-hook 'folded)))))
3206
3207 ;; TAB emulation
3208 (buffer-read-only (org-back-to-heading))
3209 ((if (and (eq org-cycle-emulate-tab 'white)
3210 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
3211 t
3212 (eq org-cycle-emulate-tab t))
3213 (if (and (looking-at "[ \n\r\t]")
3214 (string-match "^[ \t]*$" (buffer-substring
3215 (point-at-bol) (point))))
3216 (progn
3217 (beginning-of-line 1)
3218 (and (looking-at "[ \t]+") (replace-match ""))))
3219 (indent-relative))
3220
3221 (t (save-excursion
3222 (org-back-to-heading)
3223 (org-cycle))))))
3224
3225 ;;;###autoload
3226 (defun org-global-cycle ()
3227 "Cycle the global visibility. For details see `org-cycle'."
3228 (interactive)
3229 (org-cycle '(4)))
3230
3231 (defun org-overview ()
3232 "Switch to overview mode, shoing only top-level headlines.
3233 Really, this shows all headlines with level equal or greater than the level
3234 of the first headline in the buffer. This is important, because if the
3235 first headline is not level one, then (hide-sublevels 1) gives confusing
3236 results."
3237 (interactive)
3238 (hide-sublevels (save-excursion
3239 (goto-char (point-min))
3240 (if (re-search-forward (concat "^" outline-regexp) nil t)
3241 (progn
3242 (goto-char (match-beginning 0))
3243 (funcall outline-level))
3244 1))))
3245
3246 ;; FIXME: allow an argument to give a limiting level for this.
3247 (defun org-content ()
3248 "Show all headlines in the buffer, like a table of contents"
3249 (interactive)
3250 (save-excursion
3251 ;; Visit all headings and show their offspring
3252 (goto-char (point-max))
3253 (catch 'exit
3254 (while (and (progn (condition-case nil
3255 (outline-previous-visible-heading 1)
3256 (error (goto-char (point-min))))
3257 t)
3258 (looking-at outline-regexp))
3259 (show-branches)
3260 (if (bobp) (throw 'exit nil))))))
3261
3262
3263 (defun org-optimize-window-after-visibility-change (state)
3264 "Adjust the window after a change in outline visibility.
3265 This function is the default value of the hook `org-cycle-hook'."
3266 (when (get-buffer-window (current-buffer))
3267 (cond
3268 ((eq state 'overview) (org-first-headline-recenter 1))
3269 ((eq state 'content) nil)
3270 ((eq state 'all) nil)
3271 ((eq state 'folded) nil)
3272 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3273 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3274
3275 (defun org-subtree-end-visible-p ()
3276 "Is the end of the current subtree visible?"
3277 (pos-visible-in-window-p
3278 (save-excursion (org-end-of-subtree t) (point))))
3279
3280 (defun org-first-headline-recenter (&optional N)
3281 "Move cursor to the first headline and recenter the headline.
3282 Optional argument N means, put the headline into the Nth line of the window."
3283 (goto-char (point-min))
3284 (when (re-search-forward (concat "^" outline-regexp) nil t)
3285 (beginning-of-line)
3286 (recenter (prefix-numeric-value N))))
3287
3288 (defvar org-goto-window-configuration nil)
3289 (defvar org-goto-marker nil)
3290 (defvar org-goto-map (make-sparse-keymap))
3291 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3292 (while (setq cmd (pop cmds))
3293 (substitute-key-definition cmd cmd org-goto-map global-map)))
3294 (define-key org-goto-map "\C-m" 'org-goto-ret)
3295 (define-key org-goto-map [(left)] 'org-goto-left)
3296 (define-key org-goto-map [(right)] 'org-goto-right)
3297 (define-key org-goto-map [(?q)] 'org-goto-quit)
3298 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3299 (define-key org-goto-map "\C-i" 'org-cycle)
3300 (define-key org-goto-map [(tab)] 'org-cycle)
3301 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3302 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3303 (define-key org-goto-map "n" 'outline-next-visible-heading)
3304 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3305 (define-key org-goto-map "f" 'outline-forward-same-level)
3306 (define-key org-goto-map "b" 'outline-backward-same-level)
3307 (define-key org-goto-map "u" 'outline-up-heading)
3308 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3309 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3310 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3311 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3312 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3313 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3314 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3315
3316 (defconst org-goto-help
3317 "Select a location to jump to, press RET
3318 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3319
3320 (defun org-goto ()
3321 "Go to a different location of the document, keeping current visibility.
3322
3323 When you want to go to a different location in a document, the fastest way
3324 is often to fold the entire buffer and then dive into the tree. This
3325 method has the disadvantage, that the previous location will be folded,
3326 which may not be what you want.
3327
3328 This command works around this by showing a copy of the current buffer in
3329 overview mode. You can dive into the tree in that copy, to find the
3330 location you want to reach. When pressing RET, the command returns to the
3331 original buffer in which the visibility is still unchanged. It then jumps
3332 to the new location, making it and the headline hierarchy above it visible."
3333 (interactive)
3334 (let* ((org-goto-start-pos (point))
3335 (selected-point
3336 (org-get-location (current-buffer) org-goto-help)))
3337 (if selected-point
3338 (progn
3339 (org-mark-ring-push org-goto-start-pos)
3340 (goto-char selected-point)
3341 (if (or (org-invisible-p) (org-invisible-p2))
3342 (org-show-hierarchy-above)))
3343 (error "Quit"))))
3344
3345 (defun org-get-location (buf help)
3346 "Let the user select a location in the Org-mode buffer BUF.
3347 This function uses a recursive edit. It returns the selected position
3348 or nil."
3349 (let (org-selected-point)
3350 (save-excursion
3351 (save-window-excursion
3352 (delete-other-windows)
3353 (switch-to-buffer (get-buffer-create "*org-goto*"))
3354 (with-output-to-temp-buffer "*Help*"
3355 (princ help))
3356 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3357 (setq buffer-read-only nil)
3358 (erase-buffer)
3359 (insert-buffer-substring buf)
3360 (let ((org-startup-truncated t)
3361 (org-startup-folded t)
3362 (org-startup-align-all-tables nil)
3363 (org-startup-with-deadline-check nil))
3364 (org-mode))
3365 (setq buffer-read-only t)
3366 (if (boundp 'org-goto-start-pos)
3367 (goto-char org-goto-start-pos)
3368 (goto-char (point-min)))
3369 (org-beginning-of-line)
3370 (message "Select location and press RET")
3371 ;; now we make sure that during selection, ony very few keys work
3372 ;; and that it is impossible to switch to another window.
3373 (let ((gm (current-global-map))
3374 (overriding-local-map org-goto-map))
3375 (unwind-protect
3376 (progn
3377 (use-global-map org-goto-map)
3378 (recursive-edit))
3379 (use-global-map gm)))))
3380 (kill-buffer "*org-goto*")
3381 org-selected-point))
3382
3383 (defun org-goto-ret (&optional arg)
3384 "Finish `org-goto' by going to the new location."
3385 (interactive "P")
3386 (setq org-selected-point (point)
3387 current-prefix-arg arg)
3388 (throw 'exit nil))
3389
3390 (defun org-goto-left ()
3391 "Finish `org-goto' by going to the new location."
3392 (interactive)
3393 (if (org-on-heading-p)
3394 (progn
3395 (beginning-of-line 1)
3396 (setq org-selected-point (point)
3397 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3398 (throw 'exit nil))
3399 (error "Not on a heading")))
3400
3401 (defun org-goto-right ()
3402 "Finish `org-goto' by going to the new location."
3403 (interactive)
3404 (if (org-on-heading-p)
3405 (progn
3406 (outline-end-of-subtree)
3407 (or (eobp) (forward-char 1))
3408 (setq org-selected-point (point)
3409 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3410 (throw 'exit nil))
3411 (error "Not on a heading")))
3412
3413 (defun org-goto-quit ()
3414 "Finish `org-goto' without cursor motion."
3415 (interactive)
3416 (setq org-selected-point nil)
3417 (throw 'exit nil))
3418
3419 ;;; Promotion, Demotion, Inserting new headlines
3420
3421 (defvar org-ignore-region nil
3422 "To temporarily disable the active region.")
3423
3424 (defun org-insert-heading (&optional force-heading)
3425 "Insert a new heading or item with same depth at point.
3426 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
3427 If point is at the beginning of a headline, insert a sibling before the
3428 current headline. If point is in the middle of a headline, split the headline
3429 at that position and make the rest of the headline part of the sibling below
3430 the current headline."
3431 (interactive "P")
3432 (if (= (buffer-size) 0)
3433 (insert "\n* ")
3434 (when (or force-heading (not (org-insert-item)))
3435 (let* ((head (save-excursion
3436 (condition-case nil
3437 (progn
3438 (org-back-to-heading)
3439 (match-string 0))
3440 (error "*"))))
3441 pos)
3442 (cond
3443 ((and (org-on-heading-p) (bolp)
3444 (save-excursion (backward-char 1) (not (org-invisible-p))))
3445 (open-line 1))
3446 ((bolp) nil)
3447 (t (newline)))
3448 (insert head) (just-one-space)
3449 (setq pos (point))
3450 (end-of-line 1)
3451 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
3452 (run-hooks 'org-insert-heading-hook)))))
3453
3454 (defun org-insert-item (&optional checkbox)
3455 "Insert a new item at the current level.
3456 Return t when things worked, nil when we are not in an item."
3457 (when (save-excursion
3458 (condition-case nil
3459 (progn
3460 (org-beginning-of-item)
3461 (org-at-item-p)
3462 t)
3463 (error nil)))
3464 (let* ((bul (match-string 0))
3465 (end (match-end 0))
3466 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3467 (match-end 0)))
3468 (eowcol (save-excursion (goto-char eow) (current-column)))
3469 pos)
3470 (cond
3471 ((and (org-at-item-p) (<= (point) eow))
3472 ;; before the bullet
3473 (beginning-of-line 1)
3474 (open-line 1))
3475 ((<= (point) eow)
3476 (beginning-of-line 1))
3477 (t (newline)))
3478 (insert bul (if checkbox "[ ]" ""))
3479 (just-one-space)
3480 (setq pos (point))
3481 (end-of-line 1)
3482 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
3483 (org-maybe-renumber-ordered-list)
3484 t))
3485
3486 (defun org-insert-todo-heading (arg)
3487 "Insert a new heading with the same level and TODO state as current heading.
3488 If the heading has no TODO state, or if the state is DONE, use the first
3489 state (TODO by default). Also with prefix arg, force first state."
3490 (interactive "P")
3491 (when (not (org-insert-item 'checkbox))
3492 (org-insert-heading)
3493 (save-excursion
3494 (org-back-to-heading)
3495 (if org-noutline-p
3496 (outline-previous-heading)
3497 (outline-previous-visible-heading t))
3498 (looking-at org-todo-line-regexp))
3499 (if (or arg
3500 (not (match-beginning 2))
3501 (equal (match-string 2) org-done-string))
3502 (insert (car org-todo-keywords) " ")
3503 (insert (match-string 2) " "))))
3504
3505 (defun org-promote-subtree ()
3506 "Promote the entire subtree.
3507 See also `org-promote'."
3508 (interactive)
3509 (save-excursion
3510 (org-map-tree 'org-promote)))
3511
3512 (defun org-demote-subtree ()
3513 "Demote the entire subtree. See `org-demote'.
3514 See also `org-promote'."
3515 (interactive)
3516 (save-excursion
3517 (org-map-tree 'org-demote)))
3518
3519 (defun org-do-promote ()
3520 "Promote the current heading higher up the tree.
3521 If the region is active in `transient-mark-mode', promote all headings
3522 in the region."
3523 (interactive)
3524 (save-excursion
3525 (if (org-region-active-p)
3526 (org-map-region 'org-promote (region-beginning) (region-end))
3527 (org-promote)))
3528 (org-fix-position-after-promote))
3529
3530 (defun org-do-demote ()
3531 "Demote the current heading lower down the tree.
3532 If the region is active in `transient-mark-mode', demote all headings
3533 in the region."
3534 (interactive)
3535 (save-excursion
3536 (if (org-region-active-p)
3537 (org-map-region 'org-demote (region-beginning) (region-end))
3538 (org-demote)))
3539 (org-fix-position-after-promote))
3540
3541 (defun org-fix-position-after-promote ()
3542 "Make sure that after pro/demotion cursor position is right."
3543 (and (equal (char-after) ?\ )
3544 (equal (char-before) ?*)
3545 (forward-char 1)))
3546
3547 (defun org-get-legal-level (level change)
3548 "Rectify a level change under the influence of `org-odd-levels-only'
3549 LEVEL is a current level, CHANGE is by how much the level should be
3550 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3551 even level numbers will become the next higher odd number."
3552 (if org-odd-levels-only
3553 (cond ((not change) (1+ (* 2 (/ level 2))))
3554 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3555 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3556 (max 1 (+ level change))))
3557
3558 (defun org-promote ()
3559 "Promote the current heading higher up the tree.
3560 If the region is active in `transient-mark-mode', promote all headings
3561 in the region."
3562 (org-back-to-heading t)
3563 (let* ((level (save-match-data (funcall outline-level)))
3564 (up-head (make-string (org-get-legal-level level -1) ?*))
3565 (diff (abs (- level (length up-head)))))
3566 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3567 (replace-match up-head nil t)
3568 ;; Fixup tag positioning
3569 (and org-auto-align-tags (org-set-tags nil t))
3570 (if org-adapt-indentation
3571 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
3572 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
3573
3574 (defun org-demote ()
3575 "Demote the current heading lower down the tree.
3576 If the region is active in `transient-mark-mode', demote all headings
3577 in the region."
3578 (org-back-to-heading t)
3579 (let* ((level (save-match-data (funcall outline-level)))
3580 (down-head (make-string (org-get-legal-level level 1) ?*))
3581 (diff (abs (- level (length down-head)))))
3582 (replace-match down-head nil t)
3583 ;; Fixup tag positioning
3584 (and org-auto-align-tags (org-set-tags nil t))
3585 (if org-adapt-indentation
3586 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
3587
3588 (defun org-map-tree (fun)
3589 "Call FUN for every heading underneath the current one."
3590 (org-back-to-heading)
3591 (let ((level (funcall outline-level)))
3592 (save-excursion
3593 (funcall fun)
3594 (while (and (progn
3595 (outline-next-heading)
3596 (> (funcall outline-level) level))
3597 (not (eobp)))
3598 (funcall fun)))))
3599
3600 (defun org-map-region (fun beg end)
3601 "Call FUN for every heading between BEG and END."
3602 (let ((org-ignore-region t))
3603 (save-excursion
3604 (setq end (copy-marker end))
3605 (goto-char beg)
3606 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3607 (< (point) end))
3608 (funcall fun))
3609 (while (and (progn
3610 (outline-next-heading)
3611 (< (point) end))
3612 (not (eobp)))
3613 (funcall fun)))))
3614
3615 (defun org-fixup-indentation (from to prohibit)
3616 "Change the indentation in the current entry by re-replacing FROM with TO.
3617 However, if the regexp PROHIBIT matches at all, don't do anything.
3618 This is being used to change indentation along with the length of the
3619 heading marker. But if there are any lines which are not indented, nothing
3620 is changed at all."
3621 (save-excursion
3622 (let ((end (save-excursion (outline-next-heading)
3623 (point-marker))))
3624 (unless (save-excursion (re-search-forward prohibit end t))
3625 (while (re-search-forward from end t)
3626 (replace-match to)
3627 (beginning-of-line 2)))
3628 (move-marker end nil))))
3629
3630 ;;; Vertical tree motion, cutting and pasting of subtrees
3631
3632 (defun org-move-subtree-up (&optional arg)
3633 "Move the current subtree up past ARG headlines of the same level."
3634 (interactive "p")
3635 (org-move-subtree-down (- (prefix-numeric-value arg))))
3636
3637 (defun org-move-subtree-down (&optional arg)
3638 "Move the current subtree down past ARG headlines of the same level."
3639 (interactive "p")
3640 (setq arg (prefix-numeric-value arg))
3641 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3642 'outline-get-last-sibling))
3643 (ins-point (make-marker))
3644 (cnt (abs arg))
3645 beg end txt folded)
3646 ;; Select the tree
3647 (org-back-to-heading)
3648 (setq beg (point))
3649 (save-match-data
3650 (save-excursion (outline-end-of-heading)
3651 (setq folded (org-invisible-p)))
3652 (outline-end-of-subtree))
3653 (outline-next-heading)
3654 (setq end (point))
3655 ;; Find insertion point, with error handling
3656 (goto-char beg)
3657 (while (> cnt 0)
3658 (or (and (funcall movfunc) (looking-at outline-regexp))
3659 (progn (goto-char beg)
3660 (error "Cannot move past superior level or buffer limit")))
3661 (setq cnt (1- cnt)))
3662 (if (> arg 0)
3663 ;; Moving forward - still need to move over subtree
3664 (progn (outline-end-of-subtree)
3665 (outline-next-heading)
3666 (if (not (or (looking-at (concat "^" outline-regexp))
3667 (bolp)))
3668 (newline))))
3669 (move-marker ins-point (point))
3670 (setq txt (buffer-substring beg end))
3671 (delete-region beg end)
3672 (insert txt)
3673 (goto-char ins-point)
3674 (if folded (hide-subtree))
3675 (move-marker ins-point nil)))
3676
3677 (defvar org-subtree-clip ""
3678 "Clipboard for cut and paste of subtrees.
3679 This is actually only a copy of the kill, because we use the normal kill
3680 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3681
3682 (defvar org-subtree-clip-folded nil
3683 "Was the last copied subtree folded?
3684 This is used to fold the tree back after pasting.")
3685
3686 (defun org-cut-subtree ()
3687 "Cut the current subtree into the clipboard.
3688 This is a short-hand for marking the subtree and then cutting it."
3689 (interactive)
3690 (org-copy-subtree 'cut))
3691
3692 (defun org-copy-subtree (&optional cut)
3693 "Cut the current subtree into the clipboard.
3694 This is a short-hand for marking the subtree and then copying it.
3695 If CUT is non nil, actually cut the subtree."
3696 (interactive)
3697 (let (beg end folded)
3698 (org-back-to-heading)
3699 (setq beg (point))
3700 (save-match-data
3701 (save-excursion (outline-end-of-heading)
3702 (setq folded (org-invisible-p)))
3703 (outline-end-of-subtree))
3704 (if (equal (char-after) ?\n) (forward-char 1))
3705 (setq end (point))
3706 (goto-char beg)
3707 (when (> end beg)
3708 (setq org-subtree-clip-folded folded)
3709 (if cut (kill-region beg end) (copy-region-as-kill beg end))
3710 (setq org-subtree-clip (current-kill 0))
3711 (message "%s: Subtree with %d characters"
3712 (if cut "Cut" "Copied")
3713 (length org-subtree-clip)))))
3714
3715 (defun org-paste-subtree (&optional level tree)
3716 "Paste the clipboard as a subtree, with modification of headline level.
3717 The entire subtree is promoted or demoted in order to match a new headline
3718 level. By default, the new level is derived from the visible headings
3719 before and after the insertion point, and taken to be the inferior headline
3720 level of the two. So if the previous visible heading is level 3 and the
3721 next is level 4 (or vice versa), level 4 will be used for insertion.
3722 This makes sure that the subtree remains an independent subtree and does
3723 not swallow low level entries.
3724
3725 You can also force a different level, either by using a numeric prefix
3726 argument, or by inserting the heading marker by hand. For example, if the
3727 cursor is after \"*****\", then the tree will be shifted to level 5.
3728
3729 If you want to insert the tree as is, just use \\[yank].
3730
3731 If optional TREE is given, use this text instead of the kill ring."
3732 (interactive "P")
3733 (unless (org-kill-is-subtree-p tree)
3734 (error
3735 (substitute-command-keys
3736 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
3737 (let* ((txt (or tree (current-kill 0)))
3738 (^re (concat "^\\(" outline-regexp "\\)"))
3739 (re (concat "\\(" outline-regexp "\\)"))
3740 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3741
3742 (old-level (if (string-match ^re txt)
3743 (- (match-end 0) (match-beginning 0))
3744 -1))
3745 (force-level (cond (level (prefix-numeric-value level))
3746 ((string-match
3747 ^re_ (buffer-substring (point-at-bol) (point)))
3748 (- (match-end 0) (match-beginning 0)))
3749 (t nil)))
3750 (previous-level (save-excursion
3751 (condition-case nil
3752 (progn
3753 (outline-previous-visible-heading 1)
3754 (if (looking-at re)
3755 (- (match-end 0) (match-beginning 0))
3756 1))
3757 (error 1))))
3758 (next-level (save-excursion
3759 (condition-case nil
3760 (progn
3761 (outline-next-visible-heading 1)
3762 (if (looking-at re)
3763 (- (match-end 0) (match-beginning 0))
3764 1))
3765 (error 1))))
3766 (new-level (or force-level (max previous-level next-level)))
3767 (shift (if (or (= old-level -1)
3768 (= new-level -1)
3769 (= old-level new-level))
3770 0
3771 (- new-level old-level)))
3772 (shift1 shift)
3773 (delta (if (> shift 0) -1 1))
3774 (func (if (> shift 0) 'org-demote 'org-promote))
3775 (org-odd-levels-only nil)
3776 beg end)
3777 ;; Remove the forces level indicator
3778 (if force-level
3779 (delete-region (point-at-bol) (point)))
3780 ;; Make sure we start at the beginning of an empty line
3781 (if (not (bolp)) (insert "\n"))
3782 (if (not (looking-at "[ \t]*$"))
3783 (progn (insert "\n") (backward-char 1)))
3784 ;; Paste
3785 (setq beg (point))
3786 (insert txt)
3787 (setq end (point))
3788 (goto-char beg)
3789 ;; Shift if necessary
3790 (if (= shift 0)
3791 (message "Pasted at level %d, without shift" new-level)
3792 (save-restriction
3793 (narrow-to-region beg end)
3794 (while (not (= shift 0))
3795 (org-map-region func (point-min) (point-max))
3796 (setq shift (+ delta shift)))
3797 (goto-char (point-min))
3798 (message "Pasted at level %d, with shift by %d levels"
3799 new-level shift1)))
3800 (if (and (eq org-subtree-clip (current-kill 0))
3801 org-subtree-clip-folded)
3802 ;; The tree was folded before it was killed/copied
3803 (hide-subtree))))
3804
3805 (defun org-kill-is-subtree-p (&optional txt)
3806 "Check if the current kill is an outline subtree, or a set of trees.
3807 Returns nil if kill does not start with a headline, or if the first
3808 headline level is not the largest headline level in the tree.
3809 So this will actually accept several entries of equal levels as well,
3810 which is OK for `org-paste-subtree'.
3811 If optional TXT is given, check this string instead of the current kill."
3812 (let* ((kill (or txt (current-kill 0) ""))
3813 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3814 (- (match-end 0) (match-beginning 0))))
3815 (re (concat "^" outline-regexp))
3816 (start 1))
3817 (if (not start-level)
3818 nil ;; does not even start with a heading
3819 (catch 'exit
3820 (while (setq start (string-match re kill (1+ start)))
3821 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3822 (throw 'exit nil)))
3823 t))))
3824
3825 ;;; Plain list items
3826
3827 (defun org-at-item-p ()
3828 "Is point in a line starting a hand-formatted item?"
3829 (let ((llt org-plain-list-ordered-item-terminator))
3830 (save-excursion
3831 (goto-char (point-at-bol))
3832 (looking-at
3833 (cond
3834 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3835 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3836 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3837 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3838
3839 (defun org-at-item-checkbox-p ()
3840 "Is point at a line starting a plain-list item with a checklet?"
3841 (and (org-at-item-p)
3842 (save-excursion
3843 (goto-char (match-end 0))
3844 (skip-chars-forward " \t")
3845 (looking-at "\\[[ X]\\]"))))
3846
3847 (defun org-toggle-checkbox ()
3848 "Toggle the checkbox in the current line."
3849 (interactive)
3850 (save-excursion
3851 (if (org-at-item-checkbox-p)
3852 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))))
3853
3854 (defun org-get-indentation ()
3855 "Get the indentation of the current line, interpreting tabs."
3856 (save-excursion
3857 (beginning-of-line 1)
3858 (skip-chars-forward " \t")
3859 (current-column)))
3860
3861 (defun org-beginning-of-item ()
3862 "Go to the beginning of the current hand-formatted item.
3863 If the cursor is not in an item, throw an error."
3864 (interactive)
3865 (let ((pos (point))
3866 (limit (save-excursion (org-back-to-heading)
3867 (beginning-of-line 2) (point)))
3868 ind ind1)
3869 (if (org-at-item-p)
3870 (beginning-of-line 1)
3871 (beginning-of-line 1)
3872 (skip-chars-forward " \t")
3873 (setq ind (current-column))
3874 (if (catch 'exit
3875 (while t
3876 (beginning-of-line 0)
3877 (if (< (point) limit) (throw 'exit nil))
3878 (unless (looking-at " \t]*$")
3879 (skip-chars-forward " \t")
3880 (setq ind1 (current-column))
3881 (if (< ind1 ind)
3882 (throw 'exit (org-at-item-p))))))
3883 nil
3884 (goto-char pos)
3885 (error "Not in an item")))))
3886
3887 (defun org-end-of-item ()
3888 "Go to the end of the current hand-formatted item.
3889 If the cursor is not in an item, throw an error."
3890 (interactive)
3891 (let ((pos (point))
3892 (limit (save-excursion (outline-next-heading) (point)))
3893 (ind (save-excursion
3894 (org-beginning-of-item)
3895 (skip-chars-forward " \t")
3896 (current-column)))
3897 ind1)
3898 (if (catch 'exit
3899 (while t
3900 (beginning-of-line 2)
3901 (if (>= (point) limit) (throw 'exit t))
3902 (unless (looking-at "[ \t]*$")
3903 (skip-chars-forward " \t")
3904 (setq ind1 (current-column))
3905 (if (<= ind1 ind) (throw 'exit t)))))
3906 (beginning-of-line 1)
3907 (goto-char pos)
3908 (error "Not in an item"))))
3909
3910 (defun org-next-item ()
3911 "Move to the beginning of the next item in the current plain list.
3912 Error if not at a plain list, or if this is the last item in the list."
3913 (interactive)
3914 (let (beg end ind ind1 (pos (point)) txt)
3915 (org-beginning-of-item)
3916 (setq beg (point))
3917 (setq ind (org-get-indentation))
3918 (org-end-of-item)
3919 (setq end (point))
3920 (setq ind1 (org-get-indentation))
3921 (unless (and (org-at-item-p) (= ind ind1))
3922 (goto-char pos)
3923 (error "This is already the last item in the list"))))
3924
3925 (defun org-previous-item ()
3926 "Move to the beginning of the previous item in the current plain list.
3927 Error if not at a plain list, or if this is the last item in the list."
3928 (interactive)
3929 (let (beg end ind ind1 (pos (point)) txt)
3930 (org-beginning-of-item)
3931 (setq beg (point))
3932 (setq ind (org-get-indentation))
3933 (goto-char beg)
3934 (catch 'exit
3935 (while t
3936 (beginning-of-line 0)
3937 (if (looking-at "[ \t]*$")
3938 nil
3939 (if (<= (setq ind1 (org-get-indentation)) ind)
3940 (throw 'exit t)))))
3941 (condition-case nil
3942 (org-beginning-of-item)
3943 (error (goto-char pos)
3944 (error "This is already the first item in the list")))))
3945
3946 (defun org-move-item-down ()
3947 "Move the plain list item at point down, i.e. swap with following item.
3948 Subitems (items with larger indentation) are considered part of the item,
3949 so this really moves item trees."
3950 (interactive)
3951 (let (beg end ind ind1 (pos (point)) txt)
3952 (org-beginning-of-item)
3953 (setq beg (point))
3954 (setq ind (org-get-indentation))
3955 (org-end-of-item)
3956 (setq end (point))
3957 (setq ind1 (org-get-indentation))
3958 (if (and (org-at-item-p) (= ind ind1))
3959 (progn
3960 (org-end-of-item)
3961 (setq txt (buffer-substring beg end))
3962 (save-excursion
3963 (delete-region beg end))
3964 (setq pos (point))
3965 (insert txt)
3966 (goto-char pos)
3967 (org-maybe-renumber-ordered-list))
3968 (goto-char pos)
3969 (error "Cannot move this item further down"))))
3970
3971 (defun org-move-item-up (arg)
3972 "Move the plain list item at point up, i.e. swap with previous item.
3973 Subitems (items with larger indentation) are considered part of the item,
3974 so this really moves item trees."
3975 (interactive "p")
3976 (let (beg end ind ind1 (pos (point)) txt)
3977 (org-beginning-of-item)
3978 (setq beg (point))
3979 (setq ind (org-get-indentation))
3980 (org-end-of-item)
3981 (setq end (point))
3982 (goto-char beg)
3983 (catch 'exit
3984 (while t
3985 (beginning-of-line 0)
3986 (if (looking-at "[ \t]*$")
3987 nil
3988 (if (<= (setq ind1 (org-get-indentation)) ind)
3989 (throw 'exit t)))))
3990 (condition-case nil
3991 (org-beginning-of-item)
3992 (error (goto-char beg)
3993 (error "Cannot move this item further up")))
3994 (setq ind1 (org-get-indentation))
3995 (if (and (org-at-item-p) (= ind ind1))
3996 (progn
3997 (setq txt (buffer-substring beg end))
3998 (save-excursion
3999 (delete-region beg end))
4000 (setq pos (point))
4001 (insert txt)
4002 (goto-char pos)
4003 (org-maybe-renumber-ordered-list))
4004 (goto-char pos)
4005 (error "Cannot move this item further up"))))
4006
4007 (defun org-maybe-renumber-ordered-list ()
4008 "Renumber the ordered list at point if setup allows it.
4009 This tests the user option `org-auto-renumber-ordered-lists' before
4010 doing the renumbering."
4011 (and org-auto-renumber-ordered-lists
4012 (org-at-item-p)
4013 (match-beginning 3)
4014 (org-renumber-ordered-list 1)))
4015
4016 (defun org-get-string-indentation (s)
4017 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4018 (let ((n -1) (i 0) (w tab-width) c)
4019 (catch 'exit
4020 (while (< (setq n (1+ n)) (length s))
4021 (setq c (aref s n))
4022 (cond ((= c ?\ ) (setq i (1+ i)))
4023 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4024 (t (throw 'exit t)))))
4025 i))
4026
4027 (defun org-renumber-ordered-list (arg)
4028 "Renumber an ordered plain list.
4029 Cursor needs to be in the first line of an item, the line that starts
4030 with something like \"1.\" or \"2)\"."
4031 (interactive "p")
4032 (unless (and (org-at-item-p)
4033 (match-beginning 3))
4034 (error "This is not an ordered list"))
4035 (let ((line (org-current-line))
4036 (col (current-column))
4037 (ind (org-get-string-indentation
4038 (buffer-substring (point-at-bol) (match-beginning 3))))
4039 ;; (term (substring (match-string 3) -1))
4040 ind1 (n (1- arg)))
4041 ;; find where this list begins
4042 (catch 'exit
4043 (while t
4044 (catch 'next
4045 (beginning-of-line 0)
4046 (if (looking-at "[ \t]*$") (throw 'next t))
4047 (skip-chars-forward " \t") (setq ind1 (current-column))
4048 (if (or (< ind1 ind)
4049 (and (= ind1 ind)
4050 (not (org-at-item-p))))
4051 (throw 'exit t)))))
4052 ;; Walk forward and replace these numbers
4053 (catch 'exit
4054 (while t
4055 (catch 'next
4056 (beginning-of-line 2)
4057 (if (eobp) (throw 'exit nil))
4058 (if (looking-at "[ \t]*$") (throw 'next nil))
4059 (skip-chars-forward " \t") (setq ind1 (current-column))
4060 (if (> ind1 ind) (throw 'next t))
4061 (if (< ind1 ind) (throw 'exit t))
4062 (if (not (org-at-item-p)) (throw 'exit nil))
4063 (if (not (match-beginning 3))
4064 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4065 (delete-region (match-beginning 3) (1- (match-end 3)))
4066 (goto-char (match-beginning 3))
4067 (insert (format "%d" (setq n (1+ n)))))))
4068 (goto-line line)
4069 (move-to-column col)))
4070
4071 (defvar org-last-indent-begin-marker (make-marker))
4072 (defvar org-last-indent-end-marker (make-marker))
4073
4074 (defun org-outdent-item (arg)
4075 "Outdent a local list item."
4076 (interactive "p")
4077 (org-indent-item (- arg)))
4078
4079 (defun org-indent-item (arg)
4080 "Indent a local list item."
4081 (interactive "p")
4082 (unless (org-at-item-p)
4083 (error "Not on an item"))
4084 (save-excursion
4085 (let (beg end ind ind1)
4086 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4087 (setq beg org-last-indent-begin-marker
4088 end org-last-indent-end-marker)
4089 (org-beginning-of-item)
4090 (setq beg (move-marker org-last-indent-begin-marker (point)))
4091 (org-end-of-item)
4092 (setq end (move-marker org-last-indent-end-marker (point))))
4093 (goto-char beg)
4094 (skip-chars-forward " \t") (setq ind (current-column))
4095 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4096 (while (< (point) end)
4097 (beginning-of-line 1)
4098 (skip-chars-forward " \t") (setq ind1 (current-column))
4099 (delete-region (point-at-bol) (point))
4100 (indent-to-column (+ ind1 arg))
4101 (beginning-of-line 2)))))
4102
4103 ;;; Archiving
4104
4105 (defun org-archive-subtree ()
4106 "Move the current subtree to the archive.
4107 The archive can be a certain top-level heading in the current file, or in
4108 a different file. The tree will be moved to that location, the subtree
4109 heading be marked DONE, and the current time will be added."
4110 (interactive)
4111 ;; Save all relevant TODO keyword-relatex variables
4112 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4113 (tr-org-todo-keywords org-todo-keywords)
4114 (tr-org-todo-interpretation org-todo-interpretation)
4115 (tr-org-done-string org-done-string)
4116 (tr-org-todo-regexp org-todo-regexp)
4117 (tr-org-todo-line-regexp org-todo-line-regexp)
4118 (this-buffer (current-buffer))
4119 file heading buffer level newfile-p)
4120 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4121 (progn
4122 (setq file (format (match-string 1 org-archive-location)
4123 (file-name-nondirectory buffer-file-name))
4124 heading (match-string 2 org-archive-location)))
4125 (error "Invalid `org-archive-location'"))
4126 (if (> (length file) 0)
4127 (setq newfile-p (not (file-exists-p file))
4128 buffer (find-file-noselect file))
4129 (setq buffer (current-buffer)))
4130 (unless buffer
4131 (error "Cannot access file \"%s\"" file))
4132 (if (and (> (length heading) 0)
4133 (string-match "^\\*+" heading))
4134 (setq level (match-end 0))
4135 (setq heading nil level 0))
4136 (save-excursion
4137 ;; We first only copy, in case something goes wrong
4138 ;; we need to protect this-command, to avoid kill-region sets it,
4139 ;; which would lead to duplication of subtrees
4140 (let (this-command) (org-copy-subtree))
4141 (set-buffer buffer)
4142 ;; Enforce org-mode for the archive buffer
4143 (if (not (eq major-mode 'org-mode))
4144 ;; Force the mode for future visits.
4145 (let ((org-insert-mode-line-in-empty-file t))
4146 (call-interactively 'org-mode)))
4147 (when newfile-p
4148 (goto-char (point-max))
4149 (insert (format "\nArchived entries from file %s\n\n"
4150 (buffer-file-name this-buffer))))
4151 ;; Force the TODO keywords of the original buffer
4152 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4153 (org-todo-keywords tr-org-todo-keywords)
4154 (org-todo-interpretation tr-org-todo-interpretation)
4155 (org-done-string tr-org-done-string)
4156 (org-todo-regexp tr-org-todo-regexp)
4157 (org-todo-line-regexp tr-org-todo-line-regexp))
4158 (goto-char (point-min))
4159 (if heading
4160 (progn
4161 (if (re-search-forward
4162 (concat "\\(^\\|\r\\)"
4163 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4164 nil t)
4165 (goto-char (match-end 0))
4166 ;; Heading not found, just insert it at the end
4167 (goto-char (point-max))
4168 (or (bolp) (insert "\n"))
4169 (insert "\n" heading "\n")
4170 (end-of-line 0))
4171 ;; Make the heading visible, and the following as well
4172 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
4173 (if (re-search-forward
4174 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
4175 nil t)
4176 (progn (goto-char (match-beginning 0)) (insert "\n")
4177 (beginning-of-line 0))
4178 (goto-char (point-max)) (insert "\n")))
4179 (goto-char (point-max)) (insert "\n"))
4180 ;; Paste
4181 (org-paste-subtree (1+ level))
4182 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4183 (if org-archive-mark-done
4184 (org-todo (length org-todo-keywords)))
4185 ;; Move cursor to right after the TODO keyword
4186 (when org-archive-stamp-time
4187 (beginning-of-line 1)
4188 (looking-at org-todo-line-regexp)
4189 (goto-char (or (match-end 2) (match-beginning 3)))
4190 (insert "(" (format-time-string (cdr org-time-stamp-formats)
4191 (org-current-time))
4192 ")"))
4193 ;; Save the buffer, if it is not the same buffer.
4194 (if (not (eq this-buffer buffer)) (save-buffer))))
4195 ;; Here we are back in the original buffer. Everything seems to have
4196 ;; worked. So now cut the tree and finish up.
4197 (let (this-command) (org-cut-subtree))
4198 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4199 (message "Subtree archived %s"
4200 (if (eq this-buffer buffer)
4201 (concat "under heading: " heading)
4202 (concat "in file: " (abbreviate-file-name file))))))
4203
4204 ;;; Completion
4205
4206 (defun org-complete (&optional arg)
4207 "Perform completion on word at point.
4208 At the beginning of a headline, this completes TODO keywords as given in
4209 `org-todo-keywords'.
4210 If the current word is preceded by a backslash, completes the TeX symbols
4211 that are supported for HTML support.
4212 If the current word is preceded by \"#+\", completes special words for
4213 setting file options.
4214 At all other locations, this simply calls `ispell-complete-word'."
4215 (interactive "P")
4216 (catch 'exit
4217 (let* ((end (point))
4218 (beg1 (save-excursion
4219 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4220 (skip-chars-backward "a-zA-Z_@0-9")
4221 (point)))
4222 (beg (save-excursion
4223 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4224 (skip-chars-backward "a-zA-Z0-9_:$")
4225 (point)))
4226 (camel (equal (char-before beg) ?*))
4227 (tag (equal (char-before beg1) ?:))
4228 (texp (equal (char-before beg) ?\\))
4229 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
4230 beg)
4231 "#+"))
4232 (completion-ignore-case opt)
4233 (type nil)
4234 (tbl nil)
4235 (table (cond
4236 (opt
4237 (setq type :opt)
4238 (mapcar (lambda (x)
4239 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
4240 (cons (match-string 2 x) (match-string 1 x)))
4241 (org-split-string (org-get-current-options) "\n")))
4242 (texp
4243 (setq type :tex)
4244 org-html-entities)
4245 ((string-match "\\`\\*+[ \t]*\\'"
4246 (buffer-substring (point-at-bol) beg))
4247 (setq type :todo)
4248 (mapcar 'list org-todo-keywords))
4249 (camel
4250 (setq type :camel)
4251 (save-excursion
4252 (goto-char (point-min))
4253 (while (re-search-forward org-todo-line-regexp nil t)
4254 (push (list
4255 (if org-file-link-context-use-camel-case
4256 (org-make-org-heading-camel (match-string 3) t)
4257 (org-make-org-heading-search-string
4258 (match-string 3) t)))
4259 tbl)))
4260 tbl)
4261 (tag (setq type :tag beg beg1)
4262 (or org-tag-alist (org-get-buffer-tags)))
4263 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
4264 (pattern (buffer-substring-no-properties beg end))
4265 (completion (try-completion pattern table)))
4266 (cond ((eq completion t)
4267 (if (equal type :opt)
4268 (insert (substring (cdr (assoc (upcase pattern) table))
4269 (length pattern)))))
4270 ((null completion)
4271 (message "Can't find completion for \"%s\"" pattern)
4272 (ding))
4273 ((not (string= pattern completion))
4274 (delete-region beg end)
4275 (if (string-match " +$" completion)
4276 (setq completion (replace-match "" t t completion)))
4277 (insert completion)
4278 (if (get-buffer-window "*Completions*")
4279 (delete-window (get-buffer-window "*Completions*")))
4280 (if (assoc completion table)
4281 (if (eq type :todo) (insert " ")
4282 (if (eq type :tag) (insert ":"))))
4283 (if (and (equal type :opt) (assoc completion table))
4284 (message "%s" (substitute-command-keys
4285 "Press \\[org-complete] again to insert example settings"))))
4286 (t
4287 (message "Making completion list...")
4288 (let ((list (sort (all-completions pattern table) 'string<)))
4289 (with-output-to-temp-buffer "*Completions*"
4290 (condition-case nil
4291 ;; Protection needed for XEmacs and emacs 21
4292 (display-completion-list list pattern)
4293 (error (display-completion-list list)))))
4294 (message "Making completion list...%s" "done"))))))
4295
4296 ;;; Comments, TODO and DEADLINE
4297
4298 (defun org-toggle-comment ()
4299 "Change the COMMENT state of an entry."
4300 (interactive)
4301 (save-excursion
4302 (org-back-to-heading)
4303 (if (looking-at (concat outline-regexp
4304 "\\( +\\<" org-comment-string "\\>\\)"))
4305 (replace-match "" t t nil 1)
4306 (if (looking-at outline-regexp)
4307 (progn
4308 (goto-char (match-end 0))
4309 (insert " " org-comment-string))))))
4310
4311 (defvar org-last-todo-state-is-todo nil
4312 "This is non-nil when the last TODO state change led to a TODO state.
4313 If the last change removed the TODO tag or switched to DONE, then
4314 this is nil.")
4315
4316 (defun org-todo (&optional arg)
4317 "Change the TODO state of an item.
4318 The state of an item is given by a keyword at the start of the heading,
4319 like
4320 *** TODO Write paper
4321 *** DONE Call mom
4322
4323 The different keywords are specified in the variable `org-todo-keywords'.
4324 By default the available states are \"TODO\" and \"DONE\".
4325 So for this example: when the item starts with TODO, it is changed to DONE.
4326 When it starts with DONE, the DONE is removed. And when neither TODO nor
4327 DONE are present, add TODO at the beginning of the heading.
4328
4329 With prefix arg, use completion to determine the new state. With numeric
4330 prefix arg, switch to that state."
4331 (interactive "P")
4332 (save-excursion
4333 (org-back-to-heading)
4334 (if (looking-at outline-regexp) (goto-char (match-end 0)))
4335 (or (looking-at (concat " +" org-todo-regexp " *"))
4336 (looking-at " *"))
4337 (let* ((this (match-string 1))
4338 (completion-ignore-case t)
4339 (member (member this org-todo-keywords))
4340 (tail (cdr member))
4341 (state (cond
4342 ((equal arg '(4))
4343 ;; Read a state with completion
4344 (completing-read "State: " (mapcar (lambda(x) (list x))
4345 org-todo-keywords)
4346 nil t))
4347 ((eq arg 'right)
4348 (if this
4349 (if tail (car tail) nil)
4350 (car org-todo-keywords)))
4351 ((eq arg 'left)
4352 (if (equal member org-todo-keywords)
4353 nil
4354 (if this
4355 (nth (- (length org-todo-keywords) (length tail) 2)
4356 org-todo-keywords)
4357 org-done-string)))
4358 (arg
4359 ;; user requests a specific state
4360 (nth (1- (prefix-numeric-value arg))
4361 org-todo-keywords))
4362 ((null member) (car org-todo-keywords))
4363 ((null tail) nil) ;; -> first entry
4364 ((eq org-todo-interpretation 'sequence)
4365 (car tail))
4366 ((memq org-todo-interpretation '(type priority))
4367 (if (eq this-command last-command)
4368 (car tail)
4369 (if (> (length tail) 0) org-done-string nil)))
4370 (t nil)))
4371 (next (if state (concat " " state " ") " ")))
4372 (replace-match next t t)
4373 (setq org-last-todo-state-is-todo
4374 (not (equal state org-done-string)))
4375 (when org-log-done
4376 (if (equal state org-done-string)
4377 (org-add-planning-info 'closed (current-time) 'scheduled)
4378 (if (not this)
4379 (org-add-planning-info nil nil 'closed))))
4380 ;; Fixup tag positioning
4381 (and org-auto-align-tags (org-set-tags nil t))
4382 (run-hooks 'org-after-todo-state-change-hook)))
4383 ;; Fixup cursor location if close to the keyword
4384 (if (and (outline-on-heading-p)
4385 (not (bolp))
4386 (save-excursion (beginning-of-line 1)
4387 (looking-at org-todo-line-regexp))
4388 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
4389 (progn
4390 (goto-char (or (match-end 2) (match-end 1)))
4391 (just-one-space))))
4392
4393 (defun org-log-done (&optional undone)
4394 "Add a time stamp logging that a TODO entry has been closed.
4395 When UNDONE is non-nil, remove such a time stamp again."
4396 (interactive)
4397 (let (beg end col)
4398 (save-excursion
4399 (org-back-to-heading t)
4400 (setq beg (point))
4401 (looking-at (concat outline-regexp " *"))
4402 (goto-char (match-end 0))
4403 (setq col (current-column))
4404 (outline-next-heading)
4405 (setq end (point))
4406 (goto-char beg)
4407 (when (re-search-forward (concat
4408 "[\r\n]\\([ \t]*"
4409 (regexp-quote org-closed-string)
4410 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
4411 (delete-region (match-beginning 1) (match-end 1)))
4412 (unless undone
4413 (org-back-to-heading t)
4414 (skip-chars-forward "^\n\r")
4415 (goto-char (min (1+ (point)) (point-max)))
4416 (when (not (member (char-before) '(?\r ?\n)))
4417 (insert "\n"))
4418 (indent-to col)
4419 (insert org-closed-string " "
4420 (format-time-string
4421 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
4422 (org-current-time))
4423 "\n")))))
4424
4425 (defun org-show-todo-tree (arg)
4426 "Make a compact tree which shows all headlines marked with TODO.
4427 The tree will show the lines where the regexp matches, and all higher
4428 headlines above the match.
4429 With \\[universal-argument] prefix, also show the DONE entries.
4430 With a numeric prefix N, construct a sparse tree for the Nth element
4431 of `org-todo-keywords'."
4432 (interactive "P")
4433 (let ((case-fold-search nil)
4434 (kwd-re
4435 (cond ((null arg) org-not-done-regexp)
4436 ((equal arg '(4)) org-todo-regexp)
4437 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
4438 (regexp-quote (nth (1- (prefix-numeric-value arg))
4439 org-todo-keywords)))
4440 (t (error "Invalid prefix argument: %s" arg)))))
4441 (message "%d TODO entries found"
4442 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
4443
4444 (defun org-deadline ()
4445 "Insert the DEADLINE: string to make a deadline.
4446 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4447 to modify it to the correct date."
4448 (interactive)
4449 (org-add-planning-info 'deadline nil 'closed))
4450
4451 (defun org-schedule ()
4452 "Insert the SCHEDULED: string to schedule a TODO item.
4453 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4454 to modify it to the correct date."
4455 (interactive)
4456 (org-add-planning-info 'scheduled nil 'closed))
4457
4458 (defun org-add-planning-info (what &optional time &rest remove)
4459 "Insert new timestamp with keyword in the line directly after the headline.
4460 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
4461 If non is given, the user is prompted for a date.
4462 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
4463 be removed."
4464 (interactive)
4465 (when what (setq time (or time (org-read-date nil 'to-time))))
4466 (when (and org-insert-labeled-timestamps-at-point
4467 (member what '(scheduled deadline)))
4468 (insert
4469 (if (eq what 'scheduled) org-scheduled-string org-deadline-string)
4470 " "
4471 (format-time-string (car org-time-stamp-formats) time))
4472 (setq what nil))
4473 (save-excursion
4474 (let (beg end col list elt (buffer-invisibility-spec nil) ts)
4475 (org-back-to-heading t)
4476 (setq beg (point))
4477 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
4478 (goto-char (match-end 1))
4479 (setq col (current-column))
4480 (goto-char (1+ (match-end 0)))
4481 (if (and (not (looking-at outline-regexp))
4482 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
4483 "[^\r\n]*")))
4484 (narrow-to-region (match-beginning 0) (match-end 0))
4485 (insert "\n")
4486 (backward-char 1)
4487 (narrow-to-region (point) (point))
4488 (indent-to-column col))
4489 ;; Check if we have to remove something.
4490 (setq list (cons what remove))
4491 (while list
4492 (setq elt (pop list))
4493 (goto-char (point-min))
4494 (when (or (and (eq elt 'scheduled)
4495 (re-search-forward org-scheduled-time-regexp nil t))
4496 (and (eq elt 'deadline)
4497 (re-search-forward org-deadline-time-regexp nil t))
4498 (and (eq elt 'closed)
4499 (re-search-forward org-closed-time-regexp nil t)))
4500 (replace-match "")
4501 (if (looking-at " +") (replace-match ""))))
4502 (goto-char (point-max))
4503 (when what
4504 (insert
4505 (if (not (equal (char-before) ?\ )) " " "")
4506 (cond ((eq what 'scheduled) org-scheduled-string)
4507 ((eq what 'deadline) org-deadline-string)
4508 ((eq what 'closed) org-closed-string))
4509 " ")
4510 (insert
4511 (setq ts
4512 (format-time-string
4513 (if (eq what 'closed)
4514 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
4515 (car org-time-stamp-formats))
4516 time))))
4517 (goto-char (point-min))
4518 (widen)
4519 (if (looking-at "[ \t]+\r?\n")
4520 (replace-match ""))
4521 ts)))
4522
4523 (defun org-occur (regexp &optional callback)
4524 "Make a compact tree which shows all matches of REGEXP.
4525 The tree will show the lines where the regexp matches, and all higher
4526 headlines above the match. It will also show the heading after the match,
4527 to make sure editing the matching entry is easy.
4528 If CALLBACK is non-nil, it is a function which is called to confirm
4529 that the match should indeed be shown."
4530 (interactive "sRegexp: ")
4531 (org-remove-occur-highlights nil nil t)
4532 (setq regexp (org-check-occur-regexp regexp))
4533 (let ((cnt 0))
4534 (save-excursion
4535 (goto-char (point-min))
4536 (org-overview)
4537 (while (re-search-forward regexp nil t)
4538 (when (or (not callback)
4539 (save-match-data (funcall callback)))
4540 (setq cnt (1+ cnt))
4541 (org-highlight-new-match (match-beginning 0) (match-end 0))
4542 (org-show-hierarchy-above))))
4543 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
4544 nil 'local)
4545 (run-hooks 'org-occur-hook)
4546 (if (interactive-p)
4547 (message "%d match(es) for regexp %s" cnt regexp))
4548 cnt))
4549
4550 (defun org-show-hierarchy-above ()
4551 "Make sure point and the headings hierarchy above is visible."
4552 (catch 'exit
4553 (if (org-on-heading-p t)
4554 (org-flag-heading nil) ; only show the heading
4555 (and (or (org-invisible-p) (org-invisible-p2))
4556 (org-show-hidden-entry))) ; show entire entry
4557 (save-excursion
4558 (and org-show-following-heading
4559 (outline-next-heading)
4560 (org-flag-heading nil))) ; show the next heading
4561 (when org-show-hierarchy-above
4562 (save-excursion ; show all higher headings
4563 (while (and (condition-case nil
4564 (progn (org-up-heading-all 1) t)
4565 (error nil))
4566 (not (bobp)))
4567 (org-flag-heading nil))))))
4568
4569 ;; Overlay compatibility functions
4570 (defun org-make-overlay (beg end &optional buffer)
4571 (if (featurep 'xemacs)
4572 (make-extent beg end buffer)
4573 (make-overlay beg end buffer)))
4574 (defun org-delete-overlay (ovl)
4575 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4576 (defun org-detatch-overlay (ovl)
4577 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4578 (defun org-move-overlay (ovl beg end &optional buffer)
4579 (if (featurep 'xemacs)
4580 (set-extent-endpoints ovl beg end buffer)
4581 (move-overlay ovl beg end buffer)))
4582 (defun org-overlay-put (ovl prop value)
4583 (if (featurep 'xemacs)
4584 (set-extent-property ovl prop value)
4585 (overlay-put ovl prop value)))
4586
4587 (defvar org-occur-highlights nil)
4588 (defun org-highlight-new-match (beg end)
4589 "Highlight from BEG to END and mark the highlight is an occur headline."
4590 (let ((ov (org-make-overlay beg end)))
4591 (org-overlay-put ov 'face 'secondary-selection)
4592 (push ov org-occur-highlights)))
4593
4594 (defun org-remove-occur-highlights (&optional beg end noremove)
4595 "Remove the occur highlights from the buffer.
4596 BEG and END are ignored. If NOREMOVE is nil, remove this function
4597 from the `before-change-functions' in the current buffer."
4598 (interactive)
4599 (mapc 'org-delete-overlay org-occur-highlights)
4600 (setq org-occur-highlights nil)
4601 (unless noremove
4602 (remove-hook 'before-change-functions
4603 'org-remove-occur-highlights 'local)))
4604
4605 ;;; Priorities
4606
4607 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
4608 "Regular expression matching the priority indicator.")
4609
4610 (defvar org-remove-priority-next-time nil)
4611
4612 (defun org-priority-up ()
4613 "Increase the priority of the current item."
4614 (interactive)
4615 (org-priority 'up))
4616
4617 (defun org-priority-down ()
4618 "Decrease the priority of the current item."
4619 (interactive)
4620 (org-priority 'down))
4621
4622 (defun org-priority (&optional action)
4623 "Change the priority of an item by ARG.
4624 ACTION can be set, up, or down."
4625 (interactive)
4626 (setq action (or action 'set))
4627 (let (current new news have remove)
4628 (save-excursion
4629 (org-back-to-heading)
4630 (if (looking-at org-priority-regexp)
4631 (setq current (string-to-char (match-string 2))
4632 have t)
4633 (setq current org-default-priority))
4634 (cond
4635 ((eq action 'set)
4636 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
4637 (setq new (read-char-exclusive))
4638 (cond ((equal new ?\ ) (setq remove t))
4639 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
4640 (error "Priority must be between `%c' and `%c'"
4641 ?A org-lowest-priority))))
4642 ((eq action 'up)
4643 (setq new (1- current)))
4644 ((eq action 'down)
4645 (setq new (1+ current)))
4646 (t (error "Invalid action")))
4647 (setq new (min (max ?A (upcase new)) org-lowest-priority))
4648 (setq news (format "%c" new))
4649 (if have
4650 (if remove
4651 (replace-match "" t t nil 1)
4652 (replace-match news t t nil 2))
4653 (if remove
4654 (error "No priority cookie found in line")
4655 (looking-at org-todo-line-regexp)
4656 (if (match-end 2)
4657 (progn
4658 (goto-char (match-end 2))
4659 (insert " [#" news "]"))
4660 (goto-char (match-beginning 3))
4661 (insert "[#" news "] ")))))
4662 (if remove
4663 (message "Priority removed")
4664 (message "Priority of current item set to %s" news))))
4665
4666
4667 (defun org-get-priority (s)
4668 "Find priority cookie and return priority."
4669 (save-match-data
4670 (if (not (string-match org-priority-regexp s))
4671 (* 1000 (- org-lowest-priority org-default-priority))
4672 (* 1000 (- org-lowest-priority
4673 (string-to-char (match-string 2 s)))))))
4674
4675 ;;; Timestamps
4676
4677 (defvar org-last-changed-timestamp nil)
4678
4679 (defun org-time-stamp (arg)
4680 "Prompt for a date/time and insert a time stamp.
4681 If the user specifies a time like HH:MM, or if this command is called
4682 with a prefix argument, the time stamp will contain date and time.
4683 Otherwise, only the date will be included. All parts of a date not
4684 specified by the user will be filled in from the current date/time.
4685 So if you press just return without typing anything, the time stamp
4686 will represent the current date/time. If there is already a timestamp
4687 at the cursor, it will be modified."
4688 (interactive "P")
4689 (let ((fmt (if arg (cdr org-time-stamp-formats)
4690 (car org-time-stamp-formats)))
4691 (org-time-was-given nil)
4692 time)
4693 (cond
4694 ((and (org-at-timestamp-p)
4695 (eq last-command 'org-time-stamp)
4696 (eq this-command 'org-time-stamp))
4697 (insert "--")
4698 (setq time (let ((this-command this-command))
4699 (org-read-date arg 'totime)))
4700 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4701 (insert (format-time-string fmt time)))
4702 ((org-at-timestamp-p)
4703 (setq time (let ((this-command this-command))
4704 (org-read-date arg 'totime)))
4705 (and (org-at-timestamp-p) (replace-match
4706 (setq org-last-changed-timestamp
4707 (format-time-string fmt time))
4708 t t))
4709 (message "Timestamp updated"))
4710 (t
4711 (setq time (let ((this-command this-command))
4712 (org-read-date arg 'totime)))
4713 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4714 (insert (format-time-string fmt time))))))
4715
4716 (defun org-time-stamp-inactive (&optional arg)
4717 "Insert an inactive time stamp.
4718 An inactive time stamp is enclosed in square brackets instead of angle
4719 brackets. It is inactive in the sense that it does not trigger agenda entries,
4720 does not link to the calendar and cannot be changed with the S-cursor keys.
4721 So these are more for recording a certain time/date."
4722 (interactive "P")
4723 (let ((fmt (if arg (cdr org-time-stamp-formats)
4724 (car org-time-stamp-formats)))
4725 (org-time-was-given nil)
4726 time)
4727 (setq time (org-read-date arg 'totime))
4728 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4729 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
4730 (insert (format-time-string fmt time))))
4731
4732 (defvar org-date-ovl (org-make-overlay 1 1))
4733 (org-overlay-put org-date-ovl 'face 'org-warning)
4734 (org-detatch-overlay org-date-ovl)
4735
4736 (defun org-read-date (&optional with-time to-time)
4737 "Read a date and make things smooth for the user.
4738 The prompt will suggest to enter an ISO date, but you can also enter anything
4739 which will at least partially be understood by `parse-time-string'.
4740 Unrecognized parts of the date will default to the current day, month, year,
4741 hour and minute. For example,
4742 3-2-5 --> 2003-02-05
4743 feb 15 --> currentyear-02-15
4744 sep 12 9 --> 2009-09-12
4745 12:45 --> today 12:45
4746 22 sept 0:34 --> currentyear-09-22 0:34
4747 12 --> currentyear-currentmonth-12
4748 Fri --> nearest Friday (today or later)
4749 etc.
4750 The function understands only English month and weekday abbreviations,
4751 but this can be configured with the variables `parse-time-months' and
4752 `parse-time-weekdays'.
4753
4754 While prompting, a calendar is popped up - you can also select the
4755 date with the mouse (button 1). The calendar shows a period of three
4756 months. To scroll it to other months, use the keys `>' and `<'.
4757 If you don't like the calendar, turn it off with
4758 \(setq org-popup-calendar-for-date-prompt nil)
4759
4760 With optional argument TO-TIME, the date will immediately be converted
4761 to an internal time.
4762 With an optional argument WITH-TIME, the prompt will suggest to also
4763 insert a time. Note that when WITH-TIME is not set, you can still
4764 enter a time, and this function will inform the calling routine about
4765 this change. The calling routine may then choose to change the format
4766 used to insert the time stamp into the buffer to include the time."
4767 (require 'parse-time)
4768 (let* ((org-time-stamp-rounding-minutes
4769 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
4770 (ct (org-current-time))
4771 (default-time
4772 ;; Default time is either today, or, when entering a range,
4773 ;; the range start.
4774 (if (save-excursion
4775 (re-search-backward
4776 (concat org-ts-regexp "--\\=") ; FIXME: exactly two minuses?
4777 (- (point) 20) t))
4778 (apply
4779 'encode-time
4780 (mapcar (lambda(x) (or x 0))
4781 (parse-time-string (match-string 1))))
4782 ct))
4783 (calendar-move-hook nil)
4784 (view-diary-entries-initially nil)
4785 (view-calendar-holidays-initially nil)
4786 (timestr (format-time-string
4787 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
4788 (prompt (format "YYYY-MM-DD [%s]: " timestr))
4789 ans ans1 ans2
4790 second minute hour day month year tl wday wday1)
4791
4792 (if org-popup-calendar-for-date-prompt
4793 (save-excursion
4794 (save-window-excursion
4795 (calendar)
4796 (calendar-forward-day (- (time-to-days default-time)
4797 (calendar-absolute-from-gregorian
4798 (calendar-current-date))))
4799 (org-eval-in-calendar nil)
4800 (let* ((old-map (current-local-map))
4801 (map (copy-keymap calendar-mode-map))
4802 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
4803 (define-key map (kbd "RET") 'org-calendar-select)
4804 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
4805 'org-calendar-select-mouse)
4806 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
4807 'org-calendar-select-mouse)
4808 (define-key minibuffer-local-map [(meta shift left)]
4809 (lambda () (interactive)
4810 (org-eval-in-calendar '(calendar-backward-month 1))))
4811 (define-key minibuffer-local-map [(meta shift right)]
4812 (lambda () (interactive)
4813 (org-eval-in-calendar '(calendar-forward-month 1))))
4814 (define-key minibuffer-local-map [(shift up)]
4815 (lambda () (interactive)
4816 (org-eval-in-calendar '(calendar-backward-week 1))))
4817 (define-key minibuffer-local-map [(shift down)]
4818 (lambda () (interactive)
4819 (org-eval-in-calendar '(calendar-forward-week 1))))
4820 (define-key minibuffer-local-map [(shift left)]
4821 (lambda () (interactive)
4822 (org-eval-in-calendar '(calendar-backward-day 1))))
4823 (define-key minibuffer-local-map [(shift right)]
4824 (lambda () (interactive)
4825 (org-eval-in-calendar '(calendar-forward-day 1))))
4826 (define-key minibuffer-local-map ">"
4827 (lambda () (interactive)
4828 (org-eval-in-calendar '(scroll-calendar-left 1))))
4829 (define-key minibuffer-local-map "<"
4830 (lambda () (interactive)
4831 (org-eval-in-calendar '(scroll-calendar-right 1))))
4832 (unwind-protect
4833 (progn
4834 (use-local-map map)
4835 (setq ans (read-string prompt "" nil nil))
4836 (if (not (string-match "\\S-" ans)) (setq ans nil))
4837 (setq ans (or ans1 ans ans2)))
4838 (use-local-map old-map)))))
4839 ;; Naked prompt only
4840 (setq ans (read-string prompt "" nil timestr)))
4841 (org-detatch-overlay org-date-ovl)
4842
4843 (if (string-match
4844 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
4845 (progn
4846 (setq year (if (match-end 2)
4847 (string-to-number (match-string 2 ans))
4848 (string-to-number (format-time-string "%Y")))
4849 month (string-to-number (match-string 3 ans))
4850 day (string-to-number (match-string 4 ans)))
4851 (if (< year 100) (setq year (+ 2000 year)))
4852 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
4853 t nil ans))))
4854 (setq tl (parse-time-string ans)
4855 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
4856 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
4857 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
4858 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
4859 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
4860 second (or (nth 0 tl) 0)
4861 wday (nth 6 tl))
4862 (when (and wday (not (nth 3 tl)))
4863 ;; Weekday was given, but no day, so pick that day in the week
4864 ;; on or after the derived date.
4865 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
4866 (unless (equal wday wday1)
4867 (setq day (+ day (% (- wday wday1 -7) 7)))))
4868 (if (and (boundp 'org-time-was-given)
4869 (nth 2 tl))
4870 (setq org-time-was-given t))
4871 (if (< year 100) (setq year (+ 2000 year)))
4872 (if to-time
4873 (encode-time second minute hour day month year)
4874 (if (or (nth 1 tl) (nth 2 tl))
4875 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
4876 (format "%04d-%02d-%02d" year month day)))))
4877
4878 (defun org-eval-in-calendar (form)
4879 "Eval FORM in the calendar window and return to current window.
4880 Also, store the cursor date in variable ans2."
4881 (let ((sw (selected-window)))
4882 (select-window (get-buffer-window "*Calendar*"))
4883 (eval form)
4884 (when (calendar-cursor-to-date)
4885 (let* ((date (calendar-cursor-to-date))
4886 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4887 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4888 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4889 (select-window sw)))
4890
4891 (defun org-calendar-select ()
4892 "Return to `org-read-date' with the date currently selected.
4893 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4894 (interactive)
4895 (when (calendar-cursor-to-date)
4896 (let* ((date (calendar-cursor-to-date))
4897 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4898 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4899 (if (active-minibuffer-window) (exit-minibuffer))))
4900
4901 (defun org-calendar-select-mouse (ev)
4902 "Return to `org-read-date' with the date currently selected.
4903 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4904 (interactive "e")
4905 (mouse-set-point ev)
4906 (when (calendar-cursor-to-date)
4907 (let* ((date (calendar-cursor-to-date))
4908 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4909 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4910 (if (active-minibuffer-window) (exit-minibuffer))))
4911
4912 (defun org-check-deadlines (ndays)
4913 "Check if there are any deadlines due or past due.
4914 A deadline is considered due if it happens within `org-deadline-warning-days'
4915 days from today's date. If the deadline appears in an entry marked DONE,
4916 it is not shown. The prefix arg NDAYS can be used to test that many
4917 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4918 (interactive "P")
4919 (let* ((org-warn-days
4920 (cond
4921 ((equal ndays '(4)) 100000)
4922 (ndays (prefix-numeric-value ndays))
4923 (t org-deadline-warning-days)))
4924 (case-fold-search nil)
4925 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4926 (callback
4927 (lambda ()
4928 (and (let ((d1 (time-to-days (current-time)))
4929 (d2 (time-to-days
4930 (org-time-string-to-time (match-string 1)))))
4931 (< (- d2 d1) org-warn-days))
4932 (not (org-entry-is-done-p))))))
4933 (message "%d deadlines past-due or due within %d days"
4934 (org-occur regexp callback)
4935 org-warn-days)))
4936
4937 (defun org-evaluate-time-range (&optional to-buffer)
4938 "Evaluate a time range by computing the difference between start and end.
4939 Normally the result is just printed in the echo area, but with prefix arg
4940 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4941 If the time range is actually in a table, the result is inserted into the
4942 next column.
4943 For time difference computation, a year is assumed to be exactly 365
4944 days in order to avoid rounding problems."
4945 (interactive "P")
4946 (save-excursion
4947 (unless (org-at-date-range-p)
4948 (goto-char (point-at-bol))
4949 (re-search-forward org-tr-regexp (point-at-eol) t))
4950 (if (not (org-at-date-range-p))
4951 (error "Not at a time-stamp range, and none found in current line")))
4952 (let* ((ts1 (match-string 1))
4953 (ts2 (match-string 2))
4954 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4955 (match-end (match-end 0))
4956 (time1 (org-time-string-to-time ts1))
4957 (time2 (org-time-string-to-time ts2))
4958 (t1 (time-to-seconds time1))
4959 (t2 (time-to-seconds time2))
4960 (diff (abs (- t2 t1)))
4961 (negative (< (- t2 t1) 0))
4962 ;; (ys (floor (* 365 24 60 60)))
4963 (ds (* 24 60 60))
4964 (hs (* 60 60))
4965 (fy "%dy %dd %02d:%02d")
4966 (fy1 "%dy %dd")
4967 (fd "%dd %02d:%02d")
4968 (fd1 "%dd")
4969 (fh "%02d:%02d")
4970 y d h m align)
4971 (if havetime
4972 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4973 y 0
4974 d (floor (/ diff ds)) diff (mod diff ds)
4975 h (floor (/ diff hs)) diff (mod diff hs)
4976 m (floor (/ diff 60)))
4977 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4978 y 0
4979 d (floor (+ (/ diff ds) 0.5))
4980 h 0 m 0))
4981 (if (not to-buffer)
4982 (message (org-make-tdiff-string y d h m))
4983 (when (org-at-table-p)
4984 (goto-char match-end)
4985 (setq align t)
4986 (and (looking-at " *|") (goto-char (match-end 0))))
4987 (if (looking-at
4988 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4989 (replace-match ""))
4990 (if negative (insert " -"))
4991 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4992 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4993 (insert " " (format fh h m))))
4994 (if align (org-table-align))
4995 (message "Time difference inserted"))))
4996
4997 (defun org-make-tdiff-string (y d h m)
4998 (let ((fmt "")
4999 (l nil))
5000 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
5001 l (push y l)))
5002 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
5003 l (push d l)))
5004 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
5005 l (push h l)))
5006 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
5007 l (push m l)))
5008 (apply 'format fmt (nreverse l))))
5009
5010 (defun org-time-string-to-time (s)
5011 (apply 'encode-time (org-parse-time-string s)))
5012
5013 (defun org-parse-time-string (s &optional nodefault)
5014 "Parse the standard Org-mode time string.
5015 This should be a lot faster than the normal `parse-time-string'.
5016 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
5017 hour and minute fields will be nil if not given."
5018 (if (string-match org-ts-regexp1 s)
5019 (list 0
5020 (if (or (match-beginning 8) (not nodefault))
5021 (string-to-number (or (match-string 8 s) "0")))
5022 (if (or (match-beginning 7) (not nodefault))
5023 (string-to-number (or (match-string 7 s) "0")))
5024 (string-to-number (match-string 4 s))
5025 (string-to-number (match-string 3 s))
5026 (string-to-number (match-string 2 s))
5027 nil nil nil)
5028 (make-list 9 0)))
5029
5030 (defun org-timestamp-up (&optional arg)
5031 "Increase the date item at the cursor by one.
5032 If the cursor is on the year, change the year. If it is on the month or
5033 the day, change that.
5034 With prefix ARG, change by that many units."
5035 (interactive "p")
5036 (org-timestamp-change (prefix-numeric-value arg)))
5037
5038 (defun org-timestamp-down (&optional arg)
5039 "Decrease the date item at the cursor by one.
5040 If the cursor is on the year, change the year. If it is on the month or
5041 the day, change that.
5042 With prefix ARG, change by that many units."
5043 (interactive "p")
5044 (org-timestamp-change (- (prefix-numeric-value arg))))
5045
5046 (defun org-timestamp-up-day (&optional arg)
5047 "Increase the date in the time stamp by one day.
5048 With prefix ARG, change that many days."
5049 (interactive "p")
5050 (if (and (not (org-at-timestamp-p))
5051 (org-on-heading-p))
5052 (org-todo 'up)
5053 (org-timestamp-change (prefix-numeric-value arg) 'day)))
5054
5055 (defun org-timestamp-down-day (&optional arg)
5056 "Decrease the date in the time stamp by one day.
5057 With prefix ARG, change that many days."
5058 (interactive "p")
5059 (if (and (not (org-at-timestamp-p))
5060 (org-on-heading-p))
5061 (org-todo 'down)
5062 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
5063
5064 (defsubst org-pos-in-match-range (pos n)
5065 (and (match-beginning n)
5066 (<= (match-beginning n) pos)
5067 (>= (match-end n) pos)))
5068
5069 (defun org-at-timestamp-p ()
5070 "Determine if the cursor is in or at a timestamp."
5071 (interactive)
5072 (let* ((tsr org-ts-regexp2)
5073 (pos (point))
5074 (ans (or (looking-at tsr)
5075 (save-excursion
5076 (skip-chars-backward "^<\n\r\t")
5077 (if (> (point) 1) (backward-char 1))
5078 (and (looking-at tsr)
5079 (> (- (match-end 0) pos) -1))))))
5080 (and (boundp 'org-ts-what)
5081 (setq org-ts-what
5082 (cond
5083 ((org-pos-in-match-range pos 2) 'year)
5084 ((org-pos-in-match-range pos 3) 'month)
5085 ((org-pos-in-match-range pos 7) 'hour)
5086 ((org-pos-in-match-range pos 8) 'minute)
5087 ((or (org-pos-in-match-range pos 4)
5088 (org-pos-in-match-range pos 5)) 'day)
5089 (t 'day))))
5090 ans))
5091
5092 (defun org-timestamp-change (n &optional what)
5093 "Change the date in the time stamp at point.
5094 The date will be changed by N times WHAT. WHAT can be `day', `month',
5095 `year', `minute', `second'. If WHAT is not given, the cursor position
5096 in the timestamp determines what will be changed."
5097 (let ((fmt (car org-time-stamp-formats))
5098 org-ts-what
5099 (pos (point))
5100 ts time time0)
5101 (if (not (org-at-timestamp-p))
5102 (error "Not at a timestamp"))
5103 (setq org-ts-what (or what org-ts-what))
5104 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
5105 (- (match-end 0) (match-beginning 0))))
5106 1)
5107 (cdr org-time-stamp-formats)
5108 (car org-time-stamp-formats)))
5109 (setq ts (match-string 0))
5110 (replace-match "")
5111 (setq time0 (org-parse-time-string ts))
5112 (setq time
5113 (apply 'encode-time
5114 (append
5115 (list (or (car time0) 0))
5116 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
5117 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
5118 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
5119 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
5120 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
5121 (nthcdr 6 time0))))
5122 (if (eq what 'calendar)
5123 (let ((cal-date
5124 (save-excursion
5125 (save-match-data
5126 (set-buffer "*Calendar*")
5127 (calendar-cursor-to-date)))))
5128 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
5129 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
5130 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
5131 (setcar time0 (or (car time0) 0))
5132 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
5133 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
5134 (setq time (apply 'encode-time time0))))
5135 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
5136 (goto-char pos)
5137 ;; Try to recenter the calendar window, if any
5138 (if (and org-calendar-follow-timestamp-change
5139 (get-buffer-window "*Calendar*" t)
5140 (memq org-ts-what '(day month year)))
5141 (org-recenter-calendar (time-to-days time)))))
5142
5143 (defun org-recenter-calendar (date)
5144 "If the calendar is visible, recenter it to DATE."
5145 (let* ((win (selected-window))
5146 (cwin (get-buffer-window "*Calendar*" t))
5147 (calendar-move-hook nil))
5148 (when cwin
5149 (select-window cwin)
5150 (calendar-goto-date (if (listp date) date
5151 (calendar-gregorian-from-absolute date)))
5152 (select-window win))))
5153
5154 (defun org-goto-calendar (&optional arg)
5155 "Go to the Emacs calendar at the current date.
5156 If there is a time stamp in the current line, go to that date.
5157 A prefix ARG can be used to force the current date."
5158 (interactive "P")
5159 (let ((tsr org-ts-regexp) diff
5160 (calendar-move-hook nil)
5161 (view-calendar-holidays-initially nil)
5162 (view-diary-entries-initially nil))
5163 (if (or (org-at-timestamp-p)
5164 (save-excursion
5165 (beginning-of-line 1)
5166 (looking-at (concat ".*" tsr))))
5167 (let ((d1 (time-to-days (current-time)))
5168 (d2 (time-to-days
5169 (org-time-string-to-time (match-string 1)))))
5170 (setq diff (- d2 d1))))
5171 (calendar)
5172 (calendar-goto-today)
5173 (if (and diff (not arg)) (calendar-forward-day diff))))
5174
5175 (defun org-date-from-calendar ()
5176 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
5177 If there is already a time stamp at the cursor position, update it."
5178 (interactive)
5179 (org-timestamp-change 0 'calendar))
5180
5181 ;;; Agenda, and Diary Integration
5182
5183 ;;; Define the mode
5184
5185 (defvar org-agenda-mode-map (make-sparse-keymap)
5186 "Keymap for `org-agenda-mode'.")
5187
5188 (defvar org-agenda-menu) ; defined later in this file.
5189 (defvar org-agenda-follow-mode nil)
5190 (defvar org-agenda-show-log nil)
5191 (defvar org-agenda-buffer-name "*Org Agenda*")
5192 (defvar org-agenda-redo-command nil)
5193 (defvar org-agenda-mode-hook nil)
5194 (defvar org-agenda-type nil)
5195 (defvar org-agenda-force-single-file nil)
5196
5197 (defun org-agenda-mode ()
5198 "Mode for time-sorted view on action items in Org-mode files.
5199
5200 The following commands are available:
5201
5202 \\{org-agenda-mode-map}"
5203 (interactive)
5204 (kill-all-local-variables)
5205 (setq major-mode 'org-agenda-mode)
5206 (setq mode-name "Org-Agenda")
5207 (use-local-map org-agenda-mode-map)
5208 (easy-menu-add org-agenda-menu)
5209 (if org-startup-truncated (setq truncate-lines t))
5210 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
5211 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
5212 (unless org-agenda-keep-modes
5213 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
5214 org-agenda-show-log nil))
5215 (easy-menu-change
5216 '("Agenda") "Agenda Files"
5217 (append
5218 (list
5219 (vector
5220 (if (get 'org-agenda-files 'org-restrict)
5221 "Restricted to single file"
5222 "Edit File List")
5223 '(org-edit-agenda-file-list)
5224 (not (get 'org-agenda-files 'org-restrict)))
5225 "--")
5226 (mapcar 'org-file-menu-entry (org-agenda-files))))
5227 (org-agenda-set-mode-name)
5228 (apply
5229 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
5230 (list 'org-agenda-mode-hook)))
5231
5232 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
5233 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
5234 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
5235 (define-key org-agenda-mode-map " " 'org-agenda-show)
5236 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
5237 (define-key org-agenda-mode-map "o" 'delete-other-windows)
5238 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
5239 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
5240 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
5241 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
5242 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
5243 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
5244 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
5245 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
5246 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
5247 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
5248
5249 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
5250 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
5251 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
5252 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
5253 (while l (define-key org-agenda-mode-map
5254 (int-to-string (pop l)) 'digit-argument)))
5255
5256 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
5257 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
5258 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
5259 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
5260 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
5261 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
5262 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
5263 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
5264 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
5265 (define-key org-agenda-mode-map "n" 'next-line)
5266 (define-key org-agenda-mode-map "p" 'previous-line)
5267 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
5268 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
5269 (define-key org-agenda-mode-map "," 'org-agenda-priority)
5270 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
5271 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
5272 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
5273 (eval-after-load "calendar"
5274 '(define-key calendar-mode-map org-calendar-to-agenda-key
5275 'org-calendar-goto-agenda))
5276 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
5277 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
5278 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
5279 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
5280 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
5281 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
5282 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
5283 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
5284 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
5285 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
5286 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
5287 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
5288 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
5289 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
5290 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
5291 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
5292 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
5293 "Local keymap for agenda entries from Org-mode.")
5294
5295 (define-key org-agenda-keymap
5296 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
5297 (define-key org-agenda-keymap
5298 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
5299 (when org-agenda-mouse-1-follows-link
5300 (define-key org-agenda-keymap [follow-link] 'mouse-face))
5301 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
5302 '("Agenda"
5303 ("Agenda Files")
5304 "--"
5305 ["Show" org-agenda-show t]
5306 ["Go To (other window)" org-agenda-goto t]
5307 ["Go To (one window)" org-agenda-switch-to t]
5308 ["Follow Mode" org-agenda-follow-mode
5309 :style toggle :selected org-agenda-follow-mode :active t]
5310 "--"
5311 ["Cycle TODO" org-agenda-todo t]
5312 ("Tags"
5313 ["Show all Tags" org-agenda-show-tags t]
5314 ["Set Tags" org-agenda-set-tags t])
5315 ("Schedule"
5316 ["Schedule" org-agenda-schedule t]
5317 ["Set Deadline" org-agenda-deadline t]
5318 "--"
5319 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
5320 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
5321 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
5322 ("Priority"
5323 ["Set Priority" org-agenda-priority t]
5324 ["Increase Priority" org-agenda-priority-up t]
5325 ["Decrease Priority" org-agenda-priority-down t]
5326 ["Show Priority" org-agenda-show-priority t])
5327 "--"
5328 ;; ["New agenda command" org-agenda t]
5329 ["Rebuild buffer" org-agenda-redo t]
5330 "--"
5331 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
5332 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
5333 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
5334 "--"
5335 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
5336 :style radio :selected (equal org-agenda-ndays 1)]
5337 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
5338 :style radio :selected (equal org-agenda-ndays 7)]
5339 "--"
5340 ["Show Logbook entries" org-agenda-log-mode
5341 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
5342 ["Include Diary" org-agenda-toggle-diary
5343 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
5344 ["Use Time Grid" org-agenda-toggle-time-grid
5345 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
5346 "--"
5347 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
5348 ("Calendar Commands"
5349 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
5350 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
5351 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
5352 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
5353 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
5354 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
5355 "--"
5356 ["Quit" org-agenda-quit t]
5357 ["Exit and Release Buffers" org-agenda-exit t]
5358 ))
5359
5360 ;;;###autoload
5361 (defun org-agenda (arg)
5362 "Dispatch agenda commands to collect entries to the agenda buffer.
5363 Prompts for a character to select a command. Any prefix arg will be passed
5364 on to the selected command. The default selections are:
5365
5366 a Call `org-agenda' to display the agenda for the current day or week.
5367 t Call `org-todo-list' to display the global todo list.
5368 T Call `org-todo-list' to display the global todo list, select only
5369 entries with a specific TODO keyword (the user gets a prompt).
5370 m Call `org-tags-view' to display headlines with tags matching
5371 a condition (the user is prompted for the condition).
5372 M Like `m', but select only TODO entries, no ordinary headlines.
5373
5374 More commands can be added by configuring the variable
5375 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
5376 searches can be pre-defined in this way.
5377
5378 If the current buffer is in Org-mode and visiting a file, you can also
5379 first press `1' to indicate that the agenda should be temporarily (until the
5380 next use of \\[org-agenda]) restricted to the current file."
5381 (interactive "P")
5382 (catch 'exit
5383 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
5384 (custom org-agenda-custom-commands)
5385 c entry key type string)
5386 (put 'org-agenda-files 'org-restrict nil)
5387 (save-window-excursion
5388 (delete-other-windows)
5389 (switch-to-buffer-other-window " *Agenda Commands*")
5390 (erase-buffer)
5391 (insert
5392 "Press key for an agenda command:
5393 --------------------------------
5394 a Agenda for current week or day
5395 t List of all TODO entries T Entries with special TODO kwd
5396 m Match a TAGS query M Like m, but only TODO entries
5397 C Configure your own agenda commands")
5398 (while (setq entry (pop custom))
5399 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
5400 (insert (format "\n%-4s%-14s: %s"
5401 key
5402 (cond
5403 ((eq type 'tags) "Tags query")
5404 ((eq type 'todo) "TODO keyword")
5405 ((eq type 'tags-tree) "Tags tree")
5406 ((eq type 'todo-tree) "TODO kwd tree")
5407 ((eq type 'occur-tree) "Occur tree")
5408 (t "???"))
5409 (org-add-props string nil 'face 'org-warning))))
5410 (goto-char (point-min))
5411 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
5412 (message "Press key for agenda command%s"
5413 (if restrict-ok ", or [1] to restrict to current file" ""))
5414 (setq c (read-char-exclusive))
5415 (message "")
5416 (when (equal c ?1)
5417 (if restrict-ok
5418 (put 'org-agenda-files 'org-restrict (list buffer-file-name))
5419 (error "Cannot restrict agenda to current buffer"))
5420 (message "Press key for agenda command%s"
5421 (if restrict-ok " (restricted to current file)" ""))
5422 (setq c (read-char-exclusive))
5423 (message "")))
5424 (require 'calendar) ; FIXME: can we avoid this for some commands?
5425 ;; For example the todo list should not need it (but does...)
5426 (cond
5427 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
5428 ((equal c ?a) (call-interactively 'org-agenda-list))
5429 ((equal c ?t) (call-interactively 'org-todo-list))
5430 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
5431 ((equal c ?m) (call-interactively 'org-tags-view))
5432 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
5433 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
5434 (setq type (nth 1 entry) string (nth 2 entry))
5435 (cond
5436 ((eq type 'tags)
5437 (org-tags-view current-prefix-arg string))
5438 ((eq type 'tags-todo)
5439 (org-tags-view '(4) string))
5440 ((eq type 'todo)
5441 (org-todo-list string))
5442 ((eq type 'tags-tree)
5443 (org-check-for-org-mode)
5444 (org-tags-sparse-tree current-prefix-arg string))
5445 ((eq type 'todo-tree)
5446 (org-check-for-org-mode)
5447 (org-occur (concat "^" outline-regexp "[ \t]*"
5448 (regexp-quote string) "\\>")))
5449 ((eq type 'occur-tree)
5450 (org-check-for-org-mode)
5451 (org-occur string))
5452 (t (error "Invalid custom agenda command type %s" type))))
5453 (t (error "Invalid key"))))))
5454
5455 (defun org-check-for-org-mode ()
5456 "Make sure current buffer is in org-mode. Error if not."
5457 (or (eq major-mode 'org-mode)
5458 (error "Cannot execute org-mode agenda command on buffer in %s."
5459 major-mode)))
5460
5461 (defun org-fit-agenda-window ()
5462 "Fit the window to the buffer size."
5463 (and org-fit-agenda-window
5464 (fboundp 'fit-window-to-buffer)
5465 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
5466 (/ (frame-height) 2))))
5467
5468 (defun org-agenda-files (&optional unrestricted)
5469 "Get the list of agenda files.
5470 Optional UNRESTRICTED means return the full list even if a restriction
5471 is currently in place."
5472 (cond
5473 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
5474 ((stringp org-agenda-files) (org-read-agenda-file-list))
5475 ((listp org-agenda-files) org-agenda-files)
5476 (t (error "Invalid value of `org-agenda-files'"))))
5477
5478 (defvar org-window-configuration)
5479
5480 (defun org-edit-agenda-file-list ()
5481 "Edit the list of agenda files.
5482 Depending on setup, this either uses customize to edit the variable
5483 `org-agenda-files', or it visits the file that is holding the list. In the
5484 latter case, the buffer is set up in a way that saving it automatically kills
5485 the buffer and restores the previous window configuration."
5486 (interactive)
5487 (if (stringp org-agenda-files)
5488 (let ((cw (current-window-configuration)))
5489 (find-file org-agenda-files)
5490 (set (make-local-variable 'org-window-configuration) cw)
5491 (org-add-hook 'after-save-hook
5492 (lambda ()
5493 (set-window-configuration
5494 (prog1 org-window-configuration
5495 (kill-buffer (current-buffer))))
5496 (org-install-agenda-files-menu)
5497 (message "New agenda file list installed"))
5498 nil 'local)
5499 (message (substitute-command-keys
5500 "Edit list and finish with \\[save-buffer]")))
5501 (customize-variable 'org-agenda-files)))
5502
5503 (defun org-store-new-agenda-file-list (list)
5504 "Set new value for the agenda file list and save it correcly."
5505 (if (stringp org-agenda-files)
5506 (let ((f org-agenda-files) b)
5507 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
5508 (with-temp-file f
5509 (insert (mapconcat 'identity list "\n") "\n")))
5510 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5511 (setq org-agenda-files list)
5512 (customize-save-variable 'org-agenda-files org-agenda-files))))
5513
5514 (defun org-read-agenda-file-list ()
5515 "Read the list of agenda files from a file."
5516 (when (stringp org-agenda-files)
5517 (with-temp-buffer
5518 (insert-file-contents org-agenda-files)
5519 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
5520
5521 (defvar org-agenda-markers nil
5522 "List of all currently active markers created by `org-agenda'.")
5523 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
5524 "Creation time of the last agenda marker.")
5525
5526 (defun org-agenda-new-marker (&optional pos)
5527 "Return a new agenda marker.
5528 Org-mode keeps a list of these markers and resets them when they are
5529 no longer in use."
5530 (let ((m (copy-marker (or pos (point)))))
5531 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
5532 (push m org-agenda-markers)
5533 m))
5534
5535 (defun org-agenda-maybe-reset-markers (&optional force)
5536 "Reset markers created by `org-agenda'. But only if they are old enough."
5537 (if (or force
5538 (> (- (time-to-seconds (current-time))
5539 org-agenda-last-marker-time)
5540 5))
5541 (while org-agenda-markers
5542 (move-marker (pop org-agenda-markers) nil))))
5543
5544 (defvar org-agenda-new-buffers nil
5545 "Buffers created to visit agenda files.")
5546
5547 (defun org-get-agenda-file-buffer (file)
5548 "Get a buffer visiting FILE. If the buffer needs to be created, add
5549 it to the list of buffers which might be released later."
5550 (let ((buf (find-buffer-visiting file)))
5551 (if buf
5552 buf ; just return it
5553 ;; Make a new buffer and remember it
5554 (setq buf (find-file-noselect file))
5555 (if buf (push buf org-agenda-new-buffers))
5556 buf)))
5557
5558 (defun org-release-buffers (blist)
5559 "Release all buffers in list, asking the user for confirmation when needed.
5560 When a buffer is unmodified, it is just killed. When modified, it is saved
5561 \(if the user agrees) and then killed."
5562 (let (buf file)
5563 (while (setq buf (pop blist))
5564 (setq file (buffer-file-name buf))
5565 (when (and (buffer-modified-p buf)
5566 file
5567 (y-or-n-p (format "Save file %s? " file)))
5568 (with-current-buffer buf (save-buffer)))
5569 (kill-buffer buf))))
5570
5571 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
5572
5573 (defun org-timeline (&optional include-all keep-modes)
5574 "Show a time-sorted view of the entries in the current org file.
5575 Only entries with a time stamp of today or later will be listed. With
5576 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
5577 under the current date.
5578 If the buffer contains an active region, only check the region for
5579 dates."
5580 (interactive "P")
5581 (require 'calendar)
5582 (org-agenda-maybe-reset-markers 'force)
5583 (org-compile-prefix-format org-timeline-prefix-format)
5584 (let* ((dopast t)
5585 (dotodo include-all)
5586 (doclosed org-agenda-show-log)
5587 (org-agenda-keep-modes keep-modes)
5588 (entry buffer-file-name)
5589 (org-agenda-files (list buffer-file-name))
5590 (date (calendar-current-date))
5591 (win (selected-window))
5592 (pos1 (point))
5593 (beg (if (org-region-active-p) (region-beginning) (point-min)))
5594 (end (if (org-region-active-p) (region-end) (point-max)))
5595 (day-numbers (org-get-all-dates beg end 'no-ranges
5596 t doclosed)) ; always include today
5597 (today (time-to-days (current-time)))
5598 (org-respect-restriction t)
5599 (past t)
5600 args
5601 s e rtn d)
5602 (setq org-agenda-redo-command
5603 (list 'progn
5604 (list 'switch-to-buffer-other-window (current-buffer))
5605 (list 'org-timeline (list 'quote include-all) t)))
5606 (if (not dopast)
5607 ;; Remove past dates from the list of dates.
5608 (setq day-numbers (delq nil (mapcar (lambda(x)
5609 (if (>= x today) x nil))
5610 day-numbers))))
5611 (switch-to-buffer-other-window
5612 (get-buffer-create org-agenda-buffer-name))
5613 (setq buffer-read-only nil)
5614 (erase-buffer)
5615 (org-agenda-mode) (setq buffer-read-only nil)
5616 (set (make-local-variable 'org-agenda-type) 'timeline)
5617 (if doclosed (push :closed args))
5618 (push :timestamp args)
5619 (if dotodo (push :todo args))
5620 (while (setq d (pop day-numbers))
5621 (if (and (>= d today)
5622 dopast
5623 past)
5624 (progn
5625 (setq past nil)
5626 (insert (make-string 79 ?-) "\n")))
5627 (setq date (calendar-gregorian-from-absolute d))
5628 (setq s (point))
5629 (setq rtn (apply 'org-agenda-get-day-entries
5630 entry date args))
5631 (if (or rtn (equal d today))
5632 (progn
5633 (insert (calendar-day-name date) " "
5634 (number-to-string (extract-calendar-day date)) " "
5635 (calendar-month-name (extract-calendar-month date)) " "
5636 (number-to-string (extract-calendar-year date)) "\n")
5637 (put-text-property s (1- (point)) 'face
5638 'org-level-3)
5639 (if (equal d today)
5640 (put-text-property s (1- (point)) 'org-today t))
5641 (insert (org-finalize-agenda-entries rtn) "\n")
5642 (put-text-property s (1- (point)) 'day d))))
5643 (goto-char (point-min))
5644 (setq buffer-read-only t)
5645 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5646 (point-min)))
5647 (when (not org-select-timeline-window)
5648 (select-window win)
5649 (goto-char pos1))))
5650
5651 ;;;###autoload
5652 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
5653 "Produce a weekly view from all files in variable `org-agenda-files'.
5654 The view will be for the current week, but from the overview buffer you
5655 will be able to go to other weeks.
5656 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
5657 also be shown, under the current date.
5658 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
5659 on the days are also shown. See the variable `org-log-done' for how
5660 to turn on logging.
5661 START-DAY defaults to TODAY, or to the most recent match for the weekday
5662 given in `org-agenda-start-on-weekday'.
5663 NDAYS defaults to `org-agenda-ndays'."
5664 (interactive "P")
5665 (org-agenda-maybe-reset-markers 'force)
5666 (org-compile-prefix-format org-agenda-prefix-format)
5667 (require 'calendar)
5668 (let* ((org-agenda-start-on-weekday
5669 (if (or (equal ndays 1)
5670 (and (null ndays) (equal 1 org-agenda-ndays)))
5671 nil org-agenda-start-on-weekday))
5672 (org-agenda-keep-modes keep-modes)
5673 (thefiles (org-agenda-files))
5674 (files thefiles)
5675 (win (selected-window))
5676 (today (time-to-days (current-time)))
5677 (sd (or start-day today))
5678 (start (if (or (null org-agenda-start-on-weekday)
5679 (< org-agenda-ndays 7))
5680 sd
5681 (let* ((nt (calendar-day-of-week
5682 (calendar-gregorian-from-absolute sd)))
5683 (n1 org-agenda-start-on-weekday)
5684 (d (- nt n1)))
5685 (- sd (+ (if (< d 0) 7 0) d)))))
5686 (day-numbers (list start))
5687 (inhibit-redisplay t)
5688 s e rtn rtnall file date d start-pos end-pos todayp nd)
5689 (setq org-agenda-redo-command
5690 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
5691 ;; Make the list of days
5692 (setq ndays (or ndays org-agenda-ndays)
5693 nd ndays)
5694 (while (> ndays 1)
5695 (push (1+ (car day-numbers)) day-numbers)
5696 (setq ndays (1- ndays)))
5697 (setq day-numbers (nreverse day-numbers))
5698 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5699 (progn
5700 (delete-other-windows)
5701 (switch-to-buffer-other-window
5702 (get-buffer-create org-agenda-buffer-name))))
5703 (setq buffer-read-only nil)
5704 (erase-buffer)
5705 (org-agenda-mode) (setq buffer-read-only nil)
5706 (set (make-local-variable 'org-agenda-type) 'agenda)
5707 (set (make-local-variable 'starting-day) (car day-numbers))
5708 (set (make-local-variable 'include-all-loc) include-all)
5709 (when (and (or include-all org-agenda-include-all-todo)
5710 (member today day-numbers))
5711 (setq files thefiles
5712 rtnall nil)
5713 (while (setq file (pop files))
5714 (catch 'nextfile
5715 (org-check-agenda-file file)
5716 (setq date (calendar-gregorian-from-absolute today)
5717 rtn (org-agenda-get-day-entries
5718 file date :todo))
5719 (setq rtnall (append rtnall rtn))))
5720 (when rtnall
5721 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
5722 (add-text-properties (point-min) (1- (point))
5723 (list 'face 'org-level-3))
5724 (insert (org-finalize-agenda-entries rtnall) "\n")))
5725 (while (setq d (pop day-numbers))
5726 (setq date (calendar-gregorian-from-absolute d)
5727 s (point))
5728 (if (or (setq todayp (= d today))
5729 (and (not start-pos) (= d sd)))
5730 (setq start-pos (point))
5731 (if (and start-pos (not end-pos))
5732 (setq end-pos (point))))
5733 (setq files thefiles
5734 rtnall nil)
5735 (while (setq file (pop files))
5736 (catch 'nextfile
5737 (org-check-agenda-file file)
5738 (if org-agenda-show-log
5739 (setq rtn (org-agenda-get-day-entries
5740 file date
5741 :deadline :scheduled :timestamp :closed))
5742 (setq rtn (org-agenda-get-day-entries
5743 file date
5744 :deadline :scheduled :timestamp)))
5745 (setq rtnall (append rtnall rtn))))
5746 (if org-agenda-include-diary
5747 (progn
5748 (require 'diary-lib)
5749 (setq rtn (org-get-entries-from-diary date))
5750 (setq rtnall (append rtnall rtn))))
5751 (if (or rtnall org-agenda-show-all-dates)
5752 (progn
5753 (insert (format "%-9s %2d %s %4d\n"
5754 (calendar-day-name date)
5755 (extract-calendar-day date)
5756 (calendar-month-name (extract-calendar-month date))
5757 (extract-calendar-year date)))
5758 (put-text-property s (1- (point)) 'face
5759 'org-level-3)
5760 (if rtnall (insert
5761 (org-finalize-agenda-entries
5762 (org-agenda-add-time-grid-maybe
5763 rtnall nd todayp))
5764 "\n"))
5765 (put-text-property s (1- (point)) 'day d))))
5766 (goto-char (point-min))
5767 (setq buffer-read-only t)
5768 (org-fit-agenda-window)
5769 (unless (and (pos-visible-in-window-p (point-min))
5770 (pos-visible-in-window-p (point-max)))
5771 (goto-char (1- (point-max)))
5772 (recenter -1)
5773 (if (not (pos-visible-in-window-p (or start-pos 1)))
5774 (progn
5775 (goto-char (or start-pos 1))
5776 (recenter 1))))
5777 (goto-char (or start-pos 1))
5778 (if (not org-select-agenda-window) (select-window win))
5779 (message "")))
5780
5781 (defvar org-select-this-todo-keyword nil)
5782
5783 ;;;###autoload
5784 (defun org-todo-list (arg &optional keep-modes)
5785 "Show all TODO entries from all agenda file in a single list.
5786 The prefix arg can be used to select a specific TODO keyword and limit
5787 the list to these. When using \\[universal-argument], you will be prompted
5788 for a keyword. A numeric prefix directly selects the Nth keyword in
5789 `org-todo-keywords'."
5790 (interactive "P")
5791 (org-agenda-maybe-reset-markers 'force)
5792 (org-compile-prefix-format org-agenda-prefix-format)
5793 (let* ((org-agenda-keep-modes keep-modes)
5794 (today (time-to-days (current-time)))
5795 (date (calendar-gregorian-from-absolute today))
5796 (win (selected-window))
5797 (kwds org-todo-keywords)
5798 (completion-ignore-case t)
5799 (org-select-this-todo-keyword
5800 (if (stringp arg) arg
5801 (and arg (integerp arg) (> arg 0)
5802 (nth (1- arg) org-todo-keywords))))
5803 rtn rtnall files file pos)
5804 (when (equal arg '(4))
5805 (setq org-select-this-todo-keyword
5806 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
5807 nil t)))
5808 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
5809 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5810 (progn
5811 (delete-other-windows)
5812 (switch-to-buffer-other-window
5813 (get-buffer-create org-agenda-buffer-name))))
5814 (setq buffer-read-only nil)
5815 (erase-buffer)
5816 (org-agenda-mode) (setq buffer-read-only nil)
5817 (set (make-local-variable 'org-agenda-type) 'todo)
5818 (set (make-local-variable 'last-arg) arg)
5819 (set (make-local-variable 'org-todo-keywords) kwds)
5820 (set (make-local-variable 'org-agenda-redo-command)
5821 '(org-todo-list (or current-prefix-arg last-arg) t))
5822 (setq files (org-agenda-files)
5823 rtnall nil)
5824 (while (setq file (pop files))
5825 (catch 'nextfile
5826 (org-check-agenda-file file)
5827 (setq rtn (org-agenda-get-day-entries file date :todo))
5828 (setq rtnall (append rtnall rtn))))
5829 (insert "Global list of TODO items of type: ")
5830 (add-text-properties (point-min) (1- (point))
5831 (list 'face 'org-level-3))
5832 (setq pos (point))
5833 (insert (or org-select-this-todo-keyword "ALL") "\n")
5834 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
5835 (setq pos (point))
5836 (insert
5837 "Available with `N r': (0)ALL "
5838 (let ((n 0))
5839 (mapconcat (lambda (x)
5840 (format "(%d)%s" (setq n (1+ n)) x))
5841 org-todo-keywords " "))
5842 "\n")
5843 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
5844 (when rtnall
5845 (insert (org-finalize-agenda-entries rtnall) "\n"))
5846 (goto-char (point-min))
5847 (setq buffer-read-only t)
5848 (org-fit-agenda-window)
5849 (if (not org-select-agenda-window) (select-window win))))
5850
5851 (defun org-check-agenda-file (file)
5852 "Make sure FILE exists. If not, ask user what to do."
5853 (when (not (file-exists-p file))
5854 (message "non-existent file %s. [R]emove from list or [A]bort?"
5855 (abbreviate-file-name file))
5856 (let ((r (downcase (read-char-exclusive))))
5857 (cond
5858 ((equal r ?r)
5859 (org-remove-file file)
5860 (throw 'nextfile t))
5861 (t (error "Abort"))))))
5862
5863 (defun org-agenda-check-type (error &rest types)
5864 "Check if agenda buffer is of allowed type.
5865 If ERROR is non-nil, throw an error, otherwise just return nil."
5866 (if (memq org-agenda-type types)
5867 t
5868 (if error
5869 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
5870 nil)))
5871
5872 (defun org-agenda-quit ()
5873 "Exit agenda by removing the window or the buffer."
5874 (interactive)
5875 (let ((buf (current-buffer)))
5876 (if (not (one-window-p)) (delete-window))
5877 (kill-buffer buf)
5878 (org-agenda-maybe-reset-markers 'force)))
5879
5880 (defun org-agenda-exit ()
5881 "Exit agenda by removing the window or the buffer.
5882 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
5883 Org-mode buffers visited directly by the user will not be touched."
5884 (interactive)
5885 (org-release-buffers org-agenda-new-buffers)
5886 (setq org-agenda-new-buffers nil)
5887 (org-agenda-quit))
5888
5889 (defun org-agenda-redo ()
5890 "Rebuild Agenda.
5891 When this is the global TODO list, a prefix argument will be interpreted."
5892 (interactive)
5893 (message "Rebuilding agenda buffer...")
5894 (eval org-agenda-redo-command)
5895 (message "Rebuilding agenda buffer...done"))
5896
5897 (defun org-agenda-goto-today ()
5898 "Go to today."
5899 (interactive)
5900 (org-agenda-check-type t 'timeline 'agenda)
5901 (if (boundp 'starting-day)
5902 (let ((cmd (car org-agenda-redo-command))
5903 (iall (nth 1 org-agenda-redo-command))
5904 (nday (nth 3 org-agenda-redo-command))
5905 (keep (nth 4 org-agenda-redo-command)))
5906 (eval (list cmd iall nil nday keep)))
5907 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5908 (point-min)))))
5909
5910 (defun org-agenda-later (arg)
5911 "Go forward in time by `org-agenda-ndays' days.
5912 With prefix ARG, go forward that many times `org-agenda-ndays'."
5913 (interactive "p")
5914 (org-agenda-check-type t 'agenda)
5915 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5916 (+ starting-day (* arg org-agenda-ndays)) nil t))
5917
5918 (defun org-agenda-earlier (arg)
5919 "Go back in time by `org-agenda-ndays' days.
5920 With prefix ARG, go back that many times `org-agenda-ndays'."
5921 (interactive "p")
5922 (org-agenda-check-type t 'agenda)
5923 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5924 (- starting-day (* arg org-agenda-ndays)) nil t))
5925
5926 (defun org-agenda-week-view ()
5927 "Switch to weekly view for agenda."
5928 (interactive)
5929 (org-agenda-check-type t 'agenda)
5930 (setq org-agenda-ndays 7)
5931 (org-agenda-list include-all-loc
5932 (or (get-text-property (point) 'day)
5933 starting-day)
5934 nil t)
5935 (org-agenda-set-mode-name)
5936 (message "Switched to week view"))
5937
5938 (defun org-agenda-day-view ()
5939 "Switch to daily view for agenda."
5940 (interactive)
5941 (org-agenda-check-type t 'agenda)
5942 (setq org-agenda-ndays 1)
5943 (org-agenda-list include-all-loc
5944 (or (get-text-property (point) 'day)
5945 starting-day)
5946 nil t)
5947 (org-agenda-set-mode-name)
5948 (message "Switched to day view"))
5949
5950 (defun org-agenda-next-date-line (&optional arg)
5951 "Jump to the next line indicating a date in agenda buffer."
5952 (interactive "p")
5953 (org-agenda-check-type t 'agenda 'timeline)
5954 (beginning-of-line 1)
5955 (if (looking-at "^\\S-") (forward-char 1))
5956 (if (not (re-search-forward "^\\S-" nil t arg))
5957 (progn
5958 (backward-char 1)
5959 (error "No next date after this line in this buffer")))
5960 (goto-char (match-beginning 0)))
5961
5962 (defun org-agenda-previous-date-line (&optional arg)
5963 "Jump to the previous line indicating a date in agenda buffer."
5964 (interactive "p")
5965 (org-agenda-check-type t 'agenda 'timeline)
5966 (beginning-of-line 1)
5967 (if (not (re-search-backward "^\\S-" nil t arg))
5968 (error "No previous date before this line in this buffer")))
5969
5970 ;; Initialize the highlight
5971 (defvar org-hl (org-make-overlay 1 1))
5972 (org-overlay-put org-hl 'face 'highlight)
5973
5974 (defun org-highlight (begin end &optional buffer)
5975 "Highlight a region with overlay."
5976 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
5977 org-hl begin end (or buffer (current-buffer))))
5978
5979 (defun org-unhighlight ()
5980 "Detach overlay INDEX."
5981 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
5982
5983
5984 (defun org-agenda-follow-mode ()
5985 "Toggle follow mode in an agenda buffer."
5986 (interactive)
5987 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5988 (org-agenda-set-mode-name)
5989 (message "Follow mode is %s"
5990 (if org-agenda-follow-mode "on" "off")))
5991
5992 (defun org-agenda-log-mode ()
5993 "Toggle log mode in an agenda buffer."
5994 (interactive)
5995 (org-agenda-check-type t 'agenda 'timeline)
5996 (setq org-agenda-show-log (not org-agenda-show-log))
5997 (org-agenda-set-mode-name)
5998 (org-agenda-redo)
5999 (message "Log mode is %s"
6000 (if org-agenda-show-log "on" "off")))
6001
6002 (defun org-agenda-toggle-diary ()
6003 "Toggle diary inclusion in an agenda buffer."
6004 (interactive)
6005 (org-agenda-check-type t 'agenda)
6006 (setq org-agenda-include-diary (not org-agenda-include-diary))
6007 (org-agenda-redo)
6008 (org-agenda-set-mode-name)
6009 (message "Diary inclusion turned %s"
6010 (if org-agenda-include-diary "on" "off")))
6011
6012 (defun org-agenda-toggle-time-grid ()
6013 "Toggle time grid in an agenda buffer."
6014 (interactive)
6015 (org-agenda-check-type t 'agenda)
6016 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
6017 (org-agenda-redo)
6018 (org-agenda-set-mode-name)
6019 (message "Time-grid turned %s"
6020 (if org-agenda-use-time-grid "on" "off")))
6021
6022 (defun org-agenda-set-mode-name ()
6023 "Set the mode name to indicate all the small mode settings."
6024 (setq mode-name
6025 (concat "Org-Agenda"
6026 (if (equal org-agenda-ndays 1) " Day" "")
6027 (if (equal org-agenda-ndays 7) " Week" "")
6028 (if org-agenda-follow-mode " Follow" "")
6029 (if org-agenda-include-diary " Diary" "")
6030 (if org-agenda-use-time-grid " Grid" "")
6031 (if org-agenda-show-log " Log" "")))
6032 (force-mode-line-update))
6033
6034 (defun org-agenda-post-command-hook ()
6035 (and (eolp) (not (bolp)) (backward-char 1))
6036 (if (and org-agenda-follow-mode
6037 (get-text-property (point) 'org-marker))
6038 (org-agenda-show)))
6039
6040 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
6041
6042 (defun org-get-entries-from-diary (date)
6043 "Get the (Emacs Calendar) diary entries for DATE."
6044 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
6045 (diary-display-hook '(fancy-diary-display))
6046 (list-diary-entries-hook
6047 (cons 'org-diary-default-entry list-diary-entries-hook))
6048 (diary-file-name-prefix-function nil) ; turn this feature off
6049 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
6050 entries
6051 (org-disable-agenda-to-diary t))
6052 (save-excursion
6053 (save-window-excursion
6054 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
6055 (if (not (get-buffer fancy-diary-buffer))
6056 (setq entries nil)
6057 (with-current-buffer fancy-diary-buffer
6058 (setq buffer-read-only nil)
6059 (if (= (point-max) 1)
6060 ;; No entries
6061 (setq entries nil)
6062 ;; Omit the date and other unnecessary stuff
6063 (org-agenda-cleanup-fancy-diary)
6064 ;; Add prefix to each line and extend the text properties
6065 (if (= (point-max) 1)
6066 (setq entries nil)
6067 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
6068 (set-buffer-modified-p nil)
6069 (kill-buffer fancy-diary-buffer)))
6070 (when entries
6071 (setq entries (org-split-string entries "\n"))
6072 (setq entries
6073 (mapcar
6074 (lambda (x)
6075 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
6076 ;; Extend the text properties to the beginning of the line
6077 (org-add-props x (text-properties-at (1- (length x)) x)))
6078 entries)))))
6079
6080 (defun org-agenda-cleanup-fancy-diary ()
6081 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
6082 This gets rid of the date, the underline under the date, and
6083 the dummy entry installed by `org-mode' to ensure non-empty diary for each
6084 date. It also removes lines that contain only whitespace."
6085 (goto-char (point-min))
6086 (if (looking-at ".*?:[ \t]*")
6087 (progn
6088 (replace-match "")
6089 (re-search-forward "\n=+$" nil t)
6090 (replace-match "")
6091 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
6092 (re-search-forward "\n=+$" nil t)
6093 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
6094 (goto-char (point-min))
6095 (while (re-search-forward "^ +\n" nil t)
6096 (replace-match ""))
6097 (goto-char (point-min))
6098 (if (re-search-forward "^Org-mode dummy\n?" nil t)
6099 (replace-match "")))
6100
6101 ;; Make sure entries from the diary have the right text properties.
6102 (eval-after-load "diary-lib"
6103 '(if (boundp 'diary-modify-entry-list-string-function)
6104 ;; We can rely on the hook, nothing to do
6105 nil
6106 ;; Hook not avaiable, must use advice to make this work
6107 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
6108 "Make the position visible."
6109 (if (and org-disable-agenda-to-diary ;; called from org-agenda
6110 (stringp string)
6111 buffer-file-name)
6112 (setq string (org-modify-diary-entry-string string))))))
6113
6114 (defun org-modify-diary-entry-string (string)
6115 "Add text properties to string, allowing org-mode to act on it."
6116 (org-add-props string nil
6117 'mouse-face 'highlight
6118 'keymap org-agenda-keymap
6119 'help-echo (format "mouse-2 or RET jump to diary file %s"
6120 (abbreviate-file-name buffer-file-name))
6121 'org-agenda-diary-link t
6122 'org-marker (org-agenda-new-marker (point-at-bol))))
6123
6124 (defun org-diary-default-entry ()
6125 "Add a dummy entry to the diary.
6126 Needed to avoid empty dates which mess up holiday display."
6127 ;; Catch the error if dealing with the new add-to-diary-alist
6128 (when org-disable-agenda-to-diary
6129 (condition-case nil
6130 (add-to-diary-list original-date "Org-mode dummy" "")
6131 (error
6132 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
6133
6134 (defun org-cycle-agenda-files ()
6135 "Cycle through the files in `org-agenda-files'.
6136 If the current buffer visits an agenda file, find the next one in the list.
6137 If the current buffer does not, find the first agenda file."
6138 (interactive)
6139 (let* ((fs (org-agenda-files t))
6140 (files (append fs (list (car fs))))
6141 (tcf (if buffer-file-name (file-truename buffer-file-name)))
6142 file)
6143 (unless files (error "No agenda files"))
6144 (catch 'exit
6145 (while (setq file (pop files))
6146 (if (equal (file-truename file) tcf)
6147 (when (car files)
6148 (find-file (car files))
6149 (throw 'exit t))))
6150 (find-file (car fs)))))
6151
6152 (defun org-agenda-file-to-end ()
6153 "Move/add the current file to the end of the agenda file list.
6154 If the file is not present in the list, it is appended to the list. If it is
6155 present, it is moved there."
6156 (interactive)
6157 (org-agenda-file-to-front 'to-end))
6158
6159 (defun org-agenda-file-to-front (&optional to-end)
6160 "Move/add the current file to the top of the agenda file list.
6161 If the file is not present in the list, it is added to the front. If it is
6162 present, it is moved there. With optional argument TO-END, add/move to the
6163 end of the list."
6164 (interactive "P")
6165 (let ((file-alist (mapcar (lambda (x)
6166 (cons (file-truename x) x))
6167 (org-agenda-files t)))
6168 (ctf (file-truename buffer-file-name))
6169 x had)
6170 (setq x (assoc ctf file-alist) had x)
6171
6172 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
6173 (if to-end
6174 (setq file-alist (append (delq x file-alist) (list x)))
6175 (setq file-alist (cons x (delq x file-alist))))
6176 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
6177 (org-install-agenda-files-menu)
6178 (message "File %s to %s of agenda file list"
6179 (if had "moved" "added") (if to-end "end" "front"))))
6180
6181 (defun org-remove-file (&optional file)
6182 "Remove current file from the list of files in variable `org-agenda-files'.
6183 These are the files which are being checked for agenda entries.
6184 Optional argument FILE means, use this file instead of the current."
6185 (interactive)
6186 (let* ((file (or file buffer-file-name))
6187 (true-file (file-truename file))
6188 (afile (abbreviate-file-name file))
6189 (files (delq nil (mapcar
6190 (lambda (x)
6191 (if (equal true-file
6192 (file-truename x))
6193 nil x))
6194 (org-agenda-files t)))))
6195 (if (not (= (length files) (length (org-agenda-files t))))
6196 (progn
6197 (org-store-new-agenda-file-list files)
6198 (org-install-agenda-files-menu)
6199 (message "Removed file: %s" afile))
6200 (message "File was not in list: %s" afile))))
6201
6202 (defun org-file-menu-entry (file)
6203 (vector file (list 'find-file file) t))
6204
6205 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
6206 "Return a list of all relevant day numbers from BEG to END buffer positions.
6207 If NO-RANGES is non-nil, include only the start and end dates of a range,
6208 not every single day in the range. If FORCE-TODAY is non-nil, make
6209 sure that TODAY is included in the list. If INACTIVE is non-nil, also
6210 inactive time stamps (those in square brackets) are included."
6211 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
6212 dates date day day1 day2 ts1 ts2)
6213 (if force-today
6214 (setq dates (list (time-to-days (current-time)))))
6215 (save-excursion
6216 (goto-char beg)
6217 (while (re-search-forward re end t)
6218 (setq day (time-to-days (org-time-string-to-time
6219 (substring (match-string 1) 0 10))))
6220 (or (memq day dates) (push day dates)))
6221 (unless no-ranges
6222 (goto-char beg)
6223 (while (re-search-forward org-tr-regexp end t)
6224 (setq ts1 (substring (match-string 1) 0 10)
6225 ts2 (substring (match-string 2) 0 10)
6226 day1 (time-to-days (org-time-string-to-time ts1))
6227 day2 (time-to-days (org-time-string-to-time ts2)))
6228 (while (< (setq day1 (1+ day1)) day2)
6229 (or (memq day1 dates) (push day1 dates)))))
6230 (sort dates '<))))
6231
6232 ;;;###autoload
6233 (defun org-diary (&rest args)
6234 "Return diary information from org-files.
6235 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
6236 It accesses org files and extracts information from those files to be
6237 listed in the diary. The function accepts arguments specifying what
6238 items should be listed. The following arguments are allowed:
6239
6240 :timestamp List the headlines of items containing a date stamp or
6241 date range matching the selected date. Deadlines will
6242 also be listed, on the expiration day.
6243
6244 :deadline List any deadlines past due, or due within
6245 `org-deadline-warning-days'. The listing occurs only
6246 in the diary for *today*, not at any other date. If
6247 an entry is marked DONE, it is no longer listed.
6248
6249 :scheduled List all items which are scheduled for the given date.
6250 The diary for *today* also contains items which were
6251 scheduled earlier and are not yet marked DONE.
6252
6253 :todo List all TODO items from the org-file. This may be a
6254 long list - so this is not turned on by default.
6255 Like deadlines, these entries only show up in the
6256 diary for *today*, not at any other date.
6257
6258 The call in the diary file should look like this:
6259
6260 &%%(org-diary) ~/path/to/some/orgfile.org
6261
6262 Use a separate line for each org file to check. Or, if you omit the file name,
6263 all files listed in `org-agenda-files' will be checked automatically:
6264
6265 &%%(org-diary)
6266
6267 If you don't give any arguments (as in the example above), the default
6268 arguments (:deadline :scheduled :timestamp) are used. So the example above may
6269 also be written as
6270
6271 &%%(org-diary :deadline :timestamp :scheduled)
6272
6273 The function expects the lisp variables `entry' and `date' to be provided
6274 by the caller, because this is how the calendar works. Don't use this
6275 function from a program - use `org-agenda-get-day-entries' instead."
6276 (org-agenda-maybe-reset-markers)
6277 (org-compile-prefix-format org-agenda-prefix-format)
6278 (setq args (or args '(:deadline :scheduled :timestamp)))
6279 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
6280 (list entry)
6281 (org-agenda-files t)))
6282 file rtn results)
6283 ;; If this is called during org-agenda, don't return any entries to
6284 ;; the calendar. Org Agenda will list these entries itself.
6285 (if org-disable-agenda-to-diary (setq files nil))
6286 (while (setq file (pop files))
6287 (setq rtn (apply 'org-agenda-get-day-entries file date args))
6288 (setq results (append results rtn)))
6289 (if results
6290 (concat (org-finalize-agenda-entries results) "\n"))))
6291 (defvar org-category-table nil)
6292 (defun org-get-category-table ()
6293 "Get the table of categories and positions in current buffer."
6294 (let (tbl)
6295 (save-excursion
6296 (goto-char (point-min))
6297 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
6298 (push (cons (point) (org-trim (match-string 2))) tbl)))
6299 tbl))
6300 (defun org-get-category (&optional pos)
6301 "Get the category applying to position POS."
6302 (if (not org-category-table)
6303 (cond
6304 ((null org-category)
6305 (setq org-category
6306 (if buffer-file-name
6307 (file-name-sans-extension
6308 (file-name-nondirectory buffer-file-name))
6309 "???")))
6310 ((symbolp org-category) (symbol-name org-category))
6311 (t org-category))
6312 (let ((tbl org-category-table)
6313 (pos (or pos (point))))
6314 (while (and tbl (> (caar tbl) pos))
6315 (pop tbl))
6316 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
6317 org-category-table))))))
6318
6319 (defun org-agenda-get-day-entries (file date &rest args)
6320 "Does the work for `org-diary' and `org-agenda'.
6321 FILE is the path to a file to be checked for entries. DATE is date like
6322 the one returned by `calendar-current-date'. ARGS are symbols indicating
6323 which kind of entries should be extracted. For details about these, see
6324 the documentation of `org-diary'."
6325 (setq args (or args '(:deadline :scheduled :timestamp)))
6326 (let* ((org-startup-with-deadline-check nil)
6327 (org-startup-folded nil)
6328 (org-startup-align-all-tables nil)
6329 (buffer (if (file-exists-p file)
6330 (org-get-agenda-file-buffer file)
6331 (error "No such file %s" file)))
6332 arg results rtn)
6333 (if (not buffer)
6334 ;; If file does not exist, make sure an error message ends up in diary
6335 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
6336 (with-current-buffer buffer
6337 (unless (eq major-mode 'org-mode)
6338 (error "Agenda file %s is not in `org-mode'" file))
6339 (setq org-category-table (org-get-category-table))
6340 (let ((case-fold-search nil))
6341 (save-excursion
6342 (save-restriction
6343 (if org-respect-restriction
6344 (if (org-region-active-p)
6345 ;; Respect a region to restrict search
6346 (narrow-to-region (region-beginning) (region-end)))
6347 ;; If we work for the calendar or many files,
6348 ;; get rid of any restriction
6349 (widen))
6350 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
6351 (while (setq arg (pop args))
6352 (cond
6353 ((and (eq arg :todo)
6354 (equal date (calendar-current-date)))
6355 (setq rtn (org-agenda-get-todos))
6356 (setq results (append results rtn)))
6357 ((eq arg :timestamp)
6358 (setq rtn (org-agenda-get-blocks))
6359 (setq results (append results rtn))
6360 (setq rtn (org-agenda-get-timestamps))
6361 (setq results (append results rtn)))
6362 ((eq arg :scheduled)
6363 (setq rtn (org-agenda-get-scheduled))
6364 (setq results (append results rtn)))
6365 ((eq arg :closed)
6366 (setq rtn (org-agenda-get-closed))
6367 (setq results (append results rtn)))
6368 ((and (eq arg :deadline)
6369 (equal date (calendar-current-date)))
6370 (setq rtn (org-agenda-get-deadlines))
6371 (setq results (append results rtn))))))))
6372 results))))
6373
6374 (defun org-entry-is-done-p ()
6375 "Is the current entry marked DONE?"
6376 (save-excursion
6377 (and (re-search-backward "[\r\n]\\*" nil t)
6378 (looking-at org-nl-done-regexp))))
6379
6380 (defun org-at-date-range-p ()
6381 "Is the cursor inside a date range?"
6382 (interactive)
6383 (save-excursion
6384 (catch 'exit
6385 (let ((pos (point)))
6386 (skip-chars-backward "^<\r\n")
6387 (skip-chars-backward "<")
6388 (and (looking-at org-tr-regexp)
6389 (>= (match-end 0) pos)
6390 (throw 'exit t))
6391 (skip-chars-backward "^<\r\n")
6392 (skip-chars-backward "<")
6393 (and (looking-at org-tr-regexp)
6394 (>= (match-end 0) pos)
6395 (throw 'exit t)))
6396 nil)))
6397
6398 (defun org-agenda-get-todos ()
6399 "Return the TODO information for agenda display."
6400 (let* ((props (list 'face nil
6401 'done-face 'org-done
6402 'org-not-done-regexp org-not-done-regexp
6403 'mouse-face 'highlight
6404 'keymap org-agenda-keymap
6405 'help-echo
6406 (format "mouse-2 or RET jump to org file %s"
6407 (abbreviate-file-name buffer-file-name))))
6408 (regexp (concat "[\n\r]\\*+ *\\("
6409 (if org-select-this-todo-keyword
6410 (concat "\\<\\(" org-select-this-todo-keyword
6411 "\\)\\>")
6412 org-not-done-regexp)
6413 "[^\n\r]*\\)"))
6414 (sched-re (concat ".*\n.*?" org-scheduled-time-regexp))
6415 marker priority category tags
6416 ee txt)
6417 (goto-char (point-min))
6418 (while (re-search-forward regexp nil t)
6419 (when (not (and org-agenda-todo-ignore-scheduled
6420 (save-match-data (looking-at sched-re))))
6421 (goto-char (match-beginning 1))
6422 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
6423 category (org-get-category)
6424 tags (org-get-tags-at (point))
6425 txt (org-format-agenda-item "" (match-string 1) category tags)
6426 priority
6427 (+ (org-get-priority txt)
6428 (if org-todo-kwd-priority-p
6429 (- org-todo-kwd-max-priority -2
6430 (length
6431 (member (match-string 2) org-todo-keywords)))
6432 1)))
6433 (org-add-props txt props
6434 'org-marker marker 'org-hd-marker marker
6435 'priority priority 'category category)
6436 (push txt ee)
6437 (if org-agenda-todo-list-sublevels ; FIXME???? Change needed?
6438 (goto-char (match-end 1))
6439 (org-end-of-subtree 'invisible))))
6440 (nreverse ee)))
6441
6442 (defconst org-agenda-no-heading-message
6443 "No heading for this item in buffer or region.")
6444
6445 (defun org-agenda-get-timestamps ()
6446 "Return the date stamp information for agenda display."
6447 (let* ((props (list 'face nil
6448 'org-not-done-regexp org-not-done-regexp
6449 'mouse-face 'highlight
6450 'keymap org-agenda-keymap
6451 'help-echo
6452 (format "mouse-2 or RET jump to org file %s"
6453 (abbreviate-file-name buffer-file-name))))
6454 (regexp (regexp-quote
6455 (substring
6456 (format-time-string
6457 (car org-time-stamp-formats)
6458 (apply 'encode-time ; DATE bound by calendar
6459 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6460 0 11)))
6461 marker hdmarker deadlinep scheduledp donep tmp priority category
6462 ee txt timestr tags)
6463 (goto-char (point-min))
6464 (while (re-search-forward regexp nil t)
6465 (if (not (save-match-data (org-at-date-range-p)))
6466 (progn
6467 (setq marker (org-agenda-new-marker (match-beginning 0))
6468 category (org-get-category (match-beginning 0))
6469 tmp (buffer-substring (max (point-min)
6470 (- (match-beginning 0)
6471 org-ds-keyword-length))
6472 (match-beginning 0))
6473 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6474 deadlinep (string-match org-deadline-regexp tmp)
6475 scheduledp (string-match org-scheduled-regexp tmp)
6476 donep (org-entry-is-done-p))
6477 (if (string-match ">" timestr)
6478 ;; substring should only run to end of time stamp
6479 (setq timestr (substring timestr 0 (match-end 0))))
6480 (save-excursion
6481 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6482 (progn
6483 (goto-char (match-end 1))
6484 (setq hdmarker (org-agenda-new-marker)
6485 tags (org-get-tags-at))
6486 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6487 (setq txt (org-format-agenda-item
6488 (format "%s%s"
6489 (if deadlinep "Deadline: " "")
6490 (if scheduledp "Scheduled: " ""))
6491 (match-string 1) category tags timestr)))
6492 (setq txt org-agenda-no-heading-message))
6493 (setq priority (org-get-priority txt))
6494 (org-add-props txt props
6495 'org-marker marker 'org-hd-marker hdmarker)
6496 (if deadlinep
6497 (org-add-props txt nil
6498 'face (if donep 'org-done 'org-warning)
6499 'undone-face 'org-warning 'done-face 'org-done
6500 'category category 'priority (+ 100 priority))
6501 (if scheduledp
6502 (org-add-props txt nil
6503 'face 'org-scheduled-today
6504 'undone-face 'org-scheduled-today 'done-face 'org-done
6505 'category category 'priority (+ 99 priority))
6506 (org-add-props txt nil 'priority priority 'category category)))
6507 (push txt ee))
6508 (outline-next-heading))))
6509 (nreverse ee)))
6510
6511 (defun org-agenda-get-closed ()
6512 "Return the logged TODO entries for agenda display."
6513 (let* ((props (list 'mouse-face 'highlight
6514 'org-not-done-regexp org-not-done-regexp
6515 'keymap org-agenda-keymap
6516 'help-echo
6517 (format "mouse-2 or RET jump to org file %s"
6518 (abbreviate-file-name buffer-file-name))))
6519 (regexp (concat
6520 "\\<" org-closed-string " *\\["
6521 (regexp-quote
6522 (substring
6523 (format-time-string
6524 (car org-time-stamp-formats)
6525 (apply 'encode-time ; DATE bound by calendar
6526 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6527 1 11))))
6528 marker hdmarker priority category tags
6529 ee txt timestr)
6530 (goto-char (point-min))
6531 (while (re-search-forward regexp nil t)
6532 (if (not (save-match-data (org-at-date-range-p)))
6533 (progn
6534 (setq marker (org-agenda-new-marker (match-beginning 0))
6535 category (org-get-category (match-beginning 0))
6536 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6537 ;; donep (org-entry-is-done-p)
6538 )
6539 (if (string-match "\\]" timestr)
6540 ;; substring should only run to end of time stamp
6541 (setq timestr (substring timestr 0 (match-end 0))))
6542 (save-excursion
6543 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6544 (progn
6545 (goto-char (match-end 1))
6546 (setq hdmarker (org-agenda-new-marker)
6547 tags (org-get-tags-at))
6548 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6549 (setq txt (org-format-agenda-item
6550 "Closed: "
6551 (match-string 1) category tags timestr)))
6552 (setq txt org-agenda-no-heading-message))
6553 (setq priority 100000)
6554 (org-add-props txt props
6555 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
6556 'priority priority 'category category
6557 'undone-face 'org-warning 'done-face 'org-done)
6558 (push txt ee))
6559 (outline-next-heading))))
6560 (nreverse ee)))
6561
6562 (defun org-agenda-get-deadlines ()
6563 "Return the deadline information for agenda display."
6564 (let* ((wdays org-deadline-warning-days)
6565 (props (list 'mouse-face 'highlight
6566 'org-not-done-regexp org-not-done-regexp
6567 'keymap org-agenda-keymap
6568 'help-echo
6569 (format "mouse-2 or RET jump to org file %s"
6570 (abbreviate-file-name buffer-file-name))))
6571 (regexp org-deadline-time-regexp)
6572 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6573 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6574 d2 diff pos pos1 category tags
6575 ee txt head)
6576 (goto-char (point-min))
6577 (while (re-search-forward regexp nil t)
6578 (setq pos (1- (match-beginning 1))
6579 d2 (time-to-days
6580 (org-time-string-to-time (match-string 1)))
6581 diff (- d2 d1))
6582 ;; When to show a deadline in the calendar:
6583 ;; If the expiration is within wdays warning time.
6584 ;; Past-due deadlines are only shown on the current date
6585 (if (and (< diff wdays) todayp (not (= diff 0)))
6586 (save-excursion
6587 (setq category (org-get-category))
6588 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6589 (progn
6590 (goto-char (match-end 0))
6591 (setq pos1 (match-end 1))
6592 (setq tags (org-get-tags-at pos1))
6593 (setq head (buffer-substring-no-properties
6594 (point)
6595 (progn (skip-chars-forward "^\r\n")
6596 (point))))
6597 (if (string-match org-looking-at-done-regexp head)
6598 (setq txt nil)
6599 (setq txt (org-format-agenda-item
6600 (format "In %3d d.: " diff) head category tags))))
6601 (setq txt org-agenda-no-heading-message))
6602 (when txt
6603 (org-add-props txt props
6604 'org-marker (org-agenda-new-marker pos)
6605 'org-hd-marker (org-agenda-new-marker pos1)
6606 'priority (+ (- 10 diff) (org-get-priority txt))
6607 'category category
6608 'face (cond ((<= diff 0) 'org-warning)
6609 ((<= diff 5) 'org-scheduled-previously)
6610 (t nil))
6611 'undone-face (cond
6612 ((<= diff 0) 'org-warning)
6613 ((<= diff 5) 'org-scheduled-previously)
6614 (t nil))
6615 'done-face 'org-done)
6616 (push txt ee)))))
6617 ee))
6618
6619 (defun org-agenda-get-scheduled ()
6620 "Return the scheduled information for agenda display."
6621 (let* ((props (list 'face 'org-scheduled-previously
6622 'org-not-done-regexp org-not-done-regexp
6623 'undone-face 'org-scheduled-previously
6624 'done-face 'org-done
6625 'mouse-face 'highlight
6626 'keymap org-agenda-keymap
6627 'help-echo
6628 (format "mouse-2 or RET jump to org file %s"
6629 (abbreviate-file-name buffer-file-name))))
6630 (regexp org-scheduled-time-regexp)
6631 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6632 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6633 d2 diff pos pos1 category tags
6634 ee txt head)
6635 (goto-char (point-min))
6636 (while (re-search-forward regexp nil t)
6637 (setq pos (1- (match-beginning 1))
6638 d2 (time-to-days
6639 (org-time-string-to-time (match-string 1)))
6640 diff (- d2 d1))
6641 ;; When to show a scheduled item in the calendar:
6642 ;; If it is on or past the date.
6643 (if (and (< diff 0) todayp)
6644 (save-excursion
6645 (setq category (org-get-category))
6646 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6647 (progn
6648 (goto-char (match-end 0))
6649 (setq pos1 (match-end 1))
6650 (setq tags (org-get-tags-at))
6651 (setq head (buffer-substring-no-properties
6652 (point)
6653 (progn (skip-chars-forward "^\r\n") (point))))
6654 (if (string-match org-looking-at-done-regexp head)
6655 (setq txt nil)
6656 (setq txt (org-format-agenda-item
6657 (format "Sched.%2dx: " (- 1 diff)) head
6658 category tags))))
6659 (setq txt org-agenda-no-heading-message))
6660 (when txt
6661 (org-add-props txt props
6662 'org-marker (org-agenda-new-marker pos)
6663 'org-hd-marker (org-agenda-new-marker pos1)
6664 'priority (+ (- 5 diff) (org-get-priority txt))
6665 'category category)
6666 (push txt ee)))))
6667 ee))
6668
6669 (defun org-agenda-get-blocks ()
6670 "Return the date-range information for agenda display."
6671 (let* ((props (list 'face nil
6672 'org-not-done-regexp org-not-done-regexp
6673 'mouse-face 'highlight
6674 'keymap org-agenda-keymap
6675 'help-echo
6676 (format "mouse-2 or RET jump to org file %s"
6677 (abbreviate-file-name buffer-file-name))))
6678 (regexp org-tr-regexp)
6679 (d0 (calendar-absolute-from-gregorian date))
6680 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
6681 (goto-char (point-min))
6682 (while (re-search-forward regexp nil t)
6683 (setq timestr (match-string 0)
6684 s1 (match-string 1)
6685 s2 (match-string 2)
6686 d1 (time-to-days (org-time-string-to-time s1))
6687 d2 (time-to-days (org-time-string-to-time s2)))
6688 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
6689 ;; Only allow days between the limits, because the normal
6690 ;; date stamps will catch the limits.
6691 (save-excursion
6692 (setq marker (org-agenda-new-marker (point)))
6693 (setq category (org-get-category))
6694 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6695 (progn
6696 (setq hdmarker (org-agenda-new-marker (match-end 1)))
6697 (goto-char (match-end 1))
6698 (setq tags (org-get-tags-at))
6699 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6700 (setq txt (org-format-agenda-item
6701 (format (if (= d1 d2) "" "(%d/%d): ")
6702 (1+ (- d0 d1)) (1+ (- d2 d1)))
6703 (match-string 1) category tags
6704 (if (= d0 d1) timestr))))
6705 (setq txt org-agenda-no-heading-message))
6706 (org-add-props txt props
6707 'org-marker marker 'org-hd-marker hdmarker
6708 'priority (org-get-priority txt) 'category category)
6709 (push txt ee)))
6710 (outline-next-heading))
6711 ;; Sort the entries by expiration date.
6712 (nreverse ee)))
6713
6714 (defconst org-plain-time-of-day-regexp
6715 (concat
6716 "\\(\\<[012]?[0-9]"
6717 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6718 "\\(--?"
6719 "\\(\\<[012]?[0-9]"
6720 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6721 "\\)?")
6722 "Regular expression to match a plain time or time range.
6723 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
6724 groups carry important information:
6725 0 the full match
6726 1 the first time, range or not
6727 8 the second time, if it is a range.")
6728
6729 (defconst org-stamp-time-of-day-regexp
6730 (concat
6731 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
6732 "\\([012][0-9]:[0-5][0-9]\\)>"
6733 "\\(--?"
6734 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
6735 "Regular expression to match a timestamp time or time range.
6736 After a match, the following groups carry important information:
6737 0 the full match
6738 1 date plus weekday, for backreferencing to make sure both times on same day
6739 2 the first time, range or not
6740 4 the second time, if it is a range.")
6741
6742 (defvar org-prefix-has-time nil
6743 "A flag, set by `org-compile-prefix-format'.
6744 The flag is set if the currently compiled format contains a `%t'.")
6745 (defvar org-prefix-has-tag nil
6746 "A flag, set by `org-compile-prefix-format'.
6747 The flag is set if the currently compiled format contains a `%T'.")
6748
6749 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
6750 "Format TXT to be inserted into the agenda buffer.
6751 In particular, it adds the prefix and corresponding text properties. EXTRA
6752 must be a string and replaces the `%s' specifier in the prefix format.
6753 CATEGORY (string, symbol or nil) may be used to overrule the default
6754 category taken from local variable or file name. It will replace the `%c'
6755 specifier in the format. DOTIME, when non-nil, indicates that a
6756 time-of-day should be extracted from TXT for sorting of this entry, and for
6757 the `%t' specifier in the format. When DOTIME is a string, this string is
6758 searched for a time before TXT is. NOPREFIX is a flag and indicates that
6759 only the correctly processes TXT should be returned - this is used by
6760 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
6761 (save-match-data
6762 ;; Diary entries sometimes have extra whitespace at the beginning
6763 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
6764 (let* ((category (or category
6765 org-category
6766 (if buffer-file-name
6767 (file-name-sans-extension
6768 (file-name-nondirectory buffer-file-name))
6769 "")))
6770 (tag (if tags (nth (1- (length tags)) tags) ""))
6771 time ;; needed for the eval of the prefix format
6772 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
6773 (time-of-day (and dotime (org-get-time-of-day ts)))
6774 stamp plain s0 s1 s2 rtn)
6775 (when (and dotime time-of-day org-prefix-has-time)
6776 ;; Extract starting and ending time and move them to prefix
6777 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
6778 (setq plain (string-match org-plain-time-of-day-regexp ts)))
6779 (setq s0 (match-string 0 ts)
6780 s1 (match-string (if plain 1 2) ts)
6781 s2 (match-string (if plain 8 4) ts))
6782
6783 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
6784 ;; them, we might want to remove them there to avoid duplication.
6785 ;; The user can turn this off with a variable.
6786 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
6787 (string-match (concat (regexp-quote s0) " *") txt)
6788 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
6789 (= (match-beginning 0) 0)
6790 t))
6791 (setq txt (replace-match "" nil nil txt))))
6792 ;; Normalize the time(s) to 24 hour
6793 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
6794 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
6795
6796 ; (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
6797 ; (and org-agenda-remove-tags-when-in-prefix
6798 ; org-prefix-has-tag))
6799 ; (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
6800 ; (setq txt (replace-match "" t t txt)))
6801
6802 ;; FIXME!!!
6803 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
6804 ;; Tags are in the string
6805 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
6806 (and org-agenda-remove-tags-when-in-prefix
6807 org-prefix-has-tag))
6808 (setq txt (replace-match "" t t txt))
6809 (setq txt (replace-match
6810 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
6811 (match-string 2 txt))
6812 t t txt))))
6813
6814 ;; Create the final string
6815 (if noprefix
6816 (setq rtn txt)
6817 ;; Prepare the variables needed in the eval of the compiled format
6818 (setq time (cond (s2 (concat s1 "-" s2))
6819 (s1 (concat s1 "......"))
6820 (t ""))
6821 extra (or extra "")
6822 category (if (symbolp category) (symbol-name category) category))
6823 ;; Evaluate the compiled format
6824 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
6825
6826 ;; And finally add the text properties
6827 (org-add-props rtn nil
6828 'category (downcase category) 'tags tags
6829 'prefix-length (- (length rtn) (length txt))
6830 'time-of-day time-of-day
6831 'dotime dotime))))
6832
6833 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
6834 (catch 'exit
6835 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
6836 ((and todayp (member 'today (car org-agenda-time-grid))))
6837 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
6838 ((member 'weekly (car org-agenda-time-grid)))
6839 (t (throw 'exit list)))
6840 (let* ((have (delq nil (mapcar
6841 (lambda (x) (get-text-property 1 'time-of-day x))
6842 list)))
6843 (string (nth 1 org-agenda-time-grid))
6844 (gridtimes (nth 2 org-agenda-time-grid))
6845 (req (car org-agenda-time-grid))
6846 (remove (member 'remove-match req))
6847 new time)
6848 (if (and (member 'require-timed req) (not have))
6849 ;; don't show empty grid
6850 (throw 'exit list))
6851 (while (setq time (pop gridtimes))
6852 (unless (and remove (member time have))
6853 (setq time (int-to-string time))
6854 (push (org-format-agenda-item
6855 nil string "" nil
6856 (concat (substring time 0 -2) ":" (substring time -2)))
6857 new)
6858 (put-text-property
6859 1 (length (car new)) 'face 'org-time-grid (car new))))
6860 (if (member 'time-up org-agenda-sorting-strategy)
6861 (append new list)
6862 (append list new)))))
6863
6864 (defun org-compile-prefix-format (format)
6865 "Compile the prefix format into a Lisp form that can be evaluated.
6866 The resulting form is returned and stored in the variable
6867 `org-prefix-format-compiled'."
6868 (setq org-prefix-has-time nil org-prefix-has-tag nil)
6869 (let ((start 0) varform vars var (s format)e c f opt)
6870 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
6871 s start)
6872 (setq var (cdr (assoc (match-string 4 s)
6873 '(("c" . category) ("t" . time) ("s" . extra)
6874 ("T" . tag))))
6875 c (or (match-string 3 s) "")
6876 opt (match-beginning 1)
6877 start (1+ (match-beginning 0)))
6878 (if (equal var 'time) (setq org-prefix-has-time t))
6879 (if (equal var 'tag) (setq org-prefix-has-tag t))
6880 (setq f (concat "%" (match-string 2 s) "s"))
6881 (if opt
6882 (setq varform
6883 `(if (equal "" ,var)
6884 ""
6885 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
6886 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
6887 (setq s (replace-match "%s" t nil s))
6888 (push varform vars))
6889 (setq vars (nreverse vars))
6890 (setq org-prefix-format-compiled `(format ,s ,@vars))))
6891
6892 (defun org-get-time-of-day (s &optional string)
6893 "Check string S for a time of day.
6894 If found, return it as a military time number between 0 and 2400.
6895 If not found, return nil.
6896 The optional STRING argument forces conversion into a 5 character wide string
6897 HH:MM."
6898 (save-match-data
6899 (when
6900 (or
6901 (string-match
6902 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
6903 (string-match
6904 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
6905 (let* ((t0 (+ (* 100
6906 (+ (string-to-number (match-string 1 s))
6907 (if (and (match-beginning 4)
6908 (equal (downcase (match-string 4 s)) "pm"))
6909 12 0)))
6910 (if (match-beginning 3)
6911 (string-to-number (match-string 3 s))
6912 0)))
6913 (t1 (concat " "
6914 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6915 (int-to-string t0))))
6916 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6917
6918 (defun org-finalize-agenda-entries (list)
6919 "Sort and concatenate the agenda items."
6920 (setq list (mapcar 'org-agenda-highlight-todo list))
6921 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6922
6923 (defun org-agenda-highlight-todo (x)
6924 (let (re)
6925 (if (eq x 'line)
6926 (save-excursion
6927 (beginning-of-line 1)
6928 (setq re (get-text-property (point) 'org-not-done-regexp))
6929 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
6930 (and (looking-at (concat "[ \t]*" re))
6931 (add-text-properties (match-beginning 0) (match-end 0)
6932 '(face org-todo))))
6933 (setq re (get-text-property 0 'org-not-done-regexp x))
6934 (and re (string-match re x)
6935 (add-text-properties (match-beginning 0) (match-end 0)
6936 '(face org-todo) x))
6937 x)))
6938
6939 (defsubst org-cmp-priority (a b)
6940 "Compare the priorities of string A and B."
6941 (let ((pa (or (get-text-property 1 'priority a) 0))
6942 (pb (or (get-text-property 1 'priority b) 0)))
6943 (cond ((> pa pb) +1)
6944 ((< pa pb) -1)
6945 (t nil))))
6946
6947 (defsubst org-cmp-category (a b)
6948 "Compare the string values of categories of strings A and B."
6949 (let ((ca (or (get-text-property 1 'category a) ""))
6950 (cb (or (get-text-property 1 'category b) "")))
6951 (cond ((string-lessp ca cb) -1)
6952 ((string-lessp cb ca) +1)
6953 (t nil))))
6954
6955 (defsubst org-cmp-time (a b)
6956 "Compare the time-of-day values of strings A and B."
6957 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6958 (ta (or (get-text-property 1 'time-of-day a) def))
6959 (tb (or (get-text-property 1 'time-of-day b) def)))
6960 (cond ((< ta tb) -1)
6961 ((< tb ta) +1)
6962 (t nil))))
6963
6964 (defun org-entries-lessp (a b)
6965 "Predicate for sorting agenda entries."
6966 ;; The following variables will be used when the form is evaluated.
6967 (let* ((time-up (org-cmp-time a b))
6968 (time-down (if time-up (- time-up) nil))
6969 (priority-up (org-cmp-priority a b))
6970 (priority-down (if priority-up (- priority-up) nil))
6971 (category-up (org-cmp-category a b))
6972 (category-down (if category-up (- category-up) nil))
6973 (category-keep (if category-up +1 nil)))
6974 (cdr (assoc
6975 (eval (cons 'or org-agenda-sorting-strategy))
6976 '((-1 . t) (1 . nil) (nil . nil))))))
6977
6978 (defun org-agenda-show-priority ()
6979 "Show the priority of the current item.
6980 This priority is composed of the main priority given with the [#A] cookies,
6981 and by additional input from the age of a schedules or deadline entry."
6982 (interactive)
6983 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6984 (message "Priority is %d" (if pri pri -1000))))
6985
6986 (defun org-agenda-show-tags ()
6987 "Show the tags applicable to the current item."
6988 (interactive)
6989 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6990 (if tags
6991 (message "Tags are :%s:"
6992 (org-no-properties (mapconcat 'identity tags ":")))
6993 (message "No tags associated with this line"))))
6994
6995 (defun org-agenda-goto (&optional highlight)
6996 "Go to the Org-mode file which contains the item at point."
6997 (interactive)
6998 (let* ((marker (or (get-text-property (point) 'org-marker)
6999 (org-agenda-error)))
7000 (buffer (marker-buffer marker))
7001 (pos (marker-position marker)))
7002 (switch-to-buffer-other-window buffer)
7003 (widen)
7004 (goto-char pos)
7005 (when (eq major-mode 'org-mode)
7006 (org-show-hidden-entry)
7007 (save-excursion
7008 (and (outline-next-heading)
7009 (org-flag-heading nil)))) ; show the next heading
7010 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
7011
7012 (defun org-agenda-switch-to ()
7013 "Go to the Org-mode file which contains the item at point."
7014 (interactive)
7015 (let* ((marker (or (get-text-property (point) 'org-marker)
7016 (org-agenda-error)))
7017 (buffer (marker-buffer marker))
7018 (pos (marker-position marker)))
7019 (switch-to-buffer buffer)
7020 (delete-other-windows)
7021 (widen)
7022 (goto-char pos)
7023 (when (eq major-mode 'org-mode)
7024 (org-show-hidden-entry)
7025 (save-excursion
7026 (and (outline-next-heading)
7027 (org-flag-heading nil)))))) ; show the next heading
7028
7029 (defun org-agenda-goto-mouse (ev)
7030 "Go to the Org-mode file which contains the item at the mouse click."
7031 (interactive "e")
7032 (mouse-set-point ev)
7033 (org-agenda-goto))
7034
7035 (defun org-agenda-show ()
7036 "Display the Org-mode file which contains the item at point."
7037 (interactive)
7038 (let ((win (selected-window)))
7039 (org-agenda-goto t)
7040 (select-window win)))
7041
7042 (defun org-agenda-recenter (arg)
7043 "Display the Org-mode file which contains the item at point and recenter."
7044 (interactive "P")
7045 (let ((win (selected-window)))
7046 (org-agenda-goto t)
7047 (recenter arg)
7048 (select-window win)))
7049
7050 (defun org-agenda-show-mouse (ev)
7051 "Display the Org-mode file which contains the item at the mouse click."
7052 (interactive "e")
7053 (mouse-set-point ev)
7054 (org-agenda-show))
7055
7056 (defun org-agenda-check-no-diary ()
7057 "Check if the entry is a diary link and abort if yes."
7058 (if (get-text-property (point) 'org-agenda-diary-link)
7059 (org-agenda-error)))
7060
7061 (defun org-agenda-error ()
7062 (error "Command not allowed in this line"))
7063
7064 (defvar org-last-heading-marker (make-marker)
7065 "Marker pointing to the headline that last changed its TODO state
7066 by a remote command from the agenda.")
7067
7068 (defun org-agenda-todo (&optional arg)
7069 "Cycle TODO state of line at point, also in Org-mode file.
7070 This changes the line at point, all other lines in the agenda referring to
7071 the same tree node, and the headline of the tree node in the Org-mode file."
7072 (interactive "P")
7073 (org-agenda-check-no-diary)
7074 (let* ((col (current-column))
7075 (marker (or (get-text-property (point) 'org-marker)
7076 (org-agenda-error)))
7077 (buffer (marker-buffer marker))
7078 (pos (marker-position marker))
7079 (hdmarker (get-text-property (point) 'org-hd-marker))
7080 (buffer-read-only nil)
7081 newhead)
7082 (with-current-buffer buffer
7083 (widen)
7084 (goto-char pos)
7085 (org-show-hidden-entry)
7086 (save-excursion
7087 (and (outline-next-heading)
7088 (org-flag-heading nil))) ; show the next heading
7089 (org-todo arg)
7090 (and (bolp) (forward-char 1))
7091 (setq newhead (org-get-heading))
7092 (save-excursion
7093 (org-back-to-heading)
7094 (move-marker org-last-heading-marker (point))))
7095 (beginning-of-line 1)
7096 (save-excursion
7097 (org-agenda-change-all-lines newhead hdmarker 'fixface))
7098 (move-to-column col)))
7099
7100 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
7101 "Change all lines in the agenda buffer which match HDMARKER.
7102 The new content of the line will be NEWHEAD (as modified by
7103 `org-format-agenda-item'). HDMARKER is checked with
7104 `equal' against all `org-hd-marker' text properties in the file.
7105 If FIXFACE is non-nil, the face of each item is modified acording to
7106 the new TODO state."
7107 (let* (props m pl undone-face done-face finish new dotime cat tags)
7108 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
7109 (save-excursion
7110 (goto-char (point-max))
7111 (beginning-of-line 1)
7112 (while (not finish)
7113 (setq finish (bobp))
7114 (when (and (setq m (get-text-property (point) 'org-hd-marker))
7115 (equal m hdmarker))
7116 (setq props (text-properties-at (point))
7117 dotime (get-text-property (point) 'dotime)
7118 cat (get-text-property (point) 'category)
7119 tags (get-text-property (point) 'tags)
7120 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
7121 pl (get-text-property (point) 'prefix-length)
7122 undone-face (get-text-property (point) 'undone-face)
7123 done-face (get-text-property (point) 'done-face))
7124 (move-to-column pl)
7125 (if (looking-at ".*")
7126 (progn
7127 (replace-match new t t)
7128 (beginning-of-line 1)
7129 (add-text-properties (point-at-bol) (point-at-eol) props)
7130 (when fixface
7131 (add-text-properties
7132 (point-at-bol) (point-at-eol)
7133 (list 'face
7134 (if org-last-todo-state-is-todo
7135 undone-face done-face)))
7136 (org-agenda-highlight-todo 'line))
7137 (beginning-of-line 1))
7138 (error "Line update did not work")))
7139 (beginning-of-line 0)))))
7140
7141 (defun org-agenda-priority-up ()
7142 "Increase the priority of line at point, also in Org-mode file."
7143 (interactive)
7144 (org-agenda-priority 'up))
7145
7146 (defun org-agenda-priority-down ()
7147 "Decrease the priority of line at point, also in Org-mode file."
7148 (interactive)
7149 (org-agenda-priority 'down))
7150
7151 (defun org-agenda-priority (&optional force-direction)
7152 "Set the priority of line at point, also in Org-mode file.
7153 This changes the line at point, all other lines in the agenda referring to
7154 the same tree node, and the headline of the tree node in the Org-mode file."
7155 (interactive)
7156 (org-agenda-check-no-diary)
7157 (let* ((marker (or (get-text-property (point) 'org-marker)
7158 (org-agenda-error)))
7159 (buffer (marker-buffer marker))
7160 (pos (marker-position marker))
7161 (hdmarker (get-text-property (point) 'org-hd-marker))
7162 (buffer-read-only nil)
7163 newhead)
7164 (with-current-buffer buffer
7165 (widen)
7166 (goto-char pos)
7167 (org-show-hidden-entry)
7168 (save-excursion
7169 (and (outline-next-heading)
7170 (org-flag-heading nil))) ; show the next heading
7171 (funcall 'org-priority force-direction)
7172 (end-of-line 1)
7173 (setq newhead (org-get-heading)))
7174 (org-agenda-change-all-lines newhead hdmarker)
7175 (beginning-of-line 1)))
7176
7177 (defun org-get-tags-at (&optional pos)
7178 "Get a list of all headline tags applicable at POS.
7179 POS defaults to point. If tags are inherited, the list contains
7180 the targets in the same sequence as the headlines appear, i.e.
7181 the tags of the current headline come last."
7182 (interactive)
7183 (let (tags)
7184 (save-excursion
7185 (goto-char (or pos (point)))
7186 (save-match-data
7187 (org-back-to-heading t)
7188 (condition-case nil
7189 (while t
7190 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
7191 (setq tags (append (org-split-string
7192 (org-match-string-no-properties 1) ":")
7193 tags)))
7194 (or org-use-tag-inheritance (error ""))
7195 (org-up-heading-all 1))
7196 (error nil))))
7197 (message "%s" tags)
7198 tags))
7199
7200 (defun org-agenda-set-tags ()
7201 "Set tags for the current headline."
7202 (interactive)
7203 (org-agenda-check-no-diary)
7204 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
7205 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
7206 (org-agenda-error)))
7207 (buffer (marker-buffer hdmarker))
7208 (pos (marker-position hdmarker))
7209 (buffer-read-only nil)
7210 newhead)
7211 (with-current-buffer buffer
7212 (widen)
7213 (goto-char pos)
7214 (org-show-hidden-entry)
7215 (save-excursion
7216 (and (outline-next-heading)
7217 (org-flag-heading nil))) ; show the next heading
7218 (call-interactively 'org-set-tags)
7219 (end-of-line 1)
7220 (setq newhead (org-get-heading)))
7221 (org-agenda-change-all-lines newhead hdmarker)
7222 (beginning-of-line 1)))
7223
7224 (defun org-agenda-date-later (arg &optional what)
7225 "Change the date of this item to one day later."
7226 (interactive "p")
7227 (org-agenda-check-type t 'agenda 'timeline)
7228 (org-agenda-check-no-diary)
7229 (let* ((marker (or (get-text-property (point) 'org-marker)
7230 (org-agenda-error)))
7231 (buffer (marker-buffer marker))
7232 (pos (marker-position marker)))
7233 (with-current-buffer buffer
7234 (widen)
7235 (goto-char pos)
7236 (if (not (org-at-timestamp-p))
7237 (error "Cannot find time stamp"))
7238 (org-timestamp-change arg (or what 'day))
7239 (message "Time stamp changed to %s" org-last-changed-timestamp))))
7240
7241 (defun org-agenda-date-earlier (arg &optional what)
7242 "Change the date of this item to one day earlier."
7243 (interactive "p")
7244 (org-agenda-date-later (- arg) what))
7245
7246 (defun org-agenda-date-prompt (arg)
7247 "Change the date of this item. Date is prompted for, with default today.
7248 The prefix ARG is passed to the `org-time-stamp' command and can therefore
7249 be used to request time specification in the time stamp."
7250 (interactive "P")
7251 (org-agenda-check-type t 'agenda 'timeline)
7252 (org-agenda-check-no-diary)
7253 (let* ((marker (or (get-text-property (point) 'org-marker)
7254 (org-agenda-error)))
7255 (buffer (marker-buffer marker))
7256 (pos (marker-position marker)))
7257 (with-current-buffer buffer
7258 (widen)
7259 (goto-char pos)
7260 (if (not (org-at-timestamp-p))
7261 (error "Cannot find time stamp"))
7262 (org-time-stamp arg)
7263 (message "Time stamp changed to %s" org-last-changed-timestamp))))
7264
7265 (defun org-agenda-schedule (arg)
7266 "Schedule the item at point."
7267 (interactive "P")
7268 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
7269 (org-agenda-check-no-diary)
7270 (let* ((marker (or (get-text-property (point) 'org-marker)
7271 (org-agenda-error)))
7272 (buffer (marker-buffer marker))
7273 (pos (marker-position marker))
7274 (org-insert-labeled-timestamps-at-point nil)
7275 ts)
7276 (with-current-buffer buffer
7277 (widen)
7278 (goto-char pos)
7279 (setq ts (org-schedule))
7280 (message "Item scheduled for %s" ts))))
7281
7282 (defun org-agenda-deadline (arg)
7283 "Schedule the item at point."
7284 (interactive "P")
7285 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
7286 (org-agenda-check-no-diary)
7287 (let* ((marker (or (get-text-property (point) 'org-marker)
7288 (org-agenda-error)))
7289 (buffer (marker-buffer marker))
7290 (pos (marker-position marker))
7291 (org-insert-labeled-timestamps-at-point nil)
7292 ts)
7293 (with-current-buffer buffer
7294 (widen)
7295 (goto-char pos)
7296 (setq ts (org-deadline))
7297 (message "Deadline for this item set to %s" ts))))
7298
7299 (defun org-get-heading ()
7300 "Return the heading of the current entry, without the stars."
7301 (save-excursion
7302 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
7303 (if (and (re-search-backward "[\r\n]\\*" nil t)
7304 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
7305 (match-string 1)
7306 "")))
7307
7308 (defun org-agenda-diary-entry ()
7309 "Make a diary entry, like the `i' command from the calendar.
7310 All the standard commands work: block, weekly etc."
7311 (interactive)
7312 (org-agenda-check-type t 'agenda 'timeline)
7313 (require 'diary-lib)
7314 (let* ((char (progn
7315 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
7316 (read-char-exclusive)))
7317 (cmd (cdr (assoc char
7318 '((?d . insert-diary-entry)
7319 (?w . insert-weekly-diary-entry)
7320 (?m . insert-monthly-diary-entry)
7321 (?y . insert-yearly-diary-entry)
7322 (?a . insert-anniversary-diary-entry)
7323 (?b . insert-block-diary-entry)
7324 (?c . insert-cyclic-diary-entry)))))
7325 (oldf (symbol-function 'calendar-cursor-to-date))
7326 (point (point))
7327 (mark (or (mark t) (point))))
7328 (unless cmd
7329 (error "No command associated with <%c>" char))
7330 (unless (and (get-text-property point 'day)
7331 (or (not (equal ?b char))
7332 (get-text-property mark 'day)))
7333 (error "Don't know which date to use for diary entry"))
7334 ;; We implement this by hacking the `calendar-cursor-to-date' function
7335 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
7336 (let ((calendar-mark-ring
7337 (list (calendar-gregorian-from-absolute
7338 (or (get-text-property mark 'day)
7339 (get-text-property point 'day))))))
7340 (unwind-protect
7341 (progn
7342 (fset 'calendar-cursor-to-date
7343 (lambda (&optional error)
7344 (calendar-gregorian-from-absolute
7345 (get-text-property point 'day))))
7346 (call-interactively cmd))
7347 (fset 'calendar-cursor-to-date oldf)))))
7348
7349
7350 (defun org-agenda-execute-calendar-command (cmd)
7351 "Execute a calendar command from the agenda, with the date associated to
7352 the cursor position."
7353 (org-agenda-check-type t 'agenda 'timeline)
7354 (require 'diary-lib)
7355 (unless (get-text-property (point) 'day)
7356 (error "Don't know which date to use for calendar command"))
7357 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
7358 (point (point))
7359 (date (calendar-gregorian-from-absolute
7360 (get-text-property point 'day)))
7361 (displayed-day (extract-calendar-day date))
7362 (displayed-month (extract-calendar-month date))
7363 (displayed-year (extract-calendar-year date)))
7364 (unwind-protect
7365 (progn
7366 (fset 'calendar-cursor-to-date
7367 (lambda (&optional error)
7368 (calendar-gregorian-from-absolute
7369 (get-text-property point 'day))))
7370 (call-interactively cmd))
7371 (fset 'calendar-cursor-to-date oldf))))
7372
7373 (defun org-agenda-phases-of-moon ()
7374 "Display the phases of the moon for the 3 months around the cursor date."
7375 (interactive)
7376 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
7377
7378 (defun org-agenda-holidays ()
7379 "Display the holidays for the 3 months around the cursor date."
7380 (interactive)
7381 (org-agenda-execute-calendar-command 'list-calendar-holidays))
7382
7383 (defun org-agenda-sunrise-sunset (arg)
7384 "Display sunrise and sunset for the cursor date.
7385 Latitude and longitude can be specified with the variables
7386 `calendar-latitude' and `calendar-longitude'. When called with prefix
7387 argument, latitude and longitude will be prompted for."
7388 (interactive "P")
7389 (let ((calendar-longitude (if arg nil calendar-longitude))
7390 (calendar-latitude (if arg nil calendar-latitude))
7391 (calendar-location-name
7392 (if arg "the given coordinates" calendar-location-name)))
7393 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
7394
7395 (defun org-agenda-goto-calendar ()
7396 "Open the Emacs calendar with the date at the cursor."
7397 (interactive)
7398 (org-agenda-check-type t 'agenda 'timeline)
7399 (let* ((day (or (get-text-property (point) 'day)
7400 (error "Don't know which date to open in calendar")))
7401 (date (calendar-gregorian-from-absolute day))
7402 (calendar-move-hook nil)
7403 (view-calendar-holidays-initially nil)
7404 (view-diary-entries-initially nil))
7405 (calendar)
7406 (calendar-goto-date date)))
7407
7408 (defun org-calendar-goto-agenda ()
7409 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
7410 This is a command that has to be installed in `calendar-mode-map'."
7411 (interactive)
7412 (org-agenda-list nil (calendar-absolute-from-gregorian
7413 (calendar-cursor-to-date))
7414 nil t))
7415
7416 (defun org-agenda-convert-date ()
7417 (interactive)
7418 (org-agenda-check-type t 'agenda 'timeline)
7419 (let ((day (get-text-property (point) 'day))
7420 date s)
7421 (unless day
7422 (error "Don't know which date to convert"))
7423 (setq date (calendar-gregorian-from-absolute day))
7424 (setq s (concat
7425 "Gregorian: " (calendar-date-string date) "\n"
7426 "ISO: " (calendar-iso-date-string date) "\n"
7427 "Day of Yr: " (calendar-day-of-year-string date) "\n"
7428 "Julian: " (calendar-julian-date-string date) "\n"
7429 "Astron. JD: " (calendar-astro-date-string date)
7430 " (Julian date number at noon UTC)\n"
7431 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
7432 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
7433 "French: " (calendar-french-date-string date) "\n"
7434 "Mayan: " (calendar-mayan-date-string date) "\n"
7435 "Coptic: " (calendar-coptic-date-string date) "\n"
7436 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
7437 "Persian: " (calendar-persian-date-string date) "\n"
7438 "Chinese: " (calendar-chinese-date-string date) "\n"))
7439 (with-output-to-temp-buffer "*Dates*"
7440 (princ s))
7441 (if (fboundp 'fit-window-to-buffer)
7442 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
7443
7444 ;;; Tags
7445
7446 (defun org-scan-tags (action matcher &optional todo-only)
7447 "Scan headline tags with inheritance and produce output ACTION.
7448 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
7449 evaluated, testing if a given set of tags qualifies a headline for
7450 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
7451 are included in the output."
7452 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
7453 (mapconcat 'regexp-quote
7454 (nreverse (cdr (reverse org-todo-keywords)))
7455 "\\|")
7456 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
7457 (props (list 'face nil
7458 'done-face 'org-done
7459 'undone-face nil
7460 'mouse-face 'highlight
7461 'keymap org-agenda-keymap
7462 'help-echo
7463 (format "mouse-2 or RET jump to org file %s"
7464 (abbreviate-file-name buffer-file-name))))
7465 lspos
7466 tags tags-list tags-alist (llast 0) rtn level category i txt
7467 todo marker)
7468
7469 (save-excursion
7470 (goto-char (point-min))
7471 (when (eq action 'sparse-tree) (org-overview))
7472 (while (re-search-forward re nil t)
7473 (setq todo (if (match-end 1) (match-string 2))
7474 tags (if (match-end 4) (match-string 4)))
7475 (goto-char (setq lspos (1+ (match-beginning 0))))
7476 (setq level (funcall outline-level)
7477 category (org-get-category))
7478 (setq i llast llast level)
7479 ;; remove tag lists from same and sublevels
7480 (while (>= i level)
7481 (when (setq entry (assoc i tags-alist))
7482 (setq tags-alist (delete entry tags-alist)))
7483 (setq i (1- i)))
7484 ;; add the nex tags
7485 (when tags
7486 (setq tags (mapcar 'downcase (org-split-string tags ":"))
7487 tags-alist
7488 (cons (cons level tags) tags-alist)))
7489 ;; compile tags for current headline
7490 (setq tags-list
7491 (if org-use-tag-inheritance
7492 (apply 'append (mapcar 'cdr tags-alist))
7493 tags))
7494 (when (and (or (not todo-only) todo)
7495 (eval matcher))
7496 ;; list this headline
7497 (if (eq action 'sparse-tree)
7498 (progn
7499 (org-show-hierarchy-above))
7500 (setq txt (org-format-agenda-item
7501 ""
7502 (concat
7503 (if org-tags-match-list-sublevels
7504 (make-string (1- level) ?.) "")
7505 (org-get-heading))
7506 category tags-list))
7507 (goto-char lspos)
7508 (setq marker (org-agenda-new-marker))
7509 (org-add-props txt props
7510 'org-marker marker 'org-hd-marker marker 'category category)
7511 (push txt rtn))
7512 ;; if we are to skip sublevels, jump to end of subtree
7513 (point)
7514 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
7515 (nreverse rtn)))
7516
7517 (defun org-tags-sparse-tree (&optional arg match)
7518 "Create a sparse tree according to tags search string MATCH.
7519 MATCH can contain positive and negative selection of tags, like
7520 \"+WORK+URGENT-WITHBOSS\"."
7521 (interactive "P")
7522 (let ((org-show-following-heading nil)
7523 (org-show-hierarchy-above nil))
7524 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
7525
7526 (defun org-make-tags-matcher (match)
7527 "Create the TAGS matcher form for the tags-selecting string MATCH."
7528 (unless match
7529 ;; Get a new match request, with completion
7530 (setq org-last-tags-completion-table
7531 (or (org-get-buffer-tags)
7532 org-last-tags-completion-table))
7533 (setq match (completing-read
7534 "Tags: " 'org-tags-completion-function nil nil nil
7535 'org-tags-history)))
7536 ;; parse the string and create a lisp form
7537 (let ((match0 match) minus tag mm matcher orterms term orlist)
7538 (setq orterms (org-split-string match "|"))
7539 (while (setq term (pop orterms))
7540 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
7541 (setq minus (and (match-end 1)
7542 (equal (match-string 1 term) "-"))
7543 tag (match-string 2 term)
7544 term (substring term (match-end 0))
7545 mm (list 'member (downcase tag) 'tags-list)
7546 mm (if minus (list 'not mm) mm))
7547 (push mm matcher))
7548 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
7549 orlist)
7550 (setq matcher nil))
7551 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
7552 ;; Return the string and lisp forms of the matcher
7553 (cons match0 matcher)))
7554
7555 ;;;###autoload
7556 (defun org-tags-view (&optional todo-only match keep-modes)
7557 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
7558 The prefix arg TODO-ONLY limits the search to TODO entries."
7559 (interactive "P")
7560 (org-agenda-maybe-reset-markers 'force)
7561 (org-compile-prefix-format org-agenda-prefix-format)
7562 (let* ((org-agenda-keep-modes keep-modes)
7563 (org-tags-match-list-sublevels
7564 (if todo-only t org-tags-match-list-sublevels))
7565 (win (selected-window))
7566 (completion-ignore-case t)
7567 rtn rtnall files file pos matcher
7568 buffer)
7569 (setq matcher (org-make-tags-matcher match)
7570 match (car matcher) matcher (cdr matcher))
7571 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
7572 (progn
7573 (delete-other-windows)
7574 (switch-to-buffer-other-window
7575 (get-buffer-create org-agenda-buffer-name))))
7576 (setq buffer-read-only nil)
7577 (erase-buffer)
7578 (org-agenda-mode) (setq buffer-read-only nil)
7579 (set (make-local-variable 'org-agenda-type) 'tags)
7580 (set (make-local-variable 'org-agenda-redo-command)
7581 (list 'org-tags-view (list 'quote todo-only)
7582 (list 'if 'current-prefix-arg nil match) t))
7583 (setq files (org-agenda-files)
7584 rtnall nil)
7585 (while (setq file (pop files))
7586 (catch 'nextfile
7587 (org-check-agenda-file file)
7588 (setq buffer (if (file-exists-p file)
7589 (org-get-agenda-file-buffer file)
7590 (error "No such file %s" file)))
7591 (if (not buffer)
7592 ;; If file does not exist, merror message to agenda
7593 (setq rtn (list
7594 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7595 rtnall (append rtnall rtn))
7596 (with-current-buffer buffer
7597 (unless (eq major-mode 'org-mode)
7598 (error "Agenda file %s is not in `org-mode'" file))
7599 (save-excursion
7600 (save-restriction
7601 (if org-respect-restriction
7602 (if (org-region-active-p)
7603 ;; Respect a region to restrict search
7604 (narrow-to-region (region-beginning) (region-end)))
7605 ;; If we work for the calendar or many files,
7606 ;; get rid of any restriction
7607 (widen))
7608 (setq rtn (org-scan-tags 'agenda matcher todo-only))
7609 (setq rtnall (append rtnall rtn))))))))
7610 (insert "Headlines with TAGS match: ")
7611 (add-text-properties (point-min) (1- (point))
7612 (list 'face 'org-level-3))
7613 (setq pos (point))
7614 (insert match "\n")
7615 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7616 (setq pos (point))
7617 (insert "Press `C-u r' to search again with new search string\n")
7618 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7619 (when rtnall
7620 (insert (mapconcat 'identity rtnall "\n")))
7621 (goto-char (point-min))
7622 (setq buffer-read-only t)
7623 (org-fit-agenda-window)
7624 (if (not org-select-agenda-window) (select-window win))))
7625
7626 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
7627 (defun org-set-tags (&optional arg just-align)
7628 "Set the tags for the current headline.
7629 With prefix ARG, realign all tags in headings in the current buffer."
7630 (interactive "P")
7631 (let* ((re (concat "^" outline-regexp))
7632 (col (current-column))
7633 (current (org-get-tags))
7634 table current-tags inherited-tags ; computed below when needed
7635 tags hd empty invis)
7636 (if arg
7637 (save-excursion
7638 (goto-char (point-min))
7639 (while (re-search-forward re nil t)
7640 (org-set-tags nil t))
7641 (message "All tags realigned to column %d" org-tags-column))
7642 (if just-align
7643 (setq tags current)
7644 (setq table (or org-tag-alist (org-get-buffer-tags))
7645 org-last-tags-completion-table table
7646 current-tags (org-split-string current ":")
7647 inherited-tags (nreverse
7648 (nthcdr (length current-tags)
7649 (nreverse (org-get-tags-at))))
7650 tags
7651 (if (or (eq t org-use-fast-tag-selection)
7652 (and org-use-fast-tag-selection (cdar table)))
7653 (org-fast-tag-selection current-tags inherited-tags table)
7654 (let ((org-add-colon-after-tag-completion t))
7655 (completing-read "Tags: " 'org-tags-completion-function
7656 nil nil current 'org-tags-history))))
7657 (while (string-match "[-+&]+" tags)
7658 (setq tags (replace-match ":" t t tags))))
7659
7660 ;; FIXME: still optimize this by not checking when JUST-ALIGN?
7661 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
7662 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
7663 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
7664 (if (equal current "")
7665 (progn
7666 (end-of-line 1)
7667 (or empty (insert-before-markers " ")))
7668 (beginning-of-line 1)
7669 (setq invis (org-invisible-p))
7670 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
7671 (setq hd (match-string 1))
7672 (delete-region (match-beginning 0) (match-end 0))
7673 (insert-before-markers (org-trim hd) (if empty "" " ")))
7674 (unless (equal tags "")
7675 (move-to-column (max (current-column)
7676 (if (> org-tags-column 0)
7677 org-tags-column
7678 (- (- org-tags-column) (length tags))))
7679 t)
7680 (insert-before-markers tags)
7681 (if (and (not invis) (org-invisible-p))
7682 (outline-flag-region (point-at-bol) (point) nil)))
7683 (move-to-column col))))
7684
7685 (defun org-tags-completion-function (string predicate &optional flag)
7686 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
7687 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
7688 (setq s1 (match-string 1 string)
7689 s2 (match-string 2 string))
7690 (setq s1 "" s2 string))
7691 (cond
7692 ((eq flag nil)
7693 ;; try completion
7694 (setq rtn (try-completion s2 ctable))
7695 (if (stringp rtn)
7696 (concat s1 s2 (substring rtn (length s2))
7697 (if (and org-add-colon-after-tag-completion
7698 (assoc rtn ctable))
7699 ":" "")))
7700 )
7701 ((eq flag t)
7702 ;; all-completions
7703 (all-completions s2 ctable)
7704 )
7705 ((eq flag 'lambda)
7706 ;; exact match?
7707 (assoc s2 ctable)))
7708 ))
7709
7710 (defun org-fast-tag-insert (kwd tags face &optional end)
7711 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
7712 (insert (format "%-12s" (concat kwd ":"))
7713 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
7714 (or end "")))
7715
7716 (defun org-fast-tag-selection (current inherited table)
7717 "Fast tag selection with single keys.
7718 CURRENT is the current list of tags in the headline, INHERITED is the
7719 list of inherited tags, and TABLE is an alist of tags and corresponding keys.
7720 If the keys are nil, a-z are automatically assigned.
7721 Returns the new tags string, or nil to not change the current settings."
7722 (let* ((maxlen (apply 'max (mapcar (lambda (x)
7723 (string-width (car x))) table)))
7724 (fwidth (+ maxlen 3 1 3))
7725 (ncol (/ (window-width) fwidth))
7726 (i-face 'org-done)
7727 (c-face 'org-tag)
7728 tg cnt e c char ntable tbl rtn)
7729 (save-window-excursion
7730 (delete-other-windows)
7731 (split-window-vertically)
7732 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
7733 (erase-buffer)
7734 (org-fast-tag-insert "Inherited" inherited i-face "\n")
7735 (org-fast-tag-insert "Current" current c-face "\n\n")
7736 (setq tbl table char (1- ?a) cnt 0)
7737 (while (setq e (pop tbl))
7738 (setq tg (car e) c (or (cdr e) (setq char (1+ char))))
7739 (setq tg (org-add-props tg nil 'face
7740 (cond
7741 ((member tg current) c-face)
7742 ((member tg inherited) i-face)
7743 (t nil))))
7744 (insert "[" c "] " tg (make-string
7745 (- fwidth 4 (length tg)) ?\ ))
7746 (push (cons tg c) ntable)
7747 (when (= (setq cnt (1+ cnt)) ncol)
7748 (insert "\n")
7749 (setq cnt 0)))
7750 (insert "\n")
7751 (goto-char (point-min))
7752 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
7753 (setq rtn
7754 (catch 'exit
7755 (while t
7756 (message "[key]:Toggle SPC: clear current RET accept")
7757 (setq c (read-char-exclusive))
7758 (cond
7759 ((= c ?\r) (throw 'exit t))
7760 ((= c ?\C-g) (throw 'exit nil))
7761 ((= c ?\ ) (setq current nil))
7762 (t (setq e (rassoc c ntable) tg (car e))
7763 (if (member tg current)
7764 (setq current (delete tg current))
7765 (setq current (append current (list tg))))))
7766 (goto-char (point-min))
7767 (beginning-of-line 2)
7768 (delete-region (point) (point-at-eol))
7769 (org-fast-tag-insert "Current" current c-face)
7770 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
7771 (setq tg (match-string 1))
7772 (add-text-properties (match-beginning 1) (match-end 1)
7773 (list 'face
7774 (cond
7775 ((member tg current) c-face)
7776 ((member tg inherited) i-face)
7777 (t nil)))))
7778 (goto-char (point-min)))))
7779 (if rtn
7780 (mapconcat 'identity current ":")
7781 nil))))
7782
7783 (defun org-get-tags ()
7784 "Get the TAGS string in the current headline."
7785 (unless (org-on-heading-p)
7786 (error "Not on a heading"))
7787 (save-excursion
7788 (beginning-of-line 1)
7789 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
7790 (org-match-string-no-properties 1)
7791 "")))
7792
7793 (defun org-get-buffer-tags ()
7794 "Get a table of all tags used in the buffer, for completion."
7795 (let (tags)
7796 (save-excursion
7797 (goto-char (point-min))
7798 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
7799 (mapc (lambda (x) (add-to-list 'tags x))
7800 (org-split-string (org-match-string-no-properties 1) ":"))))
7801 (mapcar 'list tags)))
7802
7803 ;;; Link Stuff
7804
7805 (defvar org-create-file-search-functions nil
7806 "List of functions to construct the right search string for a file link.
7807 These functions are called in turn with point at the location to
7808 which the link should point.
7809
7810 A function in the hook should first test if it would like to
7811 handle this file type, for example by checking the major-mode or
7812 the file extension. If it decides not to handle this file, it
7813 should just return nil to give other functions a chance. If it
7814 does handle the file, it must return the search string to be used
7815 when following the link. The search string will be part of the
7816 file link, given after a double colon, and `org-open-at-point'
7817 will automatically search for it. If special measures must be
7818 taken to make the search successful, another function should be
7819 added to the companion hook `org-execute-file-search-functions',
7820 which see.
7821
7822 A function in this hook may also use `setq' to set the variable
7823 `description' to provide a suggestion for the descriptive text to
7824 be used for this link when it gets inserted into an Org-mode
7825 buffer with \\[org-insert-link].")
7826
7827 (defvar org-execute-file-search-functions nil
7828 "List of functions to execute a file search triggered by a link.
7829
7830 Functions added to this hook must accept a single argument, the
7831 search string that was part of the file link, the part after the
7832 double colon. The function must first check if it would like to
7833 handle this search, for example by checking the major-mode or the
7834 file extension. If it decides not to handle this search, it
7835 should just return nil to give other functions a chance. If it
7836 does handle the search, it must return a non-nil value to keep
7837 other functions from trying.
7838
7839 Each function can access the current prefix argument through the
7840 variable `current-prefix-argument'. Note that a single prefix is
7841 used to force opening a link in Emacs, so it may be good to only
7842 use a numeric or double prefix to guide the search function.
7843
7844 In case this is needed, a function in this hook can also restore
7845 the window configuration before `org-open-at-point' was called using:
7846
7847 (set-window-configuration org-window-config-before-follow-link)")
7848
7849 (defun org-find-file-at-mouse (ev)
7850 "Open file link or URL at mouse."
7851 (interactive "e")
7852 (mouse-set-point ev)
7853 (org-open-at-point 'in-emacs))
7854
7855 (defun org-open-at-mouse (ev)
7856 "Open file link or URL at mouse."
7857 (interactive "e")
7858 (mouse-set-point ev)
7859 (org-open-at-point))
7860
7861 (defvar org-window-config-before-follow-link nil
7862 "The window configuration before following a link.
7863 This is saved in case the need arises to restore it.")
7864
7865 (defun org-open-at-point (&optional in-emacs)
7866 "Open link at or after point.
7867 If there is no link at point, this function will search forward up to
7868 the end of the current subtree.
7869 Normally, files will be opened by an appropriate application. If the
7870 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7871 (interactive "P")
7872 (setq org-window-config-before-follow-link (current-window-configuration))
7873 (org-remove-occur-highlights nil nil t)
7874 (if (org-at-timestamp-p)
7875 (org-agenda-list nil (time-to-days (org-time-string-to-time
7876 (substring (match-string 1) 0 10)))
7877 1)
7878 (let (type path link line search (pos (point)))
7879 (catch 'match
7880 (save-excursion
7881 (skip-chars-forward "^]\n\r")
7882 (when (and (re-search-backward "\\[\\[" nil t)
7883 (looking-at org-bracket-link-regexp)
7884 (<= (match-beginning 0) pos)
7885 (>= (match-end 0) pos))
7886 (setq link (org-link-unescape (org-match-string-no-properties 1)))
7887 (while (string-match " *\n *" link)
7888 (setq link (replace-match " " t t link)))
7889 (if (string-match org-link-re-with-space2 link)
7890 (setq type (match-string 1 link)
7891 path (match-string 2 link))
7892 (setq type "thisfile"
7893 path link))
7894 (throw 'match t)))
7895
7896 (when (get-text-property (point) 'org-linked-text)
7897 (setq type "thisfile"
7898 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7899 (1+ (point)) (point))
7900 path (buffer-substring
7901 (previous-single-property-change pos 'org-linked-text)
7902 (next-single-property-change pos 'org-linked-text)))
7903 (throw 'match t))
7904
7905 (save-excursion
7906 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
7907 (if (equal (char-before) ?<) (backward-char 1))
7908 (when (or (looking-at org-angle-link-re)
7909 (looking-at org-plain-link-re)
7910 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
7911 (re-search-forward org-plain-link-re (point-at-eol) t))
7912 (<= (match-beginning 0) pos)
7913 (>= (match-end 0) pos)))
7914 (setq type (match-string 1)
7915 path (match-string 2))
7916 (throw 'match t)))
7917 (save-excursion
7918 (skip-chars-backward "^ \t\n\r")
7919 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
7920 (setq type "tags"
7921 path (match-string 1))
7922 (while (string-match ":" path)
7923 (setq path (replace-match "+" t t path)))
7924 (throw 'match t)))
7925 (save-excursion
7926 (skip-chars-backward "a-zA-Z_")
7927 (when (and (memq 'camel org-activate-links)
7928 (looking-at org-camel-regexp))
7929 (setq type "camel" path (match-string 0))
7930 (if (equal (char-before) ?*)
7931 (setq path (concat "*" path))))
7932 (throw 'match t)))
7933 (unless path
7934 (error "No link found"))
7935 ;; Remove any trailing spaces in path
7936 (if (string-match " +\\'" path)
7937 (setq path (replace-match "" t t path)))
7938
7939 (cond
7940
7941 ((member type '("http" "https" "ftp" "mailto" "news"))
7942 (browse-url (concat type ":" path)))
7943
7944 ((string= type "tags")
7945 (org-tags-view in-emacs path))
7946 ((or (string= type "camel")
7947 (string= type "thisfile"))
7948 (org-mark-ring-push)
7949 (org-link-search
7950 path
7951 (cond ((equal in-emacs '(4)) 'occur)
7952 ((equal in-emacs '(16)) 'org-occur)
7953 (t nil))))
7954
7955 ((string= type "file")
7956 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
7957 ;; FIXME: It is unsafe to allow a single colon.
7958 (setq line (string-to-number (match-string 1 path))
7959 path (substring path 0 (match-beginning 0)))
7960 (if (string-match "::\\(.+\\)\\'" path)
7961 (setq search (match-string 1 path)
7962 path (substring path 0 (match-beginning 0)))))
7963 (org-open-file path in-emacs line search))
7964
7965 ((string= type "news")
7966 (org-follow-gnus-link path))
7967
7968 ((string= type "bbdb")
7969 (org-follow-bbdb-link path))
7970
7971 ((string= type "info")
7972 (org-follow-info-link path))
7973
7974 ((string= type "gnus")
7975 (let (group article)
7976 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7977 (error "Error in Gnus link"))
7978 (setq group (match-string 1 path)
7979 article (match-string 3 path))
7980 (org-follow-gnus-link group article)))
7981
7982 ((string= type "vm")
7983 (let (folder article)
7984 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7985 (error "Error in VM link"))
7986 (setq folder (match-string 1 path)
7987 article (match-string 3 path))
7988 ;; in-emacs is the prefix arg, will be interpreted as read-only
7989 (org-follow-vm-link folder article in-emacs)))
7990
7991 ((string= type "wl")
7992 (let (folder article)
7993 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7994 (error "Error in Wanderlust link"))
7995 (setq folder (match-string 1 path)
7996 article (match-string 3 path))
7997 (org-follow-wl-link folder article)))
7998
7999 ((string= type "mhe")
8000 (let (folder article)
8001 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8002 (error "Error in MHE link"))
8003 (setq folder (match-string 1 path)
8004 article (match-string 3 path))
8005 (org-follow-mhe-link folder article)))
8006
8007 ((string= type "rmail")
8008 (let (folder article)
8009 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
8010 (error "Error in RMAIL link"))
8011 (setq folder (match-string 1 path)
8012 article (match-string 3 path))
8013 (org-follow-rmail-link folder article)))
8014
8015 ((string= type "shell")
8016 (let ((cmd path))
8017 (while (string-match "@{" cmd)
8018 (setq cmd (replace-match "<" t t cmd)))
8019 (while (string-match "@}" cmd)
8020 (setq cmd (replace-match ">" t t cmd)))
8021 (if (or (not org-confirm-shell-link-function)
8022 (funcall org-confirm-shell-link-function
8023 (format "Execute \"%s\" in shell? "
8024 (org-add-props cmd nil
8025 'face 'org-warning))))
8026 (progn
8027 (message "Executing %s" cmd)
8028 (shell-command cmd))
8029 (error "Abort"))))
8030
8031 ((string= type "elisp")
8032 (let ((cmd path))
8033 (if (or (not org-confirm-elisp-link-function)
8034 (funcall org-confirm-elisp-link-function
8035 (format "Execute \"%s\" as elisp? "
8036 (org-add-props cmd nil
8037 'face 'org-warning))))
8038 (message "%s => %s" cmd (eval (read cmd)))
8039 (error "Abort"))))
8040
8041 (t
8042 (browse-url-at-point))))))
8043
8044 (defun org-link-search (s &optional type)
8045 "Search for a link search option.
8046 When S is a CamelCaseWord, search for a target, or for a sentence containing
8047 the words. If S is surrounded by forward slashes, it is interpreted as a
8048 regular expression. In org-mode files, this will create an `org-occur'
8049 sparse tree. In ordinary files, `occur' will be used to list matches.
8050 If the current buffer is in `dired-mode', grep will be used to search
8051 in all files."
8052 (let ((case-fold-search t)
8053 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8054 (pos (point))
8055 (pre "") (post "")
8056 words re0 re1 re2 re3 re4 re5 re2a reall camel)
8057 (cond
8058 ;; First check if there are any special
8059 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8060 ;; Now try the builtin stuff
8061 ((save-excursion
8062 (goto-char (point-min))
8063 (and
8064 (re-search-forward
8065 (concat "<<" (regexp-quote s0) ">>") nil t)
8066 (setq pos (match-beginning 0))))
8067 ;; There is an exact target for this
8068 (goto-char pos))
8069 ((string-match "^/\\(.*\\)/$" s)
8070 ;; A regular expression
8071 (cond
8072 ((eq major-mode 'org-mode)
8073 (org-occur (match-string 1 s)))
8074 ;;((eq major-mode 'dired-mode)
8075 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8076 (t (org-do-occur (match-string 1 s)))))
8077 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
8078 t)
8079 ;; A camel or a normal search string
8080 (when (equal (string-to-char s) ?*)
8081 ;; Anchor on headlines, post may include tags.
8082 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
8083 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
8084 s (substring s 1)))
8085 (remove-text-properties
8086 0 (length s)
8087 '(face nil mouse-face nil keymap nil fontified nil) s)
8088 ;; Make a series of regular expressions to find a match
8089 (setq words
8090 (if camel
8091 (org-camel-to-words s)
8092 (org-split-string s "[ \n\r\t]+"))
8093 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8094 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
8095 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8096 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8097 re1 (concat pre re2 post)
8098 re3 (concat pre re4 post)
8099 re5 (concat pre ".*" re4)
8100 re2 (concat pre re2)
8101 re2a (concat pre re2a)
8102 re4 (concat pre re4)
8103 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8104 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8105 re5 "\\)"
8106 ))
8107 (cond
8108 ((eq type 'org-occur) (org-occur reall))
8109 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8110 (t (goto-char (point-min))
8111 (if (or (org-search-not-link re0 nil t)
8112 (org-search-not-link re1 nil t)
8113 (org-search-not-link re2 nil t)
8114 (org-search-not-link re2a nil t)
8115 (org-search-not-link re3 nil t)
8116 (org-search-not-link re4 nil t)
8117 (org-search-not-link re5 nil t)
8118 )
8119 (goto-char (match-beginning 1)) ;; Fixme: does every re have group 1?
8120 (goto-char pos)
8121 (error "No match")))))
8122 (t
8123 ;; Normal string-search
8124 (goto-char (point-min))
8125 (if (search-forward s nil t)
8126 (goto-char (match-beginning 0))
8127 (error "No match"))))
8128 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
8129
8130 (defun org-search-not-link (&rest args)
8131 "Execute `re-search-forward', but only accept matches that are not a link."
8132 (catch 'exit
8133 (let ((pos (point)) p1)
8134 (while (apply 're-search-forward args)
8135 (setq p1 (point))
8136 (if (not (save-match-data
8137 (and (re-search-backward "\\[\\[" nil t)
8138 (looking-at org-bracket-link-regexp)
8139 (<= (match-beginning 0) p1)
8140 (>= (match-end 0) p1))))
8141 (progn (goto-char (match-end 0))
8142 (throw 'exit (point)))
8143 (goto-char (match-end 0)))))))
8144
8145 (defun org-do-occur (regexp &optional cleanup)
8146 "Call the Emacs command `occur'.
8147 If CLEANUP is non-nil, remove the printout of the regular expression
8148 in the *Occur* buffer. This is useful if the regex is long and not useful
8149 to read."
8150 (occur regexp)
8151 (when cleanup
8152 (let ((cwin (selected-window)) win beg end)
8153 (when (setq win (get-buffer-window "*Occur*"))
8154 (select-window win))
8155 (goto-char (point-min))
8156 (when (re-search-forward "match[a-z]+" nil t)
8157 (setq beg (match-end 0))
8158 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8159 (setq end (1- (match-beginning 0)))))
8160 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
8161 (goto-char (point-min))
8162 (select-window cwin))))
8163
8164 (defvar org-mark-ring nil
8165 "Mark ring for positions before jumps in Org-mode.")
8166 (defvar org-mark-ring-last-goto nil
8167 "Last position in the mark ring used to go back.")
8168 ;; Fill and close the ring
8169 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8170 (loop for i from 1 to org-mark-ring-length do
8171 (push (make-marker) org-mark-ring))
8172 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8173 org-mark-ring)
8174
8175 (defun org-mark-ring-push (&optional pos buffer)
8176 "Put the current position or POS into the mark ring and rotate it."
8177 (interactive)
8178 (setq pos (or pos (point)))
8179 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8180 (move-marker (car org-mark-ring)
8181 (or pos (point))
8182 (or buffer (current-buffer)))
8183 (message
8184 (substitute-command-keys
8185 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8186
8187 (defun org-mark-ring-goto (&optional n)
8188 "Jump to the previous position in the mark ring.
8189 With prefix arg N, jump back that many stored positions. When
8190 called several times in succession, walk through the entire ring.
8191 Org-mode commands jumping to a different position in the current file,
8192 or to another Org-mode file, automatically push the old position
8193 onto the ring."
8194 (interactive "p")
8195 (let (p m)
8196 (if (eq last-command this-command)
8197 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8198 (setq p org-mark-ring))
8199 (setq org-mark-ring-last-goto p)
8200 (setq m (car p))
8201 (switch-to-buffer (marker-buffer m))
8202 (goto-char m)
8203 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
8204
8205 (defun org-camel-to-words (s)
8206 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
8207 (let ((case-fold-search nil)
8208 words)
8209 (while (string-match "[a-z][A-Z]" s)
8210 (push (substring s 0 (1+ (match-beginning 0))) words)
8211 (setq s (substring s (1+ (match-beginning 0)))))
8212 (nreverse (cons s words))))
8213
8214 (defun org-remove-angle-brackets (s)
8215 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8216 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8217 s)
8218 (defun org-add-angle-brackets (s)
8219 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8220 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8221 s)
8222
8223 (defun org-follow-bbdb-link (name)
8224 "Follow a BBDB link to NAME."
8225 (require 'bbdb)
8226 (let ((inhibit-redisplay t)
8227 (bbdb-electric-p nil))
8228 (catch 'exit
8229 ;; Exact match on name
8230 (bbdb-name (concat "\\`" name "\\'") nil)
8231 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8232 ;; Exact match on name
8233 (bbdb-company (concat "\\`" name "\\'") nil)
8234 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8235 ;; Partial match on name
8236 (bbdb-name name nil)
8237 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8238 ;; Partial match on company
8239 (bbdb-company name nil)
8240 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
8241 ;; General match including network address and notes
8242 (bbdb name nil)
8243 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
8244 (delete-window (get-buffer-window "*BBDB*"))
8245 (error "No matching BBDB record")))))
8246
8247
8248 (defun org-follow-info-link (name)
8249 "Follow an info file & node link to NAME."
8250 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
8251 (string-match "\\(.*\\)" name))
8252 (progn
8253 (require 'info)
8254 (if (match-string 2 name) ; If there isn't a node, choose "Top"
8255 (Info-find-node (match-string 1 name) (match-string 2 name))
8256 (Info-find-node (match-string 1 name) "Top")))
8257 (message (concat "Could not open: " name))))
8258
8259 (defun org-follow-gnus-link (&optional group article)
8260 "Follow a Gnus link to GROUP and ARTICLE."
8261 (require 'gnus)
8262 (funcall (cdr (assq 'gnus org-link-frame-setup)))
8263 (if group (gnus-fetch-group group))
8264 (if article
8265 (or (gnus-summary-goto-article article nil 'force)
8266 (if (fboundp 'gnus-summary-insert-cached-articles)
8267 (progn
8268 (gnus-summary-insert-cached-articles)
8269 (gnus-summary-goto-article article nil 'force))
8270 (message "Message could not be found.")))))
8271
8272 (defun org-follow-vm-link (&optional folder article readonly)
8273 "Follow a VM link to FOLDER and ARTICLE."
8274 (require 'vm)
8275 (setq article (org-add-angle-brackets article))
8276 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
8277 ;; ange-ftp or efs or tramp access
8278 (let ((user (or (match-string 1 folder) (user-login-name)))
8279 (host (match-string 2 folder))
8280 (file (match-string 3 folder)))
8281 (cond
8282 ((featurep 'tramp)
8283 ;; use tramp to access the file
8284 (if (featurep 'xemacs)
8285 (setq folder (format "[%s@%s]%s" user host file))
8286 (setq folder (format "/%s@%s:%s" user host file))))
8287 (t
8288 ;; use ange-ftp or efs
8289 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
8290 (setq folder (format "/%s@%s:%s" user host file))))))
8291 (when folder
8292 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
8293 (sit-for 0.1)
8294 (when article
8295 (vm-select-folder-buffer)
8296 (widen)
8297 (let ((case-fold-search t))
8298 (goto-char (point-min))
8299 (if (not (re-search-forward
8300 (concat "^" "message-id: *" (regexp-quote article))))
8301 (error "Could not find the specified message in this folder"))
8302 (vm-isearch-update)
8303 (vm-isearch-narrow)
8304 (vm-beginning-of-message)
8305 (vm-summarize)))))
8306
8307 (defun org-follow-wl-link (folder article)
8308 "Follow a Wanderlust link to FOLDER and ARTICLE."
8309 (setq article (org-add-angle-brackets article))
8310 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
8311 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
8312 (wl-summary-redisplay))
8313
8314 (defun org-follow-rmail-link (folder article)
8315 "Follow an RMAIL link to FOLDER and ARTICLE."
8316 (setq article (org-add-angle-brackets article))
8317 (let (message-number)
8318 (save-excursion
8319 (save-window-excursion
8320 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
8321 (setq message-number
8322 (save-restriction
8323 (widen)
8324 (goto-char (point-max))
8325 (if (re-search-backward
8326 (concat "^Message-ID:\\s-+" (regexp-quote
8327 (or article "")))
8328 nil t)
8329 (rmail-what-message))))))
8330 (if message-number
8331 (progn
8332 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
8333 (rmail-show-message message-number)
8334 message-number)
8335 (error "Message not found"))))
8336
8337 ;; mh-e integration based on planner-mode
8338 (defun org-mhe-get-message-real-folder ()
8339 "Return the name of the current message real folder, so if you use
8340 sequences, it will now work."
8341 (save-excursion
8342 (let* ((folder
8343 (if (equal major-mode 'mh-folder-mode)
8344 mh-current-folder
8345 ;; Refer to the show buffer
8346 mh-show-folder-buffer))
8347 (end-index
8348 (if (boundp 'mh-index-folder)
8349 (min (length mh-index-folder) (length folder))))
8350 )
8351 ;; a simple test on mh-index-data does not work, because
8352 ;; mh-index-data is always nil in a show buffer.
8353 (if (and (boundp 'mh-index-folder)
8354 (string= mh-index-folder (substring folder 0 end-index)))
8355 (if (equal major-mode 'mh-show-mode)
8356 (save-window-excursion
8357 (when (buffer-live-p (get-buffer folder))
8358 (progn
8359 (pop-to-buffer folder)
8360 (org-mhe-get-message-folder-from-index)
8361 )
8362 ))
8363 (org-mhe-get-message-folder-from-index)
8364 )
8365 folder
8366 )
8367 )))
8368
8369 (defun org-mhe-get-message-folder-from-index ()
8370 "Returns the name of the message folder in a index folder buffer."
8371 (save-excursion
8372 (mh-index-previous-folder)
8373 (re-search-forward "^\\(+.*\\)$" nil t)
8374 (message (match-string 1))))
8375
8376 (defun org-mhe-get-message-folder ()
8377 "Return the name of the current message folder. Be careful if you
8378 use sequences."
8379 (save-excursion
8380 (if (equal major-mode 'mh-folder-mode)
8381 mh-current-folder
8382 ;; Refer to the show buffer
8383 mh-show-folder-buffer)))
8384
8385 (defun org-mhe-get-message-num ()
8386 "Return the number of the current message. Be careful if you
8387 use sequences."
8388 (save-excursion
8389 (if (equal major-mode 'mh-folder-mode)
8390 (mh-get-msg-num nil)
8391 ;; Refer to the show buffer
8392 (mh-show-buffer-message-number))))
8393
8394 (defun org-mhe-get-header (header)
8395 "Return a header of the message in folder mode. This will create a
8396 show buffer for the corresponding message. If you have a more clever
8397 idea..."
8398 (let* ((folder (org-mhe-get-message-folder))
8399 (num (org-mhe-get-message-num))
8400 (buffer (get-buffer-create (concat "show-" folder)))
8401 (header-field))
8402 (with-current-buffer buffer
8403 (mh-display-msg num folder)
8404 (if (equal major-mode 'mh-folder-mode)
8405 (mh-header-display)
8406 (mh-show-header-display))
8407 (set-buffer buffer)
8408 (setq header-field (mh-get-header-field header))
8409 (if (equal major-mode 'mh-folder-mode)
8410 (mh-show)
8411 (mh-show-show))
8412 header-field)))
8413
8414 (defun org-follow-mhe-link (folder article)
8415 "Follow an MHE link to FOLDER and ARTICLE.
8416 If ARTICLE is nil FOLDER is shown. If the configuration variable
8417 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
8418 ARTICLE is searched in all folders. Indexed searches (swish++,
8419 namazu, and others supported by MH-E) will always search in all
8420 folders."
8421 (require 'mh-e)
8422 (require 'mh-search)
8423 (require 'mh-utils)
8424 (mh-find-path)
8425 (if (not article)
8426 (mh-visit-folder (mh-normalize-folder-name folder))
8427 (setq article (org-add-angle-brackets article))
8428 (mh-search-choose)
8429 (if (equal mh-searcher 'pick)
8430 (progn
8431 (mh-search folder (list "--message-id" article))
8432 (when (and org-mhe-search-all-folders
8433 (not (org-mhe-get-message-real-folder)))
8434 (kill-this-buffer)
8435 (mh-search "+" (list "--message-id" article))))
8436 (mh-search "+" article))
8437 (if (org-mhe-get-message-real-folder)
8438 (mh-show-msg 1)
8439 (kill-this-buffer)
8440 (error "Message not found"))))
8441
8442 ;; BibTeX links
8443
8444 ;; Use the custom search meachnism to construct and use search strings for
8445 ;; file links to BibTeX database entries.
8446
8447 (defun org-create-file-search-in-bibtex ()
8448 "Create the search string and description for a BibTeX database entry."
8449 (when (eq major-mode 'bibtex-mode)
8450 ;; yes, we want to construct this search string.
8451 ;; Make a good description for this entry, using names, year and the title
8452 ;; Put it into the `description' variable which is dynamically scoped.
8453 (let ((bibtex-autokey-names 1)
8454 (bibtex-autokey-names-stretch 1)
8455 (bibtex-autokey-name-case-convert-function 'identity)
8456 (bibtex-autokey-name-separator " & ")
8457 (bibtex-autokey-additional-names " et al.")
8458 (bibtex-autokey-year-length 4)
8459 (bibtex-autokey-name-year-separator " ")
8460 (bibtex-autokey-titlewords 3)
8461 (bibtex-autokey-titleword-separator " ")
8462 (bibtex-autokey-titleword-case-convert-function 'identity)
8463 (bibtex-autokey-titleword-length 'infty)
8464 (bibtex-autokey-year-title-separator ": "))
8465 (setq description (bibtex-generate-autokey)))
8466 ;; Now parse the entry, get the key and return it.
8467 (save-excursion
8468 (bibtex-beginning-of-entry)
8469 (cdr (assoc "=key=" (bibtex-parse-entry))))))
8470
8471 (defun org-execute-file-search-in-bibtex (s)
8472 "Find the link search string S as a key for a database entry."
8473 (when (eq major-mode 'bibtex-mode)
8474 ;; Yes, we want to do the search in this file.
8475 ;; We construct a regexp that searches for "@entrytype{" followed by the key
8476 (goto-char (point-min))
8477 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
8478 (regexp-quote s) "[ \t\n]*,") nil t)
8479 (goto-char (match-beginning 0)))
8480 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
8481 ;; Use double prefix to indicate that any web link should be browsed
8482 (let ((b (current-buffer)) (p (point)))
8483 ;; Restore the window configuration because we just use the web link
8484 (set-window-configuration org-window-config-before-follow-link)
8485 (save-excursion (set-buffer b) (goto-char p)
8486 (bibtex-url)))
8487 (recenter 0)) ; Move entry start to beginning of window
8488 ;; return t to indicate that the search is done.
8489 t))
8490
8491 ;; Finally add the functions to the right hooks.
8492 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
8493 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
8494
8495 ;; end of Bibtex link setup
8496
8497 (defun org-upgrade-old-links (&optional query-description)
8498 "Transfer old <...> style links to new [[...]] style links.
8499 With arg query-description, ask at each match for a description text to use
8500 for this link."
8501 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
8502 (save-excursion
8503 (goto-char (point-min))
8504 (let ((re (concat "\\([^[]\\)<\\("
8505 "\\(" (mapconcat 'identity org-link-types "\\|")
8506 "\\):"
8507 "[^" org-non-link-chars "]+\\)>"))
8508 l1 l2 (cnt 0))
8509 (while (re-search-forward re nil t)
8510 (setq cnt (1+ cnt)
8511 l1 (org-match-string-no-properties 2)
8512 l2 (save-match-data (org-link-escape l1)))
8513 (when query-description (setq l1 (read-string "Desc: " l1)))
8514 (if (equal l1 l2)
8515 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
8516 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
8517 (message "%d matches have beed treated" cnt))))
8518
8519 (defun org-open-file (path &optional in-emacs line search)
8520 "Open the file at PATH.
8521 First, this expands any special file name abbreviations. Then the
8522 configuration variable `org-file-apps' is checked if it contains an
8523 entry for this file type, and if yes, the corresponding command is launched.
8524 If no application is found, Emacs simply visits the file.
8525 With optional argument IN-EMACS, Emacs will visit the file.
8526 Optional LINE specifies a line to go to, optional SEARCH a string to
8527 search for. If LINE or SEARCH is given, the file will always be
8528 opened in Emacs.
8529 If the file does not exist, an error is thrown."
8530 (setq in-emacs (or in-emacs line search))
8531 (let* ((file (if (equal path "")
8532 buffer-file-name
8533 (convert-standard-filename (org-expand-file-name path))))
8534 (dirp (file-directory-p file))
8535 (dfile (downcase file))
8536 (old-buffer (current-buffer))
8537 (old-pos (point))
8538 (old-mode major-mode)
8539 ext cmd apps)
8540 (if (and (not (file-exists-p file))
8541 (not org-open-non-existing-files))
8542 (error "No such file: %s" file))
8543 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8544 (setq ext (match-string 1 dfile))
8545 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8546 (setq ext (match-string 1 dfile))))
8547 (setq apps (append org-file-apps (org-default-apps)))
8548 (if in-emacs
8549 (setq cmd 'emacs)
8550 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
8551 (cdr (assoc ext apps))
8552 (cdr (assoc t apps)))))
8553 (when (eq cmd 'mailcap)
8554 (require 'mailcap)
8555 (mailcap-parse-mailcaps)
8556 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8557 (command (mailcap-mime-info mime-type)))
8558 (if (stringp command)
8559 (setq cmd command)
8560 (setq cmd 'emacs))))
8561 (cond
8562 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8563 ;; Normalize use of quote, this can vary.
8564 (if (string-match "['\"]%s['\"]" cmd)
8565 (setq cmd (replace-match "'%s'" t t cmd)))
8566 (setq cmd (format cmd file))
8567 (save-window-excursion
8568 (shell-command (concat cmd " &"))))
8569 ((or (stringp cmd)
8570 (eq cmd 'emacs))
8571 (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
8572 (funcall (cdr (assq 'file org-link-frame-setup)) file))
8573 (if line (goto-line line)
8574 (if search (org-link-search search))))
8575 ((consp cmd)
8576 (eval cmd))
8577 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8578 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
8579 (or (not (equal old-buffer (current-buffer)))
8580 (not (equal old-pos (point))))
8581 (org-mark-ring-push old-pos old-buffer))))
8582
8583 (defun org-default-apps ()
8584 "Return the default applications for this operating system."
8585 (cond
8586 ((eq system-type 'darwin)
8587 org-file-apps-defaults-macosx)
8588 ((eq system-type 'windows-nt)
8589 org-file-apps-defaults-windowsnt)
8590 (t org-file-apps-defaults-gnu)))
8591
8592 (defun org-expand-file-name (path)
8593 "Replace special path abbreviations and expand the file name."
8594 (expand-file-name path))
8595
8596
8597 (defvar org-insert-link-history nil
8598 "Minibuffer history for links inserted with `org-insert-link'.")
8599
8600 (defvar org-stored-links nil
8601 "Contains the links stored with `org-store-link'.")
8602
8603 ;;;###autoload
8604 (defun org-store-link (arg)
8605 "\\<org-mode-map>Store an org-link to the current location.
8606 This link can later be inserted into an org-buffer with
8607 \\[org-insert-link].
8608 For some link types, a prefix arg is interpreted:
8609 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
8610 For file links, arg negates `org-context-in-file-links'."
8611 (interactive "P")
8612 (let (link cpltxt desc description search txt (pos (point)))
8613 (cond
8614
8615 ((eq major-mode 'bbdb-mode)
8616 (setq cpltxt (concat
8617 "bbdb:"
8618 (or (bbdb-record-name (bbdb-current-record))
8619 (bbdb-record-company (bbdb-current-record))))
8620 link (org-make-link cpltxt)))
8621
8622 ((eq major-mode 'Info-mode)
8623 (setq link (org-make-link "info:"
8624 (file-name-nondirectory Info-current-file)
8625 ":" Info-current-node))
8626 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
8627 ":" Info-current-node)))
8628
8629 ((eq major-mode 'calendar-mode)
8630 (let ((cd (calendar-cursor-to-date)))
8631 (setq link
8632 (format-time-string
8633 (car org-time-stamp-formats)
8634 (apply 'encode-time
8635 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
8636 nil nil nil))))))
8637
8638 ((or (eq major-mode 'vm-summary-mode)
8639 (eq major-mode 'vm-presentation-mode))
8640 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
8641 (vm-follow-summary-cursor)
8642 (save-excursion
8643 (vm-select-folder-buffer)
8644 (let* ((message (car vm-message-pointer))
8645 (folder buffer-file-name)
8646 (subject (vm-su-subject message))
8647 (author (vm-su-full-name message))
8648 (message-id (vm-su-message-id message)))
8649 (setq message-id (org-remove-angle-brackets message-id))
8650 (setq folder (abbreviate-file-name folder))
8651 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
8652 folder)
8653 (setq folder (replace-match "" t t folder)))
8654 (setq cpltxt (concat author " on: " subject))
8655 (setq link (org-make-link "vm:" folder "#" message-id)))))
8656
8657 ((eq major-mode 'wl-summary-mode)
8658 (let* ((msgnum (wl-summary-message-number))
8659 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
8660 msgnum 'message-id))
8661 (wl-message-entity (elmo-msgdb-overview-get-entity
8662 msgnum (wl-summary-buffer-msgdb)))
8663 (author (wl-summary-line-from)) ; FIXME: correct?
8664 (subject "???")) ; FIXME:
8665 (setq message-id (org-remove-angle-brackets message-id))
8666 (setq cpltxt (concat author " on: " subject))
8667 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
8668 "#" message-id))))
8669
8670 ((or (equal major-mode 'mh-folder-mode)
8671 (equal major-mode 'mh-show-mode))
8672 (let ((from-header (org-mhe-get-header "From:"))
8673 (to-header (org-mhe-get-header "To:"))
8674 (subject (org-mhe-get-header "Subject:")))
8675 (setq cpltxt (concat from-header " on: " subject))
8676 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
8677 (org-remove-angle-brackets
8678 (org-mhe-get-header "Message-Id:"))))))
8679
8680 ((eq major-mode 'rmail-mode)
8681 (save-excursion
8682 (save-restriction
8683 (rmail-narrow-to-non-pruned-header)
8684 (let ((folder buffer-file-name)
8685 (message-id (mail-fetch-field "message-id"))
8686 (author (mail-fetch-field "from"))
8687 (subject (mail-fetch-field "subject")))
8688 (setq message-id (org-remove-angle-brackets message-id))
8689 (setq cpltxt (concat author " on: " subject))
8690 (setq link (org-make-link "rmail:" folder "#" message-id))))))
8691
8692 ((eq major-mode 'gnus-group-mode)
8693 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
8694 (gnus-group-group-name)) ; version
8695 ((fboundp 'gnus-group-name)
8696 (gnus-group-name))
8697 (t "???"))))
8698 (setq cpltxt (concat
8699 (if (org-xor arg org-usenet-links-prefer-google)
8700 "http://groups.google.com/groups?group="
8701 "gnus:")
8702 group)
8703 link (org-make-link cpltxt))))
8704
8705 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
8706 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
8707 (gnus-summary-beginning-of-article)
8708 (let* ((group (car gnus-article-current))
8709 (article (cdr gnus-article-current))
8710 (header (gnus-summary-article-header article))
8711 (author (mail-header-from header))
8712 (message-id (mail-header-id header))
8713 (date (mail-header-date header))
8714 (subject (gnus-summary-subject-string)))
8715 (setq cpltxt (concat author " on: " subject))
8716 (if (org-xor arg org-usenet-links-prefer-google)
8717 (setq link
8718 (concat
8719 cpltxt "\n "
8720 (format "http://groups.google.com/groups?as_umsgid=%s"
8721 (org-fixup-message-id-for-http message-id))))
8722 (setq link (org-make-link "gnus:" group
8723 "#" (number-to-string article))))))
8724
8725 ((eq major-mode 'w3-mode)
8726 (setq cpltxt (url-view-url t)
8727 link (org-make-link cpltxt)))
8728 ((eq major-mode 'w3m-mode)
8729 (setq cpltxt w3m-current-url
8730 link (org-make-link cpltxt)))
8731
8732 ((setq search (run-hook-with-args-until-success
8733 'org-create-file-search-functions))
8734 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
8735 "::" search))
8736 (setq cpltxt (or description link))) ;; FIXME: is this the best way?
8737
8738 ((eq major-mode 'org-mode)
8739 ;; Just link to current headline
8740 (setq cpltxt (concat "file:"
8741 (abbreviate-file-name buffer-file-name)))
8742 ;; Add a context search string
8743 (when (org-xor org-context-in-file-links arg)
8744 ;; Check if we are on a target
8745 (if (save-excursion
8746 (skip-chars-forward "^>\n\r")
8747 (and (re-search-backward "<<" nil t)
8748 (looking-at "<<\\(.*?\\)>>")
8749 (<= (match-beginning 0) pos)
8750 (>= (match-end 0) pos)))
8751 (setq cpltxt (concat cpltxt "::" (match-string 1)))
8752 (setq txt (cond
8753 ((org-on-heading-p) nil)
8754 ((org-region-active-p)
8755 (buffer-substring (region-beginning) (region-end)))
8756 (t (buffer-substring (point-at-bol) (point-at-eol)))))
8757 (when (string-match "\\S-" txt)
8758 (setq cpltxt
8759 (concat cpltxt "::"
8760 (if org-file-link-context-use-camel-case
8761 (org-make-org-heading-camel txt)
8762 (org-make-org-heading-search-string txt)))
8763 desc "NONE"))))
8764 (if (string-match "::\\'" cpltxt)
8765 (setq cpltxt (substring cpltxt 0 -2)))
8766 (setq link (org-make-link cpltxt)))
8767
8768 (buffer-file-name
8769 ;; Just link to this file here.
8770 (setq cpltxt (concat "file:"
8771 (abbreviate-file-name buffer-file-name)))
8772 ;; Add a context string
8773 (when (org-xor org-context-in-file-links arg)
8774 (setq txt (if (org-region-active-p)
8775 (buffer-substring (region-beginning) (region-end))
8776 (buffer-substring (point-at-bol) (point-at-eol))))
8777 ;; Only use search option if there is some text.
8778 (when (string-match "\\S-" txt)
8779 (setq cpltxt
8780 (concat cpltxt "::"
8781 (if org-file-link-context-use-camel-case
8782 (org-make-org-heading-camel txt)
8783 (org-make-org-heading-search-string txt)))
8784 desc "NONE")))
8785 (setq link (org-make-link cpltxt)))
8786
8787 ((interactive-p)
8788 (error "Cannot link to a buffer which is not visiting a file"))
8789
8790 (t (setq link nil)))
8791
8792 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8793 (setq link (or link cpltxt)
8794 desc (or desc cpltxt))
8795 (if (equal desc "NONE") (setq desc nil))
8796
8797 (if (and (interactive-p) link)
8798 (progn
8799 (setq org-stored-links
8800 (cons (list cpltxt link desc) org-stored-links))
8801 (message "Stored: %s" (or cpltxt link)))
8802 (org-make-link-string link desc))))
8803
8804 (defun org-make-org-heading-search-string (&optional string heading)
8805 "Make search string for STRING or current headline."
8806 (interactive)
8807 (let ((s (or string (org-get-heading))))
8808 (unless (and string (not heading))
8809 ;; We are using a headline, clean up garbage in there.
8810 (if (string-match org-todo-regexp s)
8811 (setq s (replace-match "" t t s)))
8812 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8813 (setq s (replace-match "" t t s)))
8814 (setq s (org-trim s))
8815 (if (string-match (concat "^\\(" org-quote-string "\\|"
8816 org-comment-string "\\)") s)
8817 (setq s (replace-match "" t t s)))
8818 (while (string-match org-ts-regexp s)
8819 (setq s (replace-match "" t t s))))
8820 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8821 (setq s (replace-match " " t t s)))
8822 (or string (setq s (concat "*" s))) ; Add * for headlines
8823 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8824
8825 (defun org-make-org-heading-camel (&optional string heading)
8826 "Make a CamelCase string for STRING or the current headline."
8827 (interactive)
8828 (let ((s (or string (org-get-heading))))
8829 (unless (and string (not heading))
8830 ;; We are using a headline, clean up garbage in there.
8831 (if (string-match org-todo-regexp s)
8832 (setq s (replace-match "" t t s)))
8833 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8834 (setq s (replace-match "" t t s)))
8835 (setq s (org-trim s))
8836 (if (string-match (concat "^\\(" org-quote-string "\\|"
8837 org-comment-string "\\)") s)
8838 (setq s (replace-match "" t t s)))
8839 (while (string-match org-ts-regexp s)
8840 (setq s (replace-match "" t t s))))
8841 (while (string-match "[^a-zA-Z_ \t]+" s)
8842 (setq s (replace-match " " t t s)))
8843 (or string (setq s (concat "*" s))) ; Add * for headlines
8844 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
8845
8846 (defun org-make-link (&rest strings)
8847 "Concatenate STRINGS, format resulting string with `org-link-format'."
8848 (format org-link-format (apply 'concat strings)))
8849
8850 (defun org-make-link-string (link &optional description)
8851 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8852 (if (eq org-link-style 'plain)
8853 (if (equal description link)
8854 link
8855 (concat description "\n" link))
8856 (when (stringp description)
8857 ;; Remove brackets from the description, they are fatal.
8858 (while (string-match "\\[\\|\\]" description)
8859 (setq description (replace-match "" t t description))))
8860 (when (equal (org-link-escape link) description)
8861 ;; No description needed, it is identical
8862 (setq description nil))
8863 (when (and (not description)
8864 (not (equal link (org-link-escape link))))
8865 (setq description link))
8866 (concat "[[" (org-link-escape link) "]"
8867 (if description (concat "[" description "]") "")
8868 "]")))
8869
8870 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
8871 "Association list of escapes for some characters problematic in links.")
8872
8873 (defun org-link-escape (text)
8874 "Escape charaters in TEXT that are problematic for links."
8875 (when text
8876 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
8877 org-link-escape-chars "\\|")))
8878 (while (string-match re text)
8879 (setq text
8880 (replace-match
8881 (cdr (assoc (match-string 0 text) org-link-escape-chars))
8882 t t text)))
8883 text)))
8884
8885 (defun org-link-unescape (text)
8886 "Reverse the action of `org-link-escape'."
8887 (when text
8888 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
8889 org-link-escape-chars "\\|")))
8890 (while (string-match re text)
8891 (setq text
8892 (replace-match
8893 (car (rassoc (match-string 0 text) org-link-escape-chars))
8894 t t text)))
8895 text)))
8896
8897 (defun org-xor (a b)
8898 "Exclusive or."
8899 (if a (not b) b))
8900
8901 (defun org-get-header (header)
8902 "Find a header field in the current buffer."
8903 (save-excursion
8904 (goto-char (point-min))
8905 (let ((case-fold-search t) s)
8906 (cond
8907 ((eq header 'from)
8908 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
8909 (setq s (match-string 1)))
8910 (while (string-match "\"" s)
8911 (setq s (replace-match "" t t s)))
8912 (if (string-match "[<(].*" s)
8913 (setq s (replace-match "" t t s))))
8914 ((eq header 'message-id)
8915 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
8916 (setq s (match-string 1))))
8917 ((eq header 'subject)
8918 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
8919 (setq s (match-string 1)))))
8920 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
8921 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
8922 s)))
8923
8924
8925 (defun org-fixup-message-id-for-http (s)
8926 "Replace special characters in a message id, so it can be used in an http query."
8927 (while (string-match "<" s)
8928 (setq s (replace-match "%3C" t t s)))
8929 (while (string-match ">" s)
8930 (setq s (replace-match "%3E" t t s)))
8931 (while (string-match "@" s)
8932 (setq s (replace-match "%40" t t s)))
8933 s)
8934
8935 (defun org-insert-link (&optional complete-file)
8936 "Insert a link. At the prompt, enter the link.
8937
8938 Completion can be used to select a link previously stored with
8939 `org-store-link'. When the empty string is entered (i.e. if you just
8940 press RET at the prompt), the link defaults to the most recently
8941 stored link. As SPC triggers completion in the minibuffer, you need to
8942 use M-SPC or C-q SPC to force the insertion of a space character.
8943
8944 You will also be prompted for a description, and if one is given, it will
8945 be displayed in the buffer instead of the link.
8946
8947 If there is already a link at point, this command will allow you to edit link
8948 and description parts.
8949
8950 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
8951 selected using completion. The path to the file will be relative to
8952 the current directory if the file is in the current directory or a
8953 subdirectory. Otherwise, the link will be the absolute path as
8954 completed in the minibuffer (i.e. normally ~/path/to/file).
8955
8956 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
8957 is in the current directory or below."
8958 (interactive "P")
8959 (let (link desc entry remove file (pos (point)))
8960 (cond
8961 ((save-excursion
8962 (skip-chars-forward "^]\n\r")
8963 (and (re-search-backward "\\[\\[" nil t)
8964 (looking-at org-bracket-link-regexp)
8965 (<= (match-beginning 0) pos)
8966 (>= (match-end 0) pos)))
8967 ;; We do have a link at point, and we are going to edit it.
8968 (setq remove (list (match-beginning 0) (match-end 0)))
8969 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8970 (setq link (read-string "Link: "
8971 (org-link-unescape
8972 (org-match-string-no-properties 1)))))
8973 (complete-file
8974 ;; Completing read for file names.
8975 (setq file (read-file-name "File: "))
8976 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8977 (pwd1 (file-name-as-directory (abbreviate-file-name
8978 (expand-file-name ".")))))
8979 (cond
8980 ((equal complete-file '(16))
8981 (setq link (org-make-link
8982 "file:"
8983 (abbreviate-file-name (expand-file-name file)))))
8984 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8985 (setq link (org-make-link "file:" (match-string 1 file))))
8986 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8987 (expand-file-name file))
8988 (setq link (org-make-link
8989 "file:" (match-string 1 (expand-file-name file)))))
8990 (t (setq link (org-make-link "file:" file))))))
8991 (t
8992 ;; Read link, with completion for stored links.
8993 (setq link (org-completing-read
8994 "Link: " org-stored-links nil nil nil
8995 org-insert-link-history
8996 (or (car (car org-stored-links)))))
8997 (setq entry (assoc link org-stored-links))
8998 (if (not org-keep-stored-link-after-insertion)
8999 (setq org-stored-links (delq (assoc link org-stored-links)
9000 org-stored-links)))
9001 (setq link (if entry (nth 1 entry) link)
9002 desc (or desc (nth 2 entry)))))
9003
9004 (if (string-match org-plain-link-re link)
9005 ;; URL-like link, normalize the use of angular brackets.
9006 (setq link (org-make-link (org-remove-angle-brackets link))))
9007
9008 ;; Check if we are linking to the current file with a search option
9009 ;; If yes, simplify the link by using only the search option.
9010 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
9011 (let* ((path (match-string 1 link))
9012 (case-fold-search nil)
9013 (search (match-string 2 link)))
9014 (save-match-data
9015 (if (equal (file-truename buffer-file-name) (file-truename path))
9016 ;; We are linking to this same file, with a search option
9017 (setq link search)))))
9018
9019 ;; Check if we can/should use a relative path. If yes, simplify the link
9020 (when (string-match "\\<file:\\(.*\\)" link)
9021 (let* ((path (match-string 1 link))
9022 (case-fold-search nil))
9023 (cond
9024 ((eq org-link-file-path-type 'absolute)
9025 (setq path (abbreviate-file-name (expand-file-name path))))
9026 ((eq org-link-file-path-type 'noabbrev)
9027 (setq path (expand-file-name path)))
9028 ((eq org-link-file-path-type 'relative)
9029 (setq path (file-relative-name path)))
9030 (t
9031 (save-match-data
9032 (if (string-match (concat "^" (regexp-quote
9033 (file-name-as-directory
9034 (expand-file-name "."))))
9035 (expand-file-name path))
9036 ;; We are linking a file with relative path name.
9037 (setq path (substring (expand-file-name path)
9038 (match-end 0)))))))
9039 (setq link (concat "file:" path))))
9040
9041 (setq desc (read-string "Description: " desc))
9042 (unless (string-match "\\S-" desc) (setq desc nil))
9043 (if remove (apply 'delete-region remove))
9044 (insert (org-make-link-string link desc))))
9045
9046 (defun org-completing-read (&rest args)
9047 (let ((minibuffer-local-completion-map
9048 (copy-keymap minibuffer-local-completion-map)))
9049 (define-key minibuffer-local-completion-map " " 'self-insert-command)
9050 (apply 'completing-read args)))
9051
9052 ;;; Hooks for remember.el
9053
9054 (defvar org-finish-function nil)
9055
9056 ;;;###autoload
9057 (defun org-remember-annotation ()
9058 "Return a link to the current location as an annotation for remember.el.
9059 If you are using Org-mode files as target for data storage with
9060 remember.el, then the annotations should include a link compatible with the
9061 conventions in Org-mode. This function returns such a link."
9062 (org-store-link nil))
9063
9064 (defconst org-remember-help
9065 "Select a destination location for the note.
9066 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
9067 RET at beg-of-buf -> Append to file as level 2 headline
9068 RET on headline -> Store as sublevel entry to current headline
9069 <left>/<right> -> before/after current headline, same headings level")
9070
9071 ;;;###autoload
9072 (defun org-remember-apply-template ()
9073 "Initialize *remember* buffer with template, invoke `org-mode'.
9074 This function should be placed into `remember-mode-hook' and in fact requires
9075 to be run from that hook to fucntion properly."
9076 (if org-remember-templates
9077
9078 (let* ((entry (if (= (length org-remember-templates) 1)
9079 (cdar org-remember-templates)
9080 (message "Select template: %s"
9081 (mapconcat
9082 (lambda (x) (char-to-string (car x)))
9083 org-remember-templates " "))
9084 (cdr (assoc (read-char-exclusive) org-remember-templates))))
9085 (tpl (car entry))
9086 (file (if (consp (cdr entry)) (nth 1 entry)))
9087 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
9088 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
9089 (v-u (concat "[" (substring v-t 1 -1) "]"))
9090 (v-U (concat "[" (substring v-T 1 -1) "]"))
9091 (v-a annotation) ; defined in `remember-mode'
9092 (v-i initial) ; defined in `remember-mode'
9093 (v-n user-full-name)
9094 )
9095 (unless tpl (setq tpl "") (message "No template") (ding))
9096 (insert tpl) (goto-char (point-min))
9097 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
9098 (when (and initial (equal (match-string 0) "%i"))
9099 (save-match-data
9100 (let* ((lead (buffer-substring
9101 (point-at-bol) (match-beginning 0))))
9102 (setq v-i (mapconcat 'identity
9103 (org-split-string initial "\n")
9104 (concat "\n" lead))))))
9105 (replace-match
9106 (or (eval (intern (concat "v-" (match-string 1)))) "")
9107 t t))
9108 (let ((org-startup-folded nil)
9109 (org-startup-with-deadline-check nil))
9110 (org-mode))
9111 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
9112 (set (make-local-variable 'org-default-notes-file) file))
9113 (goto-char (point-min))
9114 (if (re-search-forward "%\\?" nil t) (replace-match "")))
9115 (let ((org-startup-folded nil)
9116 (org-startup-with-deadline-check nil))
9117 (org-mode)))
9118 (set (make-local-variable 'org-finish-function) 'remember-buffer))
9119
9120 ;;;###autoload
9121 (defun org-remember-handler ()
9122 "Store stuff from remember.el into an org file.
9123 First prompts for an org file. If the user just presses return, the value
9124 of `org-default-notes-file' is used.
9125 Then the command offers the headings tree of the selected file in order to
9126 file the text at a specific location.
9127 You can either immediately press RET to get the note appended to the
9128 file, or you can use vertical cursor motion and visibility cycling (TAB) to
9129 find a better place. Then press RET or <left> or <right> in insert the note.
9130
9131 Key Cursor position Note gets inserted
9132 -----------------------------------------------------------------------------
9133 RET buffer-start as level 2 heading at end of file
9134 RET on headline as sublevel of the heading at cursor
9135 RET no heading at cursor position, level taken from context.
9136 Or use prefix arg to specify level manually.
9137 <left> on headline as same level, before current heading
9138 <right> on headline as same level, after current heading
9139
9140 So the fastest way to store the note is to press RET RET to append it to
9141 the default file. This way your current train of thought is not
9142 interrupted, in accordance with the principles of remember.el. But with
9143 little extra effort, you can push it directly to the correct location.
9144
9145 Before being stored away, the function ensures that the text has a
9146 headline, i.e. a first line that starts with a \"*\". If not, a headline
9147 is constructed from the current date and some additional data.
9148
9149 If the variable `org-adapt-indentation' is non-nil, the entire text is
9150 also indented so that it starts in the same column as the headline
9151 \(i.e. after the stars).
9152
9153 See also the variable `org-reverse-note-order'."
9154 (catch 'quit
9155 (let* ((txt (buffer-substring (point-min) (point-max)))
9156 (fastp current-prefix-arg)
9157 (file (if fastp org-default-notes-file (org-get-org-file)))
9158 (visiting (find-buffer-visiting file))
9159 (org-startup-with-deadline-check nil)
9160 (org-startup-folded nil)
9161 (org-startup-align-all-tables nil)
9162 spos level indent reversed)
9163 ;; Modify text so that it becomes a nice subtree which can be inserted
9164 ;; into an org tree.
9165 (let* ((lines (split-string txt "\n"))
9166 first)
9167 ;; remove empty lines at the beginning
9168 (while (and lines (string-match "^[ \t]*\n" (car lines)))
9169 (setq lines (cdr lines)))
9170 (setq first (car lines) lines (cdr lines))
9171 (if (string-match "^\\*+" first)
9172 ;; Is already a headline
9173 (setq indent nil)
9174 ;; We need to add a headline: Use time and first buffer line
9175 (setq lines (cons first lines)
9176 first (concat "* " (current-time-string)
9177 " (" (remember-buffer-desc) ")")
9178 indent " "))
9179 (if (and org-adapt-indentation indent)
9180 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
9181 (setq txt (concat first "\n"
9182 (mapconcat 'identity lines "\n"))))
9183 ;; Find the file
9184 (if (not visiting)
9185 (find-file-noselect file))
9186 (with-current-buffer (get-file-buffer file)
9187 (save-excursion (and (goto-char (point-min))
9188 (not (re-search-forward "^\\* " nil t))
9189 (insert "\n* Notes\n")))
9190 (setq reversed (org-notes-order-reversed-p))
9191 (save-excursion
9192 (save-restriction
9193 (widen)
9194 ;; Ask the User for a location
9195 (setq spos (if fastp 1 (org-get-location
9196 (current-buffer)
9197 org-remember-help)))
9198 (if (not spos) (throw 'quit nil)) ; return nil to show we did
9199 ; not handle this note
9200 (goto-char spos)
9201 (cond ((bobp)
9202 ;; Put it at the start or end, as level 2
9203 (save-restriction
9204 (widen)
9205 (goto-char (if reversed (point-min) (point-max)))
9206 (if (not (bolp)) (newline))
9207 (org-paste-subtree 2 txt)))
9208 ((and (org-on-heading-p nil) (not current-prefix-arg))
9209 ;; Put it below this entry, at the beg/end of the subtree
9210 (org-back-to-heading)
9211 (setq level (funcall outline-level))
9212 (if reversed
9213 (outline-end-of-heading)
9214 (outline-end-of-subtree))
9215 (if (not (bolp)) (newline))
9216 (beginning-of-line 1)
9217 (org-paste-subtree (1+ level) txt))
9218 (t
9219 ;; Put it right there, with automatic level determined by
9220 ;; org-paste-subtree or from prefix arg
9221 (org-paste-subtree current-prefix-arg txt)))
9222 (when remember-save-after-remembering
9223 (save-buffer)
9224 (if (not visiting) (kill-buffer (current-buffer)))))))))
9225 t) ;; return t to indicate that we took care of this note.
9226
9227 (defun org-get-org-file ()
9228 "Read a filename, with default directory `org-directory'."
9229 (let ((default (or org-default-notes-file remember-data-file)))
9230 (read-file-name (format "File name [%s]: " default)
9231 (file-name-as-directory org-directory)
9232 default)))
9233
9234 (defun org-notes-order-reversed-p ()
9235 "Check if the current file should receive notes in reversed order."
9236 (cond
9237 ((not org-reverse-note-order) nil)
9238 ((eq t org-reverse-note-order) t)
9239 ((not (listp org-reverse-note-order)) nil)
9240 (t (catch 'exit
9241 (let ((all org-reverse-note-order)
9242 entry)
9243 (while (setq entry (pop all))
9244 (if (string-match (car entry) buffer-file-name)
9245 (throw 'exit (cdr entry))))
9246 nil)))))
9247
9248 ;;; Tables
9249
9250 ;; Watch out: Here we are talking about two different kind of tables.
9251 ;; Most of the code is for the tables created with the Org-mode table editor.
9252 ;; Sometimes, we talk about tables created and edited with the table.el
9253 ;; Emacs package. We call the former org-type tables, and the latter
9254 ;; table.el-type tables.
9255
9256
9257 (defun org-before-change-function (beg end)
9258 "Every change indicates that a table might need an update."
9259 (setq org-table-may-need-update t))
9260
9261 (defconst org-table-line-regexp "^[ \t]*|"
9262 "Detects an org-type table line.")
9263 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
9264 "Detects an org-type table line.")
9265 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
9266 "Detects a table line marked for automatic recalculation.")
9267 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
9268 "Detects a table line marked for automatic recalculation.")
9269 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
9270 "Detects a table line marked for automatic recalculation.")
9271 (defconst org-table-hline-regexp "^[ \t]*|-"
9272 "Detects an org-type table hline.")
9273 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
9274 "Detects a table-type table hline.")
9275 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
9276 "Detects an org-type or table-type table.")
9277 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
9278 "Searching from within a table (any type) this finds the first line
9279 outside the table.")
9280 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
9281 "Searching from within a table (any type) this finds the first line
9282 outside the table.")
9283
9284 (defun org-table-create-with-table.el ()
9285 "Use the table.el package to insert a new table.
9286 If there is already a table at point, convert between Org-mode tables
9287 and table.el tables."
9288 (interactive)
9289 (require 'table)
9290 (cond
9291 ((org-at-table.el-p)
9292 (if (y-or-n-p "Convert table to Org-mode table? ")
9293 (org-table-convert)))
9294 ((org-at-table-p)
9295 (if (y-or-n-p "Convert table to table.el table? ")
9296 (org-table-convert)))
9297 (t (call-interactively 'table-insert))))
9298
9299 (defun org-table-create-or-convert-from-region (arg)
9300 "Convert region to table, or create an empty table.
9301 If there is an active region, convert it to a table. If there is no such
9302 region, create an empty table."
9303 (interactive "P")
9304 (if (org-region-active-p)
9305 (org-table-convert-region (region-beginning) (region-end) arg)
9306 (org-table-create arg)))
9307
9308 (defun org-table-create (&optional size)
9309 "Query for a size and insert a table skeleton.
9310 SIZE is a string Columns x Rows like for example \"3x2\"."
9311 (interactive "P")
9312 (unless size
9313 (setq size (read-string
9314 (concat "Table size Columns x Rows [e.g. "
9315 org-table-default-size "]: ")
9316 "" nil org-table-default-size)))
9317
9318 (let* ((pos (point))
9319 (indent (make-string (current-column) ?\ ))
9320 (split (org-split-string size " *x *"))
9321 (rows (string-to-number (nth 1 split)))
9322 (columns (string-to-number (car split)))
9323 (line (concat (apply 'concat indent "|" (make-list columns " |"))
9324 "\n")))
9325 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
9326 (point-at-bol) (point)))
9327 (beginning-of-line 1)
9328 (newline))
9329 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
9330 (dotimes (i rows) (insert line))
9331 (goto-char pos)
9332 (if (> rows 1)
9333 ;; Insert a hline after the first row.
9334 (progn
9335 (end-of-line 1)
9336 (insert "\n|-")
9337 (goto-char pos)))
9338 (org-table-align)))
9339
9340 (defun org-table-convert-region (beg0 end0 &optional nspace)
9341 "Convert region to a table.
9342 The region goes from BEG0 to END0, but these borders will be moved
9343 slightly, to make sure a beginning of line in the first line is included.
9344 When NSPACE is non-nil, it indicates the minimum number of spaces that
9345 separate columns (default: just one space)."
9346 (interactive "rP")
9347 (let* ((beg (min beg0 end0))
9348 (end (max beg0 end0))
9349 (tabsep t)
9350 re)
9351 (goto-char beg)
9352 (beginning-of-line 1)
9353 (setq beg (move-marker (make-marker) (point)))
9354 (goto-char end)
9355 (if (bolp) (backward-char 1) (end-of-line 1))
9356 (setq end (move-marker (make-marker) (point)))
9357 ;; Lets see if this is tab-separated material. If every nonempty line
9358 ;; contains a tab, we will assume that it is tab-separated material
9359 (if nspace
9360 (setq tabsep nil)
9361 (goto-char beg)
9362 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
9363 (if nspace (setq tabsep nil))
9364 (if tabsep
9365 (setq re "^\\|\t")
9366 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
9367 (max 1 (prefix-numeric-value nspace)))))
9368 (goto-char beg)
9369 (while (re-search-forward re end t)
9370 (replace-match "|" t t))
9371 (goto-char beg)
9372 (insert " ")
9373 (org-table-align)))
9374
9375 (defun org-table-import (file arg)
9376 "Import FILE as a table.
9377 The file is assumed to be tab-separated. Such files can be produced by most
9378 spreadsheet and database applications. If no tabs (at least one per line)
9379 are found, lines will be split on whitespace into fields."
9380 (interactive "f\nP")
9381 (or (bolp) (newline))
9382 (let ((beg (point))
9383 (pm (point-max)))
9384 (insert-file-contents file)
9385 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
9386
9387 (defun org-table-export ()
9388 "Export table as a tab-separated file.
9389 Such a file can be imported into a spreadsheet program like Excel."
9390 (interactive)
9391 (let* ((beg (org-table-begin))
9392 (end (org-table-end))
9393 (table (buffer-substring beg end))
9394 (file (read-file-name "Export table to: "))
9395 buf)
9396 (unless (or (not (file-exists-p file))
9397 (y-or-n-p (format "Overwrite file %s? " file)))
9398 (error "Abort"))
9399 (with-current-buffer (find-file-noselect file)
9400 (setq buf (current-buffer))
9401 (erase-buffer)
9402 (fundamental-mode)
9403 (insert table)
9404 (goto-char (point-min))
9405 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
9406 (replace-match "" t t)
9407 (end-of-line 1))
9408 (goto-char (point-min))
9409 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
9410 (replace-match "" t t)
9411 (goto-char (min (1+ (point)) (point-max))))
9412 (goto-char (point-min))
9413 (while (re-search-forward "^-[-+]*$" nil t)
9414 (replace-match "")
9415 (if (looking-at "\n")
9416 (delete-char 1)))
9417 (goto-char (point-min))
9418 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
9419 (replace-match "\t" t t))
9420 (save-buffer))
9421 (kill-buffer buf)))
9422
9423 (defvar org-table-aligned-begin-marker (make-marker)
9424 "Marker at the beginning of the table last aligned.
9425 Used to check if cursor still is in that table, to minimize realignment.")
9426 (defvar org-table-aligned-end-marker (make-marker)
9427 "Marker at the end of the table last aligned.
9428 Used to check if cursor still is in that table, to minimize realignment.")
9429 (defvar org-table-last-alignment nil
9430 "List of flags for flushright alignment, from the last re-alignment.
9431 This is being used to correctly align a single field after TAB or RET.")
9432 (defvar org-table-last-column-widths nil
9433 "List of max width of fields in each column.
9434 This is being used to correctly align a single field after TAB or RET.")
9435
9436 (defvar org-last-recalc-line nil)
9437 (defconst org-narrow-column-arrow "=>"
9438 "Used as display property in narrowed table columns.")
9439
9440 (defun org-table-align ()
9441 "Align the table at point by aligning all vertical bars."
9442 (interactive)
9443 (let* (
9444 ;; Limits of table
9445 (beg (org-table-begin))
9446 (end (org-table-end))
9447 ;; Current cursor position
9448 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9449 (colpos (org-table-current-column))
9450 (winstart (window-start))
9451 text lines (new "") lengths l typenums ty fields maxfields i
9452 column
9453 (indent "") cnt frac
9454 rfmt hfmt
9455 (spaces '(1 . 1))
9456 (sp1 (car spaces))
9457 (sp2 (cdr spaces))
9458 (rfmt1 (concat
9459 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
9460 (hfmt1 (concat
9461 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
9462 emptystrings xx links narrow fmax fmin f1 len c e)
9463 (untabify beg end)
9464 (remove-text-properties beg end '(org-cwidth t display t))
9465 ;; Check if we have links
9466 (goto-char beg)
9467 (setq links (re-search-forward org-bracket-link-regexp end t))
9468 ;; Make sure the link properties are right FIXME: Can this be optimized????
9469 (when links (goto-char beg) (while (org-activate-bracket-links end)))
9470 ;; Check if we are narrowing any columns
9471 (goto-char beg)
9472 (setq narrow (and org-format-transports-properties-p
9473 (re-search-forward "<[0-9]+>" end t)))
9474 ;; Get the rows
9475 (setq lines (org-split-string
9476 (buffer-substring beg end) "\n"))
9477 ;; Store the indentation of the first line
9478 (if (string-match "^ *" (car lines))
9479 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
9480 ;; Mark the hlines by setting the corresponding element to nil
9481 ;; At the same time, we remove trailing space.
9482 (setq lines (mapcar (lambda (l)
9483 (if (string-match "^ *|-" l)
9484 nil
9485 (if (string-match "[ \t]+$" l)
9486 (substring l 0 (match-beginning 0))
9487 l)))
9488 lines))
9489 ;; Get the data fields by splitting the lines.
9490 (setq fields (mapcar
9491 (lambda (l)
9492 (org-split-string l " *| *"))
9493 (delq nil (copy-sequence lines))))
9494 ;; How many fields in the longest line?
9495 (condition-case nil
9496 (setq maxfields (apply 'max (mapcar 'length fields)))
9497 (error
9498 (kill-region beg end)
9499 (org-table-create org-table-default-size)
9500 (error "Empty table - created default table")))
9501 ;; A list of empty string to fill any short rows on output
9502 (setq emptystrings (make-list maxfields ""))
9503 ;; Check for special formatting.
9504 (setq i -1)
9505 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
9506 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
9507 ;; Check if there is an explicit width specified
9508 (when (and org-table-limit-column-width narrow)
9509 (setq c column fmax nil)
9510 (while c
9511 (setq e (pop c))
9512 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
9513 (setq fmax (string-to-number (match-string 1 e)) c nil)))
9514 ;; Find fields that are wider than fmax, and shorten them
9515 (when fmax
9516 (loop for xx in column do
9517 (when (and (stringp xx)
9518 (> (org-string-width xx) fmax))
9519 (org-add-props xx nil
9520 'help-echo
9521 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
9522 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
9523 (unless (> f1 1)
9524 (error "Cannot narrow field starting with wide link \"%s\""
9525 (match-string 0 xx)))
9526 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
9527 (add-text-properties (- f1 2) f1
9528 (list 'display org-narrow-column-arrow)
9529 xx)))))
9530 ;; Get the maximum width for each column
9531 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
9532 ;; Get the fraction of numbers, to decide about alignment of the column
9533 (setq cnt 0 frac 0.0)
9534 (loop for x in column do
9535 (if (equal x "")
9536 nil
9537 (setq frac ( / (+ (* frac cnt)
9538 (if (string-match org-table-number-regexp x) 1 0))
9539 (setq cnt (1+ cnt))))))
9540 (push (>= frac org-table-number-fraction) typenums))
9541 (setq lengths (nreverse lengths) typenums (nreverse typenums))
9542
9543 ;; Store the alignment of this table, for later editing of single fields
9544 (setq org-table-last-alignment typenums
9545 org-table-last-column-widths lengths)
9546
9547 ;; With invisible characters, `format' does not get the field width right
9548 ;; So we need to make these fields wide by hand.
9549 (when links
9550 (loop for i from 0 upto (1- maxfields) do
9551 (setq len (nth i lengths))
9552 (loop for j from 0 upto (1- (length fields)) do
9553 (setq c (nthcdr i (car (nthcdr j fields))))
9554 (if (and (stringp (car c))
9555 (string-match org-bracket-link-regexp (car c))
9556 (< (org-string-width (car c)) len))
9557 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
9558
9559 ;; Compute the formats needed for output of the table
9560 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
9561 (while (setq l (pop lengths))
9562 (setq ty (if (pop typenums) "" "-")) ; number types flushright
9563 (setq rfmt (concat rfmt (format rfmt1 ty l))
9564 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
9565 (setq rfmt (concat rfmt "\n")
9566 hfmt (concat (substring hfmt 0 -1) "|\n"))
9567
9568 (setq new (mapconcat
9569 (lambda (l)
9570 (if l (apply 'format rfmt
9571 (append (pop fields) emptystrings))
9572 hfmt))
9573 lines ""))
9574 ;; Replace the old one
9575 (delete-region beg end)
9576 (move-marker end nil)
9577 (move-marker org-table-aligned-begin-marker (point))
9578 (insert new)
9579 (move-marker org-table-aligned-end-marker (point))
9580 (when (and orgtbl-mode (not (eq major-mode 'org-mode)))
9581 (goto-char org-table-aligned-begin-marker)
9582 (while (org-hide-wide-columns org-table-aligned-end-marker)))
9583 ;; Try to move to the old location (approximately)
9584 (goto-line linepos)
9585 (set-window-start (selected-window) winstart 'noforce)
9586 (org-table-goto-column colpos)
9587 (setq org-table-may-need-update nil)
9588 ))
9589
9590 (defun org-string-width (s)
9591 "Compute width of string, ignoring invisible characters.
9592 This ignores character with invisibility property `org-link', and also
9593 characters with property `org-cwidth', because these will become invisible
9594 upon the next fontification round."
9595 (let (b)
9596 (when (or (eq t buffer-invisibility-spec)
9597 (assq 'org-link buffer-invisibility-spec))
9598 (while (setq b (text-property-any 0 (length s)
9599 'invisible 'org-link s))
9600 (setq s (concat (substring s 0 b)
9601 (substring s (or (next-single-property-change
9602 b 'invisible s) (length s)))))))
9603 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
9604 (setq s (concat (substring s 0 b)
9605 (substring s (or (next-single-property-change
9606 b 'org-cwidth s) (length s))))))
9607 (string-width s)))
9608
9609 (defun org-table-begin (&optional table-type)
9610 "Find the beginning of the table and return its position.
9611 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
9612 (save-excursion
9613 (if (not (re-search-backward
9614 (if table-type org-table-any-border-regexp
9615 org-table-border-regexp)
9616 nil t))
9617 (progn (goto-char (point-min)) (point))
9618 (goto-char (match-beginning 0))
9619 (beginning-of-line 2)
9620 (point))))
9621
9622 (defun org-table-end (&optional table-type)
9623 "Find the end of the table and return its position.
9624 With argument TABLE-TYPE, go to the end of a table.el-type table."
9625 (save-excursion
9626 (if (not (re-search-forward
9627 (if table-type org-table-any-border-regexp
9628 org-table-border-regexp)
9629 nil t))
9630 (goto-char (point-max))
9631 (goto-char (match-beginning 0)))
9632 (point-marker)))
9633
9634 (defun org-table-justify-field-maybe (&optional new)
9635 "Justify the current field, text to left, number to right.
9636 Optional argument NEW may specify text to replace the current field content."
9637 (cond
9638 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
9639 ((org-at-table-hline-p))
9640 ((and (not new)
9641 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
9642 (current-buffer)))
9643 (< (point) org-table-aligned-begin-marker)
9644 (>= (point) org-table-aligned-end-marker)))
9645 ;; This is not the same table, force a full re-align
9646 (setq org-table-may-need-update t))
9647 (t ;; realign the current field, based on previous full realign
9648 (let* ((pos (point)) s
9649 (col (org-table-current-column))
9650 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
9651 l f n o e)
9652 (when (> col 0)
9653 (skip-chars-backward "^|\n")
9654 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
9655 (progn
9656 (setq s (match-string 1)
9657 o (match-string 0)
9658 l (max 1 (- (match-end 0) (match-beginning 0) 3))
9659 e (not (= (match-beginning 2) (match-end 2))))
9660 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
9661 l (if e "|" (setq org-table-may-need-update t) ""))
9662 n (format f s))
9663 (if new
9664 (if (<= (length new) l) ;; FIXME: length -> str-width?
9665 (setq n (format f new t t)) ;; FIXME: t t?
9666 (setq n (concat new "|") org-table-may-need-update t)))
9667 (or (equal n o)
9668 (let (org-table-may-need-update)
9669 (replace-match n))))
9670 (setq org-table-may-need-update t))
9671 (goto-char pos))))))
9672
9673 (defun org-table-next-field ()
9674 "Go to the next field in the current table, creating new lines as needed.
9675 Before doing so, re-align the table if necessary."
9676 (interactive)
9677 (org-table-maybe-eval-formula)
9678 (org-table-maybe-recalculate-line)
9679 (if (and org-table-automatic-realign
9680 org-table-may-need-update)
9681 (org-table-align))
9682 (let ((end (org-table-end)))
9683 (if (org-at-table-hline-p)
9684 (end-of-line 1))
9685 (condition-case nil
9686 (progn
9687 (re-search-forward "|" end)
9688 (if (looking-at "[ \t]*$")
9689 (re-search-forward "|" end))
9690 (if (and (looking-at "-")
9691 org-table-tab-jumps-over-hlines
9692 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
9693 (goto-char (match-beginning 1)))
9694 (if (looking-at "-")
9695 (progn
9696 (beginning-of-line 0)
9697 (org-table-insert-row 'below))
9698 (if (looking-at " ") (forward-char 1))))
9699 (error
9700 (org-table-insert-row 'below)))))
9701
9702 (defun org-table-previous-field ()
9703 "Go to the previous field in the table.
9704 Before doing so, re-align the table if necessary."
9705 (interactive)
9706 (org-table-justify-field-maybe)
9707 (org-table-maybe-recalculate-line)
9708 (if (and org-table-automatic-realign
9709 org-table-may-need-update)
9710 (org-table-align))
9711 (if (org-at-table-hline-p)
9712 (end-of-line 1))
9713 (re-search-backward "|" (org-table-begin))
9714 (re-search-backward "|" (org-table-begin))
9715 (while (looking-at "|\\(-\\|[ \t]*$\\)")
9716 (re-search-backward "|" (org-table-begin)))
9717 (if (looking-at "| ?")
9718 (goto-char (match-end 0))))
9719
9720 (defun org-table-next-row ()
9721 "Go to the next row (same column) in the current table.
9722 Before doing so, re-align the table if necessary."
9723 (interactive)
9724 (org-table-maybe-eval-formula)
9725 (org-table-maybe-recalculate-line)
9726 (if (or (looking-at "[ \t]*$")
9727 (save-excursion (skip-chars-backward " \t") (bolp)))
9728 (newline)
9729 (if (and org-table-automatic-realign
9730 org-table-may-need-update)
9731 (org-table-align))
9732 (let ((col (org-table-current-column)))
9733 (beginning-of-line 2)
9734 (if (or (not (org-at-table-p))
9735 (org-at-table-hline-p))
9736 (progn
9737 (beginning-of-line 0)
9738 (org-table-insert-row 'below)))
9739 (org-table-goto-column col)
9740 (skip-chars-backward "^|\n\r")
9741 (if (looking-at " ") (forward-char 1)))))
9742
9743 (defun org-table-copy-down (n)
9744 "Copy a field down in the current column.
9745 If the field at the cursor is empty, copy into it the content of the nearest
9746 non-empty field above. With argument N, use the Nth non-empty field.
9747 If the current field is not empty, it is copied down to the next row, and
9748 the cursor is moved with it. Therefore, repeating this command causes the
9749 column to be filled row-by-row.
9750 If the variable `org-table-copy-increment' is non-nil and the field is an
9751 integer, it will be incremented while copying."
9752 (interactive "p")
9753 (let* ((colpos (org-table-current-column))
9754 (field (org-table-get-field))
9755 (non-empty (string-match "[^ \t]" field))
9756 (beg (org-table-begin))
9757 txt)
9758 (org-table-check-inside-data-field)
9759 (if non-empty
9760 (progn
9761 (setq txt (org-trim field))
9762 (org-table-next-row)
9763 (org-table-blank-field))
9764 (save-excursion
9765 (setq txt
9766 (catch 'exit
9767 (while (progn (beginning-of-line 1)
9768 (re-search-backward org-table-dataline-regexp
9769 beg t))
9770 (org-table-goto-column colpos t)
9771 (if (and (looking-at
9772 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
9773 (= (setq n (1- n)) 0))
9774 (throw 'exit (match-string 1))))))))
9775 (if txt
9776 (progn
9777 (if (and org-table-copy-increment
9778 (string-match "^[0-9]+$" txt))
9779 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9780 (insert txt)
9781 (org-table-maybe-recalculate-line)
9782 (org-table-align))
9783 (error "No non-empty field found"))))
9784
9785 (defun org-table-check-inside-data-field ()
9786 "Is point inside a table data field?
9787 I.e. not on a hline or before the first or after the last column?
9788 This actually throws an error, so it aborts the current command."
9789 (if (or (not (org-at-table-p))
9790 (= (org-table-current-column) 0)
9791 (org-at-table-hline-p)
9792 (looking-at "[ \t]*$"))
9793 (error "Not in table data field")))
9794
9795 (defvar org-table-clip nil
9796 "Clipboard for table regions.")
9797
9798 (defun org-table-blank-field ()
9799 "Blank the current table field or active region."
9800 (interactive)
9801 (org-table-check-inside-data-field)
9802 (if (and (interactive-p) (org-region-active-p))
9803 (let (org-table-clip)
9804 (org-table-cut-region (region-beginning) (region-end)))
9805 (skip-chars-backward "^|")
9806 (backward-char 1)
9807 (if (looking-at "|[^|\n]+")
9808 (let* ((pos (match-beginning 0))
9809 (match (match-string 0))
9810 (len (org-string-width match)))
9811 (replace-match (concat "|" (make-string (1- len) ?\ )))
9812 (goto-char (+ 2 pos))
9813 (substring match 1)))))
9814
9815 (defun org-table-get-field (&optional n replace)
9816 "Return the value of the field in column N of current row.
9817 N defaults to current field.
9818 If REPLACE is a string, replace field with this value. The return value
9819 is always the old value."
9820 (and n (org-table-goto-column n))
9821 (skip-chars-backward "^|\n")
9822 (backward-char 1)
9823 (if (looking-at "|[^|\r\n]*")
9824 (let* ((pos (match-beginning 0))
9825 (val (buffer-substring (1+ pos) (match-end 0))))
9826 (if replace
9827 (replace-match (concat "|" replace)))
9828 (goto-char (min (point-at-eol) (+ 2 pos)))
9829 val)
9830 (forward-char 1) ""))
9831
9832 (defun org-table-current-column ()
9833 "Find out which column we are in.
9834 When called interactively, column is also displayed in echo area."
9835 (interactive)
9836 (if (interactive-p) (org-table-check-inside-data-field))
9837 (save-excursion
9838 (let ((cnt 0) (pos (point)))
9839 (beginning-of-line 1)
9840 (while (search-forward "|" pos t)
9841 (setq cnt (1+ cnt)))
9842 (if (interactive-p) (message "This is table column %d" cnt))
9843 cnt)))
9844
9845 (defun org-table-goto-column (n &optional on-delim force)
9846 "Move the cursor to the Nth column in the current table line.
9847 With optional argument ON-DELIM, stop with point before the left delimiter
9848 of the field.
9849 If there are less than N fields, just go to after the last delimiter.
9850 However, when FORCE is non-nil, create new columns if necessary."
9851 (interactive "p")
9852 (let ((pos (point-at-eol)))
9853 (beginning-of-line 1)
9854 (when (> n 0)
9855 (while (and (> (setq n (1- n)) -1)
9856 (or (search-forward "|" pos t)
9857 (and force
9858 (progn (end-of-line 1)
9859 (skip-chars-backward "^|")
9860 (insert " | "))))))
9861 ; (backward-char 2) t)))))
9862 (when (and force (not (looking-at ".*|")))
9863 (save-excursion (end-of-line 1) (insert " | ")))
9864 (if on-delim
9865 (backward-char 1)
9866 (if (looking-at " ") (forward-char 1))))))
9867
9868 (defun org-at-table-p (&optional table-type)
9869 "Return t if the cursor is inside an org-type table.
9870 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9871 (if org-enable-table-editor
9872 (save-excursion
9873 (beginning-of-line 1)
9874 (looking-at (if table-type org-table-any-line-regexp
9875 org-table-line-regexp)))
9876 nil))
9877
9878 (defun org-at-table.el-p ()
9879 "Return t if and only if we are at a table.el table."
9880 (and (org-at-table-p 'any)
9881 (save-excursion
9882 (goto-char (org-table-begin 'any))
9883 (looking-at org-table1-hline-regexp))))
9884
9885 (defun org-table-recognize-table.el ()
9886 "If there is a table.el table nearby, recognize it and move into it."
9887 (if org-table-tab-recognizes-table.el
9888 (if (org-at-table.el-p)
9889 (progn
9890 (beginning-of-line 1)
9891 (if (looking-at org-table-dataline-regexp)
9892 nil
9893 (if (looking-at org-table1-hline-regexp)
9894 (progn
9895 (beginning-of-line 2)
9896 (if (looking-at org-table-any-border-regexp)
9897 (beginning-of-line -1)))))
9898 (if (re-search-forward "|" (org-table-end t) t)
9899 (progn
9900 (require 'table)
9901 (if (table--at-cell-p (point))
9902 t
9903 (message "recognizing table.el table...")
9904 (table-recognize-table)
9905 (message "recognizing table.el table...done")))
9906 (error "This should not happen..."))
9907 t)
9908 nil)
9909 nil))
9910
9911 (defun org-at-table-hline-p ()
9912 "Return t if the cursor is inside a hline in a table."
9913 (if org-enable-table-editor
9914 (save-excursion
9915 (beginning-of-line 1)
9916 (looking-at org-table-hline-regexp))
9917 nil))
9918
9919 (defun org-table-insert-column ()
9920 "Insert a new column into the table."
9921 (interactive)
9922 (if (not (org-at-table-p))
9923 (error "Not at a table"))
9924 (org-table-find-dataline)
9925 (let* ((col (max 1 (org-table-current-column)))
9926 (beg (org-table-begin))
9927 (end (org-table-end))
9928 ;; Current cursor position
9929 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9930 (colpos col))
9931 (goto-char beg)
9932 (while (< (point) end)
9933 (if (org-at-table-hline-p)
9934 nil
9935 (org-table-goto-column col t)
9936 (insert "| "))
9937 (beginning-of-line 2))
9938 (move-marker end nil)
9939 (goto-line linepos)
9940 (org-table-goto-column colpos)
9941 (org-table-align)
9942 (org-table-modify-formulas 'insert col)))
9943
9944 (defun org-table-find-dataline ()
9945 "Find a dataline in the current table, which is needed for column commands."
9946 (if (and (org-at-table-p)
9947 (not (org-at-table-hline-p)))
9948 t
9949 (let ((col (current-column))
9950 (end (org-table-end)))
9951 (move-to-column col)
9952 (while (and (< (point) end)
9953 (or (not (= (current-column) col))
9954 (org-at-table-hline-p)))
9955 (beginning-of-line 2)
9956 (move-to-column col))
9957 (if (and (org-at-table-p)
9958 (not (org-at-table-hline-p)))
9959 t
9960 (error
9961 "Please position cursor in a data line for column operations")))))
9962
9963 (defun org-table-delete-column ()
9964 "Delete a column from the table."
9965 (interactive)
9966 (if (not (org-at-table-p))
9967 (error "Not at a table"))
9968 (org-table-find-dataline)
9969 (org-table-check-inside-data-field)
9970 (let* ((col (org-table-current-column))
9971 (beg (org-table-begin))
9972 (end (org-table-end))
9973 ;; Current cursor position
9974 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9975 (colpos col))
9976 (goto-char beg)
9977 (while (< (point) end)
9978 (if (org-at-table-hline-p)
9979 nil
9980 (org-table-goto-column col t)
9981 (and (looking-at "|[^|\n]+|")
9982 (replace-match "|")))
9983 (beginning-of-line 2))
9984 (move-marker end nil)
9985 (goto-line linepos)
9986 (org-table-goto-column colpos)
9987 (org-table-align)
9988 (org-table-modify-formulas 'remove col)))
9989
9990 (defun org-table-move-column-right ()
9991 "Move column to the right."
9992 (interactive)
9993 (org-table-move-column nil))
9994 (defun org-table-move-column-left ()
9995 "Move column to the left."
9996 (interactive)
9997 (org-table-move-column 'left))
9998
9999 (defun org-table-move-column (&optional left)
10000 "Move the current column to the right. With arg LEFT, move to the left."
10001 (interactive "P")
10002 (if (not (org-at-table-p))
10003 (error "Not at a table"))
10004 (org-table-find-dataline)
10005 (org-table-check-inside-data-field)
10006 (let* ((col (org-table-current-column))
10007 (col1 (if left (1- col) col))
10008 (beg (org-table-begin))
10009 (end (org-table-end))
10010 ;; Current cursor position
10011 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10012 (colpos (if left (1- col) (1+ col))))
10013 (if (and left (= col 1))
10014 (error "Cannot move column further left"))
10015 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
10016 (error "Cannot move column further right"))
10017 (goto-char beg)
10018 (while (< (point) end)
10019 (if (org-at-table-hline-p)
10020 nil
10021 (org-table-goto-column col1 t)
10022 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
10023 (replace-match "|\\2|\\1|")))
10024 (beginning-of-line 2))
10025 (move-marker end nil)
10026 (goto-line linepos)
10027 (org-table-goto-column colpos)
10028 (org-table-align)
10029 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
10030
10031 (defun org-table-move-row-down ()
10032 "Move table row down."
10033 (interactive)
10034 (org-table-move-row nil))
10035 (defun org-table-move-row-up ()
10036 "Move table row up."
10037 (interactive)
10038 (org-table-move-row 'up))
10039
10040 (defun org-table-move-row (&optional up)
10041 "Move the current table line down. With arg UP, move it up."
10042 (interactive "P")
10043 (let ((col (current-column))
10044 (pos (point))
10045 (tonew (if up 0 2))
10046 txt)
10047 (beginning-of-line tonew)
10048 (if (not (org-at-table-p))
10049 (progn
10050 (goto-char pos)
10051 (error "Cannot move row further")))
10052 (goto-char pos)
10053 (beginning-of-line 1)
10054 (setq pos (point))
10055 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
10056 (delete-region (point) (1+ (point-at-eol)))
10057 (beginning-of-line tonew)
10058 (insert txt)
10059 (beginning-of-line 0)
10060 (move-to-column col)))
10061
10062 (defun org-table-insert-row (&optional arg)
10063 "Insert a new row above the current line into the table.
10064 With prefix ARG, insert below the current line."
10065 (interactive "P")
10066 (if (not (org-at-table-p))
10067 (error "Not at a table"))
10068 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
10069 (new (org-table-clean-line line)))
10070 ;; Fix the first field if necessary
10071 (if (string-match "^[ \t]*| *[#$] *|" line)
10072 (setq new (replace-match (match-string 0 line) t t new)))
10073 (beginning-of-line (if arg 2 1))
10074 (let (org-table-may-need-update) (insert-before-markers new "\n"))
10075 (beginning-of-line 0)
10076 (re-search-forward "| ?" (point-at-eol) t)
10077 (and org-table-may-need-update (org-table-align))))
10078
10079 (defun org-table-insert-hline (&optional arg)
10080 "Insert a horizontal-line below the current line into the table.
10081 With prefix ARG, insert above the current line."
10082 (interactive "P")
10083 (if (not (org-at-table-p))
10084 (error "Not at a table"))
10085 (let ((line (org-table-clean-line
10086 (buffer-substring (point-at-bol) (point-at-eol))))
10087 (col (current-column)))
10088 (while (string-match "|\\( +\\)|" line)
10089 (setq line (replace-match
10090 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
10091 ?-) "|") t t line)))
10092 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
10093 (beginning-of-line (if arg 1 2))
10094 (insert line "\n")
10095 (beginning-of-line (if arg 1 -1))
10096 (move-to-column col)))
10097
10098 (defun org-table-clean-line (s)
10099 "Convert a table line S into a string with only \"|\" and space.
10100 In particular, this does handle wide and invisible characters."
10101 (if (string-match "^[ \t]*|-" s)
10102 ;; It's a hline, just map the characters
10103 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
10104 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
10105 (setq s (replace-match
10106 (concat "|" (make-string (org-string-width (match-string 1 s))
10107 ?\ ) "|")
10108 t t s)))
10109 s))
10110
10111 (defun org-table-kill-row ()
10112 "Delete the current row or horizontal line from the table."
10113 (interactive)
10114 (if (not (org-at-table-p))
10115 (error "Not at a table"))
10116 (let ((col (current-column)))
10117 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
10118 (if (not (org-at-table-p)) (beginning-of-line 0))
10119 (move-to-column col)))
10120
10121 (defun org-table-sort-lines (beg end numericp)
10122 "Sort table lines in region.
10123 Point and mark define the first and last line to include. Both point and
10124 mark should be in the column that is used for sorting. For example, to
10125 sort according to column 3, put the mark in the first line to sort, in
10126 table column 3. Put point into the last line to be included in the sorting,
10127 also in table column 3. The command will prompt for the sorting method
10128 \(n for numerical, a for alphanumeric)."
10129 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
10130 (setq numericp (string-match "[nN]" numericp))
10131 (org-table-align) ;; Just to be safe
10132 (let* (bcol ecol cmp column lns)
10133 (goto-char beg)
10134 (org-table-check-inside-data-field)
10135 (setq column (org-table-current-column)
10136 beg (move-marker (make-marker) (point-at-bol)))
10137 (goto-char end)
10138 (org-table-check-inside-data-field)
10139 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
10140 (untabify beg end)
10141 (goto-char beg)
10142 (org-table-goto-column column)
10143 (skip-chars-backward "^|")
10144 (setq bcol (current-column))
10145 (org-table-goto-column (1+ column))
10146 (skip-chars-backward "^|")
10147 (setq ecol (1- (current-column)))
10148 (setq cmp (if numericp
10149 (lambda (a b) (< (car a) (car b)))
10150 (lambda (a b) (string< (car a) (car b)))))
10151 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
10152 (org-split-string (buffer-substring beg end) "\n")))
10153 (if numericp
10154 (setq lns (mapcar (lambda(x)
10155 (cons (string-to-number (car x)) (cdr x)))
10156 lns)))
10157 (delete-region beg end)
10158 (move-marker beg nil)
10159 (move-marker end nil)
10160 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
10161 (message "%d lines sorted %s based on column %d"
10162 (length lns)
10163 (if numericp "numerically" "alphabetically") column)))
10164
10165 (defun org-table-cut-region (beg end)
10166 "Copy region in table to the clipboard and blank all relevant fields."
10167 (interactive "r")
10168 (org-table-copy-region beg end 'cut))
10169
10170 (defun org-table-copy-region (beg end &optional cut)
10171 "Copy rectangular region in table to clipboard.
10172 A special clipboard is used which can only be accessed
10173 with `org-table-paste-rectangle'."
10174 (interactive "rP")
10175 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
10176 region cols
10177 (rpl (if cut " " nil)))
10178 (goto-char beg)
10179 (org-table-check-inside-data-field)
10180 (setq l01 (count-lines (point-min) (point))
10181 c01 (org-table-current-column))
10182 (goto-char end)
10183 (org-table-check-inside-data-field)
10184 (setq l02 (count-lines (point-min) (point))
10185 c02 (org-table-current-column))
10186 (setq l1 (min l01 l02) l2 (max l01 l02)
10187 c1 (min c01 c02) c2 (max c01 c02))
10188 (catch 'exit
10189 (while t
10190 (catch 'nextline
10191 (if (> l1 l2) (throw 'exit t))
10192 (goto-line l1)
10193 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
10194 (setq cols nil ic1 c1 ic2 c2)
10195 (while (< ic1 (1+ ic2))
10196 (push (org-table-get-field ic1 rpl) cols)
10197 (setq ic1 (1+ ic1)))
10198 (push (nreverse cols) region)
10199 (setq l1 (1+ l1)))))
10200 (setq org-table-clip (nreverse region))
10201 (if cut (org-table-align))
10202 org-table-clip))
10203
10204 (defun org-table-paste-rectangle ()
10205 "Paste a rectangular region into a table.
10206 The upper right corner ends up in the current field. All involved fields
10207 will be overwritten. If the rectangle does not fit into the present table,
10208 the table is enlarged as needed. The process ignores horizontal separator
10209 lines."
10210 (interactive)
10211 (unless (and org-table-clip (listp org-table-clip))
10212 (error "First cut/copy a region to paste!"))
10213 (org-table-check-inside-data-field)
10214 (let* ((clip org-table-clip)
10215 (line (count-lines (point-min) (point)))
10216 (col (org-table-current-column))
10217 (org-enable-table-editor t)
10218 (org-table-automatic-realign nil)
10219 c cols field)
10220 (while (setq cols (pop clip))
10221 (while (org-at-table-hline-p) (beginning-of-line 2))
10222 (if (not (org-at-table-p))
10223 (progn (end-of-line 0) (org-table-next-field)))
10224 (setq c col)
10225 (while (setq field (pop cols))
10226 (org-table-goto-column c nil 'force)
10227 (org-table-get-field nil field)
10228 (setq c (1+ c)))
10229 (beginning-of-line 2))
10230 (goto-line line)
10231 (org-table-goto-column col)
10232 (org-table-align)))
10233
10234 (defun org-table-convert ()
10235 "Convert from `org-mode' table to table.el and back.
10236 Obviously, this only works within limits. When an Org-mode table is
10237 converted to table.el, all horizontal separator lines get lost, because
10238 table.el uses these as cell boundaries and has no notion of horizontal lines.
10239 A table.el table can be converted to an Org-mode table only if it does not
10240 do row or column spanning. Multiline cells will become multiple cells.
10241 Beware, Org-mode does not test if the table can be successfully converted - it
10242 blindly applies a recipe that works for simple tables."
10243 (interactive)
10244 (require 'table)
10245 (if (org-at-table.el-p)
10246 ;; convert to Org-mode table
10247 (let ((beg (move-marker (make-marker) (org-table-begin t)))
10248 (end (move-marker (make-marker) (org-table-end t))))
10249 (table-unrecognize-region beg end)
10250 (goto-char beg)
10251 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
10252 (replace-match ""))
10253 (goto-char beg))
10254 (if (org-at-table-p)
10255 ;; convert to table.el table
10256 (let ((beg (move-marker (make-marker) (org-table-begin)))
10257 (end (move-marker (make-marker) (org-table-end))))
10258 ;; first, get rid of all horizontal lines
10259 (goto-char beg)
10260 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
10261 (replace-match ""))
10262 ;; insert a hline before first
10263 (goto-char beg)
10264 (org-table-insert-hline 'above)
10265 (beginning-of-line -1)
10266 ;; insert a hline after each line
10267 (while (progn (beginning-of-line 3) (< (point) end))
10268 (org-table-insert-hline))
10269 (goto-char beg)
10270 (setq end (move-marker end (org-table-end)))
10271 ;; replace "+" at beginning and ending of hlines
10272 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
10273 (replace-match "\\1+-"))
10274 (goto-char beg)
10275 (while (re-search-forward "-|[ \t]*$" end t)
10276 (replace-match "-+"))
10277 (goto-char beg)))))
10278
10279 (defun org-table-wrap-region (arg)
10280 "Wrap several fields in a column like a paragraph.
10281 This is useful if you'd like to spread the contents of a field over several
10282 lines, in order to keep the table compact.
10283
10284 If there is an active region, and both point and mark are in the same column,
10285 the text in the column is wrapped to minimum width for the given number of
10286 lines. Generally, this makes the table more compact. A prefix ARG may be
10287 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
10288 formats the selected text to two lines. If the region was longer than two
10289 lines, the remaining lines remain empty. A negative prefix argument reduces
10290 the current number of lines by that amount. The wrapped text is pasted back
10291 into the table. If you formatted it to more lines than it was before, fields
10292 further down in the table get overwritten - so you might need to make space in
10293 the table first.
10294
10295 If there is no region, the current field is split at the cursor position and
10296 the text fragment to the right of the cursor is prepended to the field one
10297 line down.
10298
10299 If there is no region, but you specify a prefix ARG, the current field gets
10300 blank, and the content is appended to the field above."
10301 (interactive "P")
10302 (org-table-check-inside-data-field)
10303 (if (org-region-active-p)
10304 ;; There is a region: fill as a paragraph
10305 (let ((beg (region-beginning))
10306 nlines)
10307 (org-table-cut-region (region-beginning) (region-end))
10308 (if (> (length (car org-table-clip)) 1)
10309 (error "Region must be limited to single column"))
10310 (setq nlines (if arg
10311 (if (< arg 1)
10312 (+ (length org-table-clip) arg)
10313 arg)
10314 (length org-table-clip)))
10315 (setq org-table-clip
10316 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
10317 nil nlines)))
10318 (goto-char beg)
10319 (org-table-paste-rectangle))
10320 ;; No region, split the current field at point
10321 (if arg
10322 ;; combine with field above
10323 (let ((s (org-table-blank-field))
10324 (col (org-table-current-column)))
10325 (beginning-of-line 0)
10326 (while (org-at-table-hline-p) (beginning-of-line 0))
10327 (org-table-goto-column col)
10328 (skip-chars-forward "^|")
10329 (skip-chars-backward " ")
10330 (insert " " (org-trim s))
10331 (org-table-align))
10332 ;; split field
10333 (when (looking-at "\\([^|]+\\)+|")
10334 (let ((s (match-string 1)))
10335 (replace-match " |")
10336 (goto-char (match-beginning 0))
10337 (org-table-next-row)
10338 (insert (org-trim s) " ")
10339 (org-table-align))))))
10340
10341 (defvar org-field-marker nil)
10342
10343 (defun org-table-edit-field (arg)
10344 "Edit table field in a different window.
10345 This is mainly useful for fields that contain hidden parts.
10346 When called with a \\[universal-argument] prefix, just make the full field visible so that
10347 it can be edited in place."
10348 (interactive "P")
10349 (if arg
10350 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
10351 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
10352 (remove-text-properties b e '(org-cwidth t invisible t
10353 display t intangible t))
10354 (if (and (boundp 'font-lock-mode) font-lock-mode)
10355 (font-lock-fontify-block)))
10356 (let ((pos (move-marker (make-marker) (point)))
10357 (field (org-table-get-field))
10358 (cw (current-window-configuration))
10359 p)
10360 (switch-to-buffer-other-window "*Org tmp*")
10361 (erase-buffer)
10362 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
10363 (org-mode)
10364 (goto-char (setq p (point-max)))
10365 (insert (org-trim field))
10366 (remove-text-properties p (point-max)
10367 '(invisible t org-cwidth t display t
10368 intangible t))
10369 (goto-char p)
10370 (set (make-local-variable 'org-finish-function)
10371 'org-table-finish-edit-field)
10372 (set (make-local-variable 'org-window-configuration) cw)
10373 (set (make-local-variable 'org-field-marker) pos)
10374 (message "Edit and finish with C-c C-c"))))
10375
10376 (defun org-table-finish-edit-field ()
10377 "Finish editing a table data field.
10378 Remove all newline characters, insert the result into the table, realign
10379 the table and kill the editing buffer."
10380 (let ((pos org-field-marker)
10381 (cw org-window-configuration)
10382 (cb (current-buffer))
10383 text)
10384 (goto-char (point-min))
10385 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
10386 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
10387 (replace-match " "))
10388 (setq text (org-trim (buffer-string)))
10389 (set-window-configuration cw)
10390 (kill-buffer cb)
10391 (select-window (get-buffer-window (marker-buffer pos)))
10392 (goto-char pos)
10393 (move-marker pos nil)
10394 (org-table-check-inside-data-field)
10395 (org-table-get-field nil text)
10396 (org-table-align)
10397 (message "New field value inserted")))
10398
10399 (defun org-trim (s)
10400 "Remove whitespace at beginning and end of string."
10401 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
10402 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
10403 s)
10404
10405 (defun org-wrap (string &optional width lines)
10406 "Wrap string to either a number of lines, or a width in characters.
10407 If WIDTH is non-nil, the string is wrapped to that width, however many lines
10408 that costs. If there is a word longer than WIDTH, the text is actually
10409 wrapped to the length of that word.
10410 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
10411 many lines, whatever width that takes.
10412 The return value is a list of lines, without newlines at the end."
10413 (let* ((words (org-split-string string "[ \t\n]+"))
10414 (maxword (apply 'max (mapcar 'org-string-width words)))
10415 w ll)
10416 (cond (width
10417 (org-do-wrap words (max maxword width)))
10418 (lines
10419 (setq w maxword)
10420 (setq ll (org-do-wrap words maxword))
10421 (if (<= (length ll) lines)
10422 ll
10423 (setq ll words)
10424 (while (> (length ll) lines)
10425 (setq w (1+ w))
10426 (setq ll (org-do-wrap words w)))
10427 ll))
10428 (t (error "Cannot wrap this")))))
10429
10430
10431 (defun org-do-wrap (words width)
10432 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
10433 (let (lines line)
10434 (while words
10435 (setq line (pop words))
10436 (while (and words (< (+ (length line) (length (car words))) width))
10437 (setq line (concat line " " (pop words))))
10438 (setq lines (push line lines)))
10439 (nreverse lines)))
10440
10441 (defun org-split-string (string &optional separators)
10442 "Splits STRING into substrings at SEPARATORS.
10443 No empty strings are returned if there are matches at the beginning
10444 and end of string."
10445 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
10446 (start 0)
10447 notfirst
10448 (list nil))
10449 (while (and (string-match rexp string
10450 (if (and notfirst
10451 (= start (match-beginning 0))
10452 (< start (length string)))
10453 (1+ start) start))
10454 (< (match-beginning 0) (length string)))
10455 (setq notfirst t)
10456 (or (eq (match-beginning 0) 0)
10457 (and (eq (match-beginning 0) (match-end 0))
10458 (eq (match-beginning 0) start))
10459 (setq list
10460 (cons (substring string start (match-beginning 0))
10461 list)))
10462 (setq start (match-end 0)))
10463 (or (eq start (length string))
10464 (setq list
10465 (cons (substring string start)
10466 list)))
10467 (nreverse list)))
10468
10469 (defun org-table-map-tables (function)
10470 "Apply FUNCTION to the start of all tables in the buffer."
10471 (save-excursion
10472 (save-restriction
10473 (widen)
10474 (goto-char (point-min))
10475 (while (re-search-forward org-table-any-line-regexp nil t)
10476 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
10477 (beginning-of-line 1)
10478 (if (looking-at org-table-line-regexp)
10479 (save-excursion (funcall function)))
10480 (re-search-forward org-table-any-border-regexp nil 1))))
10481 (message "Mapping tables: done"))
10482
10483 (defun org-table-sum (&optional beg end nlast)
10484 "Sum numbers in region of current table column.
10485 The result will be displayed in the echo area, and will be available
10486 as kill to be inserted with \\[yank].
10487
10488 If there is an active region, it is interpreted as a rectangle and all
10489 numbers in that rectangle will be summed. If there is no active
10490 region and point is located in a table column, sum all numbers in that
10491 column.
10492
10493 If at least one number looks like a time HH:MM or HH:MM:SS, all other
10494 numbers are assumed to be times as well (in decimal hours) and the
10495 numbers are added as such.
10496
10497 If NLAST is a number, only the NLAST fields will actually be summed."
10498 (interactive)
10499 (save-excursion
10500 (let (col (timecnt 0) diff h m s org-table-clip)
10501 (cond
10502 ((and beg end)) ; beg and end given explicitly
10503 ((org-region-active-p)
10504 (setq beg (region-beginning) end (region-end)))
10505 (t
10506 (setq col (org-table-current-column))
10507 (goto-char (org-table-begin))
10508 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
10509 (error "No table data"))
10510 (org-table-goto-column col)
10511 ;not needed? (skip-chars-backward "^|")
10512 (setq beg (point))
10513 (goto-char (org-table-end))
10514 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
10515 (error "No table data"))
10516 (org-table-goto-column col)
10517 ;not needed? (skip-chars-forward "^|")
10518 (setq end (point))))
10519 (let* ((items (apply 'append (org-table-copy-region beg end)))
10520 (items1 (cond ((not nlast) items)
10521 ((>= nlast (length items)) items)
10522 (t (setq items (reverse items))
10523 (setcdr (nthcdr (1- nlast) items) nil)
10524 (nreverse items))))
10525 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
10526 items1)))
10527 (res (apply '+ numbers))
10528 (sres (if (= timecnt 0)
10529 (format "%g" res)
10530 (setq diff (* 3600 res)
10531 h (floor (/ diff 3600)) diff (mod diff 3600)
10532 m (floor (/ diff 60)) diff (mod diff 60)
10533 s diff)
10534 (format "%d:%02d:%02d" h m s))))
10535 (kill-new sres)
10536 (if (interactive-p)
10537 (message "%s"
10538 (substitute-command-keys
10539 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
10540 (length numbers) sres))))
10541 sres))))
10542
10543 (defun org-table-get-number-for-summing (s)
10544 (let (n)
10545 (if (string-match "^ *|? *" s)
10546 (setq s (replace-match "" nil nil s)))
10547 (if (string-match " *|? *$" s)
10548 (setq s (replace-match "" nil nil s)))
10549 (setq n (string-to-number s))
10550 (cond
10551 ((and (string-match "0" s)
10552 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
10553 ((string-match "\\`[ \t]+\\'" s) nil)
10554 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
10555 (let ((h (string-to-number (or (match-string 1 s) "0")))
10556 (m (string-to-number (or (match-string 2 s) "0")))
10557 (s (string-to-number (or (match-string 4 s) "0"))))
10558 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
10559 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
10560 ((equal n 0) nil)
10561 (t n))))
10562
10563 (defun org-table-get-vertical-vector (desc &optional tbeg col)
10564 "Get a calc vector from a column, accorting to descriptor DESC.
10565 Optional arguments TBEG and COL can give the beginning of the table and
10566 the current column, to avoid unnecessary parsing."
10567 (save-excursion
10568 (or tbeg (setq tbeg (org-table-begin)))
10569 (or col (setq col (org-table-current-column)))
10570 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
10571 (cond
10572 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
10573 (setq n1 (- (match-end 1) (match-beginning 1)))
10574 (if (match-beginning 3)
10575 (setq n2 (- (match-end 2) (match-beginning 3))))
10576 (setq n (if n2 (max n1 n2) n1))
10577 (setq n1 (if n2 (min n1 n2)))
10578 (setq nn n)
10579 (while (and (> nn 0)
10580 (re-search-backward org-table-hline-regexp tbeg t))
10581 (push (org-current-line) hline-list)
10582 (setq nn (1- nn)))
10583 (setq hline-list (nreverse hline-list))
10584 (goto-line (nth (1- n) hline-list))
10585 (when (re-search-forward org-table-dataline-regexp)
10586 (org-table-goto-column col)
10587 (setq beg (point)))
10588 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
10589 (when (re-search-backward org-table-dataline-regexp)
10590 (org-table-goto-column col)
10591 (setq end (point)))
10592 (setq l (apply 'append (org-table-copy-region beg end)))
10593 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
10594 (if (equal x "") "0" x))
10595 l ",") "]"))
10596 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
10597 (setq n1 (string-to-number (match-string 1 desc))
10598 n2 (string-to-number (match-string 2 desc)))
10599 (beginning-of-line 1)
10600 (save-excursion
10601 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
10602 (org-table-goto-column col)
10603 (setq beg (point))))
10604 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
10605 (org-table-goto-column col)
10606 (setq end (point)))
10607 (setq l (apply 'append (org-table-copy-region beg end)))
10608 (concat "[" (mapconcat
10609 (lambda (x) (setq x (org-trim x))
10610 (if (equal x "") "0" x))
10611 l ",") "]"))
10612 ((string-match "\\([0-9]+\\)" desc)
10613 (beginning-of-line 1)
10614 (when (re-search-backward org-table-dataline-regexp tbeg t
10615 (string-to-number (match-string 0 desc)))
10616 (org-table-goto-column col)
10617 (org-trim (org-table-get-field))))))))
10618
10619 (defvar org-table-formula-history nil)
10620
10621 (defvar org-table-column-names nil
10622 "Alist with column names, derived from the `!' line.")
10623 (defvar org-table-column-name-regexp nil
10624 "Regular expression matching the current column names.")
10625 (defvar org-table-local-parameters nil
10626 "Alist with parameter names, derived from the `$' line.")
10627 (defvar org-table-named-field-locations nil
10628 "Alist with locations of named fields.")
10629
10630 (defun org-table-get-formula (&optional equation named)
10631 "Read a formula from the minibuffer, offer stored formula as default."
10632 (let* ((name (car (rassoc (list (org-current-line)
10633 (org-table-current-column))
10634 org-table-named-field-locations)))
10635 (scol (if named
10636 (if name name
10637 (error "Not in a named field"))
10638 (int-to-string (org-table-current-column))))
10639 (dummy (and name (not named)
10640 (not (y-or-n-p "Replace named-field formula with column equation? " ))
10641 (error "Abort")))
10642 (org-table-may-need-update nil)
10643 (stored-list (org-table-get-stored-formulas))
10644 (stored (cdr (assoc scol stored-list)))
10645 (eq (cond
10646 ((and stored equation (string-match "^ *=? *$" equation))
10647 stored)
10648 ((stringp equation)
10649 equation)
10650 (t (read-string
10651 (format "%s formula $%s=" (if named "Field" "Column") scol)
10652 (or stored "") 'org-table-formula-history
10653 ;stored
10654 ))))
10655 mustsave)
10656 (when (not (string-match "\\S-" eq))
10657 ;; remove formula
10658 (setq stored-list (delq (assoc scol stored-list) stored-list))
10659 (org-table-store-formulas stored-list)
10660 (error "Formula removed"))
10661 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
10662 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
10663 (if (and name (not named))
10664 ;; We set the column equation, delete the named one.
10665 (setq stored-list (delq (assoc name stored-list) stored-list)
10666 mustsave t))
10667 (if stored
10668 (setcdr (assoc scol stored-list) eq)
10669 (setq stored-list (cons (cons scol eq) stored-list)))
10670 (if (or mustsave (not (equal stored eq)))
10671 (org-table-store-formulas stored-list))
10672 eq))
10673
10674 (defun org-table-store-formulas (alist)
10675 "Store the list of formulas below the current table."
10676 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
10677 (save-excursion
10678 (goto-char (org-table-end))
10679 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
10680 (delete-region (point) (match-end 0)))
10681 (insert "#+TBLFM: "
10682 (mapconcat (lambda (x)
10683 (concat "$" (car x) "=" (cdr x)))
10684 alist "::")
10685 "\n")))
10686
10687 (defun org-table-get-stored-formulas ()
10688 "Return an alist with the stored formulas directly after current table."
10689 (interactive)
10690 (let (scol eq eq-alist strings string seen)
10691 (save-excursion
10692 (goto-char (org-table-end))
10693 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
10694 (setq strings (org-split-string (match-string 2) " *:: *"))
10695 (while (setq string (pop strings))
10696 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
10697 (setq scol (match-string 1 string)
10698 eq (match-string 2 string)
10699 eq-alist (cons (cons scol eq) eq-alist))
10700 (if (member scol seen)
10701 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
10702 (push scol seen))))))
10703 (nreverse eq-alist)))
10704
10705 (defun org-table-modify-formulas (action &rest columns)
10706 "Modify the formulas stored below the current table.
10707 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
10708 expected, for the other actions only a single column number is needed."
10709 (let ((list (org-table-get-stored-formulas))
10710 (nmax (length (org-split-string
10711 (buffer-substring (point-at-bol) (point-at-eol))
10712 "|")))
10713 col col1 col2 scol si sc1 sc2)
10714 (cond
10715 ((null list)) ; No action needed if there are no stored formulas
10716 ((eq action 'remove)
10717 (setq col (car columns)
10718 scol (int-to-string col))
10719 (org-table-replace-in-formulas list scol "INVALID")
10720 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
10721 (loop for i from (1+ col) upto nmax by 1 do
10722 (setq si (int-to-string i))
10723 (org-table-replace-in-formulas list si (int-to-string (1- i)))
10724 (if (assoc si list) (setcar (assoc si list)
10725 (int-to-string (1- i))))))
10726 ((eq action 'insert)
10727 (setq col (car columns))
10728 (loop for i from nmax downto col by 1 do
10729 (setq si (int-to-string i))
10730 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
10731 (if (assoc si list) (setcar (assoc si list)
10732 (int-to-string (1+ i))))))
10733 ((eq action 'swap)
10734 (setq col1 (car columns) col2 (nth 1 columns)
10735 sc1 (int-to-string col1) sc2 (int-to-string col2))
10736 ;; Hopefully, ZqZtZ will never be a name in a table
10737 (org-table-replace-in-formulas list sc1 "ZqZtZ")
10738 (org-table-replace-in-formulas list sc2 sc1)
10739 (org-table-replace-in-formulas list "ZqZtZ" sc2)
10740 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
10741 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
10742 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
10743 (t (error "Invalid action in `org-table-modify-formulas'")))
10744 (if list (org-table-store-formulas list))))
10745
10746 (defun org-table-replace-in-formulas (list s1 s2)
10747 (let (elt re s)
10748 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
10749 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
10750 re (concat (regexp-quote s1) "\\>"))
10751 (while (setq elt (pop list))
10752 (setq s (cdr elt))
10753 (while (string-match re s)
10754 (setq s (replace-match s2 t t s)))
10755 (setcdr elt s))))
10756
10757 (defun org-table-get-specials ()
10758 "Get the column names and local parameters for this table."
10759 (save-excursion
10760 (let ((beg (org-table-begin)) (end (org-table-end))
10761 names name fields fields1 field cnt c v line col)
10762 (setq org-table-column-names nil
10763 org-table-local-parameters nil
10764 org-table-named-field-locations nil)
10765 (goto-char beg)
10766 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10767 (setq names (org-split-string (match-string 1) " *| *")
10768 cnt 1)
10769 (while (setq name (pop names))
10770 (setq cnt (1+ cnt))
10771 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10772 (push (cons name (int-to-string cnt)) org-table-column-names))))
10773 (setq org-table-column-names (nreverse org-table-column-names))
10774 (setq org-table-column-name-regexp
10775 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10776 (goto-char beg)
10777 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10778 (setq fields (org-split-string (match-string 1) " *| *"))
10779 (while (setq field (pop fields))
10780 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10781 (push (cons (match-string 1 field) (match-string 2 field))
10782 org-table-local-parameters))))
10783 (goto-char beg)
10784 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10785 (setq c (match-string 1)
10786 fields (org-split-string (match-string 2) " *| *"))
10787 (save-excursion
10788 (beginning-of-line (if (equal c "_") 2 0))
10789 (setq line (org-current-line) col 1)
10790 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10791 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10792 (while (and fields1 (setq field (pop fields)))
10793 (setq v (pop fields1) col (1+ col))
10794 (when (and (stringp field) (stringp v)
10795 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10796 (push (cons field v) org-table-local-parameters)
10797 (push (list field line col) org-table-named-field-locations)))))))
10798
10799 (defun org-this-word ()
10800 ;; Get the current word
10801 (save-excursion
10802 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
10803 (end (progn (skip-chars-forward "^ \t\n") (point))))
10804 (buffer-substring-no-properties beg end))))
10805
10806 (defun org-table-maybe-eval-formula ()
10807 "Check if the current field starts with \"=\" or \":=\".
10808 If yes, store the formula and apply it."
10809 ;; We already know we are in a table. Get field will only return a formula
10810 ;; when appropriate. It might return a separator line, but no problem.
10811 (when org-table-formula-evaluate-inline
10812 (let* ((field (org-trim (or (org-table-get-field) "")))
10813 named eq)
10814 (when (string-match "^:?=\\(.*\\)" field)
10815 (setq named (equal (string-to-char field) ?:)
10816 eq (match-string 1 field))
10817 (if (fboundp 'calc-eval)
10818 (org-table-eval-formula (if named '(4) nil) eq))))))
10819
10820 (defvar org-recalc-commands nil
10821 "List of commands triggering the recalculation of a line.
10822 Will be filled automatically during use.")
10823
10824 (defvar org-recalc-marks
10825 '((" " . "Unmarked: no special line, no automatic recalculation")
10826 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10827 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10828 ("!" . "Column name definition line. Reference in formula as $name.")
10829 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10830 ("_" . "Names for values in row below this one.")
10831 ("^" . "Names for values in row above this one.")))
10832
10833 (defun org-table-rotate-recalc-marks (&optional newchar)
10834 "Rotate the recalculation mark in the first column.
10835 If in any row, the first field is not consistent with a mark,
10836 insert a new column for the markers.
10837 When there is an active region, change all the lines in the region,
10838 after prompting for the marking character.
10839 After each change, a message will be displayed indicating the meaning
10840 of the new mark."
10841 (interactive)
10842 (unless (org-at-table-p) (error "Not at a table"))
10843 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10844 (beg (org-table-begin))
10845 (end (org-table-end))
10846 (l (org-current-line))
10847 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10848 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10849 (have-col
10850 (save-excursion
10851 (goto-char beg)
10852 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10853 (col (org-table-current-column))
10854 (forcenew (car (assoc newchar org-recalc-marks)))
10855 epos new)
10856 (when l1
10857 (message "Change region to what mark? Type # * ! $ or SPC: ")
10858 (setq newchar (char-to-string (read-char-exclusive))
10859 forcenew (car (assoc newchar org-recalc-marks))))
10860 (if (and newchar (not forcenew))
10861 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10862 newchar))
10863 (if l1 (goto-line l1))
10864 (save-excursion
10865 (beginning-of-line 1)
10866 (unless (looking-at org-table-dataline-regexp)
10867 (error "Not at a table data line")))
10868 (unless have-col
10869 (org-table-goto-column 1)
10870 (org-table-insert-column)
10871 (org-table-goto-column (1+ col)))
10872 (setq epos (point-at-eol))
10873 (save-excursion
10874 (beginning-of-line 1)
10875 (org-table-get-field
10876 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10877 (concat " "
10878 (setq new (or forcenew
10879 (cadr (member (match-string 1) marks))))
10880 " ")
10881 " # ")))
10882 (if (and l1 l2)
10883 (progn
10884 (goto-line l1)
10885 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10886 (and (looking-at org-table-dataline-regexp)
10887 (org-table-get-field 1 (concat " " new " "))))
10888 (goto-line l1)))
10889 (if (not (= epos (point-at-eol))) (org-table-align))
10890 (goto-line l)
10891 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
10892
10893 (defun org-table-maybe-recalculate-line ()
10894 "Recompute the current line if marked for it, and if we haven't just done it."
10895 (interactive)
10896 (and org-table-allow-automatic-line-recalculation
10897 (not (and (memq last-command org-recalc-commands)
10898 (equal org-last-recalc-line (org-current-line))))
10899 (save-excursion (beginning-of-line 1)
10900 (looking-at org-table-auto-recalculate-regexp))
10901 (fboundp 'calc-eval)
10902 (org-table-recalculate) t))
10903
10904 (defvar org-table-formula-debug nil
10905 "Non-nil means, debug table formulas.
10906 When nil, simply write \"#ERROR\" in corrupted fields.")
10907
10908 (defvar modes)
10909 (defsubst org-set-calc-mode (var &optional value)
10910 (if (stringp var)
10911 (setq var (assoc var '(("D" calc-angle-mode deg)
10912 ("R" calc-angle-mode rad)
10913 ("F" calc-prefer-frac t)
10914 ("S" calc-symbolic-mode t)))
10915 value (nth 2 var) var (nth 1 var)))
10916 (if (memq var modes)
10917 (setcar (cdr (memq var modes)) value)
10918 (cons var (cons value modes)))
10919 modes)
10920
10921 (defun org-table-eval-formula (&optional arg equation
10922 suppress-align suppress-const
10923 suppress-store)
10924 "Replace the table field value at the cursor by the result of a calculation.
10925
10926 This function makes use of Dave Gillespie's Calc package, in my view the
10927 most exciting program ever written for GNU Emacs. So you need to have Calc
10928 installed in order to use this function.
10929
10930 In a table, this command replaces the value in the current field with the
10931 result of a formula. It also installs the formula as the \"current\" column
10932 formula, by storing it in a special line below the table. When called
10933 with a `C-u' prefix, the current field must ba a named field, and the
10934 formula is installed as valid in only this specific field.
10935
10936 When called, the command first prompts for a formula, which is read in
10937 the minibuffer. Previously entered formulas are available through the
10938 history list, and the last used formula is offered as a default.
10939 These stored formulas are adapted correctly when moving, inserting, or
10940 deleting columns with the corresponding commands.
10941
10942 The formula can be any algebraic expression understood by the Calc package.
10943 For details, see the Org-mode manual.
10944
10945 This function can also be called from Lisp programs and offers
10946 additional arguments: EQUATION can be the formula to apply. If this
10947 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10948 used to speed-up recursive calls by by-passing unnecessary aligns.
10949 SUPPRESS-CONST suppresses the interpretation of constants in the
10950 formula, assuming that this has been done already outside the function.
10951 SUPPRESS-STORE means the formula should not be stored, either because
10952 it is already stored, or because it is a modified equation that should
10953 not overwrite the stored one."
10954 (interactive "P")
10955 (require 'calc)
10956 (org-table-check-inside-data-field)
10957 (org-table-get-specials)
10958 (let* (fields
10959 (ndown (if (integerp arg) arg 1))
10960 (org-table-automatic-realign nil)
10961 (case-fold-search nil)
10962 (down (> ndown 1))
10963 (formula (if (and equation suppress-store)
10964 equation
10965 (org-table-get-formula equation (equal arg '(4)))))
10966 (n0 (org-table-current-column))
10967 (modes (copy-sequence org-calc-default-modes))
10968 n form fmt x ev orig c lispp)
10969 ;; Parse the format string. Since we have a lot of modes, this is
10970 ;; a lot of work. However, I think calc still uses most of the time.
10971 (if (string-match ";" formula)
10972 (let ((tmp (org-split-string formula ";")))
10973 (setq formula (car tmp)
10974 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10975 (nth 1 tmp)))
10976 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
10977 (setq c (string-to-char (match-string 1 fmt))
10978 n (string-to-number (or (match-string 1 fmt) "")))
10979 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
10980 (setq modes (org-set-calc-mode
10981 'calc-float-format
10982 (list (cdr (assoc c '((?n . float) (?f . fix)
10983 (?s . sci) (?e . eng))))
10984 n))))
10985 (setq fmt (replace-match "" t t fmt)))
10986 (while (string-match "[DRFS]" fmt)
10987 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10988 (setq fmt (replace-match "" t t fmt)))
10989 (unless (string-match "\\S-" fmt)
10990 (setq fmt nil))))
10991 (if (and (not suppress-const) org-table-formula-use-constants)
10992 (setq formula (org-table-formula-substitute-names formula)))
10993 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10994 (while (> ndown 0)
10995 (setq fields (org-split-string
10996 (buffer-substring
10997 (point-at-bol) (point-at-eol)) " *| *"))
10998 (if org-table-formula-numbers-only
10999 (setq fields (mapcar
11000 (lambda (x) (number-to-string (string-to-number x)))
11001 fields)))
11002 (setq ndown (1- ndown))
11003 (setq form (copy-sequence formula)
11004 lispp (equal (substring form 0 2) "'("))
11005 ;; Insert the references to fields in same row
11006 (while (string-match "\\$\\([0-9]+\\)?" form)
11007 (setq n (if (match-beginning 1)
11008 (string-to-number (match-string 1 form))
11009 n0)
11010 x (nth (1- n) fields))
11011 (unless x (error "Invalid field specifier \"%s\""
11012 (match-string 0 form)))
11013 (if (equal x "") (setq x "0"))
11014 (setq form (replace-match
11015 (if lispp x (concat "(" x ")"))
11016 t t form)))
11017 ;; Insert ranges in current column
11018 (while (string-match "\\&[-I0-9]+" form)
11019 (setq form (replace-match
11020 (save-match-data
11021 (org-table-get-vertical-vector (match-string 0 form)
11022 nil n0))
11023 t t form)))
11024 ;; (setq ev (calc-eval (cons form modes)
11025 ;; FIXME (if org-table-formula-numbers-only 'num)))
11026
11027 (if lispp
11028 (setq ev (eval (eval (read form)))
11029 ev (if (numberp ev) (number-to-string ev) ev))
11030 (setq ev (calc-eval (cons form modes)
11031 (if org-table-formula-numbers-only 'num))))
11032
11033 (when org-table-formula-debug
11034 (with-output-to-temp-buffer "*Help*"
11035 (princ (format "Substitution history of formula
11036 Orig: %s
11037 $xyz-> %s
11038 $1-> %s\n" orig formula form))
11039 (if (listp ev)
11040 (princ (format " %s^\nError: %s"
11041 (make-string (car ev) ?\-) (nth 1 ev)))
11042 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
11043 ev (or fmt "NONE")
11044 (if fmt (format fmt (string-to-number ev)) ev)))))
11045 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
11046 (unless (and (interactive-p) (not ndown))
11047 (unless (let (inhibit-redisplay)
11048 (y-or-n-p "Debugging Formula. Continue to next? "))
11049 (org-table-align)
11050 (error "Abort"))
11051 (delete-window (get-buffer-window "*Help*"))
11052 (message "")))
11053 (if (listp ev) (setq fmt nil ev "#ERROR"))
11054 (org-table-justify-field-maybe
11055 (if fmt (format fmt (string-to-number ev)) ev))
11056 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
11057 (call-interactively 'org-return)
11058 (setq ndown 0)))
11059 (and down (org-table-maybe-recalculate-line))
11060 (or suppress-align (and org-table-may-need-update
11061 (org-table-align)))))
11062
11063 (defun org-table-recalculate (&optional all noalign)
11064 "Recalculate the current table line by applying all stored formulas.
11065 With prefix arg ALL, do this for all lines in the table."
11066 (interactive "P")
11067 (or (memq this-command org-recalc-commands)
11068 (setq org-recalc-commands (cons this-command org-recalc-commands)))
11069 (unless (org-at-table-p) (error "Not at a table"))
11070 (org-table-get-specials)
11071 (let* ((eqlist (sort (org-table-get-stored-formulas)
11072 (lambda (a b) (string< (car a) (car b)))))
11073 (inhibit-redisplay t)
11074 (line-re org-table-dataline-regexp)
11075 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11076 (thiscol (org-table-current-column))
11077 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
11078 ;; Insert constants in all formulas
11079 (setq eqlist
11080 (mapcar (lambda (x)
11081 (setcdr x (org-table-formula-substitute-names (cdr x)))
11082 x)
11083 eqlist))
11084 ;; Split the equation list
11085 (while (setq eq (pop eqlist))
11086 (if (<= (string-to-char (car eq)) ?9)
11087 (push eq eqlnum)
11088 (push eq eqlname)))
11089 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
11090 (if all
11091 (progn
11092 (setq end (move-marker (make-marker) (1+ (org-table-end))))
11093 (goto-char (setq beg (org-table-begin)))
11094 (if (re-search-forward org-table-calculate-mark-regexp end t)
11095 ;; This is a table with marked lines, only compute selected lines
11096 (setq line-re org-table-recalculate-regexp)
11097 ;; Move forward to the first non-header line
11098 (if (and (re-search-forward org-table-dataline-regexp end t)
11099 (re-search-forward org-table-hline-regexp end t)
11100 (re-search-forward org-table-dataline-regexp end t))
11101 (setq beg (match-beginning 0))
11102 nil))) ;; just leave beg where it is
11103 (setq beg (point-at-bol)
11104 end (move-marker (make-marker) (1+ (point-at-eol)))))
11105 (goto-char beg)
11106 (and all (message "Re-applying formulas to full table..."))
11107 (while (re-search-forward line-re end t)
11108 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
11109 ;; Unprotected line, recalculate
11110 (and all (message "Re-applying formulas to full table...(line %d)"
11111 (setq cnt (1+ cnt))))
11112 (setq org-last-recalc-line (org-current-line))
11113 (setq eql eqlnum)
11114 (while (setq entry (pop eql))
11115 (goto-line org-last-recalc-line)
11116 (org-table-goto-column (string-to-number (car entry)) nil 'force)
11117 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
11118 (goto-line thisline)
11119 (org-table-goto-column thiscol)
11120 (or noalign (and org-table-may-need-update (org-table-align))
11121 (and all (message "Re-applying formulas to %d lines...done" cnt)))
11122 ;; Now do the names fields
11123 (while (setq eq (pop eqlname))
11124 (setq name (car eq)
11125 a (assoc name org-table-named-field-locations))
11126 (when a
11127 (message "Re-applying formula to named field: %s" name)
11128 (goto-line (nth 1 a))
11129 (org-table-goto-column (nth 2 a))
11130 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
11131 ;; back to initial position
11132 (goto-line thisline)
11133 (org-table-goto-column thiscol)
11134 (or noalign (and org-table-may-need-update (org-table-align))
11135 (and all (message "Re-applying formulas...done")))))
11136
11137 (defun org-table-formula-substitute-names (f)
11138 "Replace $const with values in string F."
11139 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
11140 ;; First, check for column names
11141 (while (setq start (string-match org-table-column-name-regexp f start))
11142 (setq start (1+ start))
11143 (setq a (assoc (match-string 1 f) org-table-column-names))
11144 (setq f (replace-match (concat "$" (cdr a)) t t f)))
11145 ;; Expand ranges to vectors
11146 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
11147 (setq n1 (string-to-number (match-string 1 f))
11148 n2 (string-to-number (match-string 2 f))
11149 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
11150 s (concat "[($" (number-to-string (1- nn1)) ")"))
11151 (loop for i from nn1 upto nn2 do
11152 (setq s (concat s ",($" (int-to-string i) ")")))
11153 (setq s (concat s "]"))
11154 (if (< n2 n1) (setq s (concat "rev(" s ")")))
11155 (setq f (replace-match s t t f)))
11156 ;; Parameters and constants
11157 (setq start 0)
11158 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
11159 (setq start (1+ start))
11160 (if (setq a (save-match-data
11161 (org-table-get-constant (match-string 1 f))))
11162 (setq f (replace-match (concat "(" a ")") t t f))))
11163 (if org-table-formula-debug
11164 (put-text-property 0 (length f) :orig-formula f1 f))
11165 f))
11166
11167 (defun org-table-get-constant (const)
11168 "Find the value for a parameter or constant in a formula.
11169 Parameters get priority."
11170 (or (cdr (assoc const org-table-local-parameters))
11171 (cdr (assoc const org-table-formula-constants))
11172 (and (fboundp 'constants-get) (constants-get const))
11173 "#UNDEFINED_NAME"))
11174
11175 (defvar org-edit-formulas-map (make-sparse-keymap))
11176 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
11177 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
11178 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
11179
11180 (defvar org-pos)
11181
11182 (defun org-table-edit-formulas ()
11183 "Edit the formulas of the current table in a separate buffer."
11184 (interactive)
11185 (unless (org-at-table-p)
11186 (error "Not at a table"))
11187 (org-table-get-specials)
11188 (let ((eql (org-table-get-stored-formulas))
11189 (pos (move-marker (make-marker) (point)))
11190 (wc (current-window-configuration))
11191 entry loc s)
11192 (switch-to-buffer-other-window "*Edit Formulas*")
11193 (erase-buffer)
11194 (fundamental-mode)
11195 (set (make-local-variable 'org-pos) pos)
11196 (set (make-local-variable 'org-window-configuration) wc)
11197 (use-local-map org-edit-formulas-map)
11198 (setq s "# Edit formulas and finish with `C-c C-c'.
11199 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
11200 # Use `C-c ?' to get information about $name at point.
11201 # To cancel editing, press `C-c C-q'.\n")
11202 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
11203 (insert s)
11204 (while (setq entry (pop eql))
11205 (when (setq loc (assoc (car entry) org-table-named-field-locations))
11206 (setq s (format "# Named formula, referring to column %d in line %d\n"
11207 (nth 2 loc) (nth 1 loc)))
11208 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
11209 (insert s))
11210 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
11211 (remove-text-properties 0 (length s) '(face nil) s)
11212 (insert s))
11213 (goto-char (point-min))
11214 (message "Edit formulas and finish with `C-c C-c'.")))
11215
11216 (defun org-show-variable ()
11217 "Show the location/value of the $ expression at point."
11218 (interactive)
11219 (let (var (pos org-pos) (win (selected-window)) e)
11220 (save-excursion
11221 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
11222 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
11223 (setq var (match-string 1))
11224 (error "No variable at point")))
11225 (cond
11226 ((setq e (assoc var org-table-named-field-locations))
11227 (switch-to-buffer-other-window (marker-buffer pos))
11228 (goto-line (nth 1 e))
11229 (org-table-goto-column (nth 2 e))
11230 (select-window win)
11231 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
11232 ((setq e (assoc var org-table-column-names))
11233 (switch-to-buffer-other-window (marker-buffer pos))
11234 (goto-char pos)
11235 (goto-char (org-table-begin))
11236 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
11237 (org-table-end) t)
11238 (progn
11239 (goto-char (match-beginning 1))
11240 (message "Named column (column %s)" (cdr e)))
11241 (error "Column name not found"))
11242 (select-window win))
11243 ((string-match "^[0-9]$" var)
11244 ;; column number
11245 (switch-to-buffer-other-window (marker-buffer pos))
11246 (goto-char pos)
11247 (goto-char (org-table-begin))
11248 (recenter 1)
11249 (if (re-search-forward org-table-dataline-regexp
11250 (org-table-end) t)
11251 (progn
11252 (goto-char (match-beginning 0))
11253 (org-table-goto-column (string-to-number var))
11254 (message "Column %s" var))
11255 (error "Column name not found"))
11256 (select-window win))
11257 ((setq e (assoc var org-table-local-parameters))
11258 (switch-to-buffer-other-window (marker-buffer pos))
11259 (goto-char pos)
11260 (goto-char (org-table-begin))
11261 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
11262 (progn
11263 (goto-char (match-beginning 1))
11264 (message "Local parameter."))
11265 (error "Parameter not found"))
11266 (select-window win))
11267 (t
11268 (cond
11269 ((setq e (assoc var org-table-formula-constants))
11270 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
11271 ((setq e (and (fboundp 'constants-get) (constants-get var)))
11272 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
11273 (t (error "Undefined name $%s" var)))))))
11274
11275 (defun org-finish-edit-formulas (&optional arg)
11276 "Parse the buffer for formula definitions and install them.
11277 With prefix ARG, apply the new formulas to the table."
11278 (interactive "P")
11279 (let ((pos org-pos) eql)
11280 (goto-char (point-min))
11281 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
11282 (push (cons (match-string 1) (match-string 2)) eql))
11283 (set-window-configuration org-window-configuration)
11284 (select-window (get-buffer-window (marker-buffer pos)))
11285 (goto-char pos)
11286 (unless (org-at-table-p)
11287 (error "Lost table position - cannot install formulae"))
11288 (org-table-store-formulas eql)
11289 (move-marker pos nil)
11290 (kill-buffer "*Edit Formulas*")
11291 (if arg
11292 (org-table-recalculate 'all)
11293 (message "New formulas installed - press C-u C-c C-c to apply."))))
11294
11295 (defun org-abort-edit-formulas ()
11296 "Abort editing formulas, without installing the changes."
11297 (interactive)
11298 (let ((pos org-pos))
11299 (set-window-configuration org-window-configuration)
11300 (select-window (get-buffer-window (marker-buffer pos)))
11301 (goto-char pos)
11302 (message "Formula editing aborted without installing changes")))
11303
11304 ;;; The orgtbl minor mode
11305
11306 ;; Define a minor mode which can be used in other modes in order to
11307 ;; integrate the org-mode table editor.
11308
11309 ;; This is really a hack, because the org-mode table editor uses several
11310 ;; keys which normally belong to the major mode, for example the TAB and
11311 ;; RET keys. Here is how it works: The minor mode defines all the keys
11312 ;; necessary to operate the table editor, but wraps the commands into a
11313 ;; function which tests if the cursor is currently inside a table. If that
11314 ;; is the case, the table editor command is executed. However, when any of
11315 ;; those keys is used outside a table, the function uses `key-binding' to
11316 ;; look up if the key has an associated command in another currently active
11317 ;; keymap (minor modes, major mode, global), and executes that command.
11318 ;; There might be problems if any of the keys used by the table editor is
11319 ;; otherwise used as a prefix key.
11320
11321 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
11322 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
11323 ;; addresses this by checking explicitly for both bindings.
11324
11325 ;; The optimized version (see variable `orgtbl-optimized') takes over
11326 ;; all keys which are bound to `self-insert-command' in the *global map*.
11327 ;; Some modes bind other commands to simple characters, for example
11328 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
11329 ;; active, this binding is ignored inside tables and replaced with a
11330 ;; modified self-insert.
11331
11332 (defvar orgtbl-mode nil
11333 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
11334 table editor in arbitrary modes.")
11335 (make-variable-buffer-local 'orgtbl-mode)
11336
11337 (defvar orgtbl-mode-map (make-keymap)
11338 "Keymap for `orgtbl-mode'.")
11339
11340 ;;;###autoload
11341 (defun turn-on-orgtbl ()
11342 "Unconditionally turn on `orgtbl-mode'."
11343 (orgtbl-mode 1))
11344
11345 ;;;###autoload
11346 (defun orgtbl-mode (&optional arg)
11347 "The `org-mode' table editor as a minor mode for use in other modes."
11348 (interactive)
11349 (if (eq major-mode 'org-mode)
11350 ;; Exit without error, in case some hook functions calls this
11351 ;; by accident in org-mode.
11352 (message "Orgtbl-mode is not useful in org-mode, command ignored")
11353 (setq orgtbl-mode
11354 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
11355 (if orgtbl-mode
11356 (progn
11357 (and (orgtbl-setup) (defun orgtbl-setup () nil))
11358 ;; Make sure we are first in minor-mode-map-alist
11359 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
11360 (and c (setq minor-mode-map-alist
11361 (cons c (delq c minor-mode-map-alist)))))
11362 (set (make-local-variable (quote org-table-may-need-update)) t)
11363 (org-add-hook 'before-change-functions 'org-before-change-function
11364 nil 'local)
11365 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
11366 auto-fill-inhibit-regexp)
11367 (set (make-local-variable 'auto-fill-inhibit-regexp)
11368 (if auto-fill-inhibit-regexp
11369 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
11370 "[ \t]*|"))
11371 (org-add-to-invisibility-spec '(org-cwidth))
11372 (easy-menu-add orgtbl-mode-menu)
11373 (run-hooks 'orgtbl-mode-hook))
11374 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
11375 (org-cleanup-narrow-column-properties)
11376 (org-remove-from-invisibility-spec '(org-cwidth))
11377 (remove-hook 'before-change-functions 'org-before-change-function t)
11378 (easy-menu-remove orgtbl-mode-menu)
11379 (force-mode-line-update 'all))))
11380
11381 (defun org-cleanup-narrow-column-properties ()
11382 "Remove all properties related to narrow-column invisibility."
11383 (let ((s 1))
11384 (while (setq s (text-property-any s (point-max)
11385 'display org-narrow-column-arrow))
11386 (remove-text-properties s (1+ s) '(display t)))
11387 (setq s 1)
11388 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
11389 (remove-text-properties s (1+ s) '(org-cwidth t)))
11390 (setq s 1)
11391 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
11392 (remove-text-properties s (1+ s) '(invisible t)))))
11393
11394 ;; Install it as a minor mode.
11395 (put 'orgtbl-mode :included t)
11396 (put 'orgtbl-mode :menu-tag "Org Table Mode")
11397 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
11398
11399 (defun orgtbl-make-binding (fun n &rest keys)
11400 "Create a function for binding in the table minor mode.
11401 FUN is the command to call inside a table. N is used to create a unique
11402 command name. KEYS are keys that should be checked in for a command
11403 to execute outside of tables."
11404 (eval
11405 (list 'defun
11406 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
11407 '(arg)
11408 (concat "In tables, run `" (symbol-name fun) "'.\n"
11409 "Outside of tables, run the binding of `"
11410 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
11411 "'.")
11412 '(interactive "p")
11413 (list 'if
11414 '(org-at-table-p)
11415 (list 'call-interactively (list 'quote fun))
11416 (list 'let '(orgtbl-mode)
11417 (list 'call-interactively
11418 (append '(or)
11419 (mapcar (lambda (k)
11420 (list 'key-binding k))
11421 keys)
11422 '('orgtbl-error))))))))
11423
11424 (defun orgtbl-error ()
11425 "Error when there is no default binding for a table key."
11426 (interactive)
11427 (error "This key is has no function outside tables"))
11428
11429 (defun orgtbl-setup ()
11430 "Setup orgtbl keymaps."
11431 (let ((nfunc 0)
11432 (bindings
11433 (list
11434 '([(meta shift left)] org-table-delete-column)
11435 '([(meta left)] org-table-move-column-left)
11436 '([(meta right)] org-table-move-column-right)
11437 '([(meta shift right)] org-table-insert-column)
11438 '([(meta shift up)] org-table-kill-row)
11439 '([(meta shift down)] org-table-insert-row)
11440 '([(meta up)] org-table-move-row-up)
11441 '([(meta down)] org-table-move-row-down)
11442 '("\C-c\C-w" org-table-cut-region)
11443 '("\C-c\M-w" org-table-copy-region)
11444 '("\C-c\C-y" org-table-paste-rectangle)
11445 '("\C-c-" org-table-insert-hline)
11446 ; '([(shift tab)] org-table-previous-field)
11447 '("\C-m" org-table-next-row)
11448 (list (org-key 'S-return) 'org-table-copy-down)
11449 '([(meta return)] org-table-wrap-region)
11450 '("\C-c\C-q" org-table-wrap-region)
11451 '("\C-c?" org-table-current-column)
11452 '("\C-c " org-table-blank-field)
11453 '("\C-c+" org-table-sum)
11454 '("\C-c=" org-table-eval-formula)
11455 '("\C-c'" org-table-edit-formulas)
11456 '("\C-c`" org-table-edit-field)
11457 '("\C-c*" org-table-recalculate)
11458 '("\C-c|" org-table-create-or-convert-from-region)
11459 '("\C-c^" org-table-sort-lines)
11460 '([(control ?#)] org-table-rotate-recalc-marks)))
11461 elt key fun cmd)
11462 (while (setq elt (pop bindings))
11463 (setq nfunc (1+ nfunc))
11464 (setq key (car elt)
11465 fun (nth 1 elt)
11466 cmd (orgtbl-make-binding fun nfunc key))
11467 (define-key orgtbl-mode-map key cmd))
11468 ;; Special treatment needed for TAB and RET
11469 (define-key orgtbl-mode-map [(return)]
11470 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
11471 (define-key orgtbl-mode-map "\C-m"
11472 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
11473 (define-key orgtbl-mode-map [(tab)]
11474 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
11475 (define-key orgtbl-mode-map "\C-i"
11476 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
11477 (define-key orgtbl-mode-map "\C-i"
11478 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
11479 (define-key orgtbl-mode-map "\C-c\C-c"
11480 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
11481 (when orgtbl-optimized
11482 ;; If the user wants maximum table support, we need to hijack
11483 ;; some standard editing functions
11484 (org-remap orgtbl-mode-map
11485 'self-insert-command 'orgtbl-self-insert-command
11486 'delete-char 'org-delete-char
11487 'delete-backward-char 'org-delete-backward-char)
11488 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
11489 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
11490 '("OrgTbl"
11491 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
11492 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
11493 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
11494 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
11495 "--"
11496 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
11497 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
11498 ["Copy Field from Above"
11499 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
11500 "--"
11501 ("Column"
11502 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
11503 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
11504 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
11505 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
11506 "--"
11507 ["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])
11508 ("Row"
11509 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
11510 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
11511 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
11512 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
11513 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
11514 "--"
11515 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
11516 ("Rectangle"
11517 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
11518 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
11519 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
11520 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
11521 "--"
11522 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
11523 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
11524 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
11525 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
11526 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
11527 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
11528 ["Sum Column/Rectangle" org-table-sum
11529 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
11530 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
11531 ["Debug Formulas"
11532 (setq org-table-formula-debug (not org-table-formula-debug))
11533 :style toggle :selected org-table-formula-debug]
11534 ))
11535 t)
11536
11537 (defun orgtbl-tab (arg)
11538 "Justification and field motion for `orgtbl-mode'."
11539 (interactive "P")
11540 (if arg (org-table-edit-field t)
11541 (org-table-justify-field-maybe)
11542 (org-table-next-field)))
11543
11544 (defun orgtbl-ret ()
11545 "Justification and field motion for `orgtbl-mode'."
11546 (interactive)
11547 (org-table-justify-field-maybe)
11548 (org-table-next-row))
11549
11550 (defun orgtbl-self-insert-command (N)
11551 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11552 If the cursor is in a table looking at whitespace, the whitespace is
11553 overwritten, and the table is not marked as requiring realignment."
11554 (interactive "p")
11555 (if (and (org-at-table-p)
11556 (or
11557 (and org-table-auto-blank-field
11558 (member last-command
11559 '(orgtbl-hijacker-command-100
11560 orgtbl-hijacker-command-101
11561 orgtbl-hijacker-command-102
11562 orgtbl-hijacker-command-103
11563 orgtbl-hijacker-command-104
11564 orgtbl-hijacker-command-105))
11565 (org-table-blank-field))
11566 t)
11567 (eq N 1)
11568 (looking-at "[^|\n]* +|"))
11569 (let (org-table-may-need-update)
11570 (goto-char (1- (match-end 0)))
11571 (delete-backward-char 1)
11572 (goto-char (match-beginning 0))
11573 (self-insert-command N))
11574 (setq org-table-may-need-update t)
11575 (let (orgtbl-mode)
11576 (call-interactively (key-binding (vector last-input-event))))))
11577
11578 (defun org-force-self-insert (N)
11579 "Needed to enforce self-insert under remapping."
11580 (interactive "p")
11581 (self-insert-command N))
11582
11583 ;;; Exporting
11584
11585 (defconst org-level-max 20)
11586
11587 (defvar org-export-html-preamble nil
11588 "Preamble, to be inserted just after <body>. Set by publishing functions.")
11589 (defvar org-export-html-postamble nil
11590 "Preamble, to be inserted just before </body>. Set by publishing functions.")
11591 (defvar org-export-html-auto-preamble t
11592 "Should default preamble be inserted? Set by publishing functions.")
11593 (defvar org-export-html-auto-postamble t
11594 "Should default postamble be inserted? Set by publishing functions.")
11595
11596 (defconst org-export-plist-vars
11597 '((:language . org-export-default-language)
11598 (:headline-levels . org-export-headline-levels)
11599 (:section-numbers . org-export-with-section-numbers)
11600 (:table-of-contents . org-export-with-toc)
11601 (:emphasize . org-export-with-emphasize)
11602 (:sub-superscript . org-export-with-sub-superscripts)
11603 (:TeX-macros . org-export-with-TeX-macros)
11604 (:fixed-width . org-export-with-fixed-width)
11605 (:timestamps . org-export-with-timestamps)
11606 (:tables . org-export-with-tables)
11607 (:table-auto-headline . org-export-highlight-first-table-line)
11608 (:style . org-export-html-style)
11609 (:convert-org-links . org-export-html-link-org-files-as-html)
11610 (:inline-images . org-export-html-inline-images)
11611 (:expand-quoted-html . org-export-html-expand)
11612 (:timestamp . org-export-html-with-timestamp)
11613 (:publishing-directory . org-export-publishing-directory)
11614 (:preamble . org-export-html-preamble)
11615 (:postamble . org-export-html-postamble)
11616 (:auto-preamble . org-export-html-auto-preamble)
11617 (:auto-postamble . org-export-html-auto-postamble)
11618 (:author . user-full-name)
11619 (:email . user-mail-address)))
11620
11621 (defun org-default-export-plist ()
11622 "Return the property list with default settings for the export variables."
11623 (let ((l org-export-plist-vars) rtn e)
11624 (while (setq e (pop l))
11625 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
11626 rtn))
11627
11628 (defun org-infile-export-plist ()
11629 "Return the property list with file-local settings for export."
11630 (save-excursion
11631 (goto-char 0)
11632 (let ((re (org-make-options-regexp
11633 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
11634 (text nil)
11635 p key val text options)
11636 (while (re-search-forward re nil t)
11637 (setq key (org-match-string-no-properties 1)
11638 val (org-match-string-no-properties 2))
11639 (cond
11640 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
11641 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
11642 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
11643 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
11644 ((string-equal key "TEXT")
11645 (setq text (if text (concat text "\n" val) val)))
11646 ((string-equal key "OPTIONS") (setq options val))))
11647 (setq p (plist-put p :text text))
11648 (when options
11649 (let ((op '(("H" . :headline-levels)
11650 ("num" . :section-numbers)
11651 ("toc" . :table-of-contents)
11652 ("\\n" . :preserve-breaks)
11653 ("@" . :expand-quoted-html)
11654 (":" . :fixed-width)
11655 ("|" . :tables)
11656 ("^" . :sub-superscript)
11657 ("*" . :emphasize)
11658 ("TeX" . :TeX-macros)))
11659 o)
11660 (while (setq o (pop op))
11661 (if (string-match (concat (regexp-quote (car o))
11662 ":\\([^ \t\n\r;,.]*\\)")
11663 options)
11664 (setq p (plist-put p (cdr o)
11665 (car (read-from-string
11666 (match-string 1 options)))))))))
11667 p)))
11668
11669 (defun org-combine-plists (&rest plists)
11670 "Create a single property list from all plists in PLISTS.
11671 The process starts by copying the last list, and then setting properties
11672 from the other lists. Settings in the first list are the most significant
11673 ones and overrule settings in the other lists."
11674 (let ((rtn (copy-sequence (pop plists)))
11675 p v ls)
11676 (while plists
11677 (setq ls (pop plists))
11678 (while ls
11679 (setq p (pop ls) v (pop ls))
11680 (setq rtn (plist-put rtn p v))))
11681 rtn))
11682
11683 (defun org-export-directory (type plist)
11684 (let* ((val (plist-get plist :publishing-directory))
11685 (dir (if (listp val)
11686 (or (cdr (assoc type val)) ".")
11687 val)))
11688 dir))
11689
11690 (defun org-export-find-first-heading-line (list)
11691 "Remove all lines from LIST which are before the first headline."
11692 (let ((orig-list list)
11693 (re (concat "^" outline-regexp)))
11694 (while (and list
11695 (not (string-match re (car list))))
11696 (pop list))
11697 (or list orig-list)))
11698
11699 (defun org-skip-comments (lines)
11700 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
11701 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
11702 (re2 "^\\(\\*+\\)[ \t\n\r]")
11703 rtn line level)
11704 (while (setq line (pop lines))
11705 (cond
11706 ((and (string-match re1 line)
11707 (setq level (- (match-end 1) (match-beginning 1))))
11708 ;; Beginning of a COMMENT subtree. Skip it.
11709 (while (and (setq line (pop lines))
11710 (or (not (string-match re2 line))
11711 (> (- (match-end 1) (match-beginning 1)) level))))
11712 (setq lines (cons line lines)))
11713 ((string-match "^#" line)
11714 ;; an ordinary comment line
11715 )
11716 ((and org-export-table-remove-special-lines
11717 (string-match "^[ \t]*| *[!_^] *|" line))
11718 ;; a special table line that should be removed
11719 )
11720 (t (setq rtn (cons line rtn)))))
11721 (nreverse rtn)))
11722
11723 ;; ASCII
11724
11725 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
11726 "Characters for underlining headings in ASCII export.")
11727
11728 (defconst org-html-entities
11729 '(("nbsp")
11730 ("iexcl")
11731 ("cent")
11732 ("pound")
11733 ("curren")
11734 ("yen")
11735 ("brvbar")
11736 ("sect")
11737 ("uml")
11738 ("copy")
11739 ("ordf")
11740 ("laquo")
11741 ("not")
11742 ("shy")
11743 ("reg")
11744 ("macr")
11745 ("deg")
11746 ("plusmn")
11747 ("sup2")
11748 ("sup3")
11749 ("acute")
11750 ("micro")
11751 ("para")
11752 ("middot")
11753 ("odot"."o")
11754 ("star"."*")
11755 ("cedil")
11756 ("sup1")
11757 ("ordm")
11758 ("raquo")
11759 ("frac14")
11760 ("frac12")
11761 ("frac34")
11762 ("iquest")
11763 ("Agrave")
11764 ("Aacute")
11765 ("Acirc")
11766 ("Atilde")
11767 ("Auml")
11768 ("Aring") ("AA"."&Aring;")
11769 ("AElig")
11770 ("Ccedil")
11771 ("Egrave")
11772 ("Eacute")
11773 ("Ecirc")
11774 ("Euml")
11775 ("Igrave")
11776 ("Iacute")
11777 ("Icirc")
11778 ("Iuml")
11779 ("ETH")
11780 ("Ntilde")
11781 ("Ograve")
11782 ("Oacute")
11783 ("Ocirc")
11784 ("Otilde")
11785 ("Ouml")
11786 ("times")
11787 ("Oslash")
11788 ("Ugrave")
11789 ("Uacute")
11790 ("Ucirc")
11791 ("Uuml")
11792 ("Yacute")
11793 ("THORN")
11794 ("szlig")
11795 ("agrave")
11796 ("aacute")
11797 ("acirc")
11798 ("atilde")
11799 ("auml")
11800 ("aring")
11801 ("aelig")
11802 ("ccedil")
11803 ("egrave")
11804 ("eacute")
11805 ("ecirc")
11806 ("euml")
11807 ("igrave")
11808 ("iacute")
11809 ("icirc")
11810 ("iuml")
11811 ("eth")
11812 ("ntilde")
11813 ("ograve")
11814 ("oacute")
11815 ("ocirc")
11816 ("otilde")
11817 ("ouml")
11818 ("divide")
11819 ("oslash")
11820 ("ugrave")
11821 ("uacute")
11822 ("ucirc")
11823 ("uuml")
11824 ("yacute")
11825 ("thorn")
11826 ("yuml")
11827 ("fnof")
11828 ("Alpha")
11829 ("Beta")
11830 ("Gamma")
11831 ("Delta")
11832 ("Epsilon")
11833 ("Zeta")
11834 ("Eta")
11835 ("Theta")
11836 ("Iota")
11837 ("Kappa")
11838 ("Lambda")
11839 ("Mu")
11840 ("Nu")
11841 ("Xi")
11842 ("Omicron")
11843 ("Pi")
11844 ("Rho")
11845 ("Sigma")
11846 ("Tau")
11847 ("Upsilon")
11848 ("Phi")
11849 ("Chi")
11850 ("Psi")
11851 ("Omega")
11852 ("alpha")
11853 ("beta")
11854 ("gamma")
11855 ("delta")
11856 ("epsilon")
11857 ("varepsilon"."&epsilon;")
11858 ("zeta")
11859 ("eta")
11860 ("theta")
11861 ("iota")
11862 ("kappa")
11863 ("lambda")
11864 ("mu")
11865 ("nu")
11866 ("xi")
11867 ("omicron")
11868 ("pi")
11869 ("rho")
11870 ("sigmaf") ("varsigma"."&sigmaf;")
11871 ("sigma")
11872 ("tau")
11873 ("upsilon")
11874 ("phi")
11875 ("chi")
11876 ("psi")
11877 ("omega")
11878 ("thetasym") ("vartheta"."&thetasym;")
11879 ("upsih")
11880 ("piv")
11881 ("bull") ("bullet"."&bull;")
11882 ("hellip") ("dots"."&hellip;")
11883 ("prime")
11884 ("Prime")
11885 ("oline")
11886 ("frasl")
11887 ("weierp")
11888 ("image")
11889 ("real")
11890 ("trade")
11891 ("alefsym")
11892 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
11893 ("uarr") ("uparrow"."&uarr;")
11894 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
11895 ("darr")("downarrow"."&darr;")
11896 ("harr") ("leftrightarrow"."&harr;")
11897 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
11898 ("lArr") ("Leftarrow"."&lArr;")
11899 ("uArr") ("Uparrow"."&uArr;")
11900 ("rArr") ("Rightarrow"."&rArr;")
11901 ("dArr") ("Downarrow"."&dArr;")
11902 ("hArr") ("Leftrightarrow"."&hArr;")
11903 ("forall")
11904 ("part") ("partial"."&part;")
11905 ("exist") ("exists"."&exist;")
11906 ("empty") ("emptyset"."&empty;")
11907 ("nabla")
11908 ("isin") ("in"."&isin;")
11909 ("notin")
11910 ("ni")
11911 ("prod")
11912 ("sum")
11913 ("minus")
11914 ("lowast") ("ast"."&lowast;")
11915 ("radic")
11916 ("prop") ("proptp"."&prop;")
11917 ("infin") ("infty"."&infin;")
11918 ("ang") ("angle"."&ang;")
11919 ("and") ("vee"."&and;")
11920 ("or") ("wedge"."&or;")
11921 ("cap")
11922 ("cup")
11923 ("int")
11924 ("there4")
11925 ("sim")
11926 ("cong") ("simeq"."&cong;")
11927 ("asymp")("approx"."&asymp;")
11928 ("ne") ("neq"."&ne;")
11929 ("equiv")
11930 ("le")
11931 ("ge")
11932 ("sub") ("subset"."&sub;")
11933 ("sup") ("supset"."&sup;")
11934 ("nsub")
11935 ("sube")
11936 ("supe")
11937 ("oplus")
11938 ("otimes")
11939 ("perp")
11940 ("sdot") ("cdot"."&sdot;")
11941 ("lceil")
11942 ("rceil")
11943 ("lfloor")
11944 ("rfloor")
11945 ("lang")
11946 ("rang")
11947 ("loz") ("Diamond"."&loz;")
11948 ("spades") ("spadesuit"."&spades;")
11949 ("clubs") ("clubsuit"."&clubs;")
11950 ("hearts") ("diamondsuit"."&hearts;")
11951 ("diams") ("diamondsuit"."&diams;")
11952 ("quot")
11953 ("amp")
11954 ("lt")
11955 ("gt")
11956 ("OElig")
11957 ("oelig")
11958 ("Scaron")
11959 ("scaron")
11960 ("Yuml")
11961 ("circ")
11962 ("tilde")
11963 ("ensp")
11964 ("emsp")
11965 ("thinsp")
11966 ("zwnj")
11967 ("zwj")
11968 ("lrm")
11969 ("rlm")
11970 ("ndash")
11971 ("mdash")
11972 ("lsquo")
11973 ("rsquo")
11974 ("sbquo")
11975 ("ldquo")
11976 ("rdquo")
11977 ("bdquo")
11978 ("dagger")
11979 ("Dagger")
11980 ("permil")
11981 ("lsaquo")
11982 ("rsaquo")
11983 ("euro")
11984
11985 ("arccos"."arccos")
11986 ("arcsin"."arcsin")
11987 ("arctan"."arctan")
11988 ("arg"."arg")
11989 ("cos"."cos")
11990 ("cosh"."cosh")
11991 ("cot"."cot")
11992 ("coth"."coth")
11993 ("csc"."csc")
11994 ("deg"."deg")
11995 ("det"."det")
11996 ("dim"."dim")
11997 ("exp"."exp")
11998 ("gcd"."gcd")
11999 ("hom"."hom")
12000 ("inf"."inf")
12001 ("ker"."ker")
12002 ("lg"."lg")
12003 ("lim"."lim")
12004 ("liminf"."liminf")
12005 ("limsup"."limsup")
12006 ("ln"."ln")
12007 ("log"."log")
12008 ("max"."max")
12009 ("min"."min")
12010 ("Pr"."Pr")
12011 ("sec"."sec")
12012 ("sin"."sin")
12013 ("sinh"."sinh")
12014 ("sup"."sup")
12015 ("tan"."tan")
12016 ("tanh"."tanh")
12017 )
12018 "Entities for TeX->HTML translation.
12019 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
12020 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
12021 In that case, \"\\ent\" will be translated to \"&other;\".
12022 The list contains HTML entities for Latin-1, Greek and other symbols.
12023 It is supplemented by a number of commonly used TeX macros with appropriate
12024 translations. There is currently no way for users to extend this.")
12025
12026 (defun org-cleaned-string-for-export (string)
12027 "Cleanup a buffer substring so that links can be created safely."
12028 (interactive)
12029 (let* ((cb (current-buffer))
12030 (re-radio (and org-target-link-regexp
12031 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
12032 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
12033 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
12034 rtn)
12035 (save-excursion
12036 (set-buffer (get-buffer-create " org-mode-tmp"))
12037 (erase-buffer)
12038 (insert string)
12039 (org-mode)
12040 ;; Find targets in comments and move them out of comments,
12041 ;; but mark them as targets that should be invisible
12042 (goto-char (point-min))
12043 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
12044 (replace-match "\\1(INVISIBLE)"))
12045 ;; Find matches for radio targets and turn them into internal links
12046 (goto-char (point-min))
12047 (when re-radio
12048 (while (re-search-forward re-radio nil t)
12049 (replace-match "\\1[[\\2]]")))
12050 ;; Find all links that contain a newline and put them into a single line
12051 (goto-char (point-min))
12052 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
12053 (replace-match "\\1 \\3")
12054 (goto-char (match-beginning 0)))
12055 ;; Normalize links: Convert angle and plain links into bracket links
12056 (goto-char (point-min))
12057 (while (re-search-forward re-plain-link nil t)
12058 (replace-match
12059 (concat
12060 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
12061 t t))
12062 (goto-char (point-min))
12063 (while (re-search-forward re-angle-link nil t)
12064 (replace-match
12065 (concat
12066 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
12067 t t))
12068
12069 ;; Remove comments
12070 (goto-char (point-min))
12071 (while (re-search-forward "^#.*\n?" nil t)
12072 (replace-match ""))
12073 (setq rtn (buffer-string)))
12074 (kill-buffer " org-mode-tmp")
12075 rtn))
12076
12077 (defun org-solidify-link-text (s &optional alist)
12078 "Take link text and make a safe target out of it."
12079 (save-match-data
12080 (let* ((rtn
12081 (mapconcat
12082 'identity
12083 (org-split-string s "[ \t\r\n]+") "--"))
12084 (a (assoc rtn alist)))
12085 (or (cdr a) rtn))))
12086
12087 (defun org-convert-to-odd-levels ()
12088 "Convert an org-mode file with all levels allowed to one with odd levels.
12089 This will leave level 1 alone, convert level 2 to level 3, level 3 to
12090 level 5 etc."
12091 (interactive)
12092 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
12093 (let ((org-odd-levels-only nil) n)
12094 (save-excursion
12095 (goto-char (point-min))
12096 (while (re-search-forward "^\\*\\*+" nil t)
12097 (setq n (1- (length (match-string 0))))
12098 (while (>= (setq n (1- n)) 0)
12099 (org-demote))
12100 (end-of-line 1))))))
12101
12102
12103 (defun org-convert-to-oddeven-levels ()
12104 "Convert an org-mode file with only odd levels to one with odd and even levels.
12105 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
12106 section with an even level, conversion would destroy the structure of the file. An error
12107 is signaled in this case."
12108 (interactive)
12109 (goto-char (point-min))
12110 ;; First check if there are no even levels
12111 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
12112 (org-show-hierarchy-above)
12113 (error "Not all levels are odd in this file. Conversion not possible."))
12114 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
12115 (let ((org-odd-levels-only nil) n)
12116 (save-excursion
12117 (goto-char (point-min))
12118 (while (re-search-forward "^\\*\\*+" nil t)
12119 (setq n (/ (length (match-string 0)) 2))
12120 (while (>= (setq n (1- n)) 0)
12121 (org-promote))
12122 (end-of-line 1))))))
12123
12124 (defun org-tr-level (n)
12125 "Make N odd if required."
12126 (if org-odd-levels-only (1+ (/ n 2)) n))
12127
12128 (defvar org-last-level nil) ; dynamically scoped variable
12129
12130 (defun org-export-as-ascii (arg)
12131 "Export the outline as a pretty ASCII file.
12132 If there is an active region, export only the region.
12133 The prefix ARG specifies how many levels of the outline should become
12134 underlined headlines. The default is 3."
12135 (interactive "P")
12136 (setq-default org-todo-line-regexp org-todo-line-regexp)
12137 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
12138 (org-infile-export-plist)))
12139 (region
12140 (buffer-substring
12141 (if (org-region-active-p) (region-beginning) (point-min))
12142 (if (org-region-active-p) (region-end) (point-max))))
12143 (lines (org-export-find-first-heading-line
12144 (org-skip-comments
12145 (org-split-string
12146 (org-cleaned-string-for-export region)
12147 "[\r\n]"))))
12148 (org-startup-with-deadline-check nil)
12149 (level 0) line txt
12150 (umax nil)
12151 (case-fold-search nil)
12152 (filename (concat (file-name-as-directory
12153 (org-export-directory :ascii opt-plist))
12154 (file-name-sans-extension
12155 (file-name-nondirectory buffer-file-name))
12156 ".txt"))
12157 (buffer (find-file-noselect filename))
12158 (levels-open (make-vector org-level-max nil))
12159 (odd org-odd-levels-only)
12160 (date (format-time-string "%Y/%m/%d" (current-time)))
12161 (time (format-time-string "%X" (org-current-time)))
12162 (author (plist-get opt-plist :author))
12163 (title (or (plist-get opt-plist :title)
12164 (file-name-sans-extension
12165 (file-name-nondirectory buffer-file-name))))
12166 (options nil)
12167 (email (plist-get opt-plist :email))
12168 (language (plist-get opt-plist :language))
12169 (text nil)
12170 (todo nil)
12171 (lang-words nil))
12172
12173 (setq org-last-level 1)
12174 (org-init-section-numbers)
12175
12176 (find-file-noselect filename)
12177
12178 (setq lang-words (or (assoc language org-export-language-setup)
12179 (assoc "en" org-export-language-setup)))
12180 (if org-export-ascii-show-new-buffer
12181 (switch-to-buffer-other-window buffer)
12182 (set-buffer buffer))
12183 (erase-buffer)
12184 (fundamental-mode)
12185 ;; create local variables for all options, to make sure all called
12186 ;; functions get the correct information
12187 (mapcar (lambda (x)
12188 (set (make-local-variable (cdr x))
12189 (plist-get opt-plist (car x))))
12190 org-export-plist-vars)
12191 (set (make-local-variable 'org-odd-levels-only) odd)
12192 (setq umax (if arg (prefix-numeric-value arg)
12193 org-export-headline-levels))
12194
12195 ;; File header
12196 (if title (org-insert-centered title ?=))
12197 (insert "\n")
12198 (if (or author email)
12199 (insert (concat (nth 1 lang-words) ": " (or author "")
12200 (if email (concat " <" email ">") "")
12201 "\n")))
12202 (if (and date time)
12203 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
12204 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
12205
12206 (insert "\n\n")
12207
12208 (if org-export-with-toc
12209 (progn
12210 (insert (nth 3 lang-words) "\n"
12211 (make-string (length (nth 3 lang-words)) ?=) "\n")
12212 (mapcar '(lambda (line)
12213 (if (string-match org-todo-line-regexp
12214 line)
12215 ;; This is a headline
12216 (progn
12217 (setq level (- (match-end 1) (match-beginning 1))
12218 level (org-tr-level level)
12219 txt (match-string 3 line)
12220 todo
12221 (or (and org-export-mark-todo-in-toc
12222 (match-beginning 2)
12223 (not (equal (match-string 2 line)
12224 org-done-string)))
12225 ; TODO, not DONE
12226 (and org-export-mark-todo-in-toc
12227 (= level umax)
12228 (org-search-todo-below
12229 line lines level))))
12230 (setq txt (org-html-expand-for-ascii txt))
12231
12232 (if org-export-with-section-numbers
12233 (setq txt (concat (org-section-number level)
12234 " " txt)))
12235 (if (<= level umax)
12236 (progn
12237 (insert
12238 (make-string (* (1- level) 4) ?\ )
12239 (format (if todo "%s (*)\n" "%s\n") txt))
12240 (setq org-last-level level))
12241 ))))
12242 lines)))
12243
12244 (org-init-section-numbers)
12245 (while (setq line (pop lines))
12246 ;; Remove the quoted HTML tags.
12247 (setq line (org-html-expand-for-ascii line))
12248 ;; Remove targets
12249 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
12250 (setq line (replace-match "" t t line)))
12251 ;; Replace internal links
12252 (while (string-match org-bracket-link-regexp line)
12253 (setq line (replace-match
12254 (if (match-end 3) "[\\3]" "[\\1]")
12255 t nil line)))
12256 (cond
12257 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
12258 ;; a Headline
12259 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
12260 txt (match-string 2 line))
12261 (org-ascii-level-start level txt umax))
12262 (t (insert line "\n"))))
12263 (normal-mode)
12264 (save-buffer)
12265 ;; remove display and invisible chars
12266 (let (beg end s)
12267 (goto-char (point-min))
12268 (while (setq beg (next-single-property-change (point) 'display))
12269 (setq end (next-single-property-change beg 'display))
12270 (delete-region beg end)
12271 (goto-char beg)
12272 (insert "=>"))
12273 (goto-char (point-min))
12274 (while (setq beg (next-single-property-change (point) 'org-cwidth))
12275 (setq end (next-single-property-change beg 'org-cwidth))
12276 (delete-region beg end)
12277 (goto-char beg)))
12278 (goto-char (point-min))))
12279
12280 (defun org-search-todo-below (line lines level)
12281 "Search the subtree below LINE for any TODO entries."
12282 (let ((rest (cdr (memq line lines)))
12283 (re org-todo-line-regexp)
12284 line lv todo)
12285 (catch 'exit
12286 (while (setq line (pop rest))
12287 (if (string-match re line)
12288 (progn
12289 (setq lv (- (match-end 1) (match-beginning 1))
12290 todo (and (match-beginning 2)
12291 (not (equal (match-string 2 line)
12292 org-done-string))))
12293 ; TODO, not DONE
12294 (if (<= lv level) (throw 'exit nil))
12295 (if todo (throw 'exit t))))))))
12296
12297 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
12298 ;; We could also implement *bold*,/italic/ and _underline_ for ASCII export
12299 (defun org-html-expand-for-ascii (line)
12300 "Handle quoted HTML for ASCII export."
12301 (if org-export-html-expand
12302 (while (string-match "@<[^<>\n]*>" line)
12303 ;; We just remove the tags for now.
12304 (setq line (replace-match "" nil nil line))))
12305 line)
12306
12307 (defun org-insert-centered (s &optional underline)
12308 "Insert the string S centered and underline it with character UNDERLINE."
12309 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
12310 (insert (make-string ind ?\ ) s "\n")
12311 (if underline
12312 (insert (make-string ind ?\ )
12313 (make-string (string-width s) underline)
12314 "\n"))))
12315
12316 (defun org-ascii-level-start (level title umax)
12317 "Insert a new level in ASCII export."
12318 (let (char)
12319 (if (> level umax)
12320 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
12321 (if (or (not (equal (char-before) ?\n))
12322 (not (equal (char-before (1- (point))) ?\n)))
12323 (insert "\n"))
12324 (setq char (nth (- umax level) (reverse org-ascii-underline)))
12325 (if org-export-with-section-numbers
12326 (setq title (concat (org-section-number level) " " title)))
12327 (insert title "\n" (make-string (string-width title) char) "\n"))))
12328
12329 (defun org-export-visible (type arg)
12330 "Create a copy of the visible part of the current buffer, and export it.
12331 The copy is created in a temporary buffer and removed after use.
12332 TYPE is the final key (as a string) of the `C-c C-x' key sequence that will
12333 run the export command - in interactive use, the command prompts for this
12334 key. As a special case, if the you type SPC at the prompt, the temporary
12335 org-mode file will not be removed but presented to you so that you can
12336 continue to use it. The prefix arg ARG is passed through to the exporting
12337 command."
12338 (interactive
12339 (list (progn
12340 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
12341 (char-to-string (read-char-exclusive)))
12342 current-prefix-arg))
12343 (if (not (member type '("a" "\C-a" "b" "\C-b" "h" "x" " ")))
12344 (error "Invalid export key"))
12345 (let* ((binding (key-binding (concat "\C-c\C-x" type)))
12346 (keepp (equal type " "))
12347 (file buffer-file-name)
12348 (buffer (get-buffer-create "*Org Export Visible*"))
12349 s e)
12350 (with-current-buffer buffer (erase-buffer))
12351 (save-excursion
12352 (setq s (goto-char (point-min)))
12353 (while (not (= (point) (point-max)))
12354 (goto-char (org-find-invisible))
12355 (append-to-buffer buffer s (point))
12356 (setq s (goto-char (org-find-visible))))
12357 (goto-char (point-min))
12358 (unless keepp
12359 ;; Copy all comment lines to the end, to make sure #+ settings are
12360 ;; still available for the second export step. Kind of a hack, but
12361 ;; does do the trick.
12362 (if (looking-at "#[^\r\n]*")
12363 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
12364 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
12365 (append-to-buffer buffer (1+ (match-beginning 0))
12366 (min (point-max) (1+ (match-end 0))))))
12367 (set-buffer buffer)
12368 (let ((buffer-file-name file)
12369 (org-inhibit-startup t))
12370 (org-mode)
12371 (show-all)
12372 (unless keepp (funcall binding arg))))
12373 (if (not keepp)
12374 (kill-buffer buffer)
12375 (switch-to-buffer-other-window buffer)
12376 (goto-char (point-min)))))
12377
12378 (defun org-find-visible ()
12379 (if (featurep 'noutline)
12380 (let ((s (point)))
12381 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
12382 (get-char-property s 'invisible)))
12383 s)
12384 (skip-chars-forward "^\n")
12385 (point)))
12386 (defun org-find-invisible ()
12387 (if (featurep 'noutline)
12388 (let ((s (point)))
12389 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
12390 (not (get-char-property s 'invisible))))
12391 s)
12392 (skip-chars-forward "^\r")
12393 (point)))
12394
12395 ;; HTML
12396
12397 (defun org-get-current-options ()
12398 "Return a string with current options as keyword options.
12399 Does include HTML export options as well as TODO and CATEGORY stuff."
12400 (format
12401 "#+TITLE: %s
12402 #+AUTHOR: %s
12403 #+EMAIL: %s
12404 #+LANGUAGE: %s
12405 #+TEXT: Some descriptive text to be emitted. Several lines OK.
12406 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
12407 #+CATEGORY: %s
12408 #+SEQ_TODO: %s
12409 #+TYP_TODO: %s
12410 #+STARTUP: %s %s %s %s %s %s
12411 #+TAGS: %s
12412 #+ARCHIVE: %s
12413 "
12414 (buffer-name) (user-full-name) user-mail-address org-export-default-language
12415 org-export-headline-levels
12416 org-export-with-section-numbers
12417 org-export-with-toc
12418 org-export-preserve-breaks
12419 org-export-html-expand
12420 org-export-with-fixed-width
12421 org-export-with-tables
12422 org-export-with-sub-superscripts
12423 org-export-with-emphasize
12424 org-export-with-TeX-macros
12425 (file-name-nondirectory buffer-file-name)
12426 (if (equal org-todo-interpretation 'sequence)
12427 (mapconcat 'identity org-todo-keywords " ")
12428 "TODO FEEDBACK VERIFY DONE")
12429 (if (equal org-todo-interpretation 'type)
12430 (mapconcat 'identity org-todo-keywords " ")
12431 "Me Jason Marie DONE")
12432 (cdr (assoc org-startup-folded
12433 '((nil . "showall") (t . "overview") (content . "content"))))
12434 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
12435 (if org-odd-levels-only "odd" "oddeven")
12436 (if org-hide-leading-stars "hidestars" "showstars")
12437 (if org-startup-align-all-tables "align" "noalign")
12438 (if org-log-done "logging" "nologging")
12439 (if org-tag-alist (mapconcat 'car org-tag-alist " ") "")
12440 org-archive-location
12441 ))
12442
12443 (defun org-insert-export-options-template ()
12444 "Insert into the buffer a template with information for exporting."
12445 (interactive)
12446 (if (not (bolp)) (newline))
12447 (let ((s (org-get-current-options)))
12448 (and (string-match "#\\+CATEGORY" s)
12449 (setq s (substring s 0 (match-beginning 0))))
12450 (insert s)))
12451
12452 (defun org-toggle-fixed-width-section (arg)
12453 "Toggle the fixed-width export.
12454 If there is no active region, the QUOTE keyword at the current headline is
12455 inserted or removed. When present, it causes the text between this headline
12456 and the next to be exported as fixed-width text, and unmodified.
12457 If there is an active region, this command adds or removes a colon as the
12458 first character of this line. If the first character of a line is a colon,
12459 this line is also exported in fixed-width font."
12460 (interactive "P")
12461 (let* ((cc 0)
12462 (regionp (org-region-active-p))
12463 (beg (if regionp (region-beginning) (point)))
12464 (end (if regionp (region-end)))
12465 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
12466 (re "[ \t]*\\(:\\)")
12467 off)
12468 (if regionp
12469 (save-excursion
12470 (goto-char beg)
12471 (setq cc (current-column))
12472 (beginning-of-line 1)
12473 (setq off (looking-at re))
12474 (while (> nlines 0)
12475 (setq nlines (1- nlines))
12476 (beginning-of-line 1)
12477 (cond
12478 (arg
12479 (move-to-column cc t)
12480 (insert ":\n")
12481 (forward-line -1))
12482 ((and off (looking-at re))
12483 (replace-match "" t t nil 1))
12484 ((not off) (move-to-column cc t) (insert ":")))
12485 (forward-line 1)))
12486 (save-excursion
12487 (org-back-to-heading)
12488 (if (looking-at (concat outline-regexp
12489 "\\( +\\<" org-quote-string "\\>\\)"))
12490 (replace-match "" t t nil 1)
12491 (if (looking-at outline-regexp)
12492 (progn
12493 (goto-char (match-end 0))
12494 (insert " " org-quote-string))))))))
12495
12496 (defun org-export-as-html-and-open (arg)
12497 "Export the outline as HTML and immediately open it with a browser.
12498 If there is an active region, export only the region.
12499 The prefix ARG specifies how many levels of the outline should become
12500 headlines. The default is 3. Lower levels will become bulleted lists."
12501 (interactive "P")
12502 (org-export-as-html arg 'hidden)
12503 (org-open-file buffer-file-name))
12504
12505 (defun org-export-as-html-batch ()
12506 "Call `org-export-as-html', may be used in batch processing as
12507 emacs --batch
12508 --load=$HOME/lib/emacs/org.el
12509 --eval \"(setq org-export-headline-levels 2)\"
12510 --visit=MyFile --funcall org-export-as-html-batch"
12511 (org-export-as-html org-export-headline-levels 'hidden))
12512
12513 (defun org-export-as-html (arg &optional hidden ext-plist)
12514 "Export the outline as a pretty HTML file.
12515 If there is an active region, export only the region.
12516 The prefix ARG specifies how many levels of the outline should become
12517 headlines. The default is 3. Lower levels will become bulleted lists.
12518 When HIDDEN is non-nil, don't display the HTML buffer.
12519 EXT-PLIST is a property list with external parameters overriding
12520 org-mode's default settings, but still inferior to file-local settings."
12521 (interactive "P")
12522 (setq-default org-todo-line-regexp org-todo-line-regexp)
12523 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
12524 (setq-default org-done-string org-done-string)
12525 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
12526 ext-plist
12527 (org-infile-export-plist)))
12528
12529 (style (plist-get opt-plist :style))
12530 (odd org-odd-levels-only)
12531 (region-p (org-region-active-p))
12532 (region
12533 (buffer-substring
12534 (if region-p (region-beginning) (point-min))
12535 (if region-p (region-end) (point-max))))
12536 (all_lines
12537 (org-skip-comments (org-split-string
12538 (org-cleaned-string-for-export region)
12539 "[\r\n]")))
12540 (lines (org-export-find-first-heading-line all_lines))
12541 (level 0) (line "") (origline "") txt todo
12542 (umax nil)
12543 (filename (concat (file-name-as-directory
12544 (org-export-directory :html opt-plist))
12545 (file-name-sans-extension
12546 (file-name-nondirectory buffer-file-name))
12547 ".html"))
12548 (buffer (find-file-noselect filename))
12549 (levels-open (make-vector org-level-max nil))
12550 (date (format-time-string "%Y/%m/%d" (current-time)))
12551 (time (format-time-string "%X" (org-current-time)))
12552 (author (plist-get opt-plist :author))
12553 (title (or (plist-get opt-plist :title)
12554 (file-name-sans-extension
12555 (file-name-nondirectory buffer-file-name))))
12556 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
12557 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
12558 (inquote nil)
12559 (infixed nil)
12560 (in-local-list nil)
12561 (local-list-num nil)
12562 (local-list-indent nil)
12563 (llt org-plain-list-ordered-item-terminator)
12564 (email (plist-get opt-plist :email))
12565 (language (plist-get opt-plist :language))
12566 (text (plist-get opt-plist :text))
12567 (lang-words nil)
12568 (target-alist nil) tg
12569 (head-count 0) cnt
12570 (start 0)
12571 ;; FIXME: The following returns always nil under XEmacs
12572 (coding-system (and (fboundp 'coding-system-get)
12573 (boundp 'buffer-file-coding-system)
12574 buffer-file-coding-system))
12575 (coding-system-for-write (or coding-system coding-system-for-write))
12576 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
12577 (charset (and coding-system
12578 (coding-system-get coding-system 'mime-charset)))
12579 table-open type
12580 table-buffer table-orig-buffer
12581 ind start-is-num starter
12582 rpl path desc descp desc1 desc2 link
12583 )
12584 (message "Exporting...")
12585
12586 (setq org-last-level 1)
12587 (org-init-section-numbers)
12588
12589 ;; Get the language-dependent settings
12590 (setq lang-words (or (assoc language org-export-language-setup)
12591 (assoc "en" org-export-language-setup)))
12592
12593 ;; Switch to the output buffer
12594 (if (or hidden (not org-export-html-show-new-buffer))
12595 (set-buffer buffer)
12596 (switch-to-buffer-other-window buffer))
12597 (erase-buffer)
12598 (fundamental-mode)
12599 (let ((case-fold-search nil)
12600 (org-odd-levels-only odd))
12601 ;; create local variables for all options, to make sure all called
12602 ;; functions get the correct information
12603 (mapcar (lambda (x)
12604 (set (make-local-variable (cdr x))
12605 (plist-get opt-plist (car x))))
12606 org-export-plist-vars)
12607 (setq umax (if arg (prefix-numeric-value arg)
12608 org-export-headline-levels))
12609
12610 ;; File header
12611 (insert (format
12612 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
12613 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
12614 <html lang=\"%s\"><head>
12615 <title>%s</title>
12616 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
12617 <meta name=generator content=\"Org-mode\">
12618 <meta name=generated content=\"%s %s\">
12619 <meta name=author content=\"%s\">
12620 %s
12621 </head><body>
12622 "
12623 language (org-html-expand title) (or charset "iso-8859-1")
12624 date time author style))
12625
12626
12627 (insert (or (plist-get opt-plist :preamble) ""))
12628
12629 (when (plist-get opt-plist :auto-preamble)
12630 (if title (insert (concat "<H1 class=\"title\">"
12631 (org-html-expand title) "</H1>\n")))
12632 ; (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
12633 ; (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
12634 ; email "&gt;</a>\n")))
12635 ; (if (or author email) (insert "<br>\n"))
12636 ; (if (and date time) (insert (concat (nth 2 lang-words) ": "
12637 ; date " " time "<br>\n")))
12638 (if text (insert (concat "<p>\n" (org-html-expand text)))))
12639
12640 (if org-export-with-toc
12641 (progn
12642 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
12643 (insert "<ul>\n")
12644 (setq lines
12645 (mapcar '(lambda (line)
12646 (if (string-match org-todo-line-regexp line)
12647 ;; This is a headline
12648 (progn
12649 (setq level (- (match-end 1) (match-beginning 1))
12650 level (org-tr-level level)
12651 txt (save-match-data
12652 (org-html-expand
12653 (org-html-cleanup-toc-line
12654 (match-string 3 line))))
12655 todo
12656 (or (and org-export-mark-todo-in-toc
12657 (match-beginning 2)
12658 (not (equal (match-string 2 line)
12659 org-done-string)))
12660 ; TODO, not DONE
12661 (and org-export-mark-todo-in-toc
12662 (= level umax)
12663 (org-search-todo-below
12664 line lines level))))
12665 (if org-export-with-section-numbers
12666 (setq txt (concat (org-section-number level)
12667 " " txt)))
12668 (if (<= level umax)
12669 (progn
12670 (setq head-count (+ head-count 1))
12671 (if (> level org-last-level)
12672 (progn
12673 (setq cnt (- level org-last-level))
12674 (while (>= (setq cnt (1- cnt)) 0)
12675 (insert "<ul>"))
12676 (insert "\n")))
12677 (if (< level org-last-level)
12678 (progn
12679 (setq cnt (- org-last-level level))
12680 (while (>= (setq cnt (1- cnt)) 0)
12681 (insert "</ul>"))
12682 (insert "\n")))
12683 ;; Check for targets
12684 (while (string-match org-target-regexp line)
12685 (setq tg (match-string 1 line)
12686 line (replace-match
12687 (concat "@<span class=\"target\">" tg "@</span> ")
12688 t t line))
12689 (push (cons (org-solidify-link-text tg)
12690 (format "sec-%d" head-count))
12691 target-alist))
12692 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
12693 (setq txt (replace-match "" t t txt)))
12694 (insert
12695 (format
12696 (if todo
12697 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
12698 "<li><a href=\"#sec-%d\">%s</a>\n")
12699 head-count txt))
12700
12701 (setq org-last-level level))
12702 )))
12703 line)
12704 lines))
12705 (while (> org-last-level 0)
12706 (setq org-last-level (1- org-last-level))
12707 (insert "</ul>\n"))
12708 ))
12709 (setq head-count 0)
12710 (org-init-section-numbers)
12711
12712 (while (setq line (pop lines) origline line)
12713 (catch 'nextline
12714
12715 ;; end of quote section?
12716 (when (and inquote (string-match "^\\*+" line))
12717 (insert "</pre>\n")
12718 (setq inquote nil))
12719 ;; inside a quote section?
12720 (when inquote
12721 (insert (org-html-protect line) "\n")
12722 (throw 'nextline nil))
12723
12724 ;; verbatim lines
12725 (when (and org-export-with-fixed-width
12726 (string-match "^[ \t]*:\\(.*\\)" line))
12727 (when (not infixed)
12728 (setq infixed t)
12729 (insert "<pre>\n"))
12730 (insert (org-html-protect (match-string 1 line)) "\n")
12731 (when (and lines
12732 (not (string-match "^[ \t]*\\(:.*\\)"
12733 (car lines))))
12734 (setq infixed nil)
12735 (insert "</pre>\n"))
12736 (throw 'nextline nil))
12737
12738
12739 ;; make targets to anchors
12740 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
12741 (cond
12742 ((match-end 2)
12743 (setq line (replace-match
12744 (concat "@<a name=\""
12745 (org-solidify-link-text (match-string 1 line))
12746 "\">\\nbsp@</a>")
12747 t t line)))
12748 ((and org-export-with-toc (equal (string-to-char line) ?*))
12749 (setq line (replace-match
12750 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
12751 ; (concat "@<i>" (match-string 1 line) "@</i> ")
12752 t t line)))
12753 (t
12754 (setq line (replace-match
12755 (concat "@<a name=\""
12756 (org-solidify-link-text (match-string 1 line))
12757 "\" class=\"target\">" (match-string 1 line) "@</a> ")
12758 t t line)))))
12759
12760 (setq line (org-html-handle-time-stamps line))
12761
12762 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
12763 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
12764 ;; Also handle sub_superscripts and checkboxes FIXME
12765 (setq line (org-html-expand line))
12766
12767 ;; Format the links
12768 (setq start 0)
12769 (while (string-match org-bracket-link-analytic-regexp line start)
12770 (setq start (match-beginning 0))
12771 (setq type (if (match-end 2) (match-string 2 line) "internal"))
12772 (setq path (match-string 3 line))
12773 (setq desc1 (if (match-end 5) (match-string 5 line))
12774 desc2 (if (match-end 2) (concat type ":" path) path)
12775 descp (and desc1 (not (equal desc1 desc2)))
12776 desc (or desc1 desc2))
12777 ;; FIXME: do we need to unescape here somewhere?
12778 (cond
12779 ((equal type "internal")
12780 (setq rpl
12781 (concat
12782 "<a href=\"#"
12783 (org-solidify-link-text path target-alist)
12784 "\">" desc "</a>")))
12785 ((member type '("http" "https" "ftp" "mailto" "news"))
12786 ;; standard URL
12787 (setq link (concat type ":" path))
12788 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
12789 ((string= type "file")
12790 ;; FILE link
12791 (let* ((filename path)
12792 (abs-p (file-name-absolute-p filename))
12793 thefile file-is-image-p search)
12794 (save-match-data
12795 (if (string-match "::\\(.*\\)" filename)
12796 (setq search (match-string 1 filename)
12797 filename (replace-match "" nil nil filename)))
12798 (setq file-is-image-p
12799 (string-match (org-image-file-name-regexp) filename))
12800 (setq thefile (if abs-p (expand-file-name filename) filename))
12801 (when (and org-export-html-link-org-files-as-html
12802 (string-match "\\.org$" thefile))
12803 (setq thefile (concat (substring thefile 0
12804 (match-beginning 0))
12805 ".html"))
12806 (if (and search
12807 ;; make sure this is can be used as target search
12808 (not (string-match "^[0-9]*$" search))
12809 (not (string-match "^\\*" search))
12810 (not (string-match "^/.*/$" search)))
12811 (setq thefile (concat thefile "#"
12812 (org-solidify-link-text
12813 (org-link-unescape search)))))
12814 (when (string-match "^file:" desc)
12815 (setq desc (replace-match "" t t desc))
12816 (if (string-match "\\.org$" desc)
12817 (setq desc (replace-match "" t t desc))))))
12818 (setq rpl (if (and file-is-image-p
12819 (or (eq t org-export-html-inline-images)
12820 (and org-export-html-inline-images
12821 (not descp))))
12822 (concat "<img src=\"" thefile "\"/>")
12823 (concat "<a href=\"" thefile "\">" desc "</a>")))))
12824 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
12825 (setq rpl (concat "<i>&lt;" type ":"
12826 (save-match-data (org-link-unescape path))
12827 "&gt;</i>"))))
12828 (setq line (replace-match rpl t t line)
12829 start (+ start (length rpl))))
12830 ;; TODO items
12831 (if (and (string-match org-todo-line-regexp line)
12832 (match-beginning 2))
12833 (if (equal (match-string 2 line) org-done-string)
12834 (setq line (replace-match
12835 "<span class=\"done\">\\2</span>"
12836 nil nil line 2))
12837 (setq line (replace-match "<span class=\"todo\">\\2</span>"
12838 nil nil line 2))))
12839
12840 (cond
12841 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
12842 ;; This is a headline
12843 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
12844 txt (match-string 2 line))
12845 (if (string-match quote-re0 txt)
12846 (setq txt (replace-match "" t t txt)))
12847 (if (<= level umax) (setq head-count (+ head-count 1)))
12848 (when in-local-list
12849 ;; Close any local lists before inserting a new header line
12850 (while local-list-num
12851 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
12852 (pop local-list-num))
12853 (setq local-list-indent nil
12854 in-local-list nil))
12855 (org-html-level-start level txt umax
12856 (and org-export-with-toc (<= level umax))
12857 head-count)
12858 ;; QUOTES
12859 (when (string-match quote-re line)
12860 (insert "<pre>")
12861 (setq inquote t)))
12862
12863 ((and org-export-with-tables
12864 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
12865 (if (not table-open)
12866 ;; New table starts
12867 (setq table-open t table-buffer nil table-orig-buffer nil))
12868 ;; Accumulate lines
12869 (setq table-buffer (cons line table-buffer)
12870 table-orig-buffer (cons origline table-orig-buffer))
12871 (when (or (not lines)
12872 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
12873 (car lines))))
12874 (setq table-open nil
12875 table-buffer (nreverse table-buffer)
12876 table-orig-buffer (nreverse table-orig-buffer))
12877 (insert (org-format-table-html table-buffer table-orig-buffer))))
12878 (t
12879 ;; Normal lines
12880 (when (string-match
12881 (cond
12882 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
12883 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
12884 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
12885 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
12886 line)
12887 (setq ind (org-get-string-indentation line)
12888 start-is-num (match-beginning 4)
12889 starter (if (match-beginning 2)
12890 (substring (match-string 2 line) 0 -1))
12891 line (substring line (match-beginning 5)))
12892 (unless (string-match "[^ \t]" line)
12893 ;; empty line. Pretend indentation is large.
12894 (setq ind (1+ (or (car local-list-indent) 1))))
12895 (while (and in-local-list
12896 (or (and (= ind (car local-list-indent))
12897 (not starter))
12898 (< ind (car local-list-indent))))
12899 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
12900 (pop local-list-num) (pop local-list-indent)
12901 (setq in-local-list local-list-indent))
12902 (cond
12903 ((and starter
12904 (or (not in-local-list)
12905 (> ind (car local-list-indent))))
12906 ;; Start new (level of ) list
12907 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
12908 (push start-is-num local-list-num)
12909 (push ind local-list-indent)
12910 (setq in-local-list t))
12911 (starter
12912 ;; continue current list
12913 (insert "<li>\n")))
12914 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
12915 (setq line
12916 (replace-match
12917 (if (equal (match-string 1 line) "X")
12918 "<b>[X]</b>"
12919 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
12920 t t line))))
12921
12922 ;; Empty lines start a new paragraph. If hand-formatted lists
12923 ;; are not fully interpreted, lines starting with "-", "+", "*"
12924 ;; also start a new paragraph.
12925 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
12926 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
12927 ))
12928
12929 ;; Properly close all local lists and other lists
12930 (when inquote (insert "</pre>\n"))
12931 (when in-local-list
12932 ;; Close any local lists before inserting a new header line
12933 (while local-list-num
12934 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
12935 (pop local-list-num))
12936 (setq local-list-indent nil
12937 in-local-list nil))
12938 (org-html-level-start 1 nil umax
12939 (and org-export-with-toc (<= level umax))
12940 head-count)
12941
12942 (when (plist-get opt-plist :auto-postamble)
12943 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
12944 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
12945 email "&gt;</a>\n")))
12946 (if (or author email) (insert "<br>\n"))
12947 (if (and date time) (insert (concat (nth 2 lang-words) ": "
12948 date " " time "<br>\n"))))
12949
12950 (if org-export-html-with-timestamp
12951 (insert org-export-html-html-helper-timestamp))
12952 (insert (or (plist-get opt-plist :postamble) ""))
12953 (insert "</body>\n</html>\n")
12954 (normal-mode)
12955 (save-buffer)
12956 (goto-char (point-min)))))
12957
12958 (defun org-format-table-html (lines olines)
12959 "Find out which HTML converter to use and return the HTML code."
12960 (if (string-match "^[ \t]*|" (car lines))
12961 ;; A normal org table
12962 (org-format-org-table-html lines)
12963 ;; Table made by table.el - test for spanning
12964 (let* ((hlines (delq nil (mapcar
12965 (lambda (x)
12966 (if (string-match "^[ \t]*\\+-" x) x
12967 nil))
12968 lines)))
12969 (first (car hlines))
12970 (ll (and (string-match "\\S-+" first)
12971 (match-string 0 first)))
12972 (re (concat "^[ \t]*" (regexp-quote ll)))
12973 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
12974 hlines))))
12975 (if (and (not spanning)
12976 (not org-export-prefer-native-exporter-for-tables))
12977 ;; We can use my own converter with HTML conversions
12978 (org-format-table-table-html lines)
12979 ;; Need to use the code generator in table.el, with the original text.
12980 (org-format-table-table-html-using-table-generate-source olines)))))
12981
12982 (defun org-format-org-table-html (lines)
12983 "Format a table into HTML."
12984 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
12985 (setq lines (nreverse lines))
12986 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
12987 (setq lines (nreverse lines))
12988 (when org-export-table-remove-special-lines
12989 ;; Check if the table has a marking column. If yes remove the
12990 ;; column and the special lines
12991 (let* ((special
12992 (not
12993 (memq nil
12994 (mapcar
12995 (lambda (x)
12996 (or (string-match "^[ \t]*|-" x)
12997 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
12998 lines)))))
12999 (if special
13000 (setq lines
13001 (delq nil
13002 (mapcar
13003 (lambda (x)
13004 (if (string-match "^[ \t]*| *[!_^] *|" x)
13005 nil ; ignore this line
13006 (and (or (string-match "^[ \t]*|-+\\+" x)
13007 (string-match "^[ \t]*|[^|]*|" x))
13008 (replace-match "|" t t x))))
13009 lines))))))
13010
13011 (let ((head (and org-export-highlight-first-table-line
13012 (delq nil (mapcar
13013 (lambda (x) (string-match "^[ \t]*|-" x))
13014 (cdr lines)))))
13015 line fields html)
13016 (setq html (concat org-export-html-table-tag "\n"))
13017 (while (setq line (pop lines))
13018 (catch 'next-line
13019 (if (string-match "^[ \t]*|-" line)
13020 (progn
13021 (setq head nil) ;; head ends here, first time around
13022 ;; ignore this line
13023 (throw 'next-line t)))
13024 ;; Break the line into fields
13025 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
13026 (setq html (concat
13027 html
13028 "<tr>"
13029 (mapconcat (lambda (x)
13030 (if head
13031 (concat "<th>" x "</th>")
13032 (concat "<td>" x "</td>")))
13033 fields "")
13034 "</tr>\n"))))
13035 (setq html (concat html "</table>\n"))
13036 html))
13037
13038 (defun org-fake-empty-table-line (line)
13039 "Replace everything except \"|\" with spaces."
13040 (let ((i (length line))
13041 (newstr (copy-sequence line)))
13042 (while (> i 0)
13043 (setq i (1- i))
13044 (if (not (eq (aref newstr i) ?|))
13045 (aset newstr i ?\ )))
13046 newstr))
13047
13048 (defun org-format-table-table-html (lines)
13049 "Format a table generated by table.el into HTML.
13050 This conversion does *not* use `table-generate-source' from table.el.
13051 This has the advantage that Org-mode's HTML conversions can be used.
13052 But it has the disadvantage, that no cell- or row-spanning is allowed."
13053 (let (line field-buffer
13054 (head org-export-highlight-first-table-line)
13055 fields html empty)
13056 (setq html (concat org-export-html-table-tag "\n"))
13057 (while (setq line (pop lines))
13058 (setq empty "&nbsp")
13059 (catch 'next-line
13060 (if (string-match "^[ \t]*\\+-" line)
13061 (progn
13062 (if field-buffer
13063 (progn
13064 (setq html (concat
13065 html
13066 "<tr>"
13067 (mapconcat
13068 (lambda (x)
13069 (if (equal x "") (setq x empty))
13070 (if head
13071 (concat "<th>" x "</th>\n")
13072 (concat "<td>" x "</td>\n")))
13073 field-buffer "\n")
13074 "</tr>\n"))
13075 (setq head nil)
13076 (setq field-buffer nil)))
13077 ;; Ignore this line
13078 (throw 'next-line t)))
13079 ;; Break the line into fields and store the fields
13080 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
13081 (if field-buffer
13082 (setq field-buffer (mapcar
13083 (lambda (x)
13084 (concat x "<br>" (pop fields)))
13085 field-buffer))
13086 (setq field-buffer fields))))
13087 (setq html (concat html "</table>\n"))
13088 html))
13089
13090 (defun org-format-table-table-html-using-table-generate-source (lines)
13091 "Format a table into html, using `table-generate-source' from table.el.
13092 This has the advantage that cell- or row-spanning is allowed.
13093 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
13094 (require 'table)
13095 (with-current-buffer (get-buffer-create " org-tmp1 ")
13096 (erase-buffer)
13097 (insert (mapconcat 'identity lines "\n"))
13098 (goto-char (point-min))
13099 (if (not (re-search-forward "|[^+]" nil t))
13100 (error "Error processing table"))
13101 (table-recognize-table)
13102 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
13103 (table-generate-source 'html " org-tmp2 ")
13104 (set-buffer " org-tmp2 ")
13105 (buffer-substring (point-min) (point-max))))
13106
13107 (defun org-html-handle-time-stamps (s)
13108 "Format time stamps in string S, or remove them."
13109 (let (r b)
13110 (while (string-match org-maybe-keyword-time-regexp s)
13111 (or b (setq b (substring s 0 (match-beginning 0))))
13112 (if (not org-export-with-timestamps)
13113 (setq r (concat r (substring s 0 (match-beginning 0)))
13114 s (substring s (match-end 0)))
13115 (setq r (concat
13116 r (substring s 0 (match-beginning 0))
13117 (if (match-end 1)
13118 (format "@<span class=\"timestamp-kwd\">%s @</span>"
13119 (match-string 1 s)))
13120 (format " @<span class=\"timestamp\">%s@</span>"
13121 (substring (match-string 3 s) 1 -1)))
13122 s (substring s (match-end 0)))))
13123 ;; Line break of line started and ended with time stamp stuff
13124 (if (not r)
13125 s
13126 (setq r (concat r s))
13127 (unless (string-match "\\S-" (concat b s))
13128 (setq r (concat r "@<br>")))
13129 r)))
13130
13131 (defun org-html-protect (s)
13132 ;; convert & to &amp;, < to &lt; and > to &gt;
13133 (let ((start 0))
13134 (while (string-match "&" s start)
13135 (setq s (replace-match "&amp;" t t s)
13136 start (1+ (match-beginning 0))))
13137 (while (string-match "<" s)
13138 (setq s (replace-match "&lt;" t t s)))
13139 (while (string-match ">" s)
13140 (setq s (replace-match "&gt;" t t s))))
13141 s)
13142
13143 (defun org-html-cleanup-toc-line (s)
13144 "Remove tags and time staps from lines going into the toc."
13145 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
13146 (setq s (replace-match "" t t s)))
13147 (while (string-match org-maybe-keyword-time-regexp s)
13148 (setq s (replace-match "" t t s)))
13149 s)
13150
13151 (defun org-html-expand (string)
13152 "Prepare STRING for HTML export. Applies all active conversions.
13153 If there are links in the string, don't modify these."
13154 (let* (m s l res)
13155 (while (setq m (string-match org-bracket-link-regexp string))
13156 (setq s (substring string 0 m)
13157 l (match-string 0 string)
13158 string (substring string (match-end 0)))
13159 (push (org-html-do-expand s) res)
13160 (push l res))
13161 (push (org-html-do-expand string) res)
13162 (apply 'concat (nreverse res))))
13163
13164 (defun org-html-do-expand (s)
13165 "Apply all active conversions to translate special ASCII to HTML."
13166 (setq s (org-html-protect s))
13167 (if org-export-html-expand
13168 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
13169 (setq s (replace-match "<\\1>" nil nil s))))
13170 (if org-export-with-emphasize
13171 (setq s (org-export-html-convert-emphasize s)))
13172 (if org-export-with-sub-superscripts
13173 (setq s (org-export-html-convert-sub-super s)))
13174 (if org-export-with-TeX-macros
13175 (let ((start 0) wd ass)
13176 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
13177 (setq wd (match-string 1 s))
13178 (if (setq ass (assoc wd org-html-entities))
13179 (setq s (replace-match (or (cdr ass)
13180 (concat "&" (car ass) ";"))
13181 t t s))
13182 (setq start (+ start (length wd)))))))
13183 s)
13184
13185 (defun org-create-multibrace-regexp (left right n)
13186 "Create a regular expression which will match a balanced sexp.
13187 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
13188 as single character strings.
13189 The regexp returned will match the entire expression including the
13190 delimiters. It will also define a single group which contains the
13191 match except for the outermost delimiters. The maximum depth of
13192 stacked delimiters is N. Escaping delimiters is not possible."
13193 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
13194 (or "\\|")
13195 (re nothing)
13196 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
13197 (while (> n 1)
13198 (setq n (1- n)
13199 re (concat re or next)
13200 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
13201 (concat left "\\(" re "\\)" right)))
13202
13203 (defvar org-match-substring-regexp
13204 (concat
13205 "\\([^\\]\\)\\([_^]\\)\\("
13206 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
13207 "\\|"
13208 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
13209 "\\|"
13210 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
13211 ;;;;;;;;;;;;;;;;;;;;;;;;;^ FIXME
13212 "The regular expression matching a sub- or superscript.")
13213
13214 (defun org-export-html-convert-sub-super (string)
13215 "Convert sub- and superscripts in STRING to HTML."
13216 (let (key c)
13217 (while (string-match org-match-substring-regexp string)
13218 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
13219 (setq c (or (match-string 8 string)
13220 (match-string 6 string)
13221 (match-string 5 string)))
13222 (setq string (replace-match
13223 (concat (match-string 1 string)
13224 "<" key ">" c "</" key ">")
13225 t t string)))
13226 (while (string-match "\\\\\\([_^]\\)" string)
13227 (setq string (replace-match (match-string 1 string) t t string))))
13228 string)
13229
13230 (defun org-export-html-convert-emphasize (string)
13231 (while (string-match org-italic-re string)
13232 (setq string (replace-match "\\1<i>\\3</i>\\4" t nil string)))
13233 (while (string-match org-bold-re string)
13234 (setq string (replace-match "\\1<b>\\3</b>\\4" t nil string)))
13235 (while (string-match org-underline-re string)
13236 (setq string (replace-match "\\1<u>\\3</u>\\4" t nil string)))
13237 string)
13238
13239 (defun org-html-level-start (level title umax with-toc head-count)
13240 "Insert a new level in HTML export.
13241 When TITLE is nil, just close all open levels."
13242 (let ((l (1+ (max level umax))))
13243 (while (<= l org-level-max)
13244 (if (aref levels-open (1- l))
13245 (progn
13246 (org-html-level-close l)
13247 (aset levels-open (1- l) nil)))
13248 (setq l (1+ l)))
13249 (when title
13250 ;; If title is nil, this means this function is called to close
13251 ;; all levels, so the rest is done only if title is given
13252 (if (> level umax)
13253 (progn
13254 (if (aref levels-open (1- level))
13255 (insert "<li>" title "<p>\n")
13256 (aset levels-open (1- level) t)
13257 (insert "<ul><li>" title "<p>\n")))
13258 (if org-export-with-section-numbers
13259 (setq title (concat (org-section-number level) " " title)))
13260 (setq level (+ level 1))
13261 ;; FIXME: here we need to handle the tags, somehow.
13262 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
13263 (setq title (replace-match
13264 (if org-export-with-tags
13265 (save-match-data
13266 (concat
13267 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
13268 (mapconcat 'identity (org-split-string
13269 (match-string 1 title) ":")
13270 "&nbsp;")
13271 "</span>"))
13272 "")
13273 t t title)))
13274 (if with-toc
13275 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
13276 level head-count title level))
13277 (insert (format "\n<H%d>%s</H%d>\n" level title level)))))))
13278
13279 (defun org-html-level-close (&rest args)
13280 "Terminate one level in HTML export."
13281 (insert "</ul>"))
13282
13283 ;; Variable holding the vector with section numbers
13284 (defvar org-section-numbers (make-vector org-level-max 0))
13285
13286 (defun org-init-section-numbers ()
13287 "Initialize the vector for the section numbers."
13288 (let* ((level -1)
13289 (numbers (nreverse (org-split-string "" "\\.")))
13290 (depth (1- (length org-section-numbers)))
13291 (i depth) number-string)
13292 (while (>= i 0)
13293 (if (> i level)
13294 (aset org-section-numbers i 0)
13295 (setq number-string (or (car numbers) "0"))
13296 (if (string-match "\\`[A-Z]\\'" number-string)
13297 (aset org-section-numbers i
13298 (- (string-to-char number-string) ?A -1))
13299 (aset org-section-numbers i (string-to-number number-string)))
13300 (pop numbers))
13301 (setq i (1- i)))))
13302
13303 (defun org-section-number (&optional level)
13304 "Return a string with the current section number.
13305 When LEVEL is non-nil, increase section numbers on that level."
13306 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
13307 (when level
13308 (when (> level -1)
13309 (aset org-section-numbers
13310 level (1+ (aref org-section-numbers level))))
13311 (setq idx (1+ level))
13312 (while (<= idx depth)
13313 (if (not (= idx 1))
13314 (aset org-section-numbers idx 0))
13315 (setq idx (1+ idx))))
13316 (setq idx 0)
13317 (while (<= idx depth)
13318 (setq n (aref org-section-numbers idx))
13319 (setq string (concat string (if (not (string= string "")) "." "")
13320 (int-to-string n)))
13321 (setq idx (1+ idx)))
13322 (save-match-data
13323 (if (string-match "\\`\\([@0]\\.\\)+" string)
13324 (setq string (replace-match "" nil nil string)))
13325 (if (string-match "\\(\\.0\\)+\\'" string)
13326 (setq string (replace-match "" nil nil string))))
13327 string))
13328
13329
13330 (defun org-export-icalendar-this-file ()
13331 "Export current file as an iCalendar file.
13332 The iCalendar file will be located in the same directory as the Org-mode
13333 file, but with extension `.ics'."
13334 (interactive)
13335 (org-export-icalendar nil buffer-file-name))
13336
13337 (defun org-export-as-xml (arg)
13338 "Export current buffer as XOXO XML buffer."
13339 (interactive "P")
13340 (cond ((eq org-export-xml-type 'xoxo)
13341 (org-export-as-xoxo (current-buffer)))))
13342
13343 (defun org-export-as-xoxo-insert-into (buffer &rest output)
13344 (with-current-buffer buffer
13345 (apply 'insert output)))
13346
13347 (defun org-export-as-xoxo (&optional buffer)
13348 "Export the org buffer as XOXO.
13349 The XOXO buffer is named *xoxo-<source buffer name>*"
13350 (interactive (list (current-buffer)))
13351 ;; A quickie abstraction
13352
13353 ;; Output everything as XOXO
13354 (with-current-buffer (get-buffer buffer)
13355 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
13356 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13357 (org-infile-export-plist)))
13358 (filename (concat (file-name-as-directory
13359 (org-export-directory :xoxo opt-plist))
13360 (file-name-sans-extension
13361 (file-name-nondirectory buffer-file-name))
13362 ".html"))
13363 (out (find-file-noselect filename))
13364 (last-level 1)
13365 (hanging-li nil))
13366 ;; Check the output buffer is empty.
13367 (with-current-buffer out (erase-buffer))
13368 ;; Kick off the output
13369 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
13370 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
13371 (let* ((hd (match-string-no-properties 1))
13372 (level (length hd))
13373 (text (concat
13374 (match-string-no-properties 2)
13375 (save-excursion
13376 (goto-char (match-end 0))
13377 (let ((str ""))
13378 (catch 'loop
13379 (while 't
13380 (forward-line)
13381 (if (looking-at "^[ \t]\\(.*\\)")
13382 (setq str (concat str (match-string-no-properties 1)))
13383 (throw 'loop str)))))))))
13384
13385 ;; Handle level rendering
13386 (cond
13387 ((> level last-level)
13388 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
13389
13390 ((< level last-level)
13391 (dotimes (- (- last-level level) 1)
13392 (if hanging-li
13393 (org-export-as-xoxo-insert-into out "</li>\n"))
13394 (org-export-as-xoxo-insert-into out "</ol>\n"))
13395 (when hanging-li
13396 (org-export-as-xoxo-insert-into out "</li>\n")
13397 (setq hanging-li nil)))
13398
13399 ((equal level last-level)
13400 (if hanging-li
13401 (org-export-as-xoxo-insert-into out "</li>\n")))
13402 )
13403
13404 (setq last-level level)
13405
13406 ;; And output the new li
13407 (setq hanging-li 't)
13408 (if (equal ?+ (elt text 0))
13409 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
13410 (org-export-as-xoxo-insert-into out "<li>" text))))
13411
13412 ;; Finally finish off the ol
13413 (dotimes (- last-level 1)
13414 (if hanging-li
13415 (org-export-as-xoxo-insert-into out "</li>\n"))
13416 (org-export-as-xoxo-insert-into out "</ol>\n"))
13417
13418 ;; Finish the buffer off and clean it up.
13419 (switch-to-buffer-other-window out)
13420 (indent-region (point-min) (point-max) nil)
13421 (save-buffer)
13422 (goto-char (point-min))
13423 )))
13424
13425 ;;;###autoload
13426 (defun org-export-icalendar-all-agenda-files ()
13427 "Export all files in `org-agenda-files' to iCalendar .ics files.
13428 Each iCalendar file will be located in the same directory as the Org-mode
13429 file, but with extension `.ics'."
13430 (interactive)
13431 (apply 'org-export-icalendar nil (org-agenda-files t)))
13432
13433 ;;;###autoload
13434 (defun org-export-icalendar-combine-agenda-files ()
13435 "Export all files in `org-agenda-files' to a single combined iCalendar file.
13436 The file is stored under the name `org-combined-agenda-icalendar-file'."
13437 (interactive)
13438 (apply 'org-export-icalendar t (org-agenda-files t)))
13439
13440 (defun org-export-icalendar (combine &rest files)
13441 "Create iCalendar files for all elements of FILES.
13442 If COMBINE is non-nil, combine all calendar entries into a single large
13443 file and store it under the name `org-combined-agenda-icalendar-file'."
13444 (save-excursion
13445 (let* ((dir (org-export-directory
13446 :ical (list :publishing-directory
13447 org-export-publishing-directory)))
13448 file ical-file ical-buffer category started org-agenda-new-buffers)
13449
13450 (when combine
13451 (setq ical-file
13452 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
13453 org-combined-agenda-icalendar-file
13454 (expand-file-name org-combined-agenda-icalendar-file dir))
13455 ical-buffer (org-get-agenda-file-buffer ical-file))
13456 (set-buffer ical-buffer) (erase-buffer))
13457 (while (setq file (pop files))
13458 (catch 'nextfile
13459 (org-check-agenda-file file)
13460 (set-buffer (org-get-agenda-file-buffer file))
13461 (unless combine
13462 (setq ical-file (concat (file-name-as-directory dir)
13463 (file-name-sans-extension
13464 (file-name-nondirectory buffer-file-name))
13465 ".ics"))
13466 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
13467 (with-current-buffer ical-buffer (erase-buffer)))
13468 (setq category (or org-category
13469 (file-name-sans-extension
13470 (file-name-nondirectory buffer-file-name))))
13471 (if (symbolp category) (setq category (symbol-name category)))
13472 (let ((standard-output ical-buffer))
13473 (if combine
13474 (and (not started) (setq started t)
13475 (org-start-icalendar-file org-icalendar-combined-name))
13476 (org-start-icalendar-file category))
13477 (org-print-icalendar-entries combine category)
13478 (when (or (and combine (not files)) (not combine))
13479 (org-finish-icalendar-file)
13480 (set-buffer ical-buffer)
13481 (save-buffer)
13482 (run-hooks 'org-after-save-iCalendar-file-hook)))))
13483 (org-release-buffers org-agenda-new-buffers))))
13484
13485 (defvar org-after-save-iCalendar-file-hook nil
13486 "Hook run after an iCalendar file has been saved.
13487 The iCalendar buffer is still current when this hook is run.
13488 A good way to use this is to tell a desktop calenndar application to re-read
13489 the iCalendar file.")
13490
13491 (defun org-print-icalendar-entries (&optional combine category)
13492 "Print iCalendar entries for the current Org-mode file to `standard-output'.
13493 When COMBINE is non nil, add the category to each line."
13494 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
13495 (dts (org-ical-ts-to-string
13496 (format-time-string (cdr org-time-stamp-formats) (current-time))
13497 "DTSTART"))
13498 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
13499 (save-excursion
13500 (goto-char (point-min))
13501 (while (re-search-forward org-ts-regexp nil t)
13502 (setq pos (match-beginning 0)
13503 ts (match-string 0)
13504 inc t
13505 hd (org-get-heading))
13506 (if (looking-at re2)
13507 (progn
13508 (goto-char (match-end 0))
13509 (setq ts2 (match-string 1) inc nil))
13510 (setq ts2 ts
13511 tmp (buffer-substring (max (point-min)
13512 (- pos org-ds-keyword-length))
13513 pos)
13514 deadlinep (string-match org-deadline-regexp tmp)
13515 scheduledp (string-match org-scheduled-regexp tmp)
13516 ;; donep (org-entry-is-done-p)
13517 ))
13518 (if (or (string-match org-tr-regexp hd)
13519 (string-match org-ts-regexp hd))
13520 (setq hd (replace-match "" t t hd)))
13521 (if combine
13522 (setq hd (concat hd " (category " category ")")))
13523 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
13524 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
13525 (princ (format "BEGIN:VEVENT
13526 %s
13527 %s
13528 SUMMARY:%s
13529 END:VEVENT\n"
13530 (org-ical-ts-to-string ts "DTSTART")
13531 (org-ical-ts-to-string ts2 "DTEND" inc)
13532 hd)))
13533 (when org-icalendar-include-todo
13534 (goto-char (point-min))
13535 (while (re-search-forward org-todo-line-regexp nil t)
13536 (setq state (match-string 1))
13537 (unless (equal state org-done-string)
13538 (setq hd (match-string 3))
13539 (if (string-match org-priority-regexp hd)
13540 (setq pri (string-to-char (match-string 2 hd))
13541 hd (concat (substring hd 0 (match-beginning 1))
13542 (substring hd (- (match-end 1)))))
13543 (setq pri org-default-priority))
13544 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
13545 (- org-lowest-priority ?A))))))
13546
13547 (princ (format "BEGIN:VTODO
13548 %s
13549 SUMMARY:%s
13550 SEQUENCE:1
13551 PRIORITY:%d
13552 END:VTODO\n"
13553 dts hd pri))))))))
13554
13555 (defun org-start-icalendar-file (name)
13556 "Start an iCalendar file by inserting the header."
13557 (let ((user user-full-name)
13558 (name (or name "unknown"))
13559 (timezone (cadr (current-time-zone))))
13560 (princ
13561 (format "BEGIN:VCALENDAR
13562 VERSION:2.0
13563 X-WR-CALNAME:%s
13564 PRODID:-//%s//Emacs with Org-mode//EN
13565 X-WR-TIMEZONE:%s
13566 CALSCALE:GREGORIAN\n" name user timezone))))
13567
13568 (defun org-finish-icalendar-file ()
13569 "Finish an iCalendar file by inserting the END statement."
13570 (princ "END:VCALENDAR\n"))
13571
13572 (defun org-ical-ts-to-string (s keyword &optional inc)
13573 "Take a time string S and convert it to iCalendar format.
13574 KEYWORD is added in front, to make a complete line like DTSTART....
13575 When INC is non-nil, increase the hour by two (if time string contains
13576 a time), or the day by one (if it does not contain a time)."
13577 (let ((t1 (org-parse-time-string s 'nodefault))
13578 t2 fmt have-time time)
13579 (if (and (car t1) (nth 1 t1) (nth 2 t1))
13580 (setq t2 t1 have-time t)
13581 (setq t2 (org-parse-time-string s)))
13582 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
13583 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
13584 (when inc
13585 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
13586 (setq time (encode-time s mi h d m y)))
13587 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
13588 (concat keyword (format-time-string fmt time))))
13589
13590
13591 ;;; Key bindings
13592
13593 ;; - Bindings in Org-mode map are currently
13594 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
13595 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
13596 ;; e (?) useful from outline-mode
13597 ;; i k @ expendable from outline-mode
13598 ;; 0123456789 % & ()_{} " ` free
13599
13600 ;; Make `C-c C-x' a prefix key
13601 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
13602 (define-key org-mode-map "\C-c\C-e" (make-sparse-keymap))
13603
13604 ;; TAB key with modifiers
13605 (define-key org-mode-map "\C-i" 'org-cycle)
13606 (define-key org-mode-map [(tab)] 'org-cycle)
13607 (define-key org-mode-map [(meta tab)] 'org-complete)
13608 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
13609 ;; The following line is necessary under Suse GNU/Linux
13610 (unless (featurep 'xemacs)
13611 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
13612 (define-key org-mode-map [(shift tab)] 'org-shifttab)
13613
13614 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
13615 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
13616 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
13617 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
13618 (define-key org-mode-map [(meta return)] 'org-meta-return)
13619 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
13620 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
13621
13622 ;; Cursor keys with modifiers
13623 (define-key org-mode-map [(meta left)] 'org-metaleft)
13624 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
13625 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
13626 (define-key org-mode-map [(meta right)] 'org-metaright)
13627 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
13628 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
13629 (define-key org-mode-map [(meta up)] 'org-metaup)
13630 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
13631 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
13632 (define-key org-mode-map [(meta down)] 'org-metadown)
13633 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
13634 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
13635
13636 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
13637 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
13638 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
13639 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
13640 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
13641 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
13642 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
13643 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
13644 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
13645 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
13646 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
13647 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
13648 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
13649 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
13650 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
13651 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
13652
13653 ;; All the other keys
13654
13655 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
13656 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
13657 (define-key org-mode-map "\C-c\C-j" 'org-goto)
13658 (define-key org-mode-map "\C-c\C-t" 'org-todo)
13659 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
13660 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
13661 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
13662 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
13663 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
13664 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
13665 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
13666 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
13667 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
13668 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
13669 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
13670 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
13671 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
13672 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
13673 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
13674 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
13675 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
13676 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
13677 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
13678 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
13679 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
13680 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
13681 (define-key org-mode-map "\C-c]" 'org-remove-file)
13682 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
13683 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
13684 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
13685 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
13686 (define-key org-mode-map "\C-m" 'org-return)
13687 (define-key org-mode-map "\C-c?" 'org-table-current-column)
13688 (define-key org-mode-map "\C-c " 'org-table-blank-field)
13689 (define-key org-mode-map "\C-c+" 'org-table-sum)
13690 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
13691 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
13692 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
13693 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
13694 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
13695 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
13696 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
13697 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
13698 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
13699 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
13700 (define-key org-mode-map "\C-c\C-xv" 'org-export-visible)
13701 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-visible)
13702 ;; OPML support is only an option for the future
13703 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
13704 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
13705 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
13706 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
13707 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
13708 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
13709 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
13710 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
13711 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
13712 (define-key org-mode-map "\C-c\C-xx" 'org-export-as-xml)
13713 (define-key org-mode-map "\C-c\C-x\C-x" 'org-export-as-xml)
13714 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
13715 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
13716
13717 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
13718 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
13719 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
13720 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
13721
13722 (define-key org-mode-map "\C-c\C-ef" 'org-publish-current-file)
13723 (define-key org-mode-map "\C-c\C-ep" 'org-publish-current-project)
13724 (define-key org-mode-map "\C-c\C-ec" 'org-publish)
13725 (define-key org-mode-map "\C-c\C-ea" 'org-publish-all)
13726 (define-key org-mode-map "\C-c\C-e\C-f" 'org-publish-current-file)
13727 (define-key org-mode-map "\C-c\C-e\C-p" 'org-publish-current-project)
13728 (define-key org-mode-map "\C-c\C-e\C-c" 'org-publish)
13729 (define-key org-mode-map "\C-c\C-e\C-a" 'org-publish-all)
13730
13731 (when (featurep 'xemacs)
13732 (define-key org-mode-map 'button3 'popup-mode-menu))
13733
13734 (defsubst org-table-p () (org-at-table-p))
13735
13736 (defun org-self-insert-command (N)
13737 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13738 If the cursor is in a table looking at whitespace, the whitespace is
13739 overwritten, and the table is not marked as requiring realignment."
13740 (interactive "p")
13741 (if (and (org-table-p)
13742 (progn
13743 ;; check if we blank the field, and if that triggers align
13744 (and org-table-auto-blank-field
13745 (member last-command
13746 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13747 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13748 ;; got extra space, this field does not determine column width
13749 (let (org-table-may-need-update) (org-table-blank-field))
13750 ;; no extra space, this field may determine column width
13751 (org-table-blank-field)))
13752 t)
13753 (eq N 1)
13754 (looking-at "[^|\n]* |"))
13755 (let (org-table-may-need-update)
13756 (goto-char (1- (match-end 0)))
13757 (delete-backward-char 1)
13758 (goto-char (match-beginning 0))
13759 (self-insert-command N))
13760 (setq org-table-may-need-update t)
13761 (self-insert-command N)))
13762
13763 (defun org-delete-backward-char (N)
13764 "Like `delete-backward-char', insert whitespace at field end in tables.
13765 When deleting backwards, in tables this function will insert whitespace in
13766 front of the next \"|\" separator, to keep the table aligned. The table will
13767 still be marked for re-alignment if the field did fill the entire column,
13768 because, in this case the deletion might narrow the column."
13769 (interactive "p")
13770 (if (and (org-table-p)
13771 (eq N 1)
13772 (string-match "|" (buffer-substring (point-at-bol) (point)))
13773 (looking-at ".*?|"))
13774 (let ((pos (point))
13775 (noalign (looking-at "[^|\n\r]* |"))
13776 (c org-table-may-need-update))
13777 (backward-delete-char N)
13778 (skip-chars-forward "^|")
13779 (insert " ")
13780 (goto-char (1- pos))
13781 ;; noalign: if there were two spaces at the end, this field
13782 ;; does not determine the width of the column.
13783 (if noalign (setq org-table-may-need-update c)))
13784 (backward-delete-char N)))
13785
13786 (defun org-delete-char (N)
13787 "Like `delete-char', but insert whitespace at field end in tables.
13788 When deleting characters, in tables this function will insert whitespace in
13789 front of the next \"|\" separator, to keep the table aligned. The table will
13790 still be marked for re-alignment if the field did fill the entire column,
13791 because, in this case the deletion might narrow the column."
13792 (interactive "p")
13793 (if (and (org-table-p)
13794 (not (bolp))
13795 (not (= (char-after) ?|))
13796 (eq N 1))
13797 (if (looking-at ".*?|")
13798 (let ((pos (point))
13799 (noalign (looking-at "[^|\n\r]* |"))
13800 (c org-table-may-need-update))
13801 (replace-match (concat
13802 (substring (match-string 0) 1 -1)
13803 " |"))
13804 (goto-char pos)
13805 ;; noalign: if there were two spaces at the end, this field
13806 ;; does not determine the width of the column.
13807 (if noalign (setq org-table-may-need-update c)))
13808 (delete-char N))
13809 (delete-char N)))
13810
13811 ;; How to do this: Measure non-white length of current string
13812 ;; If equal to column width, we should realign.
13813
13814 (defun org-remap (map &rest commands)
13815 "In MAP, remap the functions given in COMMANDS.
13816 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13817 (let (new old)
13818 (while commands
13819 (setq old (pop commands) new (pop commands))
13820 (if (fboundp 'command-remapping)
13821 (define-key map (vector 'remap old) new)
13822 (substitute-key-definition old new map global-map)))))
13823
13824 (when (eq org-enable-table-editor 'optimized)
13825 ;; If the user wants maximum table support, we need to hijack
13826 ;; some standard editing functions
13827 (org-remap org-mode-map
13828 'self-insert-command 'org-self-insert-command
13829 'delete-char 'org-delete-char
13830 'delete-backward-char 'org-delete-backward-char)
13831 (define-key org-mode-map "|" 'org-force-self-insert))
13832
13833 (defun org-shiftcursor-error ()
13834 "Throw an error because Shift-Cursor command was applied in wrong context."
13835 (error "This command is active in special context like tables, headlines or timestamps"))
13836
13837 (defun org-shifttab ()
13838 "Global visibility cycling or move to previous table field.
13839 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13840 on context.
13841 See the individual commands for more information."
13842 (interactive)
13843 (cond
13844 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13845 (t (call-interactively 'org-global-cycle))))
13846
13847 (defun org-shiftmetaleft ()
13848 "Promote subtree or delete table column.
13849 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
13850 See the individual commands for more information."
13851 (interactive)
13852 (cond
13853 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13854 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13855 ((org-at-item-p) (call-interactively 'org-outdent-item))
13856 (t (org-shiftcursor-error))))
13857
13858 (defun org-shiftmetaright ()
13859 "Demote subtree or insert table column.
13860 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
13861 See the individual commands for more information."
13862 (interactive)
13863 (cond
13864 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13865 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13866 ((org-at-item-p) (call-interactively 'org-indent-item))
13867 (t (org-shiftcursor-error))))
13868
13869 (defun org-shiftmetaup (&optional arg)
13870 "Move subtree up or kill table row.
13871 Calls `org-move-subtree-up' or `org-table-kill-row' or
13872 `org-move-item-up' depending on context. See the individual commands
13873 for more information."
13874 (interactive "P")
13875 (cond
13876 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13877 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13878 ((org-at-item-p) (call-interactively 'org-move-item-up))
13879 (t (org-shiftcursor-error))))
13880 (defun org-shiftmetadown (&optional arg)
13881 "Move subtree down or insert table row.
13882 Calls `org-move-subtree-down' or `org-table-insert-row' or
13883 `org-move-item-down', depending on context. See the individual
13884 commands for more information."
13885 (interactive "P")
13886 (cond
13887 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13888 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13889 ((org-at-item-p) (call-interactively 'org-move-item-down))
13890 (t (org-shiftcursor-error))))
13891
13892 (defun org-metaleft (&optional arg)
13893 "Promote heading or move table column to left.
13894 Calls `org-do-promote' or `org-table-move-column', depending on context.
13895 With no specific context, calls the Emacs default `backward-word'.
13896 See the individual commands for more information."
13897 (interactive "P")
13898 (cond
13899 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13900 ((or (org-on-heading-p) (org-region-active-p))
13901 (call-interactively 'org-do-promote))
13902 (t (call-interactively 'backward-word))))
13903
13904 (defun org-metaright (&optional arg)
13905 "Demote subtree or move table column to right.
13906 Calls `org-do-demote' or `org-table-move-column', depending on context.
13907 With no specific context, calls the Emacs default `forward-word'.
13908 See the individual commands for more information."
13909 (interactive "P")
13910 (cond
13911 ((org-at-table-p) (call-interactively 'org-table-move-column))
13912 ((or (org-on-heading-p) (org-region-active-p))
13913 (call-interactively 'org-do-demote))
13914 (t (call-interactively 'forward-word))))
13915
13916 (defun org-metaup (&optional arg)
13917 "Move subtree up or move table row up.
13918 Calls `org-move-subtree-up' or `org-table-move-row' or
13919 `org-move-item-up', depending on context. See the individual commands
13920 for more information."
13921 (interactive "P")
13922 (cond
13923 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13924 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13925 ((org-at-item-p) (call-interactively 'org-move-item-up))
13926 (t (org-shiftcursor-error))))
13927
13928 (defun org-metadown (&optional arg)
13929 "Move subtree down or move table row down.
13930 Calls `org-move-subtree-down' or `org-table-move-row' or
13931 `org-move-item-down', depending on context. See the individual
13932 commands for more information."
13933 (interactive "P")
13934 (cond
13935 ((org-at-table-p) (call-interactively 'org-table-move-row))
13936 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13937 ((org-at-item-p) (call-interactively 'org-move-item-down))
13938 (t (org-shiftcursor-error))))
13939
13940 (defun org-shiftup (&optional arg)
13941 "Increase item in timestamp or increase priority of current headline.
13942 Calls `org-timestamp-up' or `org-priority-up', depending on context.
13943 See the individual commands for more information."
13944 (interactive "P")
13945 (cond
13946 ((org-at-timestamp-p) (call-interactively 'org-timestamp-up))
13947 ((org-on-heading-p) (call-interactively 'org-priority-up))
13948 ((org-at-item-p) (call-interactively 'org-previous-item))
13949 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
13950
13951 (defun org-shiftdown (&optional arg)
13952 "Decrease item in timestamp or decrease priority of current headline.
13953 Calls `org-timestamp-down' or `org-priority-down', depending on context.
13954 See the individual commands for more information."
13955 (interactive "P")
13956 (cond
13957 ((org-at-timestamp-p) (call-interactively 'org-timestamp-down))
13958 ((org-on-heading-p) (call-interactively 'org-priority-down))
13959 (t (call-interactively 'org-next-item))))
13960
13961 (defun org-shiftright ()
13962 "Next TODO keyword or timestamp one day later, depending on context."
13963 (interactive)
13964 (cond
13965 ((org-at-timestamp-p) (call-interactively 'org-timestamp-up-day))
13966 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
13967 (t (org-shiftcursor-error))))
13968
13969 (defun org-shiftleft ()
13970 "Previous TODO keyword or timestamp one day earlier, depending on context."
13971 (interactive)
13972 (cond
13973 ((org-at-timestamp-p) (call-interactively 'org-timestamp-down-day))
13974 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
13975 (t (org-shiftcursor-error))))
13976
13977 (defun org-copy-special ()
13978 "Copy region in table or copy current subtree.
13979 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13980 See the individual commands for more information."
13981 (interactive)
13982 (call-interactively
13983 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13984
13985 (defun org-cut-special ()
13986 "Cut region in table or cut current subtree.
13987 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13988 See the individual commands for more information."
13989 (interactive)
13990 (call-interactively
13991 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13992
13993 (defun org-paste-special (arg)
13994 "Paste rectangular region into table, or past subtree relative to level.
13995 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13996 See the individual commands for more information."
13997 (interactive "P")
13998 (if (org-at-table-p)
13999 (org-table-paste-rectangle)
14000 (org-paste-subtree arg)))
14001
14002 (defun org-ctrl-c-ctrl-c (&optional arg)
14003 "Set tags in headline, or update according to changed information at point.
14004
14005 This command does many different things, depending on context:
14006
14007 - If the cursor is in a headline, prompt for tags and insert them
14008 into the current line, aligned to `org-tags-column'. When called
14009 with prefix arg, realign all tags in the current buffer.
14010
14011 - If the cursor is in one of the special #+KEYWORD lines, this
14012 triggers scanning the buffer for these lines and updating the
14013 information.
14014
14015 - If the cursor is inside a table, realign the table. This command
14016 works even if the automatic table editor has been turned off.
14017
14018 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14019 the entire table.
14020
14021 - If the cursor is inside a table created by the table.el package,
14022 activate that table.
14023
14024 - If the current buffer is a remember buffer, close note and file it.
14025 with a prefix argument, file it without further interaction to the default
14026 location.
14027
14028 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14029 links in this buffer.
14030
14031 - If the cursor is on a numbered item in a plain list, renumber the
14032 ordered list."
14033 (interactive "P")
14034 (let ((org-enable-table-editor t))
14035 (cond
14036 ((and (local-variable-p 'org-finish-function (current-buffer))
14037 (fboundp org-finish-function))
14038 (funcall org-finish-function))
14039 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14040 ((org-on-heading-p) (call-interactively 'org-set-tags))
14041 ((org-at-table.el-p)
14042 (require 'table)
14043 (beginning-of-line 1)
14044 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14045 (call-interactively 'table-recognize-table))
14046 ((org-at-table-p)
14047 (org-table-maybe-eval-formula)
14048 (if arg
14049 (call-interactively 'org-table-recalculate)
14050 (org-table-maybe-recalculate-line))
14051 (call-interactively 'org-table-align))
14052 ((org-at-item-checkbox-p)
14053 (call-interactively 'org-toggle-checkbox))
14054 ((org-at-item-p)
14055 (call-interactively 'org-renumber-ordered-list))
14056 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
14057 (cond
14058 ((equal (match-string 1) "TBLFM")
14059 ;; Recalculate the table before this line
14060 (save-excursion
14061 (beginning-of-line 1)
14062 (skip-chars-backward " \r\n\t")
14063 (if (org-at-table-p)
14064 (org-call-with-arg 'org-table-recalculate t))))
14065 (t
14066 (call-interactively 'org-mode-restart))))
14067 (t (error "C-c C-c can do nothing useful at this location.")))))
14068
14069 (defun org-mode-restart ()
14070 "Restart Org-mode, to scan again for special lines.
14071 Also updates the keyword regular expressions."
14072 (interactive)
14073 (let ((org-inhibit-startup t)) (org-mode))
14074 (message "Org-mode restarted to refresh keyword and special line setup"))
14075
14076 (defun org-return ()
14077 "Goto next table row or insert a newline.
14078 Calls `org-table-next-row' or `newline', depending on context.
14079 See the individual commands for more information."
14080 (interactive)
14081 (cond
14082 ((org-at-table-p)
14083 (org-table-justify-field-maybe)
14084 (call-interactively 'org-table-next-row))
14085 (t (newline))))
14086
14087 (defun org-meta-return (&optional arg)
14088 "Insert a new heading or wrap a region in a table.
14089 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14090 See the individual commands for more information."
14091 (interactive "P")
14092 (cond
14093 ((org-at-table-p)
14094 (call-interactively 'org-table-wrap-region))
14095 (t (call-interactively 'org-insert-heading))))
14096
14097 ;;; Menu entries
14098
14099 ;; Define the Org-mode menus
14100 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
14101 '("Tbl"
14102 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
14103 ["Next Field" org-cycle (org-at-table-p)]
14104 ["Previous Field" org-shifttab (org-at-table-p)]
14105 ["Next Row" org-return (org-at-table-p)]
14106 "--"
14107 ["Blank Field" org-table-blank-field (org-at-table-p)]
14108 ["Edit Field" org-table-edit-field (org-at-table-p)]
14109 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
14110 "--"
14111 ("Column"
14112 ["Move Column Left" org-metaleft (org-at-table-p)]
14113 ["Move Column Right" org-metaright (org-at-table-p)]
14114 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
14115 ["Insert Column" org-shiftmetaright (org-at-table-p)]
14116 "--"
14117 ["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])
14118 ("Row"
14119 ["Move Row Up" org-metaup (org-at-table-p)]
14120 ["Move Row Down" org-metadown (org-at-table-p)]
14121 ["Delete Row" org-shiftmetaup (org-at-table-p)]
14122 ["Insert Row" org-shiftmetadown (org-at-table-p)]
14123 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
14124 "--"
14125 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
14126 ("Rectangle"
14127 ["Copy Rectangle" org-copy-special (org-at-table-p)]
14128 ["Cut Rectangle" org-cut-special (org-at-table-p)]
14129 ["Paste Rectangle" org-paste-special (org-at-table-p)]
14130 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
14131 "--"
14132 ("Calculate"
14133 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
14134 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
14135 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
14136 "--"
14137 ["Recalculate line" org-table-recalculate (org-at-table-p)]
14138 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
14139 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
14140 "--"
14141 ["Sum Column/Rectangle" org-table-sum
14142 (or (org-at-table-p) (org-region-active-p))]
14143 ["Which Column?" org-table-current-column (org-at-table-p)])
14144 ["Debug Formulas"
14145 (setq org-table-formula-debug (not org-table-formula-debug))
14146 :style toggle :selected org-table-formula-debug]
14147 "--"
14148 ["Create" org-table-create (and (not (org-at-table-p))
14149 org-enable-table-editor)]
14150 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
14151 ["Import from File" org-table-import (not (org-at-table-p))]
14152 ["Export to File" org-table-export (org-at-table-p)]
14153 "--"
14154 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
14155
14156 (easy-menu-define org-org-menu org-mode-map "Org menu"
14157 '("Org"
14158 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
14159 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
14160 ["Sparse Tree" org-occur t]
14161 ["Show All" show-all t]
14162 "--"
14163 ["New Heading" org-insert-heading t]
14164 ("Navigate Headings"
14165 ["Up" outline-up-heading t]
14166 ["Next" outline-next-visible-heading t]
14167 ["Previous" outline-previous-visible-heading t]
14168 ["Next Same Level" outline-forward-same-level t]
14169 ["Previous Same Level" outline-backward-same-level t]
14170 "--"
14171 ["Jump" org-goto t])
14172 ("Edit Structure"
14173 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
14174 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
14175 "--"
14176 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
14177 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
14178 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
14179 "--"
14180 ["Promote Heading" org-metaleft (not (org-at-table-p))]
14181 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
14182 ["Demote Heading" org-metaright (not (org-at-table-p))]
14183 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
14184 "--"
14185 ["Archive Subtree" org-archive-subtree t]
14186 "--"
14187 ["Convert to odd levels" org-convert-to-odd-levels t]
14188 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
14189 "--"
14190 ("TODO Lists"
14191 ["TODO/DONE/-" org-todo t]
14192 ["Show TODO Tree" org-show-todo-tree t]
14193 ["Global TODO list" org-todo-list t]
14194 "--"
14195 ["Set Priority" org-priority t]
14196 ["Priority Up" org-shiftup t]
14197 ["Priority Down" org-shiftdown t])
14198 ("Dates and Scheduling"
14199 ["Timestamp" org-time-stamp t]
14200 ["Timestamp (inactive)" org-time-stamp-inactive t]
14201 ("Change Date"
14202 ["1 Day Later" org-timestamp-up-day t]
14203 ["1 Day Earlier" org-timestamp-down-day t]
14204 ["1 ... Later" org-shiftup t]
14205 ["1 ... Earlier" org-shiftdown t])
14206 ["Compute Time Range" org-evaluate-time-range t]
14207 ["Schedule Item" org-schedule t]
14208 ["Deadline" org-deadline t]
14209 "--"
14210 ["Goto Calendar" org-goto-calendar t]
14211 ["Date from Calendar" org-date-from-calendar t])
14212 "--"
14213 ["Agenda Command" org-agenda t]
14214 ("File List for Agenda")
14215 ("Special views current file"
14216 ["TODO Tree" org-show-todo-tree t]
14217 ["Check Deadlines" org-check-deadlines t]
14218 ["Timeline" org-timeline t]
14219 ["Tags Tree" org-tags-sparse-tree t])
14220 "--"
14221 ("Hyperlinks"
14222 ["Store Link (Global)" org-store-link t]
14223 ["Insert Link" org-insert-link t]
14224 ["Follow Link" org-open-at-point t]
14225 "--"
14226 ["Descriptive Links"
14227 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
14228 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
14229 ["Literal Links"
14230 (progn
14231 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
14232 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
14233 "--"
14234 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
14235 (save-excursion (goto-char (point-min))
14236 (re-search-forward "<[a-z]+:" nil t))])
14237 "--"
14238 ("Export"
14239 ["ASCII" org-export-as-ascii t]
14240 ["Export visible part..." org-export-visible t]
14241 ["HTML" org-export-as-html t]
14242 ["HTML and Open" org-export-as-html-and-open t]
14243 ["XOXO" org-export-as-xml t]
14244 "--"
14245 ["iCalendar this file" org-export-icalendar-this-file t]
14246 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
14247 :active t :keys "C-c C-x C-i"]
14248 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
14249 "--"
14250 ["Option Template" org-insert-export-options-template t]
14251 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
14252 ("Publish"
14253 ["Current File" org-publish-current-file t]
14254 ["Current Project" org-publish-current-project t]
14255 ["Project..." org-publish t]
14256 ["All Projects" org-publish-all t])
14257 "--"
14258 ("Documentation"
14259 ["Show Version" org-version t]
14260 ["Info Documentation" org-info t])
14261 ("Customize"
14262 ["Browse Org Group" org-customize t]
14263 "--"
14264 ["Expand This Menu" org-create-customize-menu
14265 (fboundp 'customize-menu-create)])
14266 "--"
14267 ["Refresh setup" org-mode-restart t]
14268 ))
14269
14270 (defun org-info (&optional node)
14271 "Read documentation for Org-mode in the info system.
14272 With optional NODE, go directly to that node."
14273 (interactive)
14274 (require 'info)
14275 (Info-goto-node (format "(org)%s" (or node ""))))
14276
14277 (defun org-install-agenda-files-menu ()
14278 (let ((bl (buffer-list)))
14279 (save-excursion
14280 (while bl
14281 (set-buffer (pop bl))
14282 (if (eq major-mode 'org-mode) (setq bl nil)))
14283 (when (eq major-mode 'org-mode)
14284 (easy-menu-change
14285 '("Org") "File List for Agenda"
14286 (append
14287 (list
14288 ["Edit File List" (org-edit-agenda-file-list) t]
14289 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
14290 ["Remove Current File from List" org-remove-file t]
14291 ["Cycle through agenda files" org-cycle-agenda-files t]
14292 "--")
14293 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
14294
14295 ;;; Documentation
14296
14297 (defun org-customize ()
14298 "Call the customize function with org as argument."
14299 (interactive)
14300 (customize-browse 'org))
14301
14302 (defun org-create-customize-menu ()
14303 "Create a full customization menu for Org-mode, insert it into the menu."
14304 (interactive)
14305 (if (fboundp 'customize-menu-create)
14306 (progn
14307 (easy-menu-change
14308 '("Org") "Customize"
14309 `(["Browse Org group" org-customize t]
14310 "--"
14311 ,(customize-menu-create 'org)
14312 ["Set" Custom-set t]
14313 ["Save" Custom-save t]
14314 ["Reset to Current" Custom-reset-current t]
14315 ["Reset to Saved" Custom-reset-saved t]
14316 ["Reset to Standard Settings" Custom-reset-standard t]))
14317 (message "\"Org\"-menu now contains full customization menu"))
14318 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14319
14320 ;;; Miscellaneous stuff
14321
14322 (defun org-move-line-down (arg)
14323 "Move the current line down. With prefix argument, move it past ARG lines."
14324 (interactive "p")
14325 (let ((col (current-column))
14326 beg end pos)
14327 (beginning-of-line 1) (setq beg (point))
14328 (beginning-of-line 2) (setq end (point))
14329 (beginning-of-line (+ 1 arg))
14330 (setq pos (move-marker (make-marker) (point)))
14331 (insert (delete-and-extract-region beg end))
14332 (goto-char pos)
14333 (move-to-column col)))
14334
14335 (defun org-move-line-up (arg)
14336 "Move the current line up. With prefix argument, move it past ARG lines."
14337 (interactive "p")
14338 (let ((col (current-column))
14339 beg end pos)
14340 (beginning-of-line 1) (setq beg (point))
14341 (beginning-of-line 2) (setq end (point))
14342 (beginning-of-line (- arg))
14343 (setq pos (move-marker (make-marker) (point)))
14344 (insert (delete-and-extract-region beg end))
14345 (goto-char pos)
14346 (move-to-column col)))
14347
14348 ;; Paragraph filling stuff.
14349 ;; We want this to be just right, so use the full arsenal.
14350 ;; FIXME: This very likely does not work correctly for XEmacs, because the
14351 ;; filladapt package works slightly differently.
14352
14353 (defun org-set-autofill-regexps ()
14354 (interactive)
14355 ;; In the paragraph separator we include headlines, because filling
14356 ;; text in a line directly attached to a headline would otherwise
14357 ;; fill the headline as well.
14358 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
14359 ;; The paragraph starter includes hand-formatted lists.
14360 (set (make-local-variable 'paragraph-start)
14361 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14362 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14363 ;; But only if the user has not turned off tables or fixed-width regions
14364 (set (make-local-variable 'auto-fill-inhibit-regexp)
14365 (concat "\\*\\|#"
14366 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14367 (concat
14368 "\\|[ \t]*["
14369 (if org-enable-table-editor "|" "")
14370 (if org-enable-fixed-width-editor ":" "")
14371 "]"))))
14372 ;; We use our own fill-paragraph function, to make sure that tables
14373 ;; and fixed-width regions are not wrapped. That function will pass
14374 ;; through to `fill-paragraph' when appropriate.
14375 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
14376 ;; Adaptive filling: To get full control, first make sure that
14377 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14378 (set (make-local-variable 'adaptive-fill-regexp) "\000")
14379 (set (make-local-variable 'adaptive-fill-function)
14380 'org-adaptive-fill-function))
14381
14382 (defun org-fill-paragraph (&optional justify)
14383 "Re-align a table, pass through to fill-paragraph if no table."
14384 (let ((table-p (org-at-table-p))
14385 (table.el-p (org-at-table.el-p)))
14386 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
14387 (table.el-p t) ; skip table.el tables
14388 (table-p (org-table-align) t) ; align org-mode tables
14389 (t nil)))) ; call paragraph-fill
14390
14391 ;; For reference, this is the default value of adaptive-fill-regexp
14392 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14393
14394 (defun org-adaptive-fill-function ()
14395 "Return a fill prefix for org-mode files.
14396 In particular, this makes sure hanging paragraphs for hand-formatted lists
14397 work correctly."
14398 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
14399 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
14400
14401 ;; Functions needed for Emacs/XEmacs region compatibility
14402
14403 (defun org-add-hook (hook function &optional append local)
14404 "Add-hook, compatible with both Emacsen."
14405 (if (and local (featurep 'xemacs))
14406 (add-local-hook hook function append)
14407 (add-hook hook function append local)))
14408
14409 (defun org-region-active-p ()
14410 "Is `transient-mark-mode' on and the region active?
14411 Works on both Emacs and XEmacs."
14412 (if org-ignore-region
14413 nil
14414 (if (featurep 'xemacs)
14415 (and zmacs-regions (region-active-p))
14416 (and transient-mark-mode mark-active))))
14417
14418 (defun org-add-to-invisibility-spec (arg)
14419 "Add elements to `buffer-invisibility-spec'.
14420 See documentation for `buffer-invisibility-spec' for the kind of elements
14421 that can be added."
14422 (cond
14423 ((fboundp 'add-to-invisibility-spec)
14424 (add-to-invisibility-spec arg))
14425 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
14426 (setq buffer-invisibility-spec (list arg)))
14427 (t
14428 (setq buffer-invisibility-spec
14429 (cons arg buffer-invisibility-spec)))))
14430
14431 (defun org-remove-from-invisibility-spec (arg)
14432 "Remove elements from `buffer-invisibility-spec'."
14433 (if (fboundp 'remove-from-invisibility-spec)
14434 (remove-from-invisibility-spec arg)
14435 (if (consp buffer-invisibility-spec)
14436 (setq buffer-invisibility-spec
14437 (delete arg buffer-invisibility-spec)))))
14438
14439 (defun org-in-invisibility-spec-p (arg)
14440 "Is ARG a member of `buffer-invisibility-spec'?"
14441 (if (consp buffer-invisibility-spec)
14442 (member arg buffer-invisibility-spec)
14443 nil))
14444
14445 (defun org-image-file-name-regexp ()
14446 "Return regexp matching the file names of images."
14447 (if (fboundp 'image-file-name-regexp)
14448 (image-file-name-regexp)
14449 (let ((image-file-name-extensions
14450 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14451 "xbm" "xpm" "pbm" "pgm" "ppm")))
14452 (concat "\\."
14453 (regexp-opt (nconc (mapcar 'upcase
14454 image-file-name-extensions)
14455 image-file-name-extensions)
14456 t)
14457 "\\'"))))
14458
14459 ;; Functions needed for compatibility with old outline.el.
14460
14461 ;; Programming for the old outline.el (that uses selective display
14462 ;; instead of `invisible' text properties) is a nightmare, mostly
14463 ;; because regular expressions can no longer be anchored at
14464 ;; beginning/end of line. Therefore a number of function need special
14465 ;; treatment when the old outline.el is being used.
14466
14467 ;; The following functions capture almost the entire compatibility code
14468 ;; between the different versions of outline-mode. The only other
14469 ;; places where this is important are the font-lock-keywords, and in
14470 ;; `org-export-visible'. Search for `org-noutline-p' to find them.
14471
14472 ;; C-a should go to the beginning of a *visible* line, also in the
14473 ;; new outline.el. I guess this should be patched into Emacs?
14474 (defun org-beginning-of-line ()
14475 "Go to the beginning of the current line. If that is invisible, continue
14476 to a visible line beginning. This makes the function of C-a more intuitive."
14477 (interactive)
14478 (beginning-of-line 1)
14479 (if (bobp)
14480 nil
14481 (backward-char 1)
14482 (if (org-invisible-p)
14483 (while (and (not (bobp)) (org-invisible-p))
14484 (backward-char 1)
14485 (beginning-of-line 1))
14486 (forward-char 1))))
14487
14488 (when org-noutline-p
14489 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
14490 ;; FIXME: should I use substitute-key-definition to reach other bindings
14491 ;; of beginning-of-line?
14492
14493 (defun org-invisible-p ()
14494 "Check if point is at a character currently not visible."
14495 (if org-noutline-p
14496 ;; Early versions of noutline don't have `outline-invisible-p'.
14497 (if (fboundp 'outline-invisible-p)
14498 (outline-invisible-p)
14499 (get-char-property (point) 'invisible))
14500 (save-excursion
14501 (skip-chars-backward "^\r\n")
14502 (equal (char-before) ?\r))))
14503
14504 (defun org-invisible-p2 ()
14505 "Check if point is at a character currently not visible."
14506 (save-excursion
14507 (if org-noutline-p
14508 (progn
14509 (if (and (eolp) (not (bobp))) (backward-char 1))
14510 ;; Early versions of noutline don't have `outline-invisible-p'.
14511 (if (fboundp 'outline-invisible-p)
14512 (outline-invisible-p)
14513 (get-char-property (point) 'invisible)))
14514 (skip-chars-backward "^\r\n")
14515 (equal (char-before) ?\r))))
14516
14517 (defun org-back-to-heading (&optional invisible-ok)
14518 "Move to previous heading line, or beg of this line if it's a heading.
14519 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
14520 (if org-noutline-p
14521 (outline-back-to-heading invisible-ok)
14522 (if (and (or (bobp) (memq (char-before) '(?\n ?\r)))
14523 (looking-at outline-regexp))
14524 t
14525 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
14526 outline-regexp)
14527 nil t)
14528 (if invisible-ok
14529 (progn (goto-char (or (match-end 1) (match-beginning 0)))
14530 (looking-at outline-regexp)))
14531 (error "Before first heading")))))
14532
14533 (defun org-on-heading-p (&optional invisible-ok)
14534 "Return t if point is on a (visible) heading line.
14535 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
14536 (if org-noutline-p
14537 (outline-on-heading-p 'invisible-ok)
14538 (save-excursion
14539 (skip-chars-backward "^\n\r")
14540 (and (looking-at outline-regexp)
14541 (or invisible-ok
14542 (bobp)
14543 (equal (char-before) ?\n))))))
14544
14545 (defun org-on-target-p ()
14546 (let ((pos (point)))
14547 (save-excursion
14548 (skip-chars-forward "<")
14549 (and (re-search-backward "<<" nil t)
14550 (or (looking-at org-radio-target-regexp)
14551 (looking-at org-target-regexp))
14552 (<= (match-beginning 0) pos)
14553 (>= (1+ (match-end 0)) pos)))))
14554
14555 (defun org-up-heading-all (arg)
14556 "Move to the heading line of which the present line is a subheading.
14557 This function considers both visible and invisible heading lines.
14558 With argument, move up ARG levels."
14559 (if org-noutline-p
14560 (if (fboundp 'outline-up-heading-all)
14561 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14562 (outline-up-heading arg t)) ; emacs 22 version of outline.el
14563 (org-back-to-heading t)
14564 (looking-at outline-regexp)
14565 (if (<= (- (match-end 0) (match-beginning 0)) arg)
14566 (error "Cannot move up %d levels" arg)
14567 (re-search-backward
14568 (concat "[\n\r]" (regexp-quote
14569 (make-string (- (match-end 0) (match-beginning 0) arg)
14570 ?*))
14571 "[^*]"))
14572 (forward-char 1))))
14573
14574 (defun org-show-hidden-entry ()
14575 "Show an entry where even the heading is hidden."
14576 (save-excursion
14577 (if (not org-noutline-p)
14578 (progn
14579 (org-back-to-heading t)
14580 (org-flag-heading nil)))
14581 (org-show-entry)))
14582
14583 (defun org-check-occur-regexp (regexp)
14584 "If REGEXP starts with \"^\", modify it to check for \\r as well.
14585 Of course, only for the old outline mode."
14586 (if org-noutline-p
14587 regexp
14588 (if (string-match "^\\^" regexp)
14589 (concat "[\n\r]" (substring regexp 1))
14590 regexp)))
14591
14592 (defun org-flag-heading (flag &optional entry)
14593 "Flag the current heading. FLAG non-nil means make invisible.
14594 When ENTRY is non-nil, show the entire entry."
14595 (save-excursion
14596 (org-back-to-heading t)
14597 (if (not org-noutline-p)
14598 ;; Make the current headline visible
14599 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
14600 ;; Check if we should show the entire entry
14601 (if entry
14602 (progn
14603 (org-show-entry)
14604 (save-excursion
14605 (and (outline-next-heading)
14606 (org-flag-heading nil))))
14607 (outline-flag-region (max 1 (1- (point)))
14608 (save-excursion (outline-end-of-heading) (point))
14609 (if org-noutline-p
14610 flag
14611 (if flag ?\r ?\n))))))
14612
14613 (defun org-end-of-subtree (&optional invisible-OK)
14614 ;; This is an exact copy of the original function, but it uses
14615 ;; `org-back-to-heading', to make it work also in invisible
14616 ;; trees. And is uses an invisible-OK argument.
14617 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14618 (org-back-to-heading invisible-OK)
14619 (let ((first t)
14620 (level (funcall outline-level)))
14621 (while (and (not (eobp))
14622 (or first (> (funcall outline-level) level)))
14623 (setq first nil)
14624 (outline-next-heading))
14625 (if (memq (preceding-char) '(?\n ?\^M))
14626 (progn
14627 ;; Go to end of line before heading
14628 (forward-char -1)
14629 (if (memq (preceding-char) '(?\n ?\^M))
14630 ;; leave blank line before heading
14631 (forward-char -1))))))
14632
14633 (defun org-show-subtree ()
14634 "Show everything after this heading at deeper levels."
14635 (outline-flag-region
14636 (point)
14637 (save-excursion
14638 (outline-end-of-subtree) (outline-next-heading) (point))
14639 (if org-noutline-p nil ?\n)))
14640
14641 (defun org-show-entry ()
14642 "Show the body directly following this heading.
14643 Show the heading too, if it is currently invisible."
14644 (interactive)
14645 (save-excursion
14646 (org-back-to-heading t)
14647 (outline-flag-region
14648 (max 1 (1- (point)))
14649 (save-excursion
14650 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14651 (or (match-beginning 1) (point-max)))
14652 (if org-noutline-p nil ?\n))))
14653
14654 (defun org-make-options-regexp (kwds)
14655 "Make a regular expression for keyword lines."
14656 (concat
14657 (if org-noutline-p "^" "[\n\r]")
14658 "#?[ \t]*\\+\\("
14659 (mapconcat 'regexp-quote kwds "\\|")
14660 "\\):[ \t]*"
14661 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
14662
14663 ;; Make `bookmark-jump' show the jump location if it was hidden.
14664 (eval-after-load "bookmark"
14665 '(if (boundp 'bookmark-after-jump-hook)
14666 ;; We can use the hook
14667 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14668 ;; Hook not available, use advice
14669 (defadvice bookmark-jump (after org-make-visible activate)
14670 "Make the position visible."
14671 (org-bookmark-jump-unhide))))
14672
14673 (defun org-bookmark-jump-unhide ()
14674 "Unhide the current position, to show the bookmark location."
14675 (and (eq major-mode 'org-mode)
14676 (or (org-invisible-p)
14677 (save-excursion (goto-char (max (point-min) (1- (point))))
14678 (org-invisible-p)))
14679 (org-show-hierarchy-above)))
14680
14681 ;;; Finish up
14682
14683 (provide 'org)
14684
14685 (run-hooks 'org-load-hook)
14686
14687
14688 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14689 ;;; org.el ends here