]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
(org-read-date, org-goto-calendar, org-agenda-goto-calendar): Bind
[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.26
9 ;;
10 ;; This file is part of GNU Emacs.
11 ;;
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;
28 ;;; Commentary:
29 ;;
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
32 ;;
33 ;; Org-mode develops organizational tasks around a NOTES file that contains
34 ;; information about projects as plain text. Org-mode is implemented on top
35 ;; of outline-mode - ideal to keep the content of large files well structured.
36 ;; It supports ToDo items, deadlines and time stamps, which can be extracted
37 ;; to create a daily/weekly agenda that also integrates the diary of the Emacs
38 ;; calendar. Tables are easily created with a built-in table editor. Plain
39 ;; text URL-like links connect to websites, emails (VM, RMAIL, WANDERLUST),
40 ;; Usenet messages (Gnus), BBDB entries, and any files related to the
41 ;; projects. For printing and sharing of notes, an Org-mode file (or a part
42 ;; of it) can be exported as a structured ASCII file, or as HTML.
43 ;;
44 ;; Installation
45 ;; ------------
46 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
47 ;; only need to copy the following lines to your .emacs file. The last two
48 ;; lines define *global* keys for the commands `org-store-link' and
49 ;; `org-agenda' - please choose suitable keys yourself.
50 ;;
51 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
52 ;; (define-key global-map "\C-cl" 'org-store-link)
53 ;; (define-key global-map "\C-ca" 'org-agenda)
54 ;;
55 ;; If you have downloaded Org-mode from the Web, you must byte-compile
56 ;; org.el and put it on your load path. In addition to the Emacs Lisp
57 ;; lines above, you also need to add the following lines to .emacs:
58 ;;
59 ;; (autoload 'org-mode "org" "Org mode" t)
60 ;; (autoload 'org-diary "org" "Diary entries from Org mode")
61 ;; (autoload 'org-agenda "org" "Multi-file agenda from Org mode" t)
62 ;; (autoload 'org-store-link "org" "Store a link to the current location" t)
63 ;; (autoload 'orgtbl-mode "org" "Org tables as a minor mode" t)
64 ;; (autoload 'turn-on-orgtbl "org" "Org tables as a minor mode")
65 ;;
66 ;; This setup will put all files with extension ".org" into Org-mode. As
67 ;; an alternative, make the first line of a file look like this:
68 ;;
69 ;; MY PROJECTS -*- mode: org; -*-
70 ;;
71 ;; which will select Org-mode for this buffer no matter what the file's
72 ;; name is.
73 ;;
74 ;; Documentation
75 ;; -------------
76 ;; The documentation of Org-mode can be found in the TeXInfo file. The
77 ;; distribution also contains a PDF version of it. At the homepage of
78 ;; Org-mode, you can read the same text online as HTML. There is also an
79 ;; excellent reference card made by Philip Rooke. This card can be found
80 ;; in the etc/ directory of Emacs 22.
81 ;;
82 ;; Changes since version 4.10:
83 ;; ---------------------------
84 ;; Version 4.26
85 ;; - Bug fixes.
86 ;;
87 ;; Version 4.25
88 ;; - Revision of the font-lock faces section, with better tty support.
89 ;; - TODO keywords in Agenda buffer are fontified.
90 ;; - Export converts links between .org files to links between .html files.
91 ;; - Better support for bold/italic/underline emphasis.
92 ;;
93 ;; Version 4.24
94 ;; - Bug fixes.
95 ;;
96 ;; Version 4.23
97 ;; - Bug fixes.
98 ;;
99 ;; Version 4.22
100 ;; - Bug fixes.
101 ;; - In agenda buffer, mouse-1 no longer follows link.
102 ;; See `org-agenda-mouse-1-follows-link' and `org-mouse-1-follows-link'.
103 ;;
104 ;; Version 4.20
105 ;; - Links use now the [[link][description]] format by default.
106 ;; When inserting links, the user is prompted for a description.
107 ;; - If a link has a description, only the description is displayed
108 ;; the link part is hidden. Use C-c C-l to edit the link part.
109 ;; - TAGS are now bold, but in the same color as the headline.
110 ;; - The width of a table column can be limited by using a field "<N>".
111 ;; - New structure for the customization tree.
112 ;; - Bug fixes.
113 ;;
114 ;; Version 4.13
115 ;; - The list of agenda files can be maintainted in an external file.
116 ;; - Bug fixes.
117 ;;
118 ;; Version 4.12
119 ;; - Templates for remember buffer. Note that the remember setup changes.
120 ;; To set up templates, see `org-remember-templates'.
121 ;; - The time in new time stamps can be rounded, see new option
122 ;; `org-time-stamp-rounding-minutes'.
123 ;; - Bug fixes (there are *always* more bugs).
124 ;;
125 ;;; Code:
126
127 (eval-when-compile
128 (require 'cl)
129 (require 'calendar))
130 (require 'outline)
131 (require 'time-date)
132 (require 'easymenu)
133
134 (defvar calc-embedded-close-formula) ; defined by the calc package
135 (defvar calc-embedded-open-formula) ; defined by the calc package
136 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
137
138 ;;; Customization variables
139
140 (defvar org-version "4.26"
141 "The version number of the file org.el.")
142 (defun org-version ()
143 (interactive)
144 (message "Org-mode version %s" org-version))
145
146 ;; The following constant is for compatibility with different versions
147 ;; of outline.el.
148 (defconst org-noutline-p (featurep 'noutline)
149 "Are we using the new outline mode?")
150 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
151 (defconst org-format-transports-properties-p
152 (let ((x "a"))
153 (add-text-properties 0 1 '(test t) x)
154 (get-text-property 0 'test (format "%s" x)))
155 "Does format transport text properties?")
156
157 (defgroup org nil
158 "Outline-based notes management and organizer."
159 :tag "Org"
160 :group 'outlines
161 :group 'hypermedia
162 :group 'calendar)
163
164 (defgroup org-startup nil
165 "Options concerning startup of Org-mode."
166 :tag "Org Startup"
167 :group 'org)
168
169 (defcustom org-startup-folded t
170 "Non-nil means, entering Org-mode will switch to OVERVIEW.
171 This can also be configured on a per-file basis by adding one of
172 the following lines anywhere in the buffer:
173
174 #+STARTUP: fold
175 #+STARTUP: nofold
176 #+STARTUP: content"
177 :group 'org-startup
178 :type '(choice
179 (const :tag "nofold: show all" nil)
180 (const :tag "fold: overview" t)
181 (const :tag "content: all headlines" content)))
182
183 (defcustom org-startup-truncated t
184 "Non-nil means, entering Org-mode will set `truncate-lines'.
185 This is useful since some lines containing links can be very long and
186 uninteresting. Also tables look terrible when wrapped."
187 :group 'org-startup
188 :type 'boolean)
189
190 (defcustom org-startup-align-all-tables nil
191 "Non-nil means, align all tables when visiting a file.
192 This is useful when the column width in tables is forced with <N> cookies
193 in table fields. Such tables will look correct only after the first re-align.
194 This can also be configured on a per-file basis by adding one of
195 the following lines anywhere in the buffer:
196 #+STARTUP: align
197 #+STARTUP: noalign"
198 :group 'org-startup
199 :type 'boolean)
200
201 (defcustom org-startup-with-deadline-check nil
202 "Non-nil means, entering Org-mode will run the deadline check.
203 This means, if you start editing an org file, you will get an
204 immediate reminder of any due deadlines.
205 This can also be configured on a per-file basis by adding one of
206 the following lines anywhere in the buffer:
207 #+STARTUP: dlcheck
208 #+STARTUP: nodlcheck"
209 :group 'org-startup
210 :type 'boolean)
211
212 (defcustom org-insert-mode-line-in-empty-file nil
213 "Non-nil means insert the first line setting Org-mode in empty files.
214 When the function `org-mode' is called interactively in an empty file, this
215 normally means that the file name does not automatically trigger Org-mode.
216 To ensure that the file will always be in Org-mode in the future, a
217 line enforcing Org-mode will be inserted into the buffer, if this option
218 has been set."
219 :group 'org-startup
220 :type 'boolean)
221
222 (defcustom org-CUA-compatible nil
223 "Non-nil means use alternative key bindings for S-<cursor movement>.
224 Org-mode used S-<cursor movement> for changing timestamps and priorities.
225 S-<cursor movement> is also used for example by `CUA-mode' to select text.
226 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
227 alternative bindings. Setting this variable to t will replace the following
228 keys both in Org-mode and in the Org-agenda buffer.
229
230 S-RET -> C-S-RET
231 S-up -> M-p
232 S-down -> M-n
233 S-left -> M--
234 S-right -> M-+
235
236 If you do not like the alternative keys, take a look at the variable
237 `org-disputed-keys'.
238
239 This option is only relevant at load-time of Org-mode. Changing it requires
240 a restart of Emacs to become effective."
241 :group 'org-startup
242 :type 'boolean)
243
244 (defvar org-disputed-keys
245 '((S-up [(shift up)] [(meta ?p)])
246 (S-down [(shift down)] [(meta ?n)])
247 (S-left [(shift left)] [(meta ?-)])
248 (S-right [(shift right)] [(meta ?+)])
249 (S-return [(shift return)] [(control shift return)]))
250 "Keys for which Org-mode and other modes compete.
251 This is an alist, cars are symbols for lookup, 1st element is the default key,
252 second element will be used when `org-CUA-compatible' is t.")
253
254 (defun org-key (key)
255 "Select a key according to `org-CUA-compatible'."
256 (nth (if org-CUA-compatible 2 1)
257 (or (assq key org-disputed-keys)
258 (error "Invalid Key %s in `org-key'" key))))
259
260 (defcustom org-ellipsis nil
261 "The ellipsis to use in the Org-mode outline.
262 When nil, just use the standard three dots. When a string, use that instead,
263 and just in Org-mode (which will then use its own display table).
264 Changing this requires executing `M-x org-mode' in a buffer to become
265 effective."
266 :group 'org-startup
267 :type '(choice (const :tag "Default" nil)
268 (string :tag "String" :value "...#")))
269
270 (defvar org-display-table nil
271 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
272
273 (defgroup org-keywords nil
274 "Keywords in Org-mode."
275 :tag "Org Keywords"
276 :group 'org)
277
278 (defcustom org-deadline-string "DEADLINE:"
279 "String to mark deadline entries.
280 A deadline is this string, followed by a time stamp. Should be a word,
281 terminated by a colon. You can insert a schedule keyword and
282 a timestamp with \\[org-deadline].
283 Changes become only effective after restarting Emacs."
284 :group 'org-keywords
285 :type 'string)
286
287 (defcustom org-scheduled-string "SCHEDULED:"
288 "String to mark scheduled TODO entries.
289 A schedule is this string, followed by a time stamp. Should be a word,
290 terminated by a colon. You can insert a schedule keyword and
291 a timestamp with \\[org-schedule].
292 Changes become only effective after restarting Emacs."
293 :group 'org-keywords
294 :type 'string)
295
296 (defcustom org-closed-string "CLOSED:"
297 "String used as the prefix for timestamps logging closing a TODO entry."
298 :group 'org-keywords
299 :type 'string)
300
301 (defcustom org-comment-string "COMMENT"
302 "Entries starting with this keyword will never be exported.
303 An entry can be toggled between COMMENT and normal with
304 \\[org-toggle-comment].
305 Changes become only effective after restarting Emacs."
306 :group 'org-keywords
307 :type 'string)
308
309 (defcustom org-quote-string "QUOTE"
310 "Entries starting with this keyword will be exported in fixed-width font.
311 Quoting applies only to the text in the entry following the headline, and does
312 not extend beyond the next headline, even if that is lower level.
313 An entry can be toggled between QUOTE and normal with
314 \\[org-toggle-fixed-width-section]."
315 :group 'org-keywords
316 :type 'string)
317
318 (defgroup org-structure nil
319 "Options concerning the general structure of Org-mode files."
320 :tag "Org Structure"
321 :group 'org)
322
323 (defgroup org-cycle nil
324 "Options concerning visibility cycling in Org-mode."
325 :tag "Org Cycle"
326 :group 'org-structure)
327
328 (defcustom org-cycle-emulate-tab t
329 "Where should `org-cycle' emulate TAB.
330 nil Never
331 white Only in completely white lines
332 t Everywhere except in headlines"
333 :group 'org-cycle
334 :type '(choice (const :tag "Never" nil)
335 (const :tag "Only in completely white lines" white)
336 (const :tag "Everywhere except in headlines" t)
337 ))
338
339 (defcustom org-cycle-hook '(org-optimize-window-after-visibility-change)
340 "Hook that is run after `org-cycle' has changed the buffer visibility.
341 The function(s) in this hook must accept a single argument which indicates
342 the new state that was set by the most recent `org-cycle' command. The
343 argument is a symbol. After a global state change, it can have the values
344 `overview', `content', or `all'. After a local state change, it can have
345 the values `folded', `children', or `subtree'."
346 :group 'org-cycle
347 :type 'hook)
348
349 (defgroup org-edit-structure nil
350 "Options concerning structure editing in Org-mode."
351 :tag "Org Edit Structure"
352 :group 'org-structure)
353
354 (defcustom org-odd-levels-only nil
355 "Non-nil means, skip even levels and only use odd levels for the outline.
356 This has the effect that two stars are being added/taken away in
357 promotion/demotion commands. It also influences how levels are
358 handled by the exporters.
359 Changing it requires restart of `font-lock-mode' to become effective
360 for fontification also in regions already fontified.
361 You may also set this on a per-file basis by adding one of the following
362 lines to the buffer:
363
364 #+STARTUP: odd
365 #+STARTUP: oddeven"
366 :group 'org-edit-structure
367 :group 'org-font-lock
368 :type 'boolean)
369
370 (defcustom org-adapt-indentation t
371 "Non-nil means, adapt indentation when promoting and demoting.
372 When this is set and the *entire* text in an entry is indented, the
373 indentation is increased by one space in a demotion command, and
374 decreased by one in a promotion command. If any line in the entry
375 body starts at column 0, indentation is not changed at all."
376 :group 'org-edit-structure
377 :type 'boolean)
378
379 (defcustom org-enable-fixed-width-editor t
380 "Non-nil means, lines starting with \":\" are treated as fixed-width.
381 This currently only means, they are never auto-wrapped.
382 When nil, such lines will be treated like ordinary lines.
383 See also the QUOTE keyword."
384 :group 'org-edit-structure
385 :type 'boolean)
386
387 (defgroup org-sparse-trees nil
388 "Options concerning sparse trees in Org-mode."
389 :tag "Org Sparse Trees"
390 :group 'org-structure)
391
392 (defcustom org-highlight-sparse-tree-matches t
393 "Non-nil means, highlight all matches that define a sparse tree.
394 The highlights will automatically disappear the next time the buffer is
395 changed by an edit command."
396 :group 'org-sparse-trees
397 :type 'boolean)
398
399 (defcustom org-show-hierarchy-above t
400 "Non-nil means, show full hierarchy when showing a spot in the tree.
401 Turning this off makes sparse trees more compact, but also less clear."
402 :group 'org-sparse-trees
403 :type 'boolean)
404
405 (defcustom org-show-following-heading t
406 "Non-nil means, show heading following match in `org-occur'.
407 When doing an `org-occur' it is useful to show the headline which
408 follows the match, even if they do not match the regexp. This makes it
409 easier to edit directly inside the sparse tree. However, if you use
410 `org-occur' mainly as an overview, the following headlines are
411 unnecessary clutter."
412 :group 'org-sparse-trees
413 :type 'boolean)
414
415 (defcustom org-occur-hook '(org-first-headline-recenter)
416 "Hook that is run after `org-occur' has constructed a sparse tree.
417 This can be used to recenter the window to show as much of the structure
418 as possible."
419 :group 'org-sparse-trees
420 :type 'hook)
421
422 (defgroup org-plain-lists nil
423 "Options concerning plain lists in Org-mode."
424 :tag "Org Plain lists"
425 :group 'org-structure)
426
427 (defcustom org-cycle-include-plain-lists nil
428 "Non-nil means, include plain lists into visibility cycling.
429 This means that during cycling, plain list items will *temporarily* be
430 interpreted as outline headlines with a level given by 1000+i where i is the
431 indentation of the bullet. In all other operations, plain list items are
432 not seen as headlines. For example, you cannot assign a TODO keyword to
433 such an item."
434 :group 'org-plain-lists
435 :type 'boolean)
436
437
438 (defcustom org-plain-list-ordered-item-terminator t
439 "The character that makes a line with leading number an ordered list item.
440 Valid values are ?. and ?\). To get both terminators, use t. While
441 ?. may look nicer, it creates the danger that a line with leading
442 number may be incorrectly interpreted as an item. ?\) therefore is
443 the safe choice."
444 :group 'org-plain-lists
445 :type '(choice (const :tag "dot like in \"2.\"" ?.)
446 (const :tag "paren like in \"2)\"" ?\))
447 (const :tab "both" t)))
448
449 (defcustom org-auto-renumber-ordered-lists t
450 "Non-nil means, automatically renumber ordered plain lists.
451 Renumbering happens when the sequence have been changed with
452 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
453 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
454 :group 'org-plain-lists
455 :type 'boolean)
456
457 (defgroup org-archive nil
458 "Options concerning archiving in Org-mode."
459 :tag "Org Archive"
460 :group 'org-structure)
461
462 (defcustom org-archive-location "%s_archive::"
463 "The location where subtrees should be archived.
464 This string consists of two parts, separated by a double-colon.
465
466 The first part is a file name - when omitted, archiving happens in the same
467 file. %s will be replaced by the current file name (without directory part).
468 Archiving to a different file is useful to keep archived entries from
469 contributing to the Org-mode Agenda.
470
471 The part after the double colon is a headline. The archived entries will be
472 filed under that headline. When omitted, the subtrees are simply filed away
473 at the end of the file, as top-level entries.
474
475 Here are a few examples:
476 \"%s_archive::\"
477 If the current file is Projects.org, archive in file
478 Projects.org_archive, as top-level trees. This is the default.
479
480 \"::* Archived Tasks\"
481 Archive in the current file, under the top-level headline
482 \"* Archived Tasks\".
483
484 \"~/org/archive.org::\"
485 Archive in file ~/org/archive.org (absolute path), as top-level trees.
486
487 \"basement::** Finished Tasks\"
488 Archive in file ./basement (relative path), as level 3 trees
489 below the level 2 heading \"** Finished Tasks\".
490
491 You may set this option on a per-file basis by adding to the buffer a
492 line like
493
494 #+ARCHIVE: basement::** Finished Tasks"
495 :group 'org-archive
496 :type 'string)
497
498 (defcustom org-archive-mark-done t
499 "Non-nil means, mark archived entries as DONE."
500 :group 'org-archive
501 :type 'boolean)
502
503 (defcustom org-archive-stamp-time t
504 "Non-nil means, add a time stamp to archived entries.
505 The time stamp will be added directly after the TODO state keyword in the
506 first line, so it is probably best to use this in combinations with
507 `org-archive-mark-done'."
508 :group 'org-archive
509 :type 'boolean)
510
511 (defgroup org-table nil
512 "Options concerning tables in Org-mode."
513 :tag "Org Table"
514 :group 'org)
515
516 (defcustom org-enable-table-editor 'optimized
517 "Non-nil means, lines starting with \"|\" are handled by the table editor.
518 When nil, such lines will be treated like ordinary lines.
519
520 When equal to the symbol `optimized', the table editor will be optimized to
521 do the following:
522 - Use automatic overwrite mode in front of whitespace in table fields.
523 This make the structure of the table stay in tact as long as the edited
524 field does not exceed the column width.
525 - Minimize the number of realigns. Normally, the table is aligned each time
526 TAB or RET are pressed to move to another field. With optimization this
527 happens only if changes to a field might have changed the column width.
528 Optimization requires replacing the functions `self-insert-command',
529 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
530 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
531 very good at guessing when a re-align will be necessary, but you can always
532 force one with \\[org-ctrl-c-ctrl-c].
533
534 If you would like to use the optimized version in Org-mode, but the
535 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
536
537 This variable can be used to turn on and off the table editor during a session,
538 but in order to toggle optimization, a restart is required.
539
540 See also the variable `org-table-auto-blank-field'."
541 :group 'org-table
542 :type '(choice
543 (const :tag "off" nil)
544 (const :tag "on" t)
545 (const :tag "on, optimized" optimized)))
546
547 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
548 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
549 In the optimized version, the table editor takes over all simple keys that
550 normally just insert a character. In tables, the characters are inserted
551 in a way to minimize disturbing the table structure (i.e. in overwrite mode
552 for empty fields). Outside tables, the correct binding of the keys is
553 restored.
554
555 The default for this option is t if the optimized version is also used in
556 Org-mode. See the variable `org-enable-table-editor' for details. Changing
557 this variable requires a restart of Emacs to become effective."
558 :group 'org-table
559 :type 'boolean)
560
561 (defgroup org-table-settings nil
562 "Settings for tables in Org-mode."
563 :tag "Org Table Settings"
564 :group 'org-table)
565
566 (defcustom org-table-default-size "5x2"
567 "The default size for newly created tables, Columns x Rows."
568 :group 'org-table-settings
569 :type 'string)
570
571 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
572 "Regular expression for recognizing numbers in table columns.
573 If a table column contains mostly numbers, it will be aligned to the
574 right. If not, it will be aligned to the left.
575
576 The default value of this option is a regular expression which allows
577 anything which looks remotely like a number as used in scientific
578 context. For example, all of the following will be considered a
579 number:
580 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
581
582 Other options offered by the customize interface are more restrictive."
583 :group 'org-table-settings
584 :type '(choice
585 (const :tag "Positive Integers"
586 "^[0-9]+$")
587 (const :tag "Integers"
588 "^[-+]?[0-9]+$")
589 (const :tag "Floating Point Numbers"
590 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
591 (const :tag "Floating Point Number or Integer"
592 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
593 (const :tag "Exponential, Floating point, Integer"
594 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
595 (const :tag "Very General Number-Like"
596 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
597 (string :tag "Regexp:")))
598
599 (defcustom org-table-number-fraction 0.5
600 "Fraction of numbers in a column required to make the column align right.
601 In a column all non-white fields are considered. If at least this
602 fraction of fields is matched by `org-table-number-fraction',
603 alignment to the right border applies."
604 :group 'org-table-settings
605 :type 'number)
606
607 (defgroup org-table-editing nil
608 "Bahavior of tables during editing in Org-mode."
609 :tag "Org Table Editing"
610 :group 'org-table)
611
612 (defcustom org-table-automatic-realign t
613 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
614 When nil, aligning is only done with \\[org-table-align], or after column
615 removal/insertion."
616 :group 'org-table-editing
617 :type 'boolean)
618
619 (defcustom org-table-limit-column-width t ;kw
620 "Non-nil means, allow to limit the width of table columns with <N> fields."
621 :group 'org-table-editing
622 :type 'boolean)
623
624 (defcustom org-table-auto-blank-field t
625 "Non-nil means, automatically blank table field when starting to type into it.
626 This only happens when typing immediately after a field motion
627 command (TAB, S-TAB or RET).
628 Only relevant when `org-enable-table-editor' is equal to `optimized'."
629 :group 'org-table-editing
630 :type 'boolean)
631
632 (defcustom org-table-tab-jumps-over-hlines t
633 "Non-nil means, tab in the last column of a table with jump over a hline.
634 If a horizontal separator line is following the current line,
635 `org-table-next-field' can either create a new row before that line, or jump
636 over the line. When this option is nil, a new line will be created before
637 this line."
638 :group 'org-table-editing
639 :type 'boolean)
640
641 (defcustom org-table-tab-recognizes-table.el t
642 "Non-nil means, TAB will automatically notice a table.el table.
643 When it sees such a table, it moves point into it and - if necessary -
644 calls `table-recognize-table'."
645 :group 'org-table-editing
646 :type 'boolean)
647
648 (defgroup org-table-calculation nil
649 "Options concerning tables in Org-mode."
650 :tag "Org Table Calculation"
651 :group 'org-table)
652
653 (defcustom org-table-copy-increment t
654 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
655 :group 'org-table-calculation
656 :type 'boolean)
657
658 (defcustom org-calc-default-modes
659 '(calc-internal-prec 12
660 calc-float-format (float 5)
661 calc-angle-mode deg
662 calc-prefer-frac nil
663 calc-symbolic-mode nil
664 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
665 calc-display-working-message t
666 )
667 "List with Calc mode settings for use in calc-eval for table formulas.
668 The list must contain alternating symbols (Calc modes variables and values).
669 Don't remove any of the default settings, just change the values. Org-mode
670 relies on the variables to be present in the list."
671 :group 'org-table-calculation
672 :type 'plist)
673
674 (defcustom org-table-formula-evaluate-inline t
675 "Non-nil means, TAB and RET evaluate a formula in current table field.
676 If the current field starts with an equal sign, it is assumed to be a formula
677 which should be evaluated as described in the manual and in the documentation
678 string of the command `org-table-eval-formula'. This feature requires the
679 Emacs calc package.
680 When this variable is nil, formula calculation is only available through
681 the command \\[org-table-eval-formula]."
682 :group 'org-table-calculation
683 :type 'boolean)
684
685
686 (defcustom org-table-formula-use-constants t
687 "Non-nil means, interpret constants in formulas in tables.
688 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
689 by the value given in `org-table-formula-constants', or by a value obtained
690 from the `constants.el' package."
691 :group 'org-table-calculation
692 :type 'boolean)
693
694 (defcustom org-table-formula-constants nil
695 "Alist with constant names and values, for use in table formulas.
696 The car of each element is a name of a constant, without the `$' before it.
697 The cdr is the value as a string. For example, if you'd like to use the
698 speed of light in a formula, you would configure
699
700 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
701
702 and then use it in an equation like `$1*$c'."
703 :group 'org-table-calculation
704 :type '(repeat
705 (cons (string :tag "name")
706 (string :tag "value"))))
707
708 (defcustom org-table-formula-numbers-only nil
709 "Non-nil means, calculate only with numbers in table formulas.
710 Then all input fields will be converted to a number, and the result
711 must also be a number. When nil, calc's full potential is available
712 in table calculations, including symbolics etc."
713 :group 'org-table-calculation
714 :type 'boolean)
715
716 (defcustom org-table-allow-automatic-line-recalculation t
717 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
718 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
719 :group 'org-table-calculation
720 :type 'boolean)
721
722 (defgroup org-link nil
723 "Options concerning links in Org-mode."
724 :tag "Org Link"
725 :group 'org)
726
727 (defcustom org-descriptive-links t
728 "Non-nil means, hide link part and only show description of bracket links.
729 Bracket links are like [[link][descritpion]]. This variable sets the initial
730 state in new org-mode buffers. The setting can then be toggled on a
731 per-buffer basis from the Org->Hyperlinks menu."
732 :group 'org-link
733 :type 'boolean)
734
735 (defcustom org-link-style 'bracket
736 "The style of links to be inserted with \\[org-insert-link].
737 Possible values are:
738 bracket [[link][description]]. This is recommended
739 plain Description \\n link. The old way, no longer recommended."
740 :group 'org-link
741 :type '(choice
742 (const :tag "Bracket (recommended)" bracket)
743 (const :tag "Plain (no longer recommended)" plain)))
744
745 (defcustom org-link-format "%s"
746 "Default format for external, URL-like linkes in the buffer.
747 This is a format string for printf, %s will be replaced by the link text.
748 The recommended value is just \"%s\", since links will be protected by
749 enclosing them in double brackets. If you prefer plain links (see variable
750 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
751 additional URL: prefix, so the format would be \"<URL:%s>\"."
752 :group 'org-link
753 :type '(choice
754 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
755 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
756 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
757 (string :tag "Other" :value "<%s>")))
758
759 (defcustom org-activate-links '(bracket angle plain radio tag date)
760 "Types of links that should be activated in Org-mode files.
761 This is a list of symbols, each leading to the activation of a certain link
762 type. In principle, it does not hurt to turn on most link types - there may
763 be a small gain when turning off unused link types. The types are:
764
765 bracket The recommended [[link][description]] or [[link]] links with hiding.
766 angular Links in angular brackes that may contain whitespace like
767 <bbdb:Carsten Dominik>.
768 plain Plain links in normal text, no whitespace, like http://google.com.
769 radio Text that is matched by a radio target, see manual for details.
770 tag Tag settings in a headline (link to tag search).
771 date Time stamps (link to calendar).
772 camel CamelCase words defining text searches.
773
774 Changing this variable requires a restart of Emacs to become effective."
775 :group 'org-link
776 :type '(set (const :tag "Double bracket links (new style)" bracket)
777 (const :tag "Angular bracket links (old style)" angular)
778 (const :tag "plain text links" plain)
779 (const :tag "Radio target matches" radio)
780 (const :tag "Tags" tag)
781 (const :tag "Timestamps" date)
782 (const :tag "CamelCase words" camel)))
783
784 (defgroup org-link-store nil
785 "Options concerning storing links in Org-mode"
786 :tag "Org Store Link"
787 :group 'org-link)
788
789 (defcustom org-context-in-file-links t
790 "Non-nil means, file links from `org-store-link' contain context.
791 A search string will be added to the file name with :: as separator and
792 used to find the context when the link is activated by the command
793 `org-open-at-point'.
794 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
795 negates this setting for the duration of the command."
796 :group 'org-link-store
797 :type 'boolean)
798
799 (defcustom org-file-link-context-use-camel-case nil
800 "Non-nil means, use CamelCase to store a search context in a file link.
801 When nil, the search string simply consists of the words of the string.
802 CamelCase is deprecated, and support for it may be dropped in the future."
803 :group 'org-link-store
804 :type 'boolean)
805
806 (defcustom org-keep-stored-link-after-insertion nil
807 "Non-nil means, keep link in list for entire session.
808
809 The command `org-store-link' adds a link pointing to the current
810 location to an internal list. These links accumulate during a session.
811 The command `org-insert-link' can be used to insert links into any
812 Org-mode file (offering completion for all stored links). When this
813 option is nil, every link which has been inserted once using \\[org-insert-link]
814 will be removed from the list, to make completing the unused links
815 more efficient."
816 :group 'org-link-store
817 :type 'boolean)
818
819 (defcustom org-usenet-links-prefer-google nil
820 "Non-nil means, `org-store-link' will create web links to Google groups.
821 When nil, Gnus will be used for such links.
822 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
823 negates this setting for the duration of the command."
824 :group 'org-link-store
825 :type 'boolean)
826
827 (defgroup org-link-follow nil
828 "Options concerning following links in Org-mode"
829 :tag "Org Follow Link"
830 :group 'org-link)
831
832 (defcustom org-tab-follows-link nil
833 "Non-nil means, on links TAB will follow the link.
834 Needs to be set before org.el is loaded."
835 :group 'org-link-follow
836 :type 'boolean)
837
838 (defcustom org-return-follows-link nil
839 "Non-nil means, on links RET will follow the link.
840 Needs to be set before org.el is loaded."
841 :group 'org-link-follow
842 :type 'boolean)
843
844 (defcustom org-mouse-1-follows-link t
845 "Non-nil means, mouse-1 on a link will follow the link.
846 A longer mouse click will still set point. Does not wortk on XEmacs.
847 Needs to be set before org.el is loaded."
848 :group 'org-link-follow
849 :type 'boolean)
850
851 (defcustom org-mark-ring-length 4
852 "Number of different positions to be recorded in the ring
853 Changing this requires a restart of Emacs to work correctly."
854 :group 'org-link-follow
855 :type 'interger)
856
857 (defcustom org-link-frame-setup
858 '((vm . vm-visit-folder-other-frame)
859 (gnus . gnus-other-frame)
860 (file . find-file-other-window))
861 "Setup the frame configuration for following links.
862 When following a link with Emacs, it may often be useful to display
863 this link in another window or frame. This variable can be used to
864 set this up for the different types of links.
865 For VM, use any of
866 `vm-visit-folder'
867 `vm-visit-folder-other-frame'
868 For Gnus, use any of
869 `gnus'
870 `gnus-other-frame'
871 For FILE, use any of
872 `find-file'
873 `find-file-other-window'
874 `find-file-other-frame'
875 For the calendar, use the variable `calendar-setup'.
876 For BBDB, it is currently only possible to display the matches in
877 another window."
878 :group 'org-link-follow
879 :type '(list
880 (cons (const vm)
881 (choice
882 (const vm-visit-folder)
883 (const vm-visit-folder-other-window)
884 (const vm-visit-folder-other-frame)))
885 (cons (const gnus)
886 (choice
887 (const gnus)
888 (const gnus-other-frame)))
889 (cons (const file)
890 (choice
891 (const find-file)
892 (const find-file-other-window)
893 (const find-file-other-frame)))))
894
895 (defcustom org-open-non-existing-files nil
896 "Non-nil means, `org-open-file' will open non-existing file.
897 When nil, an error will be generated."
898 :group 'org-link-follow
899 :type 'boolean)
900
901 (defcustom org-confirm-shell-links 'yes-or-no-p
902 "Non-nil means, ask for confirmation before executing shell links.
903 Shell links can be dangerous, just thing about a link
904
905 [[shell:rm -rf ~/*][Google Search]]
906
907 This link would show up in your Org-mode document as \"Google Search\"
908 but really it would remove your entire home directory. Dangerous indeed.
909 Therefore I *definitely* advise agains setting this varaiable to nil.
910 Just change it to `y-or-n-p' of you want to confirm with a single key press
911 rather than having to type \"yes\"."
912 :group 'org-link-follow
913 :type '(choice
914 (const :tag "with yes-or-no (safer)" yes-or-no-p)
915 (const :tag "with y-or-n (faster)" y-or-n-p)
916 (const :tag "no confirmation (dangerous)" nil)))
917
918 (defconst org-file-apps-defaults-gnu
919 '((t . mailcap))
920 "Default file applications on a UNIX or GNU/Linux system.
921 See `org-file-apps'.")
922
923 (defconst org-file-apps-defaults-macosx
924 '((t . "open %s")
925 ("ps" . "gv %s")
926 ("ps.gz" . "gv %s")
927 ("eps" . "gv %s")
928 ("eps.gz" . "gv %s")
929 ("dvi" . "xdvi %s")
930 ("fig" . "xfig %s"))
931 "Default file applications on a MacOS X system.
932 The system \"open\" is known as a default, but we use X11 applications
933 for some files for which the OS does not have a good default.
934 See `org-file-apps'.")
935
936 (defconst org-file-apps-defaults-windowsnt
937 '((t . (w32-shell-execute "open" file)))
938 "Default file applications on a Windows NT system.
939 The system \"open\" is used for most files.
940 See `org-file-apps'.")
941
942 (defcustom org-file-apps
943 '(
944 ("txt" . emacs)
945 ("tex" . emacs)
946 ("ltx" . emacs)
947 ("org" . emacs)
948 ("el" . emacs)
949 )
950 "External applications for opening `file:path' items in a document.
951 Org-mode uses system defaults for different file types, but
952 you can use this variable to set the application for a given file
953 extension. The entries in this list are cons cells with a file extension
954 and the corresponding command. Possible values for the command are:
955 `emacs' The file will be visited by the current Emacs process.
956 `default' Use the default application for this file type.
957 string A command to be executed by a shell; %s will be replaced
958 by the path to the file.
959 sexp A Lisp form which will be evaluated. The file path will
960 be available in the Lisp variable `file'.
961 For more examples, see the system specific constants
962 `org-file-apps-defaults-macosx'
963 `org-file-apps-defaults-windowsnt'
964 `org-file-apps-defaults-gnu'."
965 :group 'org-link-follow
966 :type '(repeat
967 (cons (choice :value ""
968 (string :tag "Extension")
969 (const :tag "Default for unrecognized files" t)
970 (const :tag "Links to a directory" directory))
971 (choice :value ""
972 (const :tag "Visit with Emacs" emacs)
973 (const :tag "Use system default" default)
974 (string :tag "Command")
975 (sexp :tag "Lisp form")))))
976
977 (defcustom org-mhe-search-all-folders nil
978 "Non-nil means, that the search for the mh-message will be extended to
979 all folders if the message cannot be found in the folder given in the link.
980 Searching all folders is very effective with one of the search engines
981 supported by MH-E, but will be slow with pick."
982 :group 'org-link-follow
983 :type 'boolean)
984
985 (defgroup org-remember nil
986 "Options concerning interaction with remember.el."
987 :tag "Org Remember"
988 :group 'org)
989
990 (defcustom org-directory "~/org"
991 "Directory with org files.
992 This directory will be used as default to prompt for org files.
993 Used by the hooks for remember.el."
994 :group 'org-remember
995 :type 'directory)
996
997 (defcustom org-default-notes-file "~/.notes"
998 "Default target for storing notes.
999 Used by the hooks for remember.el. This can be a string, or nil to mean
1000 the value of `remember-data-file'."
1001 :group 'org-remember
1002 :type '(choice
1003 (const :tag "Default from remember-data-file" nil)
1004 file))
1005
1006 (defcustom org-remember-templates nil
1007 "Templates for the creation of remember buffers.
1008 When nil, just let remember make the buffer.
1009 When not nil, this is a list of 3-element lists. In each entry, the first
1010 element is a character, a unique key to select this template.
1011 The second element is the template. The third element is optional and can
1012 specify a destination file for remember items created with this template.
1013 The default file is given by `org-default-notes-file'.
1014
1015 The template specifies the structure of the remember buffer. It should have
1016 a first line starting with a star, to act as the org-mode headline.
1017 Furthermore, the following %-escapes will be replaced with content:
1018 %t time stamp, date only
1019 %T time stamp with date and time
1020 %u inactive time stamp, date only
1021 %U inactive time stamp with date and time
1022 %n user name
1023 %a annotation, normally the link created with org-store-link
1024 %i initial content, the region when remember is called with C-u.
1025 If %i is indented, the entire inserted text will be indented as well.
1026 %? This will be removed, and the cursor placed at this position."
1027 :group 'org-remember
1028 :type '(repeat :tag "enabled"
1029 (list :value (?a "\n" nil)
1030 (character :tag "Selection Key")
1031 (string :tag "Template")
1032 (file :tag "Destination file (optional)"))))
1033
1034 (defcustom org-reverse-note-order nil
1035 "Non-nil means, store new notes at the beginning of a file or entry.
1036 When nil, new notes will be filed to the end of a file or entry."
1037 :group 'org-remember
1038 :type '(choice
1039 (const :tag "Reverse always" t)
1040 (const :tag "Reverse never" nil)
1041 (repeat :tag "By file name regexp"
1042 (cons regexp boolean))))
1043
1044 (defgroup org-todo nil
1045 "Options concerning TODO items in Org-mode."
1046 :tag "Org TODO"
1047 :group 'org)
1048
1049 (defcustom org-todo-keywords '("TODO" "DONE")
1050 "List of TODO entry keywords.
1051 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1052 considered to mean that the entry is \"done\". All the other mean that
1053 action is required, and will make the entry show up in todo lists, diaries
1054 etc.
1055 The command \\[org-todo] cycles an entry through these states, and an
1056 additional state where no keyword is present. For details about this
1057 cycling, see also the variable `org-todo-interpretation'
1058 Changes become only effective after restarting Emacs."
1059 :group 'org-todo
1060 :group 'org-keywords
1061 :type '(repeat (string :tag "Keyword")))
1062
1063 (defcustom org-todo-interpretation 'sequence
1064 "Controls how TODO keywords are interpreted.
1065 This variable is only relevant if `org-todo-keywords' contains more than two
1066 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1067
1068 When `sequence', \\[org-todo] will always switch to the next state in the
1069 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1070 to state when executed several times in direct succession. Otherwise, it
1071 switches directly to DONE from any state.
1072 See the manual for more information."
1073 :group 'org-todo
1074 :group 'org-keywords
1075 :type '(choice (const sequence)
1076 (const type)))
1077
1078 (defcustom org-after-todo-state-change-hook nil
1079 "Hook which is run after the state of a TODO item was changed.
1080 The new state (a string with a TODO keyword, or nil) is available in the
1081 Lisp variable `state'."
1082 :group 'org-todo
1083 :type 'hook)
1084
1085 (defcustom org-log-done nil
1086 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1087 When the state of an entry is changed from nothing to TODO, remove a previous
1088 closing date."
1089 :group 'org-todo
1090 :type 'boolean)
1091
1092 (defgroup org-priorities nil
1093 "Priorities in Org-mode."
1094 :tag "Org Priorities"
1095 :group 'org-todo)
1096
1097 (defcustom org-default-priority ?B
1098 "The default priority of TODO items.
1099 This is the priority an item get if no explicit priority is given."
1100 :group 'org-priorities
1101 :type 'character)
1102
1103 (defcustom org-lowest-priority ?C
1104 "The lowest priority of TODO items. A character like ?A, ?B etc."
1105 :group 'org-priorities
1106 :type 'character)
1107
1108 (defgroup org-time nil
1109 "Options concerning time stamps and deadlines in Org-mode."
1110 :tag "Org Time"
1111 :group 'org)
1112
1113 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1114 "Formats for `format-time-string' which are used for time stamps.
1115 It is not recommended to change this constant.")
1116
1117 (defcustom org-time-stamp-rounding-minutes 0
1118 "Number of minutes to round time stamps to upon insertion.
1119 When zero, insert the time unmodified. Useful rounding numbers
1120 should be factors of 60, so for example 5, 10, 15.
1121 When this is not zero, you can still force an exact time-stamp by using
1122 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1123 :group 'org-time
1124 :type 'integer)
1125
1126 (defcustom org-deadline-warning-days 30
1127 "No. of days before expiration during which a deadline becomes active.
1128 This variable governs the display in the org file."
1129 :group 'org-time
1130 :type 'number)
1131
1132 (defcustom org-popup-calendar-for-date-prompt t
1133 "Non-nil means, pop up a calendar when prompting for a date.
1134 In the calendar, the date can be selected with mouse-1. However, the
1135 minibuffer will also be active, and you can simply enter the date as well.
1136 When nil, only the minibuffer will be available."
1137 :group 'org-time
1138 :type 'boolean)
1139
1140 (defcustom org-calendar-follow-timestamp-change t
1141 "Non-nil means, make the calendar window follow timestamp changes.
1142 When a timestamp is modified and the calendar window is visible, it will be
1143 moved to the new date."
1144 :group 'org-time
1145 :type 'boolean)
1146
1147 (defgroup org-tags nil
1148 "Options concerning tags in Org-mode."
1149 :tag "Org Tags"
1150 :group 'org)
1151
1152 (defcustom org-tags-column 48
1153 "The column to which tags should be indented in a headline.
1154 If this number is positive, it specifies the column. If it is negative,
1155 it means that the tags should be flushright to that column. For example,
1156 -79 works well for a normal 80 character screen."
1157 :group 'org-tags
1158 :type 'integer)
1159
1160 (defcustom org-auto-align-tags t
1161 "Non-nil means, realign tags after pro/demotion of TODO state change.
1162 These operations change the length of a headline and therefore shift
1163 the tags around. With this options turned on, after each such operation
1164 the tags are again aligned to `org-tags-column'."
1165 :group 'org-tags
1166 :type 'boolean)
1167
1168 (defcustom org-use-tag-inheritance t
1169 "Non-nil means, tags in levels apply also for sublevels.
1170 When nil, only the tags directly given in a specific line apply there.
1171 If you turn off this option, you very likely want to turn on the
1172 companion option `org-tags-match-list-sublevels'."
1173 :group 'org-tags
1174 :type 'boolean)
1175
1176 (defcustom org-tags-match-list-sublevels nil
1177 "Non-nil means list also sublevels of headlines matching tag search.
1178 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1179 the sublevels of a headline matching a tag search often also match
1180 the same search. Listing all of them can create very long lists.
1181 Setting this variable to nil causes subtrees of a match to be skipped.
1182 This option is off by default, because inheritance in on. If you turn
1183 inheritance off, you very likely want to turn this option on.
1184
1185 As a special case, if the tag search is restricted to TODO items, the
1186 value of this variable is ignored and sublevels are always checked, to
1187 make sure all corresponding TODO items find their way into the list."
1188 :group 'org-tags
1189 :type 'boolean)
1190
1191 (defvar org-tags-history nil
1192 "History of minibuffer reads for tags.")
1193 (defvar org-last-tags-completion-table nil
1194 "The last used completion table for tags.")
1195
1196 (defgroup org-agenda nil
1197 "Options concerning agenda display Org-mode."
1198 :tag "Org Agenda"
1199 :group 'org)
1200
1201 (defvar org-category nil
1202 "Variable used by org files to set a category for agenda display.
1203 Such files should use a file variable to set it, for example
1204
1205 -*- mode: org; org-category: \"ELisp\"
1206
1207 or contain a special line
1208
1209 #+CATEGORY: ELisp
1210
1211 If the file does not specify a category, then file's base name
1212 is used instead.")
1213 (make-variable-buffer-local 'org-category)
1214
1215 (defcustom org-agenda-files nil
1216 "The files to be used for agenda display.
1217 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1218 \\[org-remove-file]. You can also use customize to edit the list.
1219
1220 If the value of the variable is not a list but a single file name, then
1221 the list of agenda files is actually stored and maintained in that file, one
1222 agenda file per line."
1223 :group 'org-agenda
1224 :type '(choice
1225 (repeat :tag "List of files" file)
1226 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1227
1228 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1229 "Custom commands for the agenda.
1230 These commands will be offered on the splash screen displayed by the
1231 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1232
1233 key The key (a single char as a string) to be associated with the command.
1234 type The command type, any of the following symbols:
1235 todo Entries with a specific TODO keyword, in all agenda files.
1236 tags Tags match in all agenda files.
1237 todo-tree Sparse tree of specific TODO keyword in *current* file.
1238 tags-tree Sparse tree with all tags matches in *current* file.
1239 occur-tree Occur sparse tree for current file.
1240 match What to search for:
1241 - a single keyword for TODO keyword searches
1242 - a tags match expression for tags searches
1243 - a regular expression for occur searches"
1244 :group 'org-agenda
1245 :type '(repeat
1246 (list (string :tag "Key")
1247 (choice :tag "Type"
1248 (const :tag "Tags search in all agenda files" tags)
1249 (const :tag "TODO keyword search in all agenda files" todo)
1250 (const :tag "Tags sparse tree in current buffer" tags-tree)
1251 (const :tag "TODO keyword tree in current buffer" todo-tree)
1252 (const :tag "Occur tree in current buffer" occur-tree))
1253 (string :tag "Match"))))
1254
1255 (defcustom org-agenda-include-all-todo t
1256 "Non-nil means, the agenda will always contain all TODO entries.
1257 When nil, date-less entries will only be shown if `org-agenda' is called
1258 with a prefix argument.
1259 When non-nil, the TODO entries will be listed at the top of the agenda, before
1260 the entries for specific days."
1261 :group 'org-agenda
1262 :type 'boolean)
1263
1264 (defcustom org-agenda-include-diary nil
1265 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1266 :group 'org-agenda
1267 :type 'boolean)
1268
1269 (defcustom org-calendar-to-agenda-key [?c]
1270 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1271 The command `org-calendar-goto-agenda' will be bound to this key. The
1272 default is the character `c' because then `c' can be used to switch back and
1273 forth between agenda and calendar."
1274 :group 'org-agenda
1275 :type 'sexp)
1276
1277 (defgroup org-agenda-window-setup nil
1278 "Options concerning setting up the Agenda window in Org Mode."
1279 :tag "Org Agenda Window Setup"
1280 :group 'org-agenda)
1281
1282 (defcustom org-agenda-mouse-1-follows-link nil
1283 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1284 A longer mouse click will still set point. Does not wortk on XEmacs.
1285 Needs to be set before org.el is loaded."
1286 :group 'org-agenda-setup
1287 :type 'boolean)
1288
1289 (defcustom org-select-timeline-window t
1290 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1291 When nil, cursor will remain in the current window."
1292 :group 'org-agenda-setup
1293 :type 'boolean)
1294
1295 (defcustom org-select-agenda-window t
1296 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1297 When nil, cursor will remain in the current window."
1298 :group 'org-agenda-setup
1299 :type 'boolean)
1300
1301 (defcustom org-fit-agenda-window t
1302 "Non-nil means, change window size of agenda to fit content."
1303 :group 'org-agenda-setup
1304 :type 'boolean)
1305
1306 (defgroup org-agenda-display nil
1307 "Options concerning what to display initially in Agenda."
1308 :tag "Org Agenda Display"
1309 :group 'org-agenda)
1310
1311 (defcustom org-agenda-show-all-dates t
1312 "Non-nil means, `org-agenda' shows every day in the selected range.
1313 When nil, only the days which actually have entries are shown."
1314 :group 'org-agenda-display
1315 :type 'boolean)
1316
1317 (defcustom org-agenda-start-on-weekday 1
1318 "Non-nil means, start the overview always on the specified weekday.
1319 0 denotes Sunday, 1 denotes Monday etc.
1320 When nil, always start on the current day."
1321 :group 'org-agenda-display
1322 :type '(choice (const :tag "Today" nil)
1323 (number :tag "Weekday No.")))
1324
1325 (defcustom org-agenda-ndays 7
1326 "Number of days to include in overview display.
1327 Should be 1 or 7."
1328 :group 'org-agenda-display
1329 :type 'number)
1330
1331 (defcustom org-agenda-use-time-grid t
1332 "Non-nil means, show a time grid in the agenda schedule.
1333 A time grid is a set of lines for specific times (like every two hours between
1334 8:00 and 20:00). The items scheduled for a day at specific times are
1335 sorted in between these lines.
1336 For details about when the grid will be shown, and what it will look like, see
1337 the variable `org-agenda-time-grid'."
1338 :group 'org-agenda-display
1339 :type 'boolean)
1340
1341 (defcustom org-agenda-time-grid
1342 '((daily today require-timed)
1343 "----------------"
1344 (800 1000 1200 1400 1600 1800 2000))
1345
1346 "The settings for time grid for agenda display.
1347 This is a list of three items. The first item is again a list. It contains
1348 symbols specifying conditions when the grid should be displayed:
1349
1350 daily if the agenda shows a single day
1351 weekly if the agenda shows an entire week
1352 today show grid on current date, independent of daily/weekly display
1353 require-timed show grid only if at least on item has a time specification
1354
1355 The second item is a string which will be places behing the grid time.
1356
1357 The third item is a list of integers, indicating the times that should have
1358 a grid line."
1359 :group 'org-agenda-display
1360 :type
1361 '(list
1362 (set :greedy t :tag "Grid Display Options"
1363 (const :tag "Show grid in single day agenda display" daily)
1364 (const :tag "Show grid in weekly agenda display" weekly)
1365 (const :tag "Always show grid for today" today)
1366 (const :tag "Show grid only if any timed entries are present"
1367 require-timed)
1368 (const :tag "Skip grid times already present in an entry"
1369 remove-match))
1370 (string :tag "Grid String")
1371 (repeat :tag "Grid Times" (integer :tag "Time"))))
1372
1373 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1374 "Sorting structure for the agenda items of a single day.
1375 This is a list of symbols which will be used in sequence to determine
1376 if an entry should be listed before another entry. The following
1377 symbols are recognized:
1378
1379 time-up Put entries with time-of-day indications first, early first
1380 time-down Put entries with time-of-day indications first, late first
1381 category-keep Keep the default order of categories, corresponding to the
1382 sequence in `org-agenda-files'.
1383 category-up Sort alphabetically by category, A-Z.
1384 category-down Sort alphabetically by category, Z-A.
1385 priority-up Sort numerically by priority, high priority last.
1386 priority-down Sort numerically by priority, high priority first.
1387
1388 The different possibilities will be tried in sequence, and testing stops
1389 if one comparison returns a \"not-equal\". For example, the default
1390 '(time-up category-keep priority-down)
1391 means: Pull out all entries having a specified time of day and sort them,
1392 in order to make a time schedule for the current day the first thing in the
1393 agenda listing for the day. Of the entries without a time indication, keep
1394 the grouped in categories, don't sort the categories, but keep them in
1395 the sequence given in `org-agenda-files'. Within each category sort by
1396 priority.
1397
1398 Leaving out `category-keep' would mean that items will be sorted across
1399 categories by priority."
1400 :group 'org-agenda-display
1401 :type '(repeat
1402 (choice
1403 (const time-up)
1404 (const time-down)
1405 (const category-keep)
1406 (const category-up)
1407 (const category-down)
1408 (const priority-up)
1409 (const priority-down))))
1410
1411 (defcustom org-sort-agenda-notime-is-late t
1412 "Non-nil means, items without time are considered late.
1413 This is only relevant for sorting. When t, items which have no explicit
1414 time like 15:30 will be considered as 24:01, i.e. later than any items which
1415 do have a time. When nil, the default time is before 0:00. You can use this
1416 option to decide if the schedule for today should come before or after timeless
1417 agenda entries."
1418 :group 'org-agenda-display
1419 :type 'boolean)
1420
1421
1422 (defgroup org-agenda-prefix nil
1423 "Options concerning the entry prefix in the Org-mode agenda display."
1424 :tag "Org Agenda Prefix"
1425 :group 'org-agenda)
1426
1427 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1428 "Format specification for the prefix of items in the agenda buffer.
1429 This format works similar to a printf format, with the following meaning:
1430
1431 %c the category of the item, \"Diary\" for entries from the diary, or
1432 as given by the CATEGORY keyword or derived from the file name.
1433 %T the first tag of the item.
1434 %t the time-of-day specification if one applies to the entry, in the
1435 format HH:MM
1436 %s Scheduling/Deadline information, a short string
1437
1438 All specifiers work basically like the standard `%s' of printf, but may
1439 contain two additional characters: A question mark just after the `%' and
1440 a whitespace/punctuation character just before the final letter.
1441
1442 If the first character after `%' is a question mark, the entire field
1443 will only be included if the corresponding value applies to the
1444 current entry. This is useful for fields which should have fixed
1445 width when present, but zero width when absent. For example,
1446 \"%?-12t\" will result in a 12 character time field if a time of the
1447 day is specified, but will completely disappear in entries which do
1448 not contain a time.
1449
1450 If there is punctuation or whitespace character just before the final
1451 format letter, this character will be appended to the field value if
1452 the value is not empty. For example, the format \"%-12:c\" leads to
1453 \"Diary: \" if the category is \"Diary\". If the category were be
1454 empty, no additional colon would be interted.
1455
1456 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1457 - Indent the line with two space characters
1458 - Give the category in a 12 chars wide field, padded with whitespace on
1459 the right (because of `-'). Append a colon if there is a category
1460 (because of `:').
1461 - If there is a time-of-day, put it into a 12 chars wide field. If no
1462 time, don't put in an empty field, just skip it (because of '?').
1463 - Finally, put the scheduling information and append a whitespace.
1464
1465 As another example, if you don't want the time-of-day of entries in
1466 the prefix, you could use:
1467
1468 (setq org-agenda-prefix-format \" %-11:c% s\")
1469
1470 See also the variables `org-agenda-remove-times-when-in-prefix' and
1471 `org-agenda-remove-tags-when-in-prefix'."
1472 :type 'string
1473 :group 'org-agenda-prefix)
1474
1475 (defcustom org-timeline-prefix-format " % s"
1476 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1477 :type 'string
1478 :group 'org-agenda-prefix)
1479
1480 (defvar org-prefix-format-compiled nil
1481 "The compiled version of the most recently used prefix format.
1482 Depending on which command was used last, this may be the compiled version
1483 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1484
1485 ;; FIXME: There seem to be situations where this does no work.
1486 (defcustom org-agenda-remove-times-when-in-prefix t
1487 "Non-nil means, remove duplicate time specifications in agenda items.
1488 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1489 time-of-day specification in a headline or diary entry is extracted and
1490 placed into the prefix. If this option is non-nil, the original specification
1491 \(a timestamp or -range, or just a plain time(range) specification like
1492 11:30-4pm) will be removed for agenda display. This makes the agenda less
1493 cluttered.
1494 The option can be t or nil. It may also be the symbol `beg', indicating
1495 that the time should only be removed what it is located at the beginning of
1496 the headline/diary entry."
1497 :group 'org-agenda-prefix
1498 :type '(choice
1499 (const :tag "Always" t)
1500 (const :tag "Never" nil)
1501 (const :tag "When at beginning of entry" beg)))
1502
1503 (defcustom org-agenda-remove-tags-when-in-prefix nil
1504 "Non-nil means, remove the tags from the headline copy in the agenda.
1505 When this is the symbol `prefix', only remove tags when
1506 `org-agenda-prefix-format' contains a `%T' specifier."
1507 :group 'org-agenda-prefix
1508 :type '(choice
1509 (const :tag "Always" t)
1510 (const :tag "Never" nil)
1511 (const :tag "When prefix format contains %T" prefix)))
1512
1513 (defgroup org-export nil
1514 "Options for exporting org-listings."
1515 :tag "Org Export"
1516 :group 'org)
1517
1518 (defgroup org-export-general nil
1519 "General options for exporting Org-mode files."
1520 :tag "Org Export General"
1521 :group 'org-export)
1522
1523 (defcustom org-export-language-setup
1524 '(("en" "Author" "Date" "Table of Contents")
1525 ("da" "Ophavsmand" "Dato" "Indhold")
1526 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1527 ("es" "Autor" "Fecha" "\xccndice")
1528 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1529 ("it" "Autore" "Data" "Indice")
1530 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1531 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1532 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1533 "Terms used in export text, translated to different languages.
1534 Use the variable `org-export-default-language' to set the language,
1535 or use the +OPTION lines for a per-file setting."
1536 :group 'org-export-general
1537 :type '(repeat
1538 (list
1539 (string :tag "HTML language tag")
1540 (string :tag "Author")
1541 (string :tag "Date")
1542 (string :tag "Table of Contents"))))
1543
1544 (defcustom org-export-default-language "en"
1545 "The default language of HTML export, as a string.
1546 This should have an association in `org-export-language-setup'."
1547 :group 'org-export-general
1548 :type 'string)
1549
1550 (defcustom org-export-headline-levels 3
1551 "The last level which is still exported as a headline.
1552 Inferior levels will produce itemize lists when exported.
1553 Note that a numeric prefix argument to an exporter function overrides
1554 this setting.
1555
1556 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1557 :group 'org-export-general
1558 :type 'number)
1559
1560 (defcustom org-export-with-section-numbers t
1561 "Non-nil means, add section numbers to headlines when exporting.
1562
1563 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1564 :group 'org-export-general
1565 :type 'boolean)
1566
1567 (defcustom org-export-with-toc t
1568 "Non-nil means, create a table of contents in exported files.
1569 The TOC contains headlines with levels up to`org-export-headline-levels'.
1570
1571 Headlines which contain any TODO items will be marked with \"(*)\" in
1572 ASCII export, and with red color in HTML output.
1573
1574 In HTML output, the TOC will be clickable.
1575
1576 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1577 :group 'org-export-general
1578 :type 'boolean)
1579
1580 (defcustom org-export-mark-todo-in-toc nil
1581 "Non-nil means, mark TOC lines that contain any open TODO items."
1582 :group 'org-export-general
1583 :type 'boolean)
1584
1585 (defcustom org-export-preserve-breaks nil
1586 "Non-nil means, preserve all line breaks when exporting.
1587 Normally, in HTML output paragraphs will be reformatted. In ASCII
1588 export, line breaks will always be preserved, regardless of this variable.
1589
1590 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1591 :group 'org-export-general
1592 :type 'boolean)
1593
1594 (defgroup org-export-translation nil
1595 "Options for translating special ascii sequences for the export backends."
1596 :tag "Org Export Translation"
1597 :group 'org-export)
1598
1599 (defcustom org-export-with-emphasize t
1600 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1601 If the export target supports emphasizing text, the word will be
1602 typeset in bold, italic, or underlined, respectively. Works only for
1603 single words, but you can say: I *really* *mean* *this*.
1604 Not all export backends support this.
1605
1606 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1607 :group 'org-export-translation
1608 :type 'boolean)
1609
1610 (defcustom org-export-with-sub-superscripts t
1611 "Non-nil means, interpret \"_\" and \"^\" for export.
1612 When this option is turned on, you can use TeX-like syntax for sub- and
1613 superscripts. Several characters after \"_\" or \"^\" will be
1614 considered as a single item - so grouping with {} is normally not
1615 needed. For example, the following things will be parsed as single
1616 sub- or superscripts.
1617
1618 10^24 or 10^tau several digits will be considered 1 item.
1619 10^-12 or 10^-tau a leading sign with digits or a word
1620 x^2-y^3 will be read as x^2 - y^3, because items are
1621 terminated by almost any nonword/nondigit char.
1622 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1623
1624 Still, ambiguity is possible - so when in doubt use {} to enclose the
1625 sub/superscript.
1626 Not all export backends support this, but HTML does.
1627
1628 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1629 :group 'org-export-translation
1630 :type 'boolean)
1631
1632 (defcustom org-export-with-TeX-macros t
1633 "Non-nil means, interpret simple TeX-like macros when exporting.
1634 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1635 No only real TeX macros will work here, but the standard HTML entities
1636 for math can be used as macro names as well. For a list of supported
1637 names in HTML export, see the constant `org-html-entities'.
1638 Not all export backends support this.
1639
1640 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1641 :group 'org-export-translation
1642 :type 'boolean)
1643
1644 (defcustom org-export-with-fixed-width t
1645 "Non-nil means, lines starting with \":\" will be in fixed width font.
1646 This can be used to have pre-formatted text, fragments of code etc. For
1647 example:
1648 : ;; Some Lisp examples
1649 : (while (defc cnt)
1650 : (ding))
1651 will be looking just like this in also HTML. See also the QUOTE keyword.
1652 Not all export backends support this.
1653
1654 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1655 :group 'org-export-translation
1656 :type 'boolean)
1657
1658 (defcustom org-match-sexp-depth 3
1659 "Number of stacked braces for sub/superscript matching.
1660 This has to be set before loading org.el to be effective."
1661 :group 'org-export-translation
1662 :type 'integer)
1663
1664 (defgroup org-export-tables nil
1665 "Options for exporting tables in Org-mode."
1666 :tag "Org Export Tables"
1667 :group 'org-export)
1668
1669 (defcustom org-export-with-tables t
1670 "If non-nil, lines starting with \"|\" define a table.
1671 For example:
1672
1673 | Name | Address | Birthday |
1674 |-------------+----------+-----------|
1675 | Arthur Dent | England | 29.2.2100 |
1676
1677 Not all export backends support this.
1678
1679 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
1680 :group 'org-export-tables
1681 :type 'boolean)
1682
1683 (defcustom org-export-highlight-first-table-line t
1684 "Non-nil means, highlight the first table line.
1685 In HTML export, this means use <th> instead of <td>.
1686 In tables created with table.el, this applies to the first table line.
1687 In Org-mode tables, all lines before the first horizontal separator
1688 line will be formatted with <th> tags."
1689 :group 'org-export-tables
1690 :type 'boolean)
1691
1692 (defcustom org-export-table-remove-special-lines t
1693 "Remove special lines and marking characters in calculating tables.
1694 This removes the special marking character column from tables that are set
1695 up for spreadsheet calculations. It also removes the entire lines
1696 marked with `!', `_', or `^'. The lines with `$' are kept, because
1697 the values of constants may be useful to have."
1698 :group 'org-export-tables
1699 :type 'boolean)
1700
1701 (defcustom org-export-prefer-native-exporter-for-tables nil
1702 "Non-nil means, always export tables created with table.el natively.
1703 Natively means, use the HTML code generator in table.el.
1704 When nil, Org-mode's own HTML generator is used when possible (i.e. if
1705 the table does not use row- or column-spanning). This has the
1706 advantage, that the automatic HTML conversions for math symbols and
1707 sub/superscripts can be applied. Org-mode's HTML generator is also
1708 much faster."
1709 :group 'org-export-tables
1710 :type 'boolean)
1711
1712 (defgroup org-export-ascii nil
1713 "Options specific for ASCII export of Org-mode files."
1714 :tag "Org Export ASCII"
1715 :group 'org-export)
1716
1717 (defcustom org-export-ascii-show-new-buffer t
1718 "Non-nil means, popup buffer containing the exported ASCII text.
1719 Otherwise the buffer will just be saved to a file and stay hidden."
1720 :group 'org-export-ascii
1721 :type 'boolean)
1722
1723 (defgroup org-export-xml nil
1724 "Options specific for XML export of Org-mode files."
1725 :tag "Org Export XML"
1726 :group 'org-export)
1727
1728 (defcustom org-export-xml-type 'xoxo ;kw, if we have only one.
1729 "The kind of XML to be produced by the XML exporter.
1730 Allowed values are:
1731 xoxo The XOXO exporter."
1732 :group 'org-export-xml
1733 :type '(choice
1734 (const :tag "XOXO" xoxo)))
1735
1736 (defgroup org-export-html nil
1737 "Options specific for HTML export of Org-mode files."
1738 :tag "Org Export HTML"
1739 :group 'org-export)
1740
1741 (defcustom org-export-html-style
1742 "<style type=\"text/css\">
1743 html {
1744 font-family: Times, serif;
1745 font-size: 12pt;
1746 }
1747 .title { text-align: center; }
1748 .todo, .deadline { color: red; }
1749 .done { color: green; }
1750 .target { background-color: lavender; }
1751 pre {
1752 border: 1pt solid #AEBDCC;
1753 background-color: #F3F5F7;
1754 padding: 5pt;
1755 font-family: courier, monospace;
1756 }
1757 table { border-collapse: collapse; }
1758 td, th {
1759 vertical-align: top;
1760 border: 1pt solid #ADB9CC;
1761 }
1762 </style>"
1763 "The default style specification for exported HTML files.
1764 Since there are different ways of setting style information, this variable
1765 needs to contain the full HTML structure to provide a style, including the
1766 surrounding HTML tags. The style specifications should include definitions
1767 for new classes todo, done, title, and deadline. For example, legal values
1768 would be:
1769
1770 <style type=\"text/css\">
1771 p { font-weight: normal; color: gray; }
1772 h1 { color: black; }
1773 .title { text-align: center; }
1774 .todo, .deadline { color: red; }
1775 .done { color: green; }
1776 </style>
1777
1778 or, if you want to keep the style in a file,
1779
1780 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
1781
1782 As the value of this option simply gets inserted into the HTML <head> header,
1783 you can \"misuse\" it to add arbitrary text to the header."
1784 :group 'org-export-html
1785 :type 'string)
1786
1787 (defcustom org-export-html-link-org-files-as-html t
1788 "Non-nil means, make file links to `file.org' point to `file.html'.
1789 When org-mode is exporting an org-mode file to HTML, links to
1790 non-html files are directly put into a href tag in HTML.
1791 However, links to other Org-mode files (recognized by the
1792 extension `.org.) should become links to the corresponding html
1793 file, assuming that the linked org-mode file will also be
1794 converted to HTML.
1795 When nil, the links still point to the plain `.org' file."
1796 :group 'org-export-html
1797 :type 'boolean)
1798
1799 (defcustom org-export-html-inline-images t
1800 "Non-nil means, inline images into exported HTML pages.
1801 The link will still be to the original location of the image file.
1802 So if you are moving the page, lets say to your public HTML site,
1803 you will have to move the image and maybe change the link."
1804 :group 'org-export-html
1805 :type 'boolean)
1806
1807 (defcustom org-export-html-expand t
1808 "Non-nil means, for HTML export, treat @<...> as HTML tag.
1809 When nil, these tags will be exported as plain text and therefore
1810 not be interpreted by a browser.
1811
1812 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
1813 :group 'org-export-html
1814 :type 'boolean)
1815
1816 (defcustom org-export-html-table-tag
1817 "<table border=1 cellspacing=0 cellpadding=6>"
1818 "The HTML tag used to start a table.
1819 This must be a <table> tag, but you may change the options like
1820 borders and spacing."
1821 :group 'org-export-html
1822 :type 'string)
1823
1824 (defcustom org-export-html-with-timestamp nil
1825 "If non-nil, write `org-export-html-html-helper-timestamp'
1826 into the exported HTML text. Otherwise, the buffer will just be saved
1827 to a file."
1828 :group 'org-export-html
1829 :type 'boolean)
1830
1831 (defcustom org-export-html-html-helper-timestamp
1832 "<br><br><hr><p><!-- hhmts start --> <!-- hhmts end -->\n"
1833 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
1834 :group 'org-export-html
1835 :type 'string)
1836
1837 (defcustom org-export-html-show-new-buffer nil
1838 "Non-nil means, popup buffer containing the exported html text.
1839 Otherwise, the buffer will just be saved to a file and stay hidden."
1840 :group 'org-export-html
1841 :type 'boolean)
1842
1843 (defgroup org-export-icalendar nil
1844 "Options specific for iCalendar export of Org-mode files."
1845 :tag "Org Export iCalendar"
1846 :group 'org-export)
1847
1848 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
1849 "The file name for the iCalendar file covering all agenda files.
1850 This file is created with the command \\[org-export-icalendar-all-agenda-files]."
1851 :group 'org-export-icalendar
1852 :type 'file)
1853
1854 (defcustom org-icalendar-include-todo nil
1855 "Non-nil means, export to iCalendar files should also cover TODO items."
1856 :group 'org-export-icalendar
1857 :type 'boolean)
1858
1859 (defcustom org-icalendar-combined-name "OrgMode"
1860 "Calendar name for the combined iCalendar representing all agenda files."
1861 :group 'org-export-icalendar
1862 :type 'string)
1863
1864 (defgroup org-font-lock nil
1865 "Font-lock settings for highlighting in Org-mode."
1866 :tag "Org Font Lock"
1867 :group 'org)
1868
1869 (defcustom org-level-color-stars-only nil
1870 "Non-nil means fontify only the stars in each headline.
1871 When nil, the entire headline is fontified.
1872 Changing it requires restart of `font-lock-mode' to become effective
1873 also in regions already fontified."
1874 :group 'org-font-lock
1875 :type 'boolean)
1876
1877 (defcustom org-hide-leading-stars nil
1878 "Non-nil means, hide the first N-1 stars in a headline.
1879 This works by using the face `org-hide' for these stars. This
1880 face is white for a light background, and black for a dark
1881 background. You may have to customize the face `org-hide' to
1882 make this work.
1883 Changing it requires restart of `font-lock-mode' to become effective
1884 also in regions already fontified.
1885 You may also set this on a per-file basis by adding one of the following
1886 lines to the buffer:
1887
1888 #+STARTUP: hidestars
1889 #+STARTUP: showstars"
1890 :group 'org-font-lock
1891 :type 'boolean)
1892
1893 (defcustom org-fontify-done-headline nil
1894 "Non-nil means, change the face of a headline if it is marked DONE.
1895 Normally, only the TODO/DONE keyword indicates the state of a headline.
1896 When this is non-nil, the headline after the keyword is set to the
1897 `org-headline-done' as an additional indication."
1898 :group 'org-font-lock
1899 :type 'boolean)
1900
1901 (defcustom org-fontify-emphasized-text t
1902 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
1903 Changing this variable requires a restart of Emacs to take effect."
1904 :group 'org-font-lock
1905 :type 'boolean)
1906
1907 (defgroup org-faces nil
1908 "Faces in Org-mode."
1909 :tag "Org Faces"
1910 :group 'org-font-lock)
1911
1912 (defun org-compatible-face (specs)
1913 "Make a compatible face specification.
1914 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
1915 For them we convert a (min-colors 8) entry to a `tty' entry and move it
1916 to the top of the list. The `min-colors' attribute will be removed from
1917 any other entries, and any resulting duplicates will be removed entirely."
1918 (if (or (featurep 'xemacs) (< emacs-major-version 22))
1919 (let (r e a)
1920 (while (setq e (pop specs))
1921 (cond
1922 ((memq (car e) '(t default)) (push e r))
1923 ((setq a (member '(min-colors 8) (car e)))
1924 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
1925 (cdr e)))))
1926 ((setq a (assq 'min-colors (car e)))
1927 (setq e (cons (delq a (car e)) (cdr e)))
1928 (or (assoc (car e) r) (push e r)))
1929 (t (or (assoc (car e) r) (push e r)))))
1930 (nreverse r))
1931 specs))
1932
1933 (defface org-hide
1934 '((((background light)) (:foreground "white"))
1935 (((background dark)) (:foreground "black")))
1936 "Face used to hide leading stars in headlines.
1937 The forground color of this face should be equal to the background
1938 color of the frame."
1939 :group 'org-faces)
1940
1941 (defface org-level-1 ;; font-lock-function-name-face
1942 (org-compatible-face
1943 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
1944 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
1945 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
1946 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
1947 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
1948 (t (:bold t))))
1949 "Face used for level 1 headlines."
1950 :group 'org-faces)
1951
1952 (defface org-level-2 ;; font-lock-variable-name-face
1953 (org-compatible-face
1954 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
1955 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
1956 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
1957 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
1958 (t (:bold t))))
1959 "Face used for level 2 headlines."
1960 :group 'org-faces)
1961
1962 (defface org-level-3 ;; font-lock-keyword-face
1963 (org-compatible-face
1964 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
1965 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
1966 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
1967 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
1968 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
1969 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
1970 (t (:bold t))))
1971 "Face used for level 3 headlines."
1972 :group 'org-faces)
1973
1974 (defface org-level-4 ;; font-lock-comment-face
1975 (org-compatible-face
1976 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
1977 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
1978 (((class color) (min-colors 16) (background light)) (:foreground "red"))
1979 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
1980 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
1981 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
1982 (t (:bold t))))
1983 "Face used for level 4 headlines."
1984 :group 'org-faces)
1985
1986 (defface org-level-5 ;; font-lock-type-face
1987 (org-compatible-face
1988 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
1989 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
1990 (((class color) (min-colors 8)) (:foreground "green"))))
1991 "Face used for level 5 headlines."
1992 :group 'org-faces)
1993
1994 (defface org-level-6 ;; font-lock-constant-face
1995 (org-compatible-face
1996 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
1997 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
1998 (((class color) (min-colors 8)) (:foreground "magenta"))))
1999 "Face used for level 6 headlines."
2000 :group 'org-faces)
2001
2002 (defface org-level-7 ;; font-lock-builtin-face
2003 (org-compatible-face
2004 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2005 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2006 (((class color) (min-colors 8)) (:foreground "blue")))) ;; FIXME: for dark bg?
2007 "Face used for level 7 headlines."
2008 :group 'org-faces)
2009
2010 (defface org-level-8 ;; font-lock-string-face
2011 (org-compatible-face
2012 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2013 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2014 (((class color) (min-colors 8)) (:foreground "green"))))
2015 "Face used for level 8 headlines."
2016 :group 'org-faces)
2017
2018 (defface org-special-keyword ;; font-lock-string-face
2019 (org-compatible-face
2020 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2021 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2022 (t (:italic t))))
2023 "Face used for special keywords."
2024 :group 'org-faces)
2025
2026 (defface org-warning ;; font-lock-warning-face
2027 (org-compatible-face
2028 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2029 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2030 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2031 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2032 (t (:bold t))))
2033 "Face for deadlines and TODO keywords."
2034 :group 'org-faces)
2035
2036 (defface org-headline-done ;; font-lock-string-face
2037 (org-compatible-face
2038 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2039 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2040 (((class color) (min-colors 8) (background light)) (:bold nil))))
2041 "Face used to indicate that a headline is DONE.
2042 This face is only used if `org-fontify-done-headline' is set."
2043 :group 'org-faces)
2044
2045 (defface org-link
2046 '((((class color) (background light)) (:foreground "Purple" :underline t))
2047 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2048 (t (:underline t)))
2049 "Face for links."
2050 :group 'org-faces)
2051
2052 (defface org-date
2053 '((((class color) (background light)) (:foreground "Purple" :underline t))
2054 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2055 (t (:underline t)))
2056 "Face for links."
2057 :group 'org-faces)
2058
2059 (defface org-tag
2060 '((t (:bold t)))
2061 "Face for tags."
2062 :group 'org-faces)
2063
2064 (defface org-todo ;; font-lock-warning-face
2065 (org-compatible-face
2066 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2067 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2068 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2069 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2070 (t (:inverse-video t :bold t))))
2071 "Face for TODO keywords."
2072 :group 'org-faces)
2073
2074 (defface org-done ;; font-lock-type-face
2075 (org-compatible-face
2076 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2077 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2078 (((class color) (min-colors 8)) (:foreground "green"))
2079 (t (:bold t))))
2080 "Face used for DONE."
2081 :group 'org-faces)
2082
2083 (defface org-table ;; font-lock-function-name-face
2084 (org-compatible-face
2085 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2086 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2087 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2088 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2089 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2090 (((class color) (min-colors 8) (background dark)))))
2091 "Face used for tables."
2092 :group 'org-faces)
2093
2094 (defface org-formula
2095 (org-compatible-face
2096 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2097 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2098 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2099 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2100 (t (:bold t :italic t))))
2101 "Face for formulas."
2102 :group 'org-faces)
2103
2104 (defface org-scheduled-today
2105 (org-compatible-face
2106 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2107 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2108 (((class color) (min-colors 8)) (:foreground "green"))
2109 (t (:bold t :italic t))))
2110 "Face for items scheduled for a certain day."
2111 :group 'org-faces)
2112
2113 (defface org-scheduled-previously
2114 (org-compatible-face
2115 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2116 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2117 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2118 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2119 (t (:bold t))))
2120 "Face for items scheduled previously, and not yet done."
2121 :group 'org-faces)
2122
2123 (defface org-time-grid ;; font-lock-variable-name-face
2124 (org-compatible-face
2125 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2126 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2127 (((class color) (min-colors 8)) (:foreground "yellow" :weight light)))) ; FIXME: turn off???
2128 "Face used for time grids."
2129 :group 'org-faces)
2130
2131 (defconst org-level-faces
2132 '(org-level-1 org-level-2 org-level-3 org-level-4
2133 org-level-5 org-level-6 org-level-7 org-level-8
2134 ))
2135 (defconst org-n-levels (length org-level-faces))
2136
2137 (defconst org-bold-re
2138 (if (featurep 'xemacs)
2139 "\\([ ]\\|^\\)\\(\\*\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)\\*\\)\\([ ,.]\\|$\\)"
2140 "\\([ ]\\|^\\)\\(\\*\\(\\w[[:word:] -_]*?\\w\\)\\*\\)\\([ ,.]\\|$\\)")
2141 "Regular expression for bold emphasis.")
2142 (defconst org-italic-re
2143 (if (featurep 'xemacs)
2144 "\\([ ]\\|^\\)\\(/\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)/\\)\\([ ,.]\\|$\\)"
2145 "\\([ ]\\|^\\)\\(/\\(\\w[[:word:] -_]*?\\w\\)/\\)\\([ ,.]\\|$\\)")
2146 "Regular expression for italic emphasis.")
2147 (defconst org-underline-re
2148 (if (featurep 'xemacs)
2149 "\\([ ]\\|^\\)\\(_\\(\\w[a-zA-Z0-9-_ ]*?\\w\\)_\\)\\([ ,.]\\|$\\)"
2150 "\\([ ]\\|^\\)\\(_\\(\\w[[:word:] -_]*?\\w\\)_\\)\\([ ,.]\\|$\\)")
2151 "Regular expression for underline emphasis.")
2152
2153 ;; Variables for pre-computed regular expressions, all buffer local
2154 (defvar org-done-string nil
2155 "The last string in `org-todo-keywords', indicating an item is DONE.")
2156 (make-variable-buffer-local 'org-done-string)
2157 (defvar org-todo-regexp nil
2158 "Matches any of the TODO state keywords.")
2159 (make-variable-buffer-local 'org-todo-regexp)
2160 (defvar org-not-done-regexp nil
2161 "Matches any of the TODO state keywords except the last one.")
2162 (make-variable-buffer-local 'org-not-done-regexp)
2163 (defvar org-todo-line-regexp nil
2164 "Matches a headline and puts TODO state into group 2 if present.")
2165 (make-variable-buffer-local 'org-todo-line-regexp)
2166 (defvar org-nl-done-regexp nil
2167 "Matches newline followed by a headline with the DONE keyword.")
2168 (make-variable-buffer-local 'org-nl-done-regexp)
2169 (defvar org-looking-at-done-regexp nil
2170 "Matches the DONE keyword a point.")
2171 (make-variable-buffer-local 'org-looking-at-done-regexp)
2172 (defvar org-todo-kwd-priority-p nil
2173 "Do TODO items have priorities?")
2174 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2175 (defvar org-todo-kwd-max-priority nil
2176 "Maximum priority of TODO items.")
2177 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2178 (defvar org-ds-keyword-length 12
2179 "Maximum length of the Deadline and SCHEDULED keywords.")
2180 (make-variable-buffer-local 'org-ds-keyword-length)
2181 (defvar org-deadline-regexp nil
2182 "Matches the DEADLINE keyword.")
2183 (make-variable-buffer-local 'org-deadline-regexp)
2184 (defvar org-deadline-time-regexp nil
2185 "Matches the DEADLINE keyword together with a time stamp.")
2186 (make-variable-buffer-local 'org-deadline-time-regexp)
2187 (defvar org-deadline-line-regexp nil
2188 "Matches the DEADLINE keyword and the rest of the line.")
2189 (make-variable-buffer-local 'org-deadline-line-regexp)
2190 (defvar org-scheduled-regexp nil
2191 "Matches the SCHEDULED keyword.")
2192 (make-variable-buffer-local 'org-scheduled-regexp)
2193 (defvar org-scheduled-time-regexp nil
2194 "Matches the SCHEDULED keyword together with a time stamp.")
2195 (make-variable-buffer-local 'org-scheduled-time-regexp)
2196
2197 (defun org-set-regexps-and-options ()
2198 "Precompute regular expressions for current buffer."
2199 (when (eq major-mode 'org-mode)
2200 (let ((re (org-make-options-regexp
2201 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2202 "STARTUP" "ARCHIVE")))
2203 (splitre "[ \t]+")
2204 kwds int key value cat arch)
2205 (save-excursion
2206 (save-restriction
2207 (widen)
2208 (goto-char (point-min))
2209 (while (re-search-forward re nil t)
2210 (setq key (match-string 1) value (match-string 2))
2211 (cond
2212 ((equal key "CATEGORY")
2213 (if (string-match "[ \t]+$" value)
2214 (setq value (replace-match "" t t value)))
2215 (setq cat (intern value)))
2216 ((equal key "SEQ_TODO")
2217 (setq int 'sequence
2218 kwds (append kwds (org-split-string value splitre))))
2219 ((equal key "PRI_TODO")
2220 (setq int 'priority
2221 kwds (append kwds (org-split-string value splitre))))
2222 ((equal key "TYP_TODO")
2223 (setq int 'type
2224 kwds (append kwds (org-split-string value splitre))))
2225 ((equal key "STARTUP")
2226 (let ((opts (org-split-string value splitre))
2227 (set '(("fold" org-startup-folded t)
2228 ("overview" org-startup-folded t)
2229 ("nofold" org-startup-folded nil)
2230 ("showall" org-startup-folded nil)
2231 ("content" org-startup-folded content)
2232 ("hidestars" org-hide-leading-stars t)
2233 ("showstars" org-hide-leading-stars nil)
2234 ("odd" org-odd-levels-only t)
2235 ("oddeven" org-odd-levels-only nil)
2236 ("align" org-startup-align-all-tables t)
2237 ("noalign" org-startup-align-all-tables nil)
2238 ("dlcheck" org-startup-with-deadline-check t)
2239 ("nodlcheck" org-startup-with-deadline-check nil)))
2240 l var val)
2241 (while (setq l (assoc (pop opts) set))
2242 (setq var (nth 1 l) val (nth 2 l))
2243 (set (make-local-variable var) val))))
2244 ((equal key "ARCHIVE")
2245 (string-match " *$" value)
2246 (setq arch (replace-match "" t t value))
2247 (remove-text-properties 0 (length arch)
2248 '(face t fontified t) arch)))
2249 )))
2250 (and cat (set (make-local-variable 'org-category) cat))
2251 (and kwds (set (make-local-variable 'org-todo-keywords) kwds))
2252 (and arch (set (make-local-variable 'org-archive-location) arch))
2253 (and int (set (make-local-variable 'org-todo-interpretation) int)))
2254 ;; Compute the regular expressions and other local variables
2255 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2256 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2257 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2258 (length org-scheduled-string)))
2259 org-done-string
2260 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2261 org-todo-regexp
2262 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2263 "\\|") "\\)\\>")
2264 org-not-done-regexp
2265 (concat "\\<\\("
2266 (mapconcat 'regexp-quote
2267 (nreverse (cdr (reverse org-todo-keywords)))
2268 "\\|")
2269 "\\)\\>")
2270 org-todo-line-regexp
2271 (concat "^\\(\\*+\\)[ \t]*\\("
2272 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2273 "\\)? *\\(.*\\)")
2274 org-nl-done-regexp
2275 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2276 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2277 org-deadline-regexp (concat "\\<" org-deadline-string)
2278 org-deadline-time-regexp
2279 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2280 org-deadline-line-regexp
2281 (concat "\\<\\(" org-deadline-string "\\).*")
2282 org-scheduled-regexp
2283 (concat "\\<" org-scheduled-string)
2284 org-scheduled-time-regexp
2285 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>"))
2286 (org-set-font-lock-defaults)))
2287
2288 ;; Tell the compiler about dynamically scoped variables,
2289 ;; and variables from other packages
2290 (defvar zmacs-regions) ; XEmacs regions
2291 (defvar original-date) ; dynamically scoped in calendar
2292 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2293 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2294 (defvar org-html-entities) ; defined later in this file
2295 (defvar org-goto-start-pos) ; dynamically scoped parameter
2296 (defvar org-time-was-given) ; dynamically scoped parameter
2297 (defvar org-ts-what) ; dynamically scoped parameter
2298 (defvar mark-active) ; Emacs only, not available in XEmacs.
2299 (defvar timecnt) ; dynamically scoped parameter
2300 (defvar levels-open) ; dynamically scoped parameter
2301 (defvar title) ; dynamically scoped parameter
2302 (defvar author) ; dynamically scoped parameter
2303 (defvar email) ; dynamically scoped parameter
2304 (defvar text) ; dynamically scoped parameter
2305 (defvar entry) ; dynamically scoped parameter
2306 (defvar date) ; dynamically scoped parameter
2307 (defvar language) ; dynamically scoped parameter
2308 (defvar options) ; dynamically scoped parameter
2309 (defvar ans1) ; dynamically scoped parameter
2310 (defvar ans2) ; dynamically scoped parameter
2311 (defvar starting-day) ; local variable
2312 (defvar include-all-loc) ; local variable
2313 (defvar vm-message-pointer) ; from vm
2314 (defvar vm-folder-directory) ; from vm
2315 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2316 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2317 (defvar gnus-group-name) ; from gnus
2318 (defvar gnus-article-current) ; from gnus
2319 (defvar w3m-current-url) ; from w3m
2320 (defvar mh-progs) ; from MH-E
2321 (defvar mh-current-folder) ; from MH-E
2322 (defvar mh-show-folder-buffer) ; from MH-E
2323 (defvar mh-index-folder) ; from MH-E
2324 (defvar mh-searcher) ; from MH-E
2325 (defvar org-selected-point) ; dynamically scoped parameter
2326 (defvar calendar-mode-map) ; from calendar.el
2327 (defvar last-arg) ; local variable
2328 (defvar remember-save-after-remembering) ; from remember.el
2329 (defvar remember-data-file) ; from remember.el
2330 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2331 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2332 (defvar orgtbl-mode) ; defined later in this file
2333 ;;; Define the mode
2334
2335 (defvar org-mode-map
2336 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2337 (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.")
2338 (copy-keymap outline-mode-map))
2339 "Keymap for Org-mode.")
2340
2341 (defvar org-struct-menu) ; defined later in this file
2342 (defvar org-org-menu) ; defined later in this file
2343 (defvar org-tbl-menu) ; defined later in this file
2344
2345 ;; We use a before-change function to check if a table might need
2346 ;; an update.
2347 (defvar org-table-may-need-update t
2348 "Indicates that a table might need an update.
2349 This variable is set by `org-before-change-function'.
2350 `org-table-align' sets it back to nil.")
2351 (defvar org-mode-hook nil)
2352 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2353 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2354
2355
2356 ;;;###autoload
2357 (define-derived-mode org-mode outline-mode "Org"
2358 "Outline-based notes management and organizer, alias
2359 \"Carsten's outline-mode for keeping track of everything.\"
2360
2361 Org-mode develops organizational tasks around a NOTES file which
2362 contains information about projects as plain text. Org-mode is
2363 implemented on top of outline-mode, which is ideal to keep the content
2364 of large files well structured. It supports ToDo items, deadlines and
2365 time stamps, which magically appear in the diary listing of the Emacs
2366 calendar. Tables are easily created with a built-in table editor.
2367 Plain text URL-like links connect to websites, emails (VM), Usenet
2368 messages (Gnus), BBDB entries, and any files related to the project.
2369 For printing and sharing of notes, an Org-mode file (or a part of it)
2370 can be exported as a structured ASCII or HTML file.
2371
2372 The following commands are available:
2373
2374 \\{org-mode-map}"
2375 (easy-menu-add org-org-menu)
2376 (easy-menu-add org-tbl-menu)
2377 (org-install-agenda-files-menu)
2378 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2379 (org-add-to-invisibility-spec '(org-cwidth))
2380 (setq outline-regexp "\\*+")
2381 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2382 (setq outline-level 'org-outline-level)
2383 (when (and org-ellipsis (stringp org-ellipsis))
2384 (unless org-display-table
2385 (setq org-display-table (make-display-table)))
2386 (set-display-table-slot org-display-table
2387 4 (string-to-vector org-ellipsis))
2388 (setq buffer-display-table org-display-table))
2389 (org-set-regexps-and-options)
2390 (if org-startup-truncated (setq truncate-lines t))
2391 (set (make-local-variable 'font-lock-unfontify-region-function)
2392 'org-unfontify-region)
2393 ;; Activate before-change-function
2394 (set (make-local-variable 'org-table-may-need-update) t)
2395 (org-add-hook 'before-change-functions 'org-before-change-function nil
2396 'local)
2397 ;; Paragraphs and auto-filling
2398 (org-set-autofill-regexps)
2399 (org-update-radio-target-regexp)
2400 ;; Settings for Calc embedded mode
2401 (set (make-local-variable 'calc-embedded-open-formula) "|\\|\n")
2402 (set (make-local-variable 'calc-embedded-close-formula) "|\\|\n")
2403 (if (and org-insert-mode-line-in-empty-file
2404 (interactive-p)
2405 (= (point-min) (point-max)))
2406 (insert " -*- mode: org -*-\n\n"))
2407
2408 ;; Get rid of Outline menus, they are not needed
2409 ;; Need to do this here because define-derived-mode sets up
2410 ;; the keymap so late.
2411 (if (featurep 'xemacs)
2412 (progn
2413 (delete-menu-item '("Headings"))
2414 (delete-menu-item '("Show"))
2415 (delete-menu-item '("Hide"))
2416 (set-menubar-dirty-flag))
2417 (define-key org-mode-map [menu-bar headings] 'undefined)
2418 (define-key org-mode-map [menu-bar hide] 'undefined)
2419 (define-key org-mode-map [menu-bar show] 'undefined))
2420
2421 (unless org-inhibit-startup
2422 (if org-startup-align-all-tables
2423 (org-table-map-tables 'org-table-align))
2424 (if org-startup-with-deadline-check
2425 (call-interactively 'org-check-deadlines)
2426 (cond
2427 ((eq org-startup-folded t)
2428 (org-cycle '(4)))
2429 ((eq org-startup-folded 'content)
2430 (let ((this-command 'org-cycle) (last-command 'org-cycle))
2431 (org-cycle '(4)) (org-cycle '(4))))))))
2432
2433 (defsubst org-current-line (&optional pos)
2434 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
2435
2436 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2437 mouse-map t)
2438 "Properties to remove when a string without properties is wanted.")
2439
2440 (defsubst org-match-string-no-properties (num &optional string)
2441 (if (featurep 'xemacs)
2442 (let ((s (match-string num string)))
2443 (remove-text-properties 0 (length s) org-rm-props s)
2444 s)
2445 (match-string-no-properties num string)))
2446
2447 (defsubst org-no-properties (s)
2448 (remove-text-properties 0 (length s) org-rm-props s)
2449 s)
2450
2451 (defun org-current-time ()
2452 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
2453 (if (> org-time-stamp-rounding-minutes 0)
2454 (let ((r org-time-stamp-rounding-minutes)
2455 (time (decode-time)))
2456 (apply 'encode-time
2457 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
2458 (nthcdr 2 time))))
2459 (current-time)))
2460
2461 (defun org-add-props (string plist &rest props)
2462 "Add text properties to entire string, from beginning to end.
2463 PLIST may be a list of properties, PROPS are individual properties and values
2464 that will be added to PLIST. Returns the string that was modified."
2465 (add-text-properties
2466 0 (length string) (if props (append plist props) plist) string)
2467 string)
2468 (put 'org-add-props 'lisp-indent-function 2)
2469
2470
2471 ;;; Font-Lock stuff
2472
2473 (defvar org-mouse-map (make-sparse-keymap))
2474 (define-key org-mouse-map
2475 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
2476 (define-key org-mouse-map
2477 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
2478 (when org-mouse-1-follows-link
2479 (define-key org-mouse-map [follow-link] 'mouse-face))
2480 (when org-tab-follows-link
2481 (define-key org-mouse-map [(tab)] 'org-open-at-point)
2482 (define-key org-mouse-map "\C-i" 'org-open-at-point))
2483 (when org-return-follows-link
2484 (define-key org-mouse-map [(return)] 'org-open-at-point)
2485 (define-key org-mouse-map "\C-m" 'org-open-at-point))
2486
2487 (require 'font-lock)
2488
2489 (defconst org-non-link-chars "]\t\n\r<>")
2490 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
2491 "wl" "mhe" "rmail" "gnus" "shell"))
2492 (defconst org-link-re-with-space
2493 (concat
2494 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2495 "\\([^" org-non-link-chars " ]"
2496 "[^" org-non-link-chars "]*"
2497 "[^" org-non-link-chars " ]\\)>?")
2498 "Matches a link with spaces, optional angular brackets around it.")
2499
2500 (defconst org-link-re-with-space2
2501 (concat
2502 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2503 "\\([^" org-non-link-chars " ]"
2504 "[^]\t\n\r]*"
2505 "[^" org-non-link-chars " ]\\)>?")
2506 "Matches a link with spaces, optional angular brackets around it.")
2507
2508 (defconst org-angle-link-re
2509 (concat
2510 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2511 "\\([^" org-non-link-chars " ]"
2512 "[^" org-non-link-chars "]*"
2513 "\\)>")
2514 "Matches link with angular brackets, spaces are allowed.")
2515 (defconst org-plain-link-re
2516 (concat
2517 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
2518 "\\([^]\t\n\r<>,;() ]+\\)")
2519 "Matches plain link, without spaces.")
2520
2521 (defconst org-bracket-link-regexp
2522 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
2523 "Matches a link in double brackets.")
2524
2525 (defconst org-bracket-link-analytic-regexp
2526 (concat
2527 "\\[\\["
2528 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
2529 "\\([^]]+\\)"
2530 "\\]"
2531 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
2532 "\\]"))
2533 ; 1: http:
2534 ; 2: http
2535 ; 3: path
2536 ; 4: [desc]
2537 ; 5: desc
2538
2539
2540 (defconst org-ts-lengths
2541 (cons (length (format-time-string (car org-time-stamp-formats)))
2542 (length (format-time-string (cdr org-time-stamp-formats))))
2543 "This holds the lengths of the two different time formats.")
2544 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
2545 "Regular expression for fast time stamp matching.")
2546 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
2547 "Regular expression for fast time stamp matching.")
2548 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
2549 "Regular expression matching time strings for analysis.")
2550 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
2551 "Regular expression matching time stamps, with groups.")
2552 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
2553 "Regular expression matching a time stamp range.")
2554 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
2555 org-ts-regexp "\\)?")
2556 "Regular expression matching a time stamp or time stamp range.")
2557
2558 (defun org-activate-plain-links (limit)
2559 "Run through the buffer and add overlays to links."
2560 (if (re-search-forward org-plain-link-re limit t)
2561 (progn
2562 (add-text-properties (match-beginning 0) (match-end 0)
2563 (list 'mouse-face 'highlight
2564 'keymap org-mouse-map
2565 ))
2566 t)))
2567
2568 (defun org-activate-angle-links (limit)
2569 "Run through the buffer and add overlays to links."
2570 (if (re-search-forward org-angle-link-re limit t)
2571 (progn
2572 (add-text-properties (match-beginning 0) (match-end 0)
2573 (list 'mouse-face 'highlight
2574 'keymap org-mouse-map
2575 ))
2576 t)))
2577
2578 (defun org-activate-bracket-links (limit)
2579 "Run through the buffer and add overlays to bracketed links."
2580 (if (re-search-forward org-bracket-link-regexp limit t)
2581 (let* ((help (concat "LINK: "
2582 (org-match-string-no-properties 1)))
2583 ;; FIXME: above we should remove the escapes.
2584 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
2585 'keymap org-mouse-map 'mouse-face 'highlight
2586 'help-echo help))
2587 (vp (list 'rear-nonsticky t
2588 'keymap org-mouse-map 'mouse-face 'highlight
2589 'help-echo help)))
2590 ;; We need to remove the invisible property here. Table narrowing
2591 ;; may have made some of this invisible.
2592 (remove-text-properties (match-beginning 0) (match-end 0)
2593 '(invisible nil))
2594 (if (match-end 3)
2595 (progn
2596 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
2597 (add-text-properties (match-beginning 3) (match-end 3) vp)
2598 (add-text-properties (match-end 3) (match-end 0) ip))
2599 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
2600 (add-text-properties (match-beginning 1) (match-end 1) vp)
2601 (add-text-properties (match-end 1) (match-end 0) ip))
2602 t)))
2603
2604 (defun org-activate-dates (limit)
2605 "Run through the buffer and add overlays to dates."
2606 (if (re-search-forward org-tsr-regexp limit t)
2607 (progn
2608 (add-text-properties (match-beginning 0) (match-end 0)
2609 (list 'mouse-face 'highlight
2610 'keymap org-mouse-map))
2611 t)))
2612
2613 (defvar org-target-link-regexp nil
2614 "Regular expression matching radio targets in plain text.")
2615 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
2616 "Regular expression matching a link target.")
2617 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
2618 "Regular expression matching a link target.")
2619
2620 (defun org-activate-target-links (limit)
2621 "Run through the buffer and add overlays to target matches."
2622 (when org-target-link-regexp
2623 (let ((case-fold-search t))
2624 (if (re-search-forward org-target-link-regexp limit t)
2625 (progn
2626 (add-text-properties (match-beginning 0) (match-end 0)
2627 (list 'mouse-face 'highlight
2628 'keymap org-mouse-map
2629 'help-echo "Radio target link"
2630 'org-linked-text t))
2631 t)))))
2632
2633 (defun org-update-radio-target-regexp ()
2634 "Find all radio targets in this file and update the regular expression."
2635 (interactive)
2636 (when (memq 'radio org-activate-links)
2637 (setq org-target-link-regexp
2638 (org-make-target-link-regexp (org-all-targets 'radio)))
2639 (org-restart-font-lock)))
2640
2641 (defun org-hide-wide-columns (limit)
2642 (let (s e)
2643 (setq s (text-property-any (point) (or limit (point-max))
2644 'org-cwidth t))
2645 (when s
2646 (setq e (next-single-property-change s 'org-cwidth))
2647 (add-text-properties s e '(invisible org-cwidth intangible t))
2648 (goto-char e)
2649 t)))
2650
2651 (defun org-restart-font-lock ()
2652 "Restart font-lock-mode, to force refontification."
2653 (when (and (boundp 'font-lock-mode) font-lock-mode)
2654 (font-lock-mode -1)
2655 (font-lock-mode 1)))
2656
2657 (defun org-all-targets (&optional radio)
2658 "Return a list of all targets in this file.
2659 With optional argument RADIO, only find radio targets."
2660 (let ((re (if radio org-radio-target-regexp org-target-regexp))
2661 rtn)
2662 (save-excursion
2663 (goto-char (point-min))
2664 (while (re-search-forward re nil t)
2665 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
2666 rtn)))
2667
2668 (defun org-make-target-link-regexp (targets)
2669 "Make regular expression matching all strings in TARGETS.
2670 The regular expression finds the targets also if there is a line break
2671 between words."
2672 (and targets
2673 (concat
2674 "\\<\\("
2675 (mapconcat
2676 (lambda (x)
2677 (while (string-match " +" x)
2678 (setq x (replace-match "\\s-+" t t x)))
2679 x)
2680 targets
2681 "\\|")
2682 "\\)\\>")))
2683
2684 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
2685 "Matches CamelCase words, possibly with a star before it.")
2686
2687 (defun org-activate-camels (limit)
2688 "Run through the buffer and add overlays to dates."
2689 (if (re-search-forward org-camel-regexp limit t)
2690 (progn
2691 (add-text-properties (match-beginning 0) (match-end 0)
2692 (list 'mouse-face 'highlight
2693 'keymap org-mouse-map))
2694 t)))
2695
2696 (defun org-activate-tags (limit)
2697 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
2698 (progn
2699 (add-text-properties (match-beginning 1) (match-end 1)
2700 (list 'mouse-face 'highlight
2701 'keymap org-mouse-map))
2702 t)))
2703
2704 (defun org-font-lock-level ()
2705 (save-excursion
2706 (org-back-to-heading t)
2707 (- (match-end 0) (match-beginning 0))))
2708
2709 (defun org-outline-level ()
2710 (save-excursion
2711 (looking-at outline-regexp)
2712 (if (match-beginning 1)
2713 (+ (org-get-string-indentation (match-string 1)) 1000)
2714 (- (match-end 0) (match-beginning 0)))))
2715
2716 (defvar org-font-lock-keywords nil)
2717
2718 (defun org-set-font-lock-defaults ()
2719 (let* ((em org-fontify-emphasized-text)
2720 (lk org-activate-links)
2721 (org-font-lock-extra-keywords
2722 (list
2723 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
2724 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
2725 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
2726 (1 'org-table))
2727 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
2728 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
2729 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
2730 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
2731 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
2732 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
2733 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
2734 (if org-table-limit-column-width
2735 '(org-hide-wide-columns (0 nil append)))
2736 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
2737 '(1 'org-todo t))
2738 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
2739 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
2740 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
2741 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
2742 ; (if em '("\\(\\W\\|^\\)\\(\\*\\w+\\*\\)\\(\\W\\|$\\)" 2 'bold prepend))
2743 ; (if em '("\\(\\W\\|^\\)\\(/\\w+/\\)\\(\\W\\|$\\)" 2 'italic prepend))
2744 ; (if em '("\\(\\W\\|^\\)\\(_\\w+_\\)\\(\\W\\|$\\)" 2 'underline prepend))
2745 (if em (list org-bold-re 2 ''bold 'prepend))
2746 (if em (list org-italic-re 2 ''italic 'prepend))
2747 (if em (list org-underline-re 2 ''underline 'prepend))
2748 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
2749 "\\|" org-quote-string "\\)\\>")
2750 '(1 'org-special-keyword t))
2751 '("^#.*" (0 'font-lock-comment-face t))
2752 (if org-fontify-done-headline
2753 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
2754 '(1 'org-done t) '(2 'org-headline-done t))
2755 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
2756 '(1 'org-done t)))
2757 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
2758 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
2759 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
2760 (if org-format-transports-properties-p
2761 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
2762 )))
2763 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
2764 ;; Now set the full font-lock-keywords
2765 (set (make-local-variable 'org-font-lock-keywords)
2766 org-font-lock-extra-keywords)
2767 (set (make-local-variable 'font-lock-defaults)
2768 '(org-font-lock-keywords t nil nil backward-paragraph))
2769 (kill-local-variable 'font-lock-keywords) nil))
2770
2771 (defvar org-m nil)
2772 (defvar org-l nil)
2773 (defvar org-f nil)
2774 (defun org-get-level-face (n)
2775 "Get the right face for match N in font-lock matching of healdines."
2776 (setq org-l (- (match-end 2) (match-beginning 1)))
2777 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
2778 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
2779 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
2780 (cond
2781 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
2782 ((eq n 2) org-f)
2783 (t (if org-level-color-stars-only nil org-f))))
2784
2785 (defun org-unfontify-region (beg end &optional maybe_loudly)
2786 "Remove fontification and activation overlays from links."
2787 (font-lock-default-unfontify-region beg end)
2788 (let* ((buffer-undo-list t)
2789 (inhibit-read-only t) (inhibit-point-motion-hooks t)
2790 (inhibit-modification-hooks t)
2791 deactivate-mark buffer-file-name buffer-file-truename)
2792 (remove-text-properties beg end
2793 '(mouse-face nil keymap nil org-linked-text nil
2794 invisible nil intangible nil))))
2795 ;;; Visibility cycling
2796
2797 (defvar org-cycle-global-status nil)
2798 (defvar org-cycle-subtree-status nil)
2799 (defun org-cycle (&optional arg)
2800 "Visibility cycling for Org-mode.
2801
2802 - When this function is called with a prefix argument, rotate the entire
2803 buffer through 3 states (global cycling)
2804 1. OVERVIEW: Show only top-level headlines.
2805 2. CONTENTS: Show all headlines of all levels, but no body text.
2806 3. SHOW ALL: Show everything.
2807
2808 - When point is at the beginning of a headline, rotate the subtree started
2809 by this line through 3 different states (local cycling)
2810 1. FOLDED: Only the main headline is shown.
2811 2. CHILDREN: The main headline and the direct children are shown.
2812 From this state, you can move to one of the children
2813 and zoom in further.
2814 3. SUBTREE: Show the entire subtree, including body text.
2815
2816 - When there is a numeric prefix, go up to a heading with level ARG, do
2817 a `show-subtree' and return to the previous cursor position. If ARG
2818 is negative, go up that many levels.
2819
2820 - When point is not at the beginning of a headline, execute
2821 `indent-relative', like TAB normally does. See the option
2822 `org-cycle-emulate-tab' for details.
2823
2824 - Special case: if point is the the beginning of the buffer and there is
2825 no headline in line 1, this function will act as if called with prefix arg."
2826 (interactive "P")
2827
2828 (if (or (and (bobp) (not (looking-at outline-regexp)))
2829 (equal arg '(4)))
2830 ;; special case: use global cycling
2831 (setq arg t))
2832
2833 (let ((outline-regexp
2834 (if org-cycle-include-plain-lists
2835 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
2836 outline-regexp)))
2837
2838 (cond
2839
2840 ((org-at-table-p 'any)
2841 ;; Enter the table or move to the next field in the table
2842 (or (org-table-recognize-table.el)
2843 (progn
2844 (if arg (org-table-edit-field t)
2845 (org-table-justify-field-maybe)
2846 (org-table-next-field)))))
2847
2848 ((eq arg t) ;; Global cycling
2849
2850 (cond
2851 ((and (eq last-command this-command)
2852 (eq org-cycle-global-status 'overview))
2853 ;; We just created the overview - now do table of contents
2854 ;; This can be slow in very large buffers, so indicate action
2855 (message "CONTENTS...")
2856 (save-excursion
2857 ;; Visit all headings and show their offspring
2858 (goto-char (point-max))
2859 (catch 'exit
2860 (while (and (progn (condition-case nil
2861 (outline-previous-visible-heading 1)
2862 (error (goto-char (point-min))))
2863 t)
2864 (looking-at outline-regexp))
2865 (show-branches)
2866 (if (bobp) (throw 'exit nil))))
2867 (message "CONTENTS...done"))
2868 (setq org-cycle-global-status 'contents)
2869 (run-hook-with-args 'org-cycle-hook 'contents))
2870
2871 ((and (eq last-command this-command)
2872 (eq org-cycle-global-status 'contents))
2873 ;; We just showed the table of contents - now show everything
2874 (show-all)
2875 (message "SHOW ALL")
2876 (setq org-cycle-global-status 'all)
2877 (run-hook-with-args 'org-cycle-hook 'all))
2878
2879 (t
2880 ;; Default action: go to overview
2881 (hide-sublevels 1)
2882 (message "OVERVIEW")
2883 (setq org-cycle-global-status 'overview)
2884 (run-hook-with-args 'org-cycle-hook 'overview))))
2885
2886 ((integerp arg)
2887 ;; Show-subtree, ARG levels up from here.
2888 (save-excursion
2889 (org-back-to-heading)
2890 (outline-up-heading (if (< arg 0) (- arg)
2891 (- (funcall outline-level) arg)))
2892 (org-show-subtree)))
2893
2894 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
2895 ;; At a heading: rotate between three different views
2896 (org-back-to-heading)
2897 (let ((goal-column 0) eoh eol eos)
2898 ;; First, some boundaries
2899 (save-excursion
2900 (org-back-to-heading)
2901 (save-excursion
2902 (beginning-of-line 2)
2903 (while (and (not (eobp)) ;; this is like `next-line'
2904 (get-char-property (1- (point)) 'invisible))
2905 (beginning-of-line 2)) (setq eol (point)))
2906 (outline-end-of-heading) (setq eoh (point))
2907 (org-end-of-subtree t) (setq eos (point))
2908 (outline-next-heading))
2909 ;; Find out what to do next and set `this-command'
2910 (cond
2911 ((= eos eoh)
2912 ;; Nothing is hidden behind this heading
2913 (message "EMPTY ENTRY")
2914 (setq org-cycle-subtree-status nil))
2915 ((>= eol eos)
2916 ;; Entire subtree is hidden in one line: open it
2917 (org-show-entry)
2918 (show-children)
2919 (message "CHILDREN")
2920 (setq org-cycle-subtree-status 'children)
2921 (run-hook-with-args 'org-cycle-hook 'children))
2922 ((and (eq last-command this-command)
2923 (eq org-cycle-subtree-status 'children))
2924 ;; We just showed the children, now show everything.
2925 (org-show-subtree)
2926 (message "SUBTREE")
2927 (setq org-cycle-subtree-status 'subtree)
2928 (run-hook-with-args 'org-cycle-hook 'subtree))
2929 (t
2930 ;; Default action: hide the subtree.
2931 (hide-subtree)
2932 (message "FOLDED")
2933 (setq org-cycle-subtree-status 'folded)
2934 (run-hook-with-args 'org-cycle-hook 'folded)))))
2935
2936 ;; TAB emulation
2937 (buffer-read-only (org-back-to-heading))
2938 ((if (and (eq org-cycle-emulate-tab 'white)
2939 (save-excursion (beginning-of-line 1) (looking-at "[ \t]+$")))
2940 t
2941 (eq org-cycle-emulate-tab t))
2942 (if (and (looking-at "[ \n\r\t]")
2943 (string-match "^[ \t]*$" (buffer-substring
2944 (point-at-bol) (point))))
2945 (progn
2946 (beginning-of-line 1)
2947 (and (looking-at "[ \t]+") (replace-match ""))))
2948 (indent-relative))
2949
2950 (t (save-excursion
2951 (org-back-to-heading)
2952 (org-cycle))))))
2953
2954 (defun org-optimize-window-after-visibility-change (state)
2955 "Adjust the window after a change in outline visibility.
2956 This function is the default value of the hook `org-cycle-hook'."
2957 (when (get-buffer-window (current-buffer))
2958 (cond
2959 ((eq state 'overview) (org-first-headline-recenter 1))
2960 ((eq state 'content) nil)
2961 ((eq state 'all) nil)
2962 ((eq state 'folded) nil)
2963 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
2964 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
2965
2966 (defun org-subtree-end-visible-p ()
2967 "Is the end of the current subtree visible?"
2968 (pos-visible-in-window-p
2969 (save-excursion (org-end-of-subtree t) (point))))
2970
2971 (defun org-first-headline-recenter (&optional N)
2972 "Move cursor to the first headline and recenter the headline.
2973 Optional argument N means, put the headline into the Nth line of the window."
2974 (goto-char (point-min))
2975 (when (re-search-forward (concat "^" outline-regexp) nil t)
2976 (beginning-of-line)
2977 (recenter (prefix-numeric-value N))))
2978
2979 (defvar org-goto-window-configuration nil)
2980 (defvar org-goto-marker nil)
2981 (defvar org-goto-map (make-sparse-keymap))
2982 (let ((cmds '(isearch-forward isearch-backward)) cmd)
2983 (while (setq cmd (pop cmds))
2984 (substitute-key-definition cmd cmd org-goto-map global-map)))
2985 (define-key org-goto-map "\C-m" 'org-goto-ret)
2986 (define-key org-goto-map [(left)] 'org-goto-left)
2987 (define-key org-goto-map [(right)] 'org-goto-right)
2988 (define-key org-goto-map [(?q)] 'org-goto-quit)
2989 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
2990 (define-key org-goto-map "\C-i" 'org-cycle)
2991 (define-key org-goto-map [(tab)] 'org-cycle)
2992 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
2993 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
2994 (define-key org-goto-map "n" 'outline-next-visible-heading)
2995 (define-key org-goto-map "p" 'outline-previous-visible-heading)
2996 (define-key org-goto-map "f" 'outline-forward-same-level)
2997 (define-key org-goto-map "b" 'outline-backward-same-level)
2998 (define-key org-goto-map "u" 'outline-up-heading)
2999 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3000 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3001 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3002 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3003 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3004 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3005 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3006
3007 (defconst org-goto-help
3008 "Select a location to jump to, press RET
3009 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3010
3011 (defun org-goto ()
3012 "Go to a different location of the document, keeping current visibility.
3013
3014 When you want to go to a different location in a document, the fastest way
3015 is often to fold the entire buffer and then dive into the tree. This
3016 method has the disadvantage, that the previous location will be folded,
3017 which may not be what you want.
3018
3019 This command works around this by showing a copy of the current buffer in
3020 overview mode. You can dive into the tree in that copy, to find the
3021 location you want to reach. When pressing RET, the command returns to the
3022 original buffer in which the visibility is still unchanged. It then jumps
3023 to the new location, making it and the headline hierarchy above it visible."
3024 (interactive)
3025 (let* ((org-goto-start-pos (point))
3026 (selected-point
3027 (org-get-location (current-buffer) org-goto-help)))
3028 (if selected-point
3029 (progn
3030 (org-mark-ring-push org-goto-start-pos)
3031 (goto-char selected-point)
3032 (if (or (org-invisible-p) (org-invisible-p2))
3033 (org-show-hierarchy-above)))
3034 (error "Quit"))))
3035
3036 (defun org-get-location (buf help)
3037 "Let the user select a location in the Org-mode buffer BUF.
3038 This function uses a recursive edit. It returns the selected position
3039 or nil."
3040 (let (org-selected-point)
3041 (save-excursion
3042 (save-window-excursion
3043 (delete-other-windows)
3044 (switch-to-buffer (get-buffer-create "*org-goto*"))
3045 (with-output-to-temp-buffer "*Help*"
3046 (princ help))
3047 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3048 (setq buffer-read-only nil)
3049 (erase-buffer)
3050 (insert-buffer-substring buf)
3051 (let ((org-startup-truncated t)
3052 (org-startup-folded t)
3053 (org-startup-align-all-tables nil)
3054 (org-startup-with-deadline-check nil))
3055 (org-mode))
3056 (setq buffer-read-only t)
3057 (if (boundp 'org-goto-start-pos)
3058 (goto-char org-goto-start-pos)
3059 (goto-char (point-min)))
3060 (org-beginning-of-line)
3061 (message "Select location and press RET")
3062 ;; now we make sure that during selection, ony very few keys work
3063 ;; and that it is impossible to switch to another window.
3064 (let ((gm (current-global-map))
3065 (overriding-local-map org-goto-map))
3066 (unwind-protect
3067 (progn
3068 (use-global-map org-goto-map)
3069 (recursive-edit))
3070 (use-global-map gm)))))
3071 (kill-buffer "*org-goto*")
3072 org-selected-point))
3073
3074 ;; FIXME: It may not be a good idea to temper with the prefix argument...
3075 (defun org-goto-ret (&optional arg)
3076 "Finish `org-goto' by going to the new location."
3077 (interactive "P")
3078 (setq org-selected-point (point)
3079 current-prefix-arg arg)
3080 (throw 'exit nil))
3081
3082 (defun org-goto-left ()
3083 "Finish `org-goto' by going to the new location."
3084 (interactive)
3085 (if (org-on-heading-p)
3086 (progn
3087 (beginning-of-line 1)
3088 (setq org-selected-point (point)
3089 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3090 (throw 'exit nil))
3091 (error "Not on a heading")))
3092
3093 (defun org-goto-right ()
3094 "Finish `org-goto' by going to the new location."
3095 (interactive)
3096 (if (org-on-heading-p)
3097 (progn
3098 (outline-end-of-subtree)
3099 (or (eobp) (forward-char 1))
3100 (setq org-selected-point (point)
3101 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3102 (throw 'exit nil))
3103 (error "Not on a heading")))
3104
3105 (defun org-goto-quit ()
3106 "Finish `org-goto' without cursor motion."
3107 (interactive)
3108 (setq org-selected-point nil)
3109 (throw 'exit nil))
3110
3111 ;;; Promotion, Demotion, Inserting new headlines
3112
3113 (defvar org-ignore-region nil
3114 "To temporarily disable the active region.")
3115
3116 (defun org-insert-heading (&optional force-heading)
3117 "Insert a new heading or item with same depth at point."
3118 (interactive "P")
3119 (when (or force-heading (not (org-insert-item)))
3120 (let* ((head (save-excursion
3121 (condition-case nil
3122 (org-back-to-heading)
3123 (error (outline-next-heading)))
3124 (prog1 (match-string 0)
3125 (funcall outline-level)))))
3126 (cond
3127 ((and (org-on-heading-p) (bolp)
3128 (save-excursion (backward-char 1) (not (org-invisible-p))))
3129 (open-line 1))
3130 ((bolp) nil)
3131 (t (newline)))
3132 (insert head)
3133 (just-one-space)
3134 (run-hooks 'org-insert-heading-hook))))
3135
3136 (defun org-insert-item ()
3137 "Insert a new item at the current level.
3138 Return t when things worked, nil when we are not in an item."
3139 (when (save-excursion
3140 (condition-case nil
3141 (progn
3142 (org-beginning-of-item)
3143 (org-at-item-p)
3144 t)
3145 (error nil)))
3146 (let* ((bul (match-string 0))
3147 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3148 (match-end 0)))
3149 (eowcol (save-excursion (goto-char eow) (current-column))))
3150 (cond
3151 ((and (org-at-item-p) (<= (point) eow))
3152 ;; before the bullet
3153 (beginning-of-line 1)
3154 (open-line 1))
3155 ((<= (point) eow)
3156 (beginning-of-line 1))
3157 (t (newline)))
3158 (insert bul)
3159 (just-one-space))
3160 (org-maybe-renumber-ordered-list)
3161 t))
3162
3163 (defun org-insert-todo-heading (arg)
3164 "Insert a new heading with the same level and TODO state as current heading.
3165 If the heading has no TODO state, or if the state is DONE, use the first
3166 state (TODO by default). Also with prefix arg, force first state."
3167 (interactive "P")
3168 (org-insert-heading)
3169 (save-excursion
3170 (org-back-to-heading)
3171 (outline-previous-heading)
3172 (looking-at org-todo-line-regexp))
3173 (if (or arg
3174 (not (match-beginning 2))
3175 (equal (match-string 2) org-done-string))
3176 (insert (car org-todo-keywords) " ")
3177 (insert (match-string 2) " ")))
3178
3179 (defun org-promote-subtree ()
3180 "Promote the entire subtree.
3181 See also `org-promote'."
3182 (interactive)
3183 (save-excursion
3184 (org-map-tree 'org-promote)))
3185
3186 (defun org-demote-subtree ()
3187 "Demote the entire subtree. See `org-demote'.
3188 See also `org-promote'."
3189 (interactive)
3190 (save-excursion
3191 (org-map-tree 'org-demote)))
3192
3193 (defun org-do-promote ()
3194 "Promote the current heading higher up the tree.
3195 If the region is active in `transient-mark-mode', promote all headings
3196 in the region."
3197 (interactive)
3198 (save-excursion
3199 (if (org-region-active-p)
3200 (org-map-region 'org-promote (region-beginning) (region-end))
3201 (org-promote)))
3202 (org-fix-position-after-promote))
3203
3204 (defun org-do-demote ()
3205 "Demote the current heading lower down the tree.
3206 If the region is active in `transient-mark-mode', demote all headings
3207 in the region."
3208 (interactive)
3209 (save-excursion
3210 (if (org-region-active-p)
3211 (org-map-region 'org-demote (region-beginning) (region-end))
3212 (org-demote)))
3213 (org-fix-position-after-promote))
3214
3215 (defun org-fix-position-after-promote ()
3216 "Make sure that after pro/demotion cursor position is right."
3217 (and (equal (char-after) ?\ )
3218 (equal (char-before) ?*)
3219 (forward-char 1)))
3220
3221 (defun org-get-legal-level (level change)
3222 "Rectify a level change under the influence of `org-odd-levels-only'
3223 LEVEL is a current level, CHANGE is by how much the level should be
3224 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3225 even level numbers will become the next higher odd number."
3226 (if org-odd-levels-only
3227 (cond ((not change) (1+ (* 2 (/ level 2))))
3228 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3229 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3230 (max 1 (+ level change))))
3231
3232 (defun org-promote ()
3233 "Promote the current heading higher up the tree.
3234 If the region is active in `transient-mark-mode', promote all headings
3235 in the region."
3236 (org-back-to-heading t)
3237 (let* ((level (save-match-data (funcall outline-level)))
3238 (up-head (make-string (org-get-legal-level level -1) ?*))
3239 (diff (abs (- level (length up-head)))))
3240 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3241 (replace-match up-head nil t)
3242 ;; Fixup tag positioning
3243 (and org-auto-align-tags (org-set-tags nil t))
3244 (if org-adapt-indentation
3245 (org-fixup-indentation (if (> diff 1) "^ " "^ ") ""
3246 (if (> diff 1) "^ ? ?\\S-" "^ ?\\S-")))))
3247
3248 (defun org-demote ()
3249 "Demote the current heading lower down the tree.
3250 If the region is active in `transient-mark-mode', demote all headings
3251 in the region."
3252 (org-back-to-heading t)
3253 (let* ((level (save-match-data (funcall outline-level)))
3254 (down-head (make-string (org-get-legal-level level 1) ?*))
3255 (diff (abs (- level (length down-head)))))
3256 (replace-match down-head nil t)
3257 ;; Fixup tag positioning
3258 (and org-auto-align-tags (org-set-tags nil t))
3259 (if org-adapt-indentation
3260 (org-fixup-indentation "^ " (if (> diff 1) " " " ") "^\\S-"))))
3261
3262 (defun org-map-tree (fun)
3263 "Call FUN for every heading underneath the current one."
3264 (org-back-to-heading)
3265 (let ((level (funcall outline-level)))
3266 (save-excursion
3267 (funcall fun)
3268 (while (and (progn
3269 (outline-next-heading)
3270 (> (funcall outline-level) level))
3271 (not (eobp)))
3272 (funcall fun)))))
3273
3274 (defun org-map-region (fun beg end)
3275 "Call FUN for every heading between BEG and END."
3276 (let ((org-ignore-region t))
3277 (save-excursion
3278 (setq end (copy-marker end))
3279 (goto-char beg)
3280 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3281 (< (point) end))
3282 (funcall fun))
3283 (while (and (progn
3284 (outline-next-heading)
3285 (< (point) end))
3286 (not (eobp)))
3287 (funcall fun)))))
3288
3289 (defun org-fixup-indentation (from to prohibit)
3290 "Change the indentation in the current entry by re-replacing FROM with TO.
3291 However, if the regexp PROHIBIT matches at all, don't do anything.
3292 This is being used to change indentation along with the length of the
3293 heading marker. But if there are any lines which are not indented, nothing
3294 is changed at all."
3295 (save-excursion
3296 (let ((end (save-excursion (outline-next-heading)
3297 (point-marker))))
3298 (unless (save-excursion (re-search-forward prohibit end t))
3299 (while (re-search-forward from end t)
3300 (replace-match to)
3301 (beginning-of-line 2)))
3302 (move-marker end nil))))
3303
3304 ;;; Vertical tree motion, cutting and pasting of subtrees
3305
3306 (defun org-move-subtree-up (&optional arg)
3307 "Move the current subtree up past ARG headlines of the same level."
3308 (interactive "p")
3309 (org-move-subtree-down (- (prefix-numeric-value arg))))
3310
3311 (defun org-move-subtree-down (&optional arg)
3312 "Move the current subtree down past ARG headlines of the same level."
3313 (interactive "p")
3314 (setq arg (prefix-numeric-value arg))
3315 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3316 'outline-get-last-sibling))
3317 (ins-point (make-marker))
3318 (cnt (abs arg))
3319 beg end txt folded)
3320 ;; Select the tree
3321 (org-back-to-heading)
3322 (setq beg (point))
3323 (save-match-data
3324 (save-excursion (outline-end-of-heading)
3325 (setq folded (org-invisible-p)))
3326 (outline-end-of-subtree))
3327 (outline-next-heading)
3328 (setq end (point))
3329 ;; Find insertion point, with error handling
3330 (goto-char beg)
3331 (while (> cnt 0)
3332 (or (and (funcall movfunc) (looking-at outline-regexp))
3333 (progn (goto-char beg)
3334 (error "Cannot move past superior level or buffer limit")))
3335 (setq cnt (1- cnt)))
3336 (if (> arg 0)
3337 ;; Moving forward - still need to move over subtree
3338 (progn (outline-end-of-subtree)
3339 (outline-next-heading)
3340 (if (not (or (looking-at (concat "^" outline-regexp))
3341 (bolp)))
3342 (newline))))
3343 (move-marker ins-point (point))
3344 (setq txt (buffer-substring beg end))
3345 (delete-region beg end)
3346 (insert txt)
3347 (goto-char ins-point)
3348 (if folded (hide-subtree))
3349 (move-marker ins-point nil)))
3350
3351 (defvar org-subtree-clip ""
3352 "Clipboard for cut and paste of subtrees.
3353 This is actually only a copy of the kill, because we use the normal kill
3354 ring. We need it to check if the kill was created by `org-copy-subtree'.")
3355
3356 (defvar org-subtree-clip-folded nil
3357 "Was the last copied subtree folded?
3358 This is used to fold the tree back after pasting.")
3359
3360 (defun org-cut-subtree ()
3361 "Cut the current subtree into the clipboard.
3362 This is a short-hand for marking the subtree and then cutting it."
3363 (interactive)
3364 (org-copy-subtree 'cut))
3365
3366 (defun org-copy-subtree (&optional cut)
3367 "Cut the current subtree into the clipboard.
3368 This is a short-hand for marking the subtree and then copying it.
3369 If CUT is non nil, actually cut the subtree."
3370 (interactive)
3371 (let (beg end folded)
3372 (org-back-to-heading)
3373 (setq beg (point))
3374 (save-match-data
3375 (save-excursion (outline-end-of-heading)
3376 (setq folded (org-invisible-p)))
3377 (outline-end-of-subtree))
3378 (if (equal (char-after) ?\n) (forward-char 1))
3379 (setq end (point))
3380 (goto-char beg)
3381 (when (> end beg)
3382 (setq org-subtree-clip-folded folded)
3383 (if cut (kill-region beg end) (copy-region-as-kill beg end))
3384 (setq org-subtree-clip (current-kill 0))
3385 (message "%s: Subtree with %d characters"
3386 (if cut "Cut" "Copied")
3387 (length org-subtree-clip)))))
3388
3389 (defun org-paste-subtree (&optional level tree)
3390 "Paste the clipboard as a subtree, with modification of headline level.
3391 The entire subtree is promoted or demoted in order to match a new headline
3392 level. By default, the new level is derived from the visible headings
3393 before and after the insertion point, and taken to be the inferior headline
3394 level of the two. So if the previous visible heading is level 3 and the
3395 next is level 4 (or vice versa), level 4 will be used for insertion.
3396 This makes sure that the subtree remains an independent subtree and does
3397 not swallow low level entries.
3398
3399 You can also force a different level, either by using a numeric prefix
3400 argument, or by inserting the heading marker by hand. For example, if the
3401 cursor is after \"*****\", then the tree will be shifted to level 5.
3402
3403 If you want to insert the tree as is, just use \\[yank].
3404
3405 If optional TREE is given, use this text instead of the kill ring."
3406 (interactive "P")
3407 (unless (org-kill-is-subtree-p tree)
3408 (error
3409 (substitute-command-keys
3410 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
3411 (let* ((txt (or tree (current-kill 0)))
3412 (^re (concat "^\\(" outline-regexp "\\)"))
3413 (re (concat "\\(" outline-regexp "\\)"))
3414 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
3415
3416 (old-level (if (string-match ^re txt)
3417 (- (match-end 0) (match-beginning 0))
3418 -1))
3419 (force-level (cond (level (prefix-numeric-value level))
3420 ((string-match
3421 ^re_ (buffer-substring (point-at-bol) (point)))
3422 (- (match-end 0) (match-beginning 0)))
3423 (t nil)))
3424 (previous-level (save-excursion
3425 (condition-case nil
3426 (progn
3427 (outline-previous-visible-heading 1)
3428 (if (looking-at re)
3429 (- (match-end 0) (match-beginning 0))
3430 1))
3431 (error 1))))
3432 (next-level (save-excursion
3433 (condition-case nil
3434 (progn
3435 (outline-next-visible-heading 1)
3436 (if (looking-at re)
3437 (- (match-end 0) (match-beginning 0))
3438 1))
3439 (error 1))))
3440 (new-level (or force-level (max previous-level next-level)))
3441 (shift (if (or (= old-level -1)
3442 (= new-level -1)
3443 (= old-level new-level))
3444 0
3445 (- new-level old-level)))
3446 (shift1 shift)
3447 (delta (if (> shift 0) -1 1))
3448 (func (if (> shift 0) 'org-demote 'org-promote))
3449 (org-odd-levels-only nil)
3450 beg end)
3451 ;; Remove the forces level indicator
3452 (if force-level
3453 (delete-region (point-at-bol) (point)))
3454 ;; Make sure we start at the beginning of an empty line
3455 (if (not (bolp)) (insert "\n"))
3456 (if (not (looking-at "[ \t]*$"))
3457 (progn (insert "\n") (backward-char 1)))
3458 ;; Paste
3459 (setq beg (point))
3460 (insert txt)
3461 (setq end (point))
3462 (goto-char beg)
3463 ;; Shift if necessary
3464 (if (= shift 0)
3465 (message "Pasted at level %d, without shift" new-level)
3466 (save-restriction
3467 (narrow-to-region beg end)
3468 (while (not (= shift 0))
3469 (org-map-region func (point-min) (point-max))
3470 (setq shift (+ delta shift)))
3471 (goto-char (point-min))
3472 (message "Pasted at level %d, with shift by %d levels"
3473 new-level shift1)))
3474 (if (and (eq org-subtree-clip (current-kill 0))
3475 org-subtree-clip-folded)
3476 ;; The tree was folded before it was killed/copied
3477 (hide-subtree))))
3478
3479 (defun org-kill-is-subtree-p (&optional txt)
3480 "Check if the current kill is an outline subtree, or a set of trees.
3481 Returns nil if kill does not start with a headline, or if the first
3482 headline level is not the largest headline level in the tree.
3483 So this will actually accept several entries of equal levels as well,
3484 which is OK for `org-paste-subtree'.
3485 If optional TXT is given, check this string instead of the current kill."
3486 (let* ((kill (or txt (current-kill 0) ""))
3487 (start-level (and (string-match (concat "\\`" outline-regexp) kill)
3488 (- (match-end 0) (match-beginning 0))))
3489 (re (concat "^" outline-regexp))
3490 (start 1))
3491 (if (not start-level)
3492 nil ;; does not even start with a heading
3493 (catch 'exit
3494 (while (setq start (string-match re kill (1+ start)))
3495 (if (< (- (match-end 0) (match-beginning 0)) start-level)
3496 (throw 'exit nil)))
3497 t))))
3498
3499 ;;; Plain list items
3500
3501 (defun org-at-item-p ()
3502 "Is point in a line starting a hand-formatted item?"
3503 (let ((llt org-plain-list-ordered-item-terminator))
3504 (save-excursion
3505 (goto-char (point-at-bol))
3506 (looking-at
3507 (cond
3508 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3509 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3510 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
3511 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
3512
3513 (defun org-get-indentation ()
3514 "Get the indentation of the current line, interpreting tabs."
3515 (save-excursion
3516 (beginning-of-line 1)
3517 (skip-chars-forward " \t")
3518 (current-column)))
3519
3520 (defun org-beginning-of-item ()
3521 "Go to the beginning of the current hand-formatted item.
3522 If the cursor is not in an item, throw an error."
3523 (let ((pos (point))
3524 (limit (save-excursion (org-back-to-heading)
3525 (beginning-of-line 2) (point)))
3526 ind ind1)
3527 (if (org-at-item-p)
3528 (beginning-of-line 1)
3529 (beginning-of-line 1)
3530 (skip-chars-forward " \t")
3531 (setq ind (current-column))
3532 (if (catch 'exit
3533 (while t
3534 (beginning-of-line 0)
3535 (if (< (point) limit) (throw 'exit nil))
3536 (unless (looking-at " \t]*$")
3537 (skip-chars-forward " \t")
3538 (setq ind1 (current-column))
3539 (if (< ind1 ind)
3540 (throw 'exit (org-at-item-p))))))
3541 nil
3542 (goto-char pos)
3543 (error "Not in an item")))))
3544
3545 (defun org-end-of-item ()
3546 "Go to the end of the current hand-formatted item.
3547 If the cursor is not in an item, throw an error."
3548 (let ((pos (point))
3549 (limit (save-excursion (outline-next-heading) (point)))
3550 (ind (save-excursion
3551 (org-beginning-of-item)
3552 (skip-chars-forward " \t")
3553 (current-column)))
3554 ind1)
3555 (if (catch 'exit
3556 (while t
3557 (beginning-of-line 2)
3558 (if (>= (point) limit) (throw 'exit t))
3559 (unless (looking-at "[ \t]*$")
3560 (skip-chars-forward " \t")
3561 (setq ind1 (current-column))
3562 (if (<= ind1 ind) (throw 'exit t)))))
3563 (beginning-of-line 1)
3564 (goto-char pos)
3565 (error "Not in an item"))))
3566
3567 (defun org-move-item-down (arg)
3568 "Move the plain list item at point down, i.e. swap with following item.
3569 Subitems (items with larger indentation) are considered part of the item,
3570 so this really moves item trees."
3571 (interactive "p")
3572 (let (beg end ind ind1 (pos (point)) txt)
3573 (org-beginning-of-item)
3574 (setq beg (point))
3575 (setq ind (org-get-indentation))
3576 (org-end-of-item)
3577 (setq end (point))
3578 (setq ind1 (org-get-indentation))
3579 (if (and (org-at-item-p) (= ind ind1))
3580 (progn
3581 (org-end-of-item)
3582 (setq txt (buffer-substring beg end))
3583 (save-excursion
3584 (delete-region beg end))
3585 (setq pos (point))
3586 (insert txt)
3587 (goto-char pos)
3588 (org-maybe-renumber-ordered-list))
3589 (goto-char pos)
3590 (error "Cannot move this item further down"))))
3591
3592 (defun org-move-item-up (arg)
3593 "Move the plain list item at point up, i.e. swap with previous item.
3594 Subitems (items with larger indentation) are considered part of the item,
3595 so this really moves item trees."
3596 (interactive "p")
3597 (let (beg end ind ind1 (pos (point)) txt)
3598 (org-beginning-of-item)
3599 (setq beg (point))
3600 (setq ind (org-get-indentation))
3601 (org-end-of-item)
3602 (setq end (point))
3603 (goto-char beg)
3604 (catch 'exit
3605 (while t
3606 (beginning-of-line 0)
3607 (if (looking-at "[ \t]*$")
3608 nil
3609 (if (<= (setq ind1 (org-get-indentation)) ind)
3610 (throw 'exit t)))))
3611 (condition-case nil
3612 (org-beginning-of-item)
3613 (error (goto-char beg)
3614 (error "Cannot move this item further up")))
3615 (setq ind1 (org-get-indentation))
3616 (if (and (org-at-item-p) (= ind ind1))
3617 (progn
3618 (setq txt (buffer-substring beg end))
3619 (save-excursion
3620 (delete-region beg end))
3621 (setq pos (point))
3622 (insert txt)
3623 (goto-char pos)
3624 (org-maybe-renumber-ordered-list))
3625 (goto-char pos)
3626 (error "Cannot move this item further up"))))
3627
3628 (defun org-maybe-renumber-ordered-list ()
3629 "Renumber the ordered list at point if setup allows it.
3630 This tests the user option `org-auto-renumber-ordered-lists' before
3631 doing the renumbering."
3632 (and org-auto-renumber-ordered-lists
3633 (org-at-item-p)
3634 (match-beginning 3)
3635 (org-renumber-ordered-list 1)))
3636
3637 (defun org-get-string-indentation (s)
3638 "What indentation has S due to SPACE and TAB at the beginning of the string?"
3639 (let ((n -1) (i 0) (w tab-width) c)
3640 (catch 'exit
3641 (while (< (setq n (1+ n)) (length s))
3642 (setq c (aref s n))
3643 (cond ((= c ?\ ) (setq i (1+ i)))
3644 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
3645 (t (throw 'exit t)))))
3646 i))
3647
3648 (defun org-renumber-ordered-list (arg)
3649 "Renumber an ordered plain list.
3650 Cursor next to be in the first line of an item, the line that starts
3651 with something like \"1.\" or \"2)\"."
3652 (interactive "p")
3653 (unless (and (org-at-item-p)
3654 (match-beginning 3))
3655 (error "This is not an ordered list"))
3656 (let ((line (org-current-line))
3657 (col (current-column))
3658 (ind (org-get-string-indentation
3659 (buffer-substring (point-at-bol) (match-beginning 3))))
3660 ;; (term (substring (match-string 3) -1))
3661 ind1 (n (1- arg)))
3662 ;; find where this list begins
3663 (catch 'exit
3664 (while t
3665 (catch 'next
3666 (beginning-of-line 0)
3667 (if (looking-at "[ \t]*$") (throw 'next t))
3668 (skip-chars-forward " \t") (setq ind1 (current-column))
3669 (if (or (< ind1 ind)
3670 (and (= ind1 ind)
3671 (not (org-at-item-p))))
3672 (throw 'exit t)))))
3673 ;; Walk forward and replace these numbers
3674 (catch 'exit
3675 (while t
3676 (catch 'next
3677 (beginning-of-line 2)
3678 (if (eobp) (throw 'exit nil))
3679 (if (looking-at "[ \t]*$") (throw 'next nil))
3680 (skip-chars-forward " \t") (setq ind1 (current-column))
3681 (if (> ind1 ind) (throw 'next t))
3682 (if (< ind1 ind) (throw 'exit t))
3683 (if (not (org-at-item-p)) (throw 'exit nil))
3684 (if (not (match-beginning 3))
3685 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
3686 (delete-region (match-beginning 3) (1- (match-end 3)))
3687 (goto-char (match-beginning 3))
3688 (insert (format "%d" (setq n (1+ n)))))))
3689 (goto-line line)
3690 (move-to-column col)))
3691
3692 (defvar org-last-indent-begin-marker (make-marker))
3693 (defvar org-last-indent-end-marker (make-marker))
3694
3695 (defun org-outdent-item (arg)
3696 "Outdent a local list item."
3697 (interactive "p")
3698 (org-indent-item (- arg)))
3699
3700 (defun org-indent-item (arg)
3701 "Indent a local list item."
3702 (interactive "p")
3703 (unless (org-at-item-p)
3704 (error "Not on an item"))
3705 (let (beg end ind ind1)
3706 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
3707 (setq beg org-last-indent-begin-marker
3708 end org-last-indent-end-marker)
3709 (org-beginning-of-item)
3710 (setq beg (move-marker org-last-indent-begin-marker (point)))
3711 (org-end-of-item)
3712 (setq end (move-marker org-last-indent-end-marker (point))))
3713 (goto-char beg)
3714 (skip-chars-forward " \t") (setq ind (current-column))
3715 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
3716 (while (< (point) end)
3717 (beginning-of-line 1)
3718 (skip-chars-forward " \t") (setq ind1 (current-column))
3719 (delete-region (point-at-bol) (point))
3720 (indent-to-column (+ ind1 arg))
3721 (beginning-of-line 2))
3722 (goto-char beg)))
3723
3724 ;;; Archiving
3725
3726 (defun org-archive-subtree ()
3727 "Move the current subtree to the archive.
3728 The archive can be a certain top-level heading in the current file, or in
3729 a different file. The tree will be moved to that location, the subtree
3730 heading be marked DONE, and the current time will be added."
3731 (interactive)
3732 ;; Save all relevant TODO keyword-relatex variables
3733 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
3734 (tr-org-todo-keywords org-todo-keywords)
3735 (tr-org-todo-interpretation org-todo-interpretation)
3736 (tr-org-done-string org-done-string)
3737 (tr-org-todo-regexp org-todo-regexp)
3738 (tr-org-todo-line-regexp org-todo-line-regexp)
3739 (this-buffer (current-buffer))
3740 file heading buffer level newfile-p)
3741 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
3742 (progn
3743 (setq file (format (match-string 1 org-archive-location)
3744 (file-name-nondirectory buffer-file-name))
3745 heading (match-string 2 org-archive-location)))
3746 (error "Invalid `org-archive-location'"))
3747 (if (> (length file) 0)
3748 (setq newfile-p (not (file-exists-p file))
3749 buffer (find-file-noselect file))
3750 (setq buffer (current-buffer)))
3751 (unless buffer
3752 (error "Cannot access file \"%s\"" file))
3753 (if (and (> (length heading) 0)
3754 (string-match "^\\*+" heading))
3755 (setq level (match-end 0))
3756 (setq heading nil level 0))
3757 (save-excursion
3758 ;; We first only copy, in case something goes wrong
3759 ;; we need to protect this-command, to avoid kill-region sets it,
3760 ;; which would lead to duplication of subtrees
3761 (let (this-command) (org-copy-subtree))
3762 (set-buffer buffer)
3763 ;; Enforce org-mode for the archive buffer
3764 (if (not (eq major-mode 'org-mode))
3765 ;; Force the mode for future visits.
3766 (let ((org-insert-mode-line-in-empty-file t))
3767 (call-interactively 'org-mode)))
3768 (when newfile-p
3769 (goto-char (point-max))
3770 (insert (format "\nArchived entries from file %s\n\n"
3771 (buffer-file-name this-buffer))))
3772 ;; Force the TODO keywords of the original buffer
3773 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
3774 (org-todo-keywords tr-org-todo-keywords)
3775 (org-todo-interpretation tr-org-todo-interpretation)
3776 (org-done-string tr-org-done-string)
3777 (org-todo-regexp tr-org-todo-regexp)
3778 (org-todo-line-regexp tr-org-todo-line-regexp))
3779 (goto-char (point-min))
3780 (if heading
3781 (progn
3782 (if (re-search-forward
3783 (concat "\\(^\\|\r\\)"
3784 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
3785 nil t)
3786 (goto-char (match-end 0))
3787 ;; Heading not found, just insert it at the end
3788 (goto-char (point-max))
3789 (or (bolp) (insert "\n"))
3790 (insert "\n" heading "\n")
3791 (end-of-line 0))
3792 ;; Make the heading visible, and the following as well
3793 (let ((org-show-following-heading t)) (org-show-hierarchy-above))
3794 (if (re-search-forward
3795 (concat "^" (regexp-quote (make-string level ?*)) "[ \t]")
3796 nil t)
3797 (progn (goto-char (match-beginning 0)) (insert "\n")
3798 (beginning-of-line 0))
3799 (goto-char (point-max)) (insert "\n")))
3800 (goto-char (point-max)) (insert "\n"))
3801 ;; Paste
3802 (org-paste-subtree (1+ level))
3803 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
3804 (if org-archive-mark-done
3805 (org-todo (length org-todo-keywords)))
3806 ;; Move cursor to right after the TODO keyword
3807 (when org-archive-stamp-time
3808 (beginning-of-line 1)
3809 (looking-at org-todo-line-regexp)
3810 (goto-char (or (match-end 2) (match-beginning 3)))
3811 (insert "(" (format-time-string (cdr org-time-stamp-formats)
3812 (org-current-time))
3813 ")"))
3814 ;; Save the buffer, if it is not the same buffer.
3815 (if (not (eq this-buffer buffer)) (save-buffer))))
3816 ;; Here we are back in the original buffer. Everything seems to have
3817 ;; worked. So now cut the tree and finish up.
3818 (let (this-command) (org-cut-subtree))
3819 (if (looking-at "[ \t]*$") (kill-line))
3820 (message "Subtree archived %s"
3821 (if (eq this-buffer buffer)
3822 (concat "under heading: " heading)
3823 (concat "in file: " (abbreviate-file-name file))))))
3824
3825 ;;; Completion
3826
3827 (defun org-complete (&optional arg)
3828 "Perform completion on word at point.
3829 At the beginning of a headline, this completes TODO keywords as given in
3830 `org-todo-keywords'.
3831 If the current word is preceded by a backslash, completes the TeX symbols
3832 that are supported for HTML support.
3833 If the current word is preceded by \"#+\", completes special words for
3834 setting file options.
3835 At all other locations, this simply calls `ispell-complete-word'."
3836 (interactive "P")
3837 (catch 'exit
3838 (let* ((end (point))
3839 (beg1 (save-excursion
3840 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3841 (skip-chars-backward "a-zA-Z_@0-9")
3842 (point)))
3843 (beg (save-excursion
3844 (if (equal (char-before (point)) ?\ ) (backward-char 1))
3845 (skip-chars-backward "a-zA-Z0-9_:$")
3846 (point)))
3847 (camel (equal (char-before beg) ?*))
3848 (tag (equal (char-before beg1) ?:))
3849 (texp (equal (char-before beg) ?\\))
3850 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
3851 beg)
3852 "#+"))
3853 (completion-ignore-case opt)
3854 (type nil)
3855 (tbl nil)
3856 (table (cond
3857 (opt
3858 (setq type :opt)
3859 (mapcar (lambda (x)
3860 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
3861 (cons (match-string 2 x) (match-string 1 x)))
3862 (org-split-string (org-get-current-options) "\n")))
3863 (texp
3864 (setq type :tex)
3865 org-html-entities)
3866 ((string-match "\\`\\*+[ \t]*\\'"
3867 (buffer-substring (point-at-bol) beg))
3868 (setq type :todo)
3869 (mapcar 'list org-todo-keywords))
3870 (camel
3871 (setq type :camel)
3872 (save-excursion
3873 (goto-char (point-min))
3874 (while (re-search-forward org-todo-line-regexp nil t)
3875 (push (list
3876 (if org-file-link-context-use-camel-case
3877 (org-make-org-heading-camel (match-string 3) t)
3878 (org-make-org-heading-search-string
3879 (match-string 3) t)))
3880 tbl)))
3881 tbl)
3882 (tag (setq type :tag beg beg1)
3883 (org-get-buffer-tags))
3884 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
3885 (pattern (buffer-substring-no-properties beg end))
3886 (completion (try-completion pattern table)))
3887 (cond ((eq completion t)
3888 (if (equal type :opt)
3889 (insert (substring (cdr (assoc (upcase pattern) table))
3890 (length pattern)))))
3891 ((null completion)
3892 (message "Can't find completion for \"%s\"" pattern)
3893 (ding))
3894 ((not (string= pattern completion))
3895 (delete-region beg end)
3896 (if (string-match " +$" completion)
3897 (setq completion (replace-match "" t t completion)))
3898 (insert completion)
3899 (if (get-buffer-window "*Completions*")
3900 (delete-window (get-buffer-window "*Completions*")))
3901 (if (assoc completion table)
3902 (if (eq type :todo) (insert " ")
3903 (if (eq type :tag) (insert ":"))))
3904 (if (and (equal type :opt) (assoc completion table))
3905 (message "%s" (substitute-command-keys
3906 "Press \\[org-complete] again to insert example settings"))))
3907 (t
3908 (message "Making completion list...")
3909 (let ((list (sort (all-completions pattern table) 'string<)))
3910 (with-output-to-temp-buffer "*Completions*"
3911 (condition-case nil
3912 ;; Protection needed for XEmacs and emacs 21
3913 (display-completion-list list pattern)
3914 (error (display-completion-list list)))))
3915 (message "Making completion list...%s" "done"))))))
3916
3917 ;;; Comments, TODO and DEADLINE
3918
3919 (defun org-toggle-comment ()
3920 "Change the COMMENT state of an entry."
3921 (interactive)
3922 (save-excursion
3923 (org-back-to-heading)
3924 (if (looking-at (concat outline-regexp
3925 "\\( +\\<" org-comment-string "\\>\\)"))
3926 (replace-match "" t t nil 1)
3927 (if (looking-at outline-regexp)
3928 (progn
3929 (goto-char (match-end 0))
3930 (insert " " org-comment-string))))))
3931
3932 (defvar org-last-todo-state-is-todo nil
3933 "This is non-nil when the last TODO state change led to a TODO state.
3934 If the last change removed the TODO tag or switched to DONE, then
3935 this is nil.")
3936
3937 (defun org-todo (&optional arg)
3938 "Change the TODO state of an item.
3939 The state of an item is given by a keyword at the start of the heading,
3940 like
3941 *** TODO Write paper
3942 *** DONE Call mom
3943
3944 The different keywords are specified in the variable `org-todo-keywords'.
3945 By default the available states are \"TODO\" and \"DONE\".
3946 So for this example: when the item starts with TODO, it is changed to DONE.
3947 When it starts with DONE, the DONE is removed. And when neither TODO nor
3948 DONE are present, add TODO at the beginning of the heading.
3949
3950 With prefix arg, use completion to determine the new state. With numeric
3951 prefix arg, switch to that state."
3952 (interactive "P")
3953 (save-excursion
3954 (org-back-to-heading)
3955 (if (looking-at outline-regexp) (goto-char (match-end 0)))
3956 (or (looking-at (concat " +" org-todo-regexp " *"))
3957 (looking-at " *"))
3958 (let* ((this (match-string 1))
3959 (completion-ignore-case t)
3960 (member (member this org-todo-keywords))
3961 (tail (cdr member))
3962 (state (cond
3963 ((equal arg '(4))
3964 ;; Read a state with completion
3965 (completing-read "State: " (mapcar (lambda(x) (list x))
3966 org-todo-keywords)
3967 nil t))
3968 ((eq arg 'right)
3969 (if this
3970 (if tail (car tail) nil)
3971 (car org-todo-keywords)))
3972 ((eq arg 'left)
3973 (if (equal member org-todo-keywords)
3974 nil
3975 (if this
3976 (nth (- (length org-todo-keywords) (length tail) 2)
3977 org-todo-keywords)
3978 org-done-string)))
3979 (arg
3980 ;; user requests a specific state
3981 (nth (1- (prefix-numeric-value arg))
3982 org-todo-keywords))
3983 ((null member) (car org-todo-keywords))
3984 ((null tail) nil) ;; -> first entry
3985 ((eq org-todo-interpretation 'sequence)
3986 (car tail))
3987 ((memq org-todo-interpretation '(type priority))
3988 (if (eq this-command last-command)
3989 (car tail)
3990 (if (> (length tail) 0) org-done-string nil)))
3991 (t nil)))
3992 (next (if state (concat " " state " ") " ")))
3993 (replace-match next t t)
3994 (setq org-last-todo-state-is-todo
3995 (not (equal state org-done-string)))
3996 (when org-log-done
3997 (if (equal state org-done-string)
3998 (org-log-done)
3999 (if (not this)
4000 (org-log-done t))))
4001 ;; Fixup tag positioning
4002 (and org-auto-align-tags (org-set-tags nil t))
4003 (run-hooks 'org-after-todo-state-change-hook)))
4004 ;; Fixup cursor location if close to the keyword
4005 (if (and (outline-on-heading-p)
4006 (not (bolp))
4007 (save-excursion (beginning-of-line 1)
4008 (looking-at org-todo-line-regexp))
4009 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
4010 (progn
4011 (goto-char (or (match-end 2) (match-end 1)))
4012 (just-one-space))))
4013
4014 (defun org-log-done (&optional undone)
4015 "Add a time stamp logging that a TODO entry has been closed.
4016 When UNDONE is non-nil, remove such a time stamp again."
4017 (interactive)
4018 (let (beg end col)
4019 (save-excursion
4020 (org-back-to-heading t)
4021 (setq beg (point))
4022 (looking-at (concat outline-regexp " *"))
4023 (goto-char (match-end 0))
4024 (setq col (current-column))
4025 (outline-next-heading)
4026 (setq end (point))
4027 (goto-char beg)
4028 (when (re-search-forward (concat
4029 "[\r\n]\\([ \t]*"
4030 (regexp-quote org-closed-string)
4031 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
4032 (delete-region (match-beginning 1) (match-end 1)))
4033 (unless undone
4034 (org-back-to-heading t)
4035 (skip-chars-forward "^\n\r")
4036 (goto-char (min (1+ (point)) (point-max)))
4037 (when (not (member (char-before) '(?\r ?\n)))
4038 (insert "\n"))
4039 (indent-to col)
4040 (insert org-closed-string " "
4041 (format-time-string
4042 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
4043 (org-current-time))
4044 "\n")))))
4045
4046 (defun org-show-todo-tree (arg)
4047 "Make a compact tree which shows all headlines marked with TODO.
4048 The tree will show the lines where the regexp matches, and all higher
4049 headlines above the match.
4050 With \\[universal-argument] prefix, also show the DONE entries.
4051 With a numeric prefix N, construct a sparse tree for the Nth element
4052 of `org-todo-keywords'."
4053 (interactive "P")
4054 (let ((case-fold-search nil)
4055 (kwd-re
4056 (cond ((null arg) org-not-done-regexp)
4057 ((equal arg '(4)) org-todo-regexp)
4058 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
4059 (regexp-quote (nth (1- (prefix-numeric-value arg))
4060 org-todo-keywords)))
4061 (t (error "Invalid prefix argument: %s" arg)))))
4062 (message "%d TODO entries found"
4063 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
4064
4065 (defun org-deadline ()
4066 "Insert the DEADLINE: string to make a deadline.
4067 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4068 to modify it to the correct date."
4069 (interactive)
4070 (insert
4071 org-deadline-string " "
4072 (format-time-string (car org-time-stamp-formats)
4073 (org-read-date nil 'to-time)))
4074 (message "%s" (substitute-command-keys
4075 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
4076
4077 (defun org-schedule ()
4078 "Insert the SCHEDULED: string to schedule a TODO item.
4079 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
4080 to modify it to the correct date."
4081 (interactive)
4082 (insert
4083 org-scheduled-string " "
4084 (format-time-string (car org-time-stamp-formats)
4085 (org-read-date nil 'to-time)))
4086 (message "%s" (substitute-command-keys
4087 "Use \\[org-timestamp-up-day] and \\[org-timestamp-down-day] to change the date.")))
4088
4089
4090 (defun org-occur (regexp &optional callback)
4091 "Make a compact tree which shows all matches of REGEXP.
4092 The tree will show the lines where the regexp matches, and all higher
4093 headlines above the match. It will also show the heading after the match,
4094 to make sure editing the matching entry is easy.
4095 If CALLBACK is non-nil, it is a function which is called to confirm
4096 that the match should indeed be shown."
4097 (interactive "sRegexp: ")
4098 (org-remove-occur-highlights nil nil t)
4099 (setq regexp (org-check-occur-regexp regexp))
4100 (let ((cnt 0))
4101 (save-excursion
4102 (goto-char (point-min))
4103 (hide-sublevels 1)
4104 (while (re-search-forward regexp nil t)
4105 (when (or (not callback)
4106 (save-match-data (funcall callback)))
4107 (setq cnt (1+ cnt))
4108 (org-highlight-new-match (match-beginning 0) (match-end 0))
4109 (org-show-hierarchy-above))))
4110 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
4111 nil 'local)
4112 (run-hooks 'org-occur-hook)
4113 (if (interactive-p)
4114 (message "%d match(es) for regexp %s" cnt regexp))
4115 cnt))
4116
4117 (defun org-show-hierarchy-above ()
4118 "Make sure point and the headings hierarchy above is visible."
4119 (catch 'exit
4120 (if (org-on-heading-p t)
4121 (org-flag-heading nil) ; only show the heading
4122 (and (or (org-invisible-p) (org-invisible-p2))
4123 (org-show-hidden-entry))) ; show entire entry
4124 (save-excursion
4125 (and org-show-following-heading
4126 (outline-next-heading)
4127 (org-flag-heading nil))) ; show the next heading
4128 (when org-show-hierarchy-above
4129 (save-excursion ; show all higher headings
4130 (while (and (condition-case nil
4131 (progn (org-up-heading-all 1) t)
4132 (error nil))
4133 (not (bobp)))
4134 (org-flag-heading nil))))))
4135
4136 ;; Overlay compatibility functions
4137 (defun org-make-overlay (beg end &optional buffer)
4138 (if (featurep 'xemacs)
4139 (make-extent beg end buffer)
4140 (make-overlay beg end buffer)))
4141 (defun org-delete-overlay (ovl)
4142 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
4143 (defun org-detatch-overlay (ovl)
4144 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
4145 (defun org-move-overlay (ovl beg end &optional buffer)
4146 (if (featurep 'xemacs)
4147 (set-extent-endpoints ovl beg end buffer)
4148 (move-overlay ovl beg end buffer)))
4149 (defun org-overlay-put (ovl prop value)
4150 (if (featurep 'xemacs)
4151 (set-extent-property ovl prop value)
4152 (overlay-put ovl prop value)))
4153
4154 (defvar org-occur-highlights nil)
4155 (defun org-highlight-new-match (beg end)
4156 "Highlight from BEG to END and mark the highlight is an occur headline."
4157 (let ((ov (org-make-overlay beg end)))
4158 (org-overlay-put ov 'face 'secondary-selection)
4159 (push ov org-occur-highlights)))
4160
4161 (defun org-remove-occur-highlights (&optional beg end noremove)
4162 "Remove the occur highlights from the buffer.
4163 BEG and END are ignored. If NOREMOVE is nil, remove this function
4164 from the `before-change-functions' in the current buffer."
4165 (interactive)
4166 (mapc 'org-delete-overlay org-occur-highlights)
4167 (setq org-occur-highlights nil)
4168 (unless noremove
4169 (remove-hook 'before-change-functions
4170 'org-remove-occur-highlights 'local)))
4171
4172 ;;; Priorities
4173
4174 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
4175 "Regular expression matching the priority indicator.")
4176
4177 (defvar org-remove-priority-next-time nil)
4178
4179 (defun org-priority-up ()
4180 "Increase the priority of the current item."
4181 (interactive)
4182 (org-priority 'up))
4183
4184 (defun org-priority-down ()
4185 "Decrease the priority of the current item."
4186 (interactive)
4187 (org-priority 'down))
4188
4189 (defun org-priority (&optional action)
4190 "Change the priority of an item by ARG.
4191 ACTION can be set, up, or down."
4192 (interactive)
4193 (setq action (or action 'set))
4194 (let (current new news have remove)
4195 (save-excursion
4196 (org-back-to-heading)
4197 (if (looking-at org-priority-regexp)
4198 (setq current (string-to-char (match-string 2))
4199 have t)
4200 (setq current org-default-priority))
4201 (cond
4202 ((eq action 'set)
4203 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
4204 (setq new (read-char-exclusive))
4205 (cond ((equal new ?\ ) (setq remove t))
4206 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
4207 (error "Priority must be between `%c' and `%c'"
4208 ?A org-lowest-priority))))
4209 ((eq action 'up)
4210 (setq new (1- current)))
4211 ((eq action 'down)
4212 (setq new (1+ current)))
4213 (t (error "Invalid action")))
4214 (setq new (min (max ?A (upcase new)) org-lowest-priority))
4215 (setq news (format "%c" new))
4216 (if have
4217 (if remove
4218 (replace-match "" t t nil 1)
4219 (replace-match news t t nil 2))
4220 (if remove
4221 (error "No priority cookie found in line")
4222 (looking-at org-todo-line-regexp)
4223 (if (match-end 2)
4224 (progn
4225 (goto-char (match-end 2))
4226 (insert " [#" news "]"))
4227 (goto-char (match-beginning 3))
4228 (insert "[#" news "] ")))))
4229 (if remove
4230 (message "Priority removed")
4231 (message "Priority of current item set to %s" news))))
4232
4233
4234 (defun org-get-priority (s)
4235 "Find priority cookie and return priority."
4236 (save-match-data
4237 (if (not (string-match org-priority-regexp s))
4238 (* 1000 (- org-lowest-priority org-default-priority))
4239 (* 1000 (- org-lowest-priority
4240 (string-to-char (match-string 2 s)))))))
4241
4242 ;;; Timestamps
4243
4244 (defvar org-last-changed-timestamp nil)
4245
4246 (defun org-time-stamp (arg)
4247 "Prompt for a date/time and insert a time stamp.
4248 If the user specifies a time like HH:MM, or if this command is called
4249 with a prefix argument, the time stamp will contain date and time.
4250 Otherwise, only the date will be included. All parts of a date not
4251 specified by the user will be filled in from the current date/time.
4252 So if you press just return without typing anything, the time stamp
4253 will represent the current date/time. If there is already a timestamp
4254 at the cursor, it will be modified."
4255 (interactive "P")
4256 (let ((fmt (if arg (cdr org-time-stamp-formats)
4257 (car org-time-stamp-formats)))
4258 (org-time-was-given nil)
4259 time)
4260 (cond
4261 ((and (org-at-timestamp-p)
4262 (eq last-command 'org-time-stamp)
4263 (eq this-command 'org-time-stamp))
4264 (insert "--")
4265 (setq time (let ((this-command this-command))
4266 (org-read-date arg 'totime)))
4267 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4268 (insert (format-time-string fmt time)))
4269 ((org-at-timestamp-p)
4270 (setq time (let ((this-command this-command))
4271 (org-read-date arg 'totime)))
4272 (and (org-at-timestamp-p) (replace-match
4273 (setq org-last-changed-timestamp
4274 (format-time-string fmt time))
4275 t t))
4276 (message "Timestamp updated"))
4277 (t
4278 (setq time (let ((this-command this-command))
4279 (org-read-date arg 'totime)))
4280 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4281 (insert (format-time-string fmt time))))))
4282
4283 (defun org-time-stamp-inactive (&optional arg)
4284 "Insert an inactive time stamp.
4285 An inactive time stamp is enclosed in square brackets instead of angle
4286 brackets. It is inactive in the sense that it does not trigger agenda entries,
4287 does not link to the calendar and cannot be changed with the S-cursor keys.
4288 So these are more for recording a certain time/date."
4289 (interactive "P")
4290 (let ((fmt (if arg (cdr org-time-stamp-formats)
4291 (car org-time-stamp-formats)))
4292 (org-time-was-given nil)
4293 time)
4294 (setq time (org-read-date arg 'totime))
4295 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
4296 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
4297 (insert (format-time-string fmt time))))
4298
4299 (defvar org-date-ovl (org-make-overlay 1 1))
4300 (org-overlay-put org-date-ovl 'face 'org-warning)
4301 (org-detatch-overlay org-date-ovl)
4302
4303 (defun org-read-date (&optional with-time to-time)
4304 "Read a date and make things smooth for the user.
4305 The prompt will suggest to enter an ISO date, but you can also enter anything
4306 which will at least partially be understood by `parse-time-string'.
4307 Unrecognized parts of the date will default to the current day, month, year,
4308 hour and minute. For example,
4309 3-2-5 --> 2003-02-05
4310 feb 15 --> currentyear-02-15
4311 sep 12 9 --> 2009-09-12
4312 12:45 --> today 12:45
4313 22 sept 0:34 --> currentyear-09-22 0:34
4314 12 --> currentyear-currentmonth-12
4315 Fri --> nearest Friday (today or later)
4316 etc.
4317 The function understands only English month and weekday abbreviations,
4318 but this can be configured with the variables `parse-time-months' and
4319 `parse-time-weekdays'.
4320
4321 While prompting, a calendar is popped up - you can also select the
4322 date with the mouse (button 1). The calendar shows a period of three
4323 months. To scroll it to other months, use the keys `>' and `<'.
4324 If you don't like the calendar, turn it off with
4325 \(setq org-popup-calendar-for-date-prompt nil)
4326
4327 With optional argument TO-TIME, the date will immediately be converted
4328 to an internal time.
4329 With an optional argument WITH-TIME, the prompt will suggest to also
4330 insert a time. Note that when WITH-TIME is not set, you can still
4331 enter a time, and this function will inform the calling routine about
4332 this change. The calling routine may then choose to change the format
4333 used to insert the time stamp into the buffer to include the time."
4334 (require 'parse-time)
4335 (let* ((org-time-stamp-rounding-minutes
4336 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
4337 (ct (org-current-time))
4338 (default-time
4339 ;; Default time is either today, or, when entering a range,
4340 ;; the range start.
4341 (if (save-excursion
4342 (re-search-backward
4343 (concat org-ts-regexp "--\\=") ; FIXME: exactly two minuses?
4344 (- (point) 20) t))
4345 (apply
4346 'encode-time
4347 (mapcar (lambda(x) (or x 0))
4348 (parse-time-string (match-string 1))))
4349 ct))
4350 (calendar-move-hook nil)
4351 (view-calendar-holidays-initially nil)
4352 (view-diary-entries-initially nil)
4353 (timestr (format-time-string
4354 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
4355 (prompt (format "YYYY-MM-DD [%s]: " timestr))
4356 ans ans1 ans2
4357 second minute hour day month year tl wday wday1)
4358
4359 (if org-popup-calendar-for-date-prompt
4360 (save-excursion
4361 (save-window-excursion
4362 (calendar)
4363 (calendar-forward-day (- (time-to-days default-time)
4364 (calendar-absolute-from-gregorian
4365 (calendar-current-date))))
4366 (org-eval-in-calendar nil)
4367 (let* ((old-map (current-local-map))
4368 (map (copy-keymap calendar-mode-map))
4369 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
4370 (define-key map (kbd "RET") 'org-calendar-select)
4371 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
4372 'org-calendar-select-mouse)
4373 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
4374 'org-calendar-select-mouse)
4375 (define-key minibuffer-local-map [(meta shift left)]
4376 (lambda () (interactive)
4377 (org-eval-in-calendar '(calendar-backward-month 1))))
4378 (define-key minibuffer-local-map [(meta shift right)]
4379 (lambda () (interactive)
4380 (org-eval-in-calendar '(calendar-forward-month 1))))
4381 (define-key minibuffer-local-map [(shift up)]
4382 (lambda () (interactive)
4383 (org-eval-in-calendar '(calendar-backward-week 1))))
4384 (define-key minibuffer-local-map [(shift down)]
4385 (lambda () (interactive)
4386 (org-eval-in-calendar '(calendar-forward-week 1))))
4387 (define-key minibuffer-local-map [(shift left)]
4388 (lambda () (interactive)
4389 (org-eval-in-calendar '(calendar-backward-day 1))))
4390 (define-key minibuffer-local-map [(shift right)]
4391 (lambda () (interactive)
4392 (org-eval-in-calendar '(calendar-forward-day 1))))
4393 (define-key minibuffer-local-map ">"
4394 (lambda () (interactive)
4395 (org-eval-in-calendar '(scroll-calendar-left 1))))
4396 (define-key minibuffer-local-map "<"
4397 (lambda () (interactive)
4398 (org-eval-in-calendar '(scroll-calendar-right 1))))
4399 (unwind-protect
4400 (progn
4401 (use-local-map map)
4402 (setq ans (read-string prompt "" nil nil))
4403 (if (not (string-match "\\S-" ans)) (setq ans nil))
4404 (setq ans (or ans1 ans ans2)))
4405 (use-local-map old-map)))))
4406 ;; Naked prompt only
4407 (setq ans (read-string prompt "" nil timestr)))
4408 (org-detatch-overlay org-date-ovl)
4409
4410 (if (string-match
4411 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
4412 (progn
4413 (setq year (if (match-end 2)
4414 (string-to-number (match-string 2 ans))
4415 (string-to-number (format-time-string "%Y")))
4416 month (string-to-number (match-string 3 ans))
4417 day (string-to-number (match-string 4 ans)))
4418 (if (< year 100) (setq year (+ 2000 year)))
4419 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
4420 t nil ans))))
4421 (setq tl (parse-time-string ans)
4422 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
4423 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
4424 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
4425 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
4426 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
4427 second (or (nth 0 tl) 0)
4428 wday (nth 6 tl))
4429 (when (and wday (not (nth 3 tl)))
4430 ;; Weekday was given, but no day, so pick that day in the week
4431 ;; on or after the derived date.
4432 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
4433 (unless (equal wday wday1)
4434 (setq day (+ day (% (- wday wday1 -7) 7)))))
4435 (if (and (boundp 'org-time-was-given)
4436 (nth 2 tl))
4437 (setq org-time-was-given t))
4438 (if (< year 100) (setq year (+ 2000 year)))
4439 (if to-time
4440 (encode-time second minute hour day month year)
4441 (if (or (nth 1 tl) (nth 2 tl))
4442 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
4443 (format "%04d-%02d-%02d" year month day)))))
4444
4445 (defun org-eval-in-calendar (form)
4446 "Eval FORM in the calendar window and return to current window.
4447 Also, store the cursor date in variable ans2."
4448 (let ((sw (selected-window)))
4449 (select-window (get-buffer-window "*Calendar*"))
4450 (eval form)
4451 (when (calendar-cursor-to-date)
4452 (let* ((date (calendar-cursor-to-date))
4453 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4454 (setq ans2 (format-time-string "%Y-%m-%d" time))))
4455 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
4456 (select-window sw)))
4457
4458 (defun org-calendar-select ()
4459 "Return to `org-read-date' with the date currently selected.
4460 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4461 (interactive)
4462 (when (calendar-cursor-to-date)
4463 (let* ((date (calendar-cursor-to-date))
4464 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4465 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4466 (if (active-minibuffer-window) (exit-minibuffer))))
4467
4468 (defun org-calendar-select-mouse (ev)
4469 "Return to `org-read-date' with the date currently selected.
4470 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
4471 (interactive "e")
4472 (mouse-set-point ev)
4473 (when (calendar-cursor-to-date)
4474 (let* ((date (calendar-cursor-to-date))
4475 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
4476 (setq ans1 (format-time-string "%Y-%m-%d" time)))
4477 (if (active-minibuffer-window) (exit-minibuffer))))
4478
4479 (defun org-check-deadlines (ndays)
4480 "Check if there are any deadlines due or past due.
4481 A deadline is considered due if it happens within `org-deadline-warning-days'
4482 days from today's date. If the deadline appears in an entry marked DONE,
4483 it is not shown. The prefix arg NDAYS can be used to test that many
4484 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
4485 (interactive "P")
4486 (let* ((org-warn-days
4487 (cond
4488 ((equal ndays '(4)) 100000)
4489 (ndays (prefix-numeric-value ndays))
4490 (t org-deadline-warning-days)))
4491 (case-fold-search nil)
4492 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
4493 (callback
4494 (lambda ()
4495 (and (let ((d1 (time-to-days (current-time)))
4496 (d2 (time-to-days
4497 (org-time-string-to-time (match-string 1)))))
4498 (< (- d2 d1) org-warn-days))
4499 (not (org-entry-is-done-p))))))
4500 (message "%d deadlines past-due or due within %d days"
4501 (org-occur regexp callback)
4502 org-warn-days)))
4503
4504 (defun org-evaluate-time-range (&optional to-buffer)
4505 "Evaluate a time range by computing the difference between start and end.
4506 Normally the result is just printed in the echo area, but with prefix arg
4507 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
4508 If the time range is actually in a table, the result is inserted into the
4509 next column.
4510 For time difference computation, a year is assumed to be exactly 365
4511 days in order to avoid rounding problems."
4512 (interactive "P")
4513 (save-excursion
4514 (unless (org-at-date-range-p)
4515 (goto-char (point-at-bol))
4516 (re-search-forward org-tr-regexp (point-at-eol) t))
4517 (if (not (org-at-date-range-p))
4518 (error "Not at a time-stamp range, and none found in current line")))
4519 (let* ((ts1 (match-string 1))
4520 (ts2 (match-string 2))
4521 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
4522 (match-end (match-end 0))
4523 (time1 (org-time-string-to-time ts1))
4524 (time2 (org-time-string-to-time ts2))
4525 (t1 (time-to-seconds time1))
4526 (t2 (time-to-seconds time2))
4527 (diff (abs (- t2 t1)))
4528 (negative (< (- t2 t1) 0))
4529 ;; (ys (floor (* 365 24 60 60)))
4530 (ds (* 24 60 60))
4531 (hs (* 60 60))
4532 (fy "%dy %dd %02d:%02d")
4533 (fy1 "%dy %dd")
4534 (fd "%dd %02d:%02d")
4535 (fd1 "%dd")
4536 (fh "%02d:%02d")
4537 y d h m align)
4538 (if havetime
4539 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4540 y 0
4541 d (floor (/ diff ds)) diff (mod diff ds)
4542 h (floor (/ diff hs)) diff (mod diff hs)
4543 m (floor (/ diff 60)))
4544 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
4545 y 0
4546 d (floor (+ (/ diff ds) 0.5))
4547 h 0 m 0))
4548 (if (not to-buffer)
4549 (message (org-make-tdiff-string y d h m))
4550 (when (org-at-table-p)
4551 (goto-char match-end)
4552 (setq align t)
4553 (and (looking-at " *|") (goto-char (match-end 0))))
4554 (if (looking-at
4555 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
4556 (replace-match ""))
4557 (if negative (insert " -"))
4558 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
4559 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
4560 (insert " " (format fh h m))))
4561 (if align (org-table-align))
4562 (message "Time difference inserted"))))
4563
4564 (defun org-make-tdiff-string (y d h m)
4565 (let ((fmt "")
4566 (l nil))
4567 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
4568 l (push y l)))
4569 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
4570 l (push d l)))
4571 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
4572 l (push h l)))
4573 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
4574 l (push m l)))
4575 (apply 'format fmt (nreverse l))))
4576
4577 (defun org-time-string-to-time (s)
4578 (apply 'encode-time (org-parse-time-string s)))
4579
4580 (defun org-parse-time-string (s &optional nodefault)
4581 "Parse the standard Org-mode time string.
4582 This should be a lot faster than the normal `parse-time-string'.
4583 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
4584 hour and minute fields will be nil if not given."
4585 (if (string-match org-ts-regexp1 s)
4586 (list 0
4587 (if (or (match-beginning 8) (not nodefault))
4588 (string-to-number (or (match-string 8 s) "0")))
4589 (if (or (match-beginning 7) (not nodefault))
4590 (string-to-number (or (match-string 7 s) "0")))
4591 (string-to-number (match-string 4 s))
4592 (string-to-number (match-string 3 s))
4593 (string-to-number (match-string 2 s))
4594 nil nil nil)
4595 (make-list 9 0)))
4596
4597 (defun org-timestamp-up (&optional arg)
4598 "Increase the date item at the cursor by one.
4599 If the cursor is on the year, change the year. If it is on the month or
4600 the day, change that.
4601 With prefix ARG, change by that many units."
4602 (interactive "p")
4603 (org-timestamp-change (prefix-numeric-value arg)))
4604
4605 (defun org-timestamp-down (&optional arg)
4606 "Decrease the date item at the cursor by one.
4607 If the cursor is on the year, change the year. If it is on the month or
4608 the day, change that.
4609 With prefix ARG, change by that many units."
4610 (interactive "p")
4611 (org-timestamp-change (- (prefix-numeric-value arg))))
4612
4613 (defun org-timestamp-up-day (&optional arg)
4614 "Increase the date in the time stamp by one day.
4615 With prefix ARG, change that many days."
4616 (interactive "p")
4617 (if (and (not (org-at-timestamp-p))
4618 (org-on-heading-p))
4619 (org-todo 'up)
4620 (org-timestamp-change (prefix-numeric-value arg) 'day)))
4621
4622 (defun org-timestamp-down-day (&optional arg)
4623 "Decrease the date in the time stamp by one day.
4624 With prefix ARG, change that many days."
4625 (interactive "p")
4626 (if (and (not (org-at-timestamp-p))
4627 (org-on-heading-p))
4628 (org-todo 'down)
4629 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
4630
4631 (defsubst org-pos-in-match-range (pos n)
4632 (and (match-beginning n)
4633 (<= (match-beginning n) pos)
4634 (>= (match-end n) pos)))
4635
4636 (defun org-at-timestamp-p ()
4637 "Determine if the cursor is in or at a timestamp."
4638 (interactive)
4639 (let* ((tsr org-ts-regexp2)
4640 (pos (point))
4641 (ans (or (looking-at tsr)
4642 (save-excursion
4643 (skip-chars-backward "^<\n\r\t")
4644 (if (> (point) 1) (backward-char 1))
4645 (and (looking-at tsr)
4646 (> (- (match-end 0) pos) -1))))))
4647 (and (boundp 'org-ts-what)
4648 (setq org-ts-what
4649 (cond
4650 ((org-pos-in-match-range pos 2) 'year)
4651 ((org-pos-in-match-range pos 3) 'month)
4652 ((org-pos-in-match-range pos 7) 'hour)
4653 ((org-pos-in-match-range pos 8) 'minute)
4654 ((or (org-pos-in-match-range pos 4)
4655 (org-pos-in-match-range pos 5)) 'day)
4656 (t 'day))))
4657 ans))
4658
4659 (defun org-timestamp-change (n &optional what)
4660 "Change the date in the time stamp at point.
4661 The date will be changed by N times WHAT. WHAT can be `day', `month',
4662 `year', `minute', `second'. If WHAT is not given, the cursor position
4663 in the timestamp determines what will be changed."
4664 (let ((fmt (car org-time-stamp-formats))
4665 org-ts-what
4666 (pos (point))
4667 ts time time0)
4668 (if (not (org-at-timestamp-p))
4669 (error "Not at a timestamp"))
4670 (setq org-ts-what (or what org-ts-what))
4671 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
4672 (- (match-end 0) (match-beginning 0))))
4673 1)
4674 (cdr org-time-stamp-formats)
4675 (car org-time-stamp-formats)))
4676 (setq ts (match-string 0))
4677 (replace-match "")
4678 (setq time0 (org-parse-time-string ts))
4679 (setq time
4680 (apply 'encode-time
4681 (append
4682 (list (or (car time0) 0))
4683 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
4684 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
4685 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
4686 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
4687 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
4688 (nthcdr 6 time0))))
4689 (if (eq what 'calendar)
4690 (let ((cal-date
4691 (save-excursion
4692 (save-match-data
4693 (set-buffer "*Calendar*")
4694 (calendar-cursor-to-date)))))
4695 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
4696 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
4697 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
4698 (setcar time0 (or (car time0) 0))
4699 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
4700 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
4701 (setq time (apply 'encode-time time0))))
4702 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
4703 (goto-char pos)
4704 ;; Try to recenter the calendar window, if any
4705 (if (and org-calendar-follow-timestamp-change
4706 (get-buffer-window "*Calendar*" t)
4707 (memq org-ts-what '(day month year)))
4708 (org-recenter-calendar (time-to-days time)))))
4709
4710 (defun org-recenter-calendar (date)
4711 "If the calendar is visible, recenter it to DATE."
4712 (let* ((win (selected-window))
4713 (cwin (get-buffer-window "*Calendar*" t))
4714 (calendar-move-hook nil))
4715 (when cwin
4716 (select-window cwin)
4717 (calendar-goto-date (if (listp date) date
4718 (calendar-gregorian-from-absolute date)))
4719 (select-window win))))
4720
4721 (defun org-goto-calendar (&optional arg)
4722 "Go to the Emacs calendar at the current date.
4723 If there is a time stamp in the current line, go to that date.
4724 A prefix ARG can be used to force the current date."
4725 (interactive "P")
4726 (let ((tsr org-ts-regexp) diff
4727 (calendar-move-hook nil)
4728 (view-calendar-holidays-initially nil)
4729 (view-diary-entries-initially nil))
4730 (if (or (org-at-timestamp-p)
4731 (save-excursion
4732 (beginning-of-line 1)
4733 (looking-at (concat ".*" tsr))))
4734 (let ((d1 (time-to-days (current-time)))
4735 (d2 (time-to-days
4736 (org-time-string-to-time (match-string 1)))))
4737 (setq diff (- d2 d1))))
4738 (calendar)
4739 (calendar-goto-today)
4740 (if (and diff (not arg)) (calendar-forward-day diff))))
4741
4742 (defun org-date-from-calendar ()
4743 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
4744 If there is already a time stamp at the cursor position, update it."
4745 (interactive)
4746 (org-timestamp-change 0 'calendar))
4747
4748 ;;; Agenda, and Diary Integration
4749
4750 ;;; Define the mode
4751
4752 (defvar org-agenda-mode-map (make-sparse-keymap)
4753 "Keymap for `org-agenda-mode'.")
4754
4755 (defvar org-agenda-menu) ; defined later in this file.
4756 (defvar org-agenda-follow-mode nil)
4757 (defvar org-agenda-show-log nil)
4758 (defvar org-agenda-buffer-name "*Org Agenda*")
4759 (defvar org-agenda-redo-command nil)
4760 (defvar org-agenda-mode-hook nil)
4761 (defvar org-agenda-type nil)
4762 (defvar org-agenda-force-single-file nil)
4763
4764 ;;;###autoload
4765 (defun org-agenda-mode ()
4766 "Mode for time-sorted view on action items in Org-mode files.
4767
4768 The following commands are available:
4769
4770 \\{org-agenda-mode-map}"
4771 (interactive)
4772 (kill-all-local-variables)
4773 (setq major-mode 'org-agenda-mode)
4774 (setq mode-name "Org-Agenda")
4775 (use-local-map org-agenda-mode-map)
4776 (easy-menu-add org-agenda-menu)
4777 (if org-startup-truncated (setq truncate-lines t))
4778 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
4779 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
4780 (unless org-agenda-keep-modes
4781 (setq org-agenda-follow-mode nil
4782 org-agenda-show-log nil))
4783 (easy-menu-change
4784 '("Agenda") "Agenda Files"
4785 (append
4786 (list
4787 (vector
4788 (if (get 'org-agenda-files 'org-restrict)
4789 "Restricted to single file"
4790 "Edit File List")
4791 '(org-edit-agenda-file-list)
4792 (not (get 'org-agenda-files 'org-restrict)))
4793 "--")
4794 (mapcar 'org-file-menu-entry (org-agenda-files))))
4795 (org-agenda-set-mode-name)
4796 (apply
4797 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
4798 (list 'org-agenda-mode-hook)))
4799
4800 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
4801 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
4802 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
4803 (define-key org-agenda-mode-map " " 'org-agenda-show)
4804 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
4805 (define-key org-agenda-mode-map "o" 'delete-other-windows)
4806 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
4807 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
4808 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
4809 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
4810 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
4811 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
4812 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
4813 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
4814 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
4815 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
4816
4817 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
4818 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
4819 (while l (define-key org-agenda-mode-map
4820 (int-to-string (pop l)) 'digit-argument)))
4821
4822 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
4823 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
4824 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
4825 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
4826 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
4827 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
4828 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
4829 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
4830 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
4831 (define-key org-agenda-mode-map "n" 'next-line)
4832 (define-key org-agenda-mode-map "p" 'previous-line)
4833 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
4834 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
4835 (define-key org-agenda-mode-map "," 'org-agenda-priority)
4836 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
4837 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
4838 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
4839 (eval-after-load "calendar"
4840 '(define-key calendar-mode-map org-calendar-to-agenda-key
4841 'org-calendar-goto-agenda))
4842 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
4843 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
4844 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
4845 (define-key org-agenda-mode-map "s" 'org-agenda-sunrise-sunset)
4846 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
4847 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
4848 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
4849 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
4850 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
4851 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
4852 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
4853 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
4854 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
4855 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
4856 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
4857 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
4858 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
4859 "Local keymap for agenda entries from Org-mode.")
4860
4861 (define-key org-agenda-keymap
4862 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
4863 (define-key org-agenda-keymap
4864 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
4865 (when org-agenda-mouse-1-follows-link
4866 (define-key org-agenda-keymap [follow-link] 'mouse-face))
4867 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
4868 '("Agenda"
4869 ("Agenda Files")
4870 "--"
4871 ["Show" org-agenda-show t]
4872 ["Go To (other window)" org-agenda-goto t]
4873 ["Go To (one window)" org-agenda-switch-to t]
4874 ["Follow Mode" org-agenda-follow-mode
4875 :style toggle :selected org-agenda-follow-mode :active t]
4876 "--"
4877 ["Cycle TODO" org-agenda-todo t]
4878 ("Tags"
4879 ["Show all Tags" org-agenda-show-tags t]
4880 ["Set Tags" org-agenda-set-tags t])
4881 ("Reschedule"
4882 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
4883 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
4884 "--"
4885 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
4886 ("Priority"
4887 ["Set Priority" org-agenda-priority t]
4888 ["Increase Priority" org-agenda-priority-up t]
4889 ["Decrease Priority" org-agenda-priority-down t]
4890 ["Show Priority" org-agenda-show-priority t])
4891 "--"
4892 ;; ["New agenda command" org-agenda t]
4893 ["Rebuild buffer" org-agenda-redo t]
4894 "--"
4895 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
4896 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
4897 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
4898 "--"
4899 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
4900 :style radio :selected (equal org-agenda-ndays 1)]
4901 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
4902 :style radio :selected (equal org-agenda-ndays 7)]
4903 "--"
4904 ["Show Logbook entries" org-agenda-log-mode
4905 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
4906 ["Include Diary" org-agenda-toggle-diary
4907 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
4908 ["Use Time Grid" org-agenda-toggle-time-grid
4909 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
4910 "--"
4911 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
4912 ("Calendar Commands"
4913 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
4914 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
4915 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
4916 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
4917 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
4918 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
4919 "--"
4920 ["Quit" org-agenda-quit t]
4921 ["Exit and Release Buffers" org-agenda-exit t]
4922 ))
4923
4924 ;;;###autoload
4925 (defun org-agenda (arg)
4926 "Dispatch agenda commands to collect entries to the agenda buffer.
4927 Prompts for a character to select a command. Any prefix arg will be passed
4928 on to the selected command. The default selections are:
4929
4930 a Call `org-agenda' to display the agenda for the current day or week.
4931 t Call `org-todo-list' to display the global todo list.
4932 T Call `org-todo-list' to display the global todo list, select only
4933 entries with a specific TODO keyword (the user gets a prompt).
4934 m Call `org-tags-view' to display headlines with tags matching
4935 a condition (the user is prompted for the condition).
4936 M Like `m', but select only TODO entries, no ordinary headlines.
4937
4938 More commands can be added by configuring the variable
4939 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
4940 searches can be pre-defined in this way.
4941
4942 If the current buffer is in Org-mode and visiting a file, you can also
4943 first press `1' to indicate that the agenda should be temporarily (until the
4944 next use of \\[org-agenda]) restricted to the current file."
4945 (interactive "P")
4946 (catch 'exit
4947 (let ((restrict-ok (and buffer-file-name (eq major-mode 'org-mode)))
4948 (custom org-agenda-custom-commands)
4949 c entry key type string)
4950 (put 'org-agenda-files 'org-restrict nil)
4951 (save-window-excursion
4952 (delete-other-windows)
4953 (switch-to-buffer-other-window " *Agenda Commands*")
4954 (erase-buffer)
4955 (insert
4956 "Press key for an agenda command:
4957 --------------------------------
4958 a Agenda for current week or day
4959 t List of all TODO entries T Entries with special TODO kwd
4960 m Match a TAGS query M Like m, but only TODO entries
4961 C Configure your own agenda commands")
4962 (while (setq entry (pop custom))
4963 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
4964 (insert (format "\n%-4s%-14s: %s"
4965 key
4966 (cond
4967 ((eq type 'tags) "Tags query")
4968 ((eq type 'todo) "TODO keyword")
4969 ((eq type 'tags-tree) "Tags tree")
4970 ((eq type 'todo-tree) "TODO kwd tree")
4971 ((eq type 'occur-tree) "Occur tree")
4972 (t "???"))
4973 (org-add-props string nil 'face 'org-warning))))
4974 (goto-char (point-min))
4975 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
4976 (message "Press key for agenda command%s"
4977 (if restrict-ok ", or [1] to restrict to current file" ""))
4978 (setq c (read-char-exclusive))
4979 (message "")
4980 (when (equal c ?1)
4981 (if restrict-ok
4982 (put 'org-agenda-files 'org-restrict (list buffer-file-name))
4983 (error "Cannot restrict agenda to current buffer"))
4984 (message "Press key for agenda command%s"
4985 (if restrict-ok " (restricted to current file)" ""))
4986 (setq c (read-char-exclusive))
4987 (message "")))
4988 (require 'calendar) ; FIXME: can we avoid this for some commands?
4989 ;; For example the todo list should not need it (but does...)
4990 (cond
4991 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
4992 ((equal c ?a) (call-interactively 'org-agenda-list))
4993 ((equal c ?t) (call-interactively 'org-todo-list))
4994 ((equal c ?T)
4995 (setq current-prefix-arg (or arg '(4)))
4996 (call-interactively 'org-todo-list))
4997 ((equal c ?m) (call-interactively 'org-tags-view))
4998 ((equal c ?M)
4999 (setq current-prefix-arg (or arg '(4)))
5000 (call-interactively 'org-tags-view))
5001 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
5002 (setq type (nth 1 entry) string (nth 2 entry))
5003 (cond
5004 ((eq type 'tags)
5005 (org-tags-view current-prefix-arg string))
5006 ((eq type 'todo)
5007 (org-todo-list string))
5008 ((eq type 'tags-tree)
5009 (org-check-for-org-mode)
5010 (org-tags-sparse-tree current-prefix-arg string))
5011 ((eq type 'todo-tree)
5012 (org-check-for-org-mode)
5013 (org-occur (concat "^" outline-regexp "[ \t]*"
5014 (regexp-quote string) "\\>")))
5015 ((eq type 'occur-tree)
5016 (org-check-for-org-mode)
5017 (org-occur string))
5018 (t (error "Invalid custom agenda command type %s" type))))
5019 (t (error "Invalid key"))))))
5020
5021 (defun org-check-for-org-mode ()
5022 "Make sure current buffer is in org-mode. Error if not."
5023 (or (eq major-mode 'org-mode)
5024 (error "Cannot execute org-mode agenda command on buffer in %s."
5025 major-mode)))
5026
5027 (defun org-fit-agenda-window ()
5028 "Fit the window to the buffer size."
5029 (and org-fit-agenda-window
5030 (fboundp 'fit-window-to-buffer)
5031 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
5032 (/ (frame-height) 2))))
5033
5034 (defun org-agenda-files (&optional unrestricted)
5035 "Get the list of agenda files.
5036 Optional UNRESTRICTED means return the full list even if a restriction
5037 is currently in place."
5038 (cond
5039 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
5040 ((stringp org-agenda-files) (org-read-agenda-file-list))
5041 ((listp org-agenda-files) org-agenda-files)
5042 (t (error "Invalid value of `org-agenda-files'"))))
5043
5044 (defvar org-window-configuration)
5045
5046 (defun org-edit-agenda-file-list ()
5047 "Edit the list of agenda files.
5048 Depending on setup, this either uses customize to edit the variable
5049 `org-agenda-files', or it visits the file that is holding the list. In the
5050 latter case, the buffer is set up in a way that saving it automatically kills
5051 the buffer and restores the previous window configuration."
5052 (interactive)
5053 (if (stringp org-agenda-files)
5054 (let ((cw (current-window-configuration)))
5055 (find-file org-agenda-files)
5056 (set (make-local-variable 'org-window-configuration) cw)
5057 (org-add-hook 'after-save-hook
5058 (lambda ()
5059 (set-window-configuration
5060 (prog1 org-window-configuration
5061 (kill-buffer (current-buffer))))
5062 (org-install-agenda-files-menu)
5063 (message "New agenda file list installed"))
5064 nil 'local)
5065 (message (substitute-command-keys
5066 "Edit list and finish with \\[save-buffer]")))
5067 (customize-variable 'org-agenda-files)))
5068
5069 (defun org-store-new-agenda-file-list (list)
5070 "Set new value for the agenda file list and save it correcly."
5071 (if (stringp org-agenda-files)
5072 (let ((f org-agenda-files) b)
5073 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
5074 (with-temp-file f
5075 (insert (mapconcat 'identity list "\n") "\n")))
5076 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
5077 (setq org-agenda-files list)
5078 (customize-save-variable 'org-agenda-files org-agenda-files))))
5079
5080 (defun org-read-agenda-file-list ()
5081 "Read the list of agenda files from a file."
5082 (when (stringp org-agenda-files)
5083 (with-temp-buffer
5084 (insert-file-contents org-agenda-files)
5085 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
5086
5087 (defvar org-agenda-markers nil
5088 "List of all currently active markers created by `org-agenda'.")
5089 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
5090 "Creation time of the last agenda marker.")
5091
5092 (defun org-agenda-new-marker (&optional pos)
5093 "Return a new agenda marker.
5094 Org-mode keeps a list of these markers and resets them when they are
5095 no longer in use."
5096 (let ((m (copy-marker (or pos (point)))))
5097 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
5098 (push m org-agenda-markers)
5099 m))
5100
5101 (defun org-agenda-maybe-reset-markers (&optional force)
5102 "Reset markers created by `org-agenda'. But only if they are old enough."
5103 (if (or force
5104 (> (- (time-to-seconds (current-time))
5105 org-agenda-last-marker-time)
5106 5))
5107 (while org-agenda-markers
5108 (move-marker (pop org-agenda-markers) nil))))
5109
5110 (defvar org-agenda-new-buffers nil
5111 "Buffers created to visit agenda files.")
5112
5113 (defun org-get-agenda-file-buffer (file)
5114 "Get a buffer visiting FILE. If the buffer needs to be created, add
5115 it to the list of buffers which might be released later."
5116 (let ((buf (find-buffer-visiting file)))
5117 (if buf
5118 buf ; just return it
5119 ;; Make a new buffer and remember it
5120 (setq buf (find-file-noselect file))
5121 (if buf (push buf org-agenda-new-buffers))
5122 buf)))
5123
5124 (defun org-release-buffers (blist)
5125 "Release all buffers in list, asking the user for confirmation when needed.
5126 When a buffer is unmodified, it is just killed. When modified, it is saved
5127 \(if the user agrees) and then killed."
5128 (let (buf file)
5129 (while (setq buf (pop blist))
5130 (setq file (buffer-file-name buf))
5131 (when (and (buffer-modified-p buf)
5132 file
5133 (y-or-n-p (format "Save file %s? " file)))
5134 (with-current-buffer buf (save-buffer)))
5135 (kill-buffer buf))))
5136
5137 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
5138
5139 (defun org-timeline (&optional include-all keep-modes)
5140 "Show a time-sorted view of the entries in the current org file.
5141 Only entries with a time stamp of today or later will be listed. With
5142 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
5143 under the current date.
5144 If the buffer contains an active region, only check the region for
5145 dates."
5146 (interactive "P")
5147 (require 'calendar)
5148 (org-agenda-maybe-reset-markers 'force)
5149 (org-compile-prefix-format org-timeline-prefix-format)
5150 (let* ((dopast t)
5151 (dotodo include-all)
5152 (doclosed org-agenda-show-log)
5153 (org-agenda-keep-modes keep-modes)
5154 (entry buffer-file-name)
5155 (org-agenda-files (list buffer-file-name))
5156 (date (calendar-current-date))
5157 (win (selected-window))
5158 (pos1 (point))
5159 (beg (if (org-region-active-p) (region-beginning) (point-min)))
5160 (end (if (org-region-active-p) (region-end) (point-max)))
5161 (day-numbers (org-get-all-dates beg end 'no-ranges
5162 t doclosed)) ; always include today
5163 (today (time-to-days (current-time)))
5164 (org-respect-restriction t)
5165 (past t)
5166 args
5167 s e rtn d)
5168 (setq org-agenda-redo-command
5169 (list 'progn
5170 (list 'switch-to-buffer-other-window (current-buffer))
5171 (list 'org-timeline (list 'quote include-all) t)))
5172 (if (not dopast)
5173 ;; Remove past dates from the list of dates.
5174 (setq day-numbers (delq nil (mapcar (lambda(x)
5175 (if (>= x today) x nil))
5176 day-numbers))))
5177 (switch-to-buffer-other-window
5178 (get-buffer-create org-agenda-buffer-name))
5179 (setq buffer-read-only nil)
5180 (erase-buffer)
5181 (org-agenda-mode) (setq buffer-read-only nil)
5182 (set (make-local-variable 'org-agenda-type) 'timeline)
5183 (if doclosed (push :closed args))
5184 (push :timestamp args)
5185 (if dotodo (push :todo args))
5186 (while (setq d (pop day-numbers))
5187 (if (and (>= d today)
5188 dopast
5189 past)
5190 (progn
5191 (setq past nil)
5192 (insert (make-string 79 ?-) "\n")))
5193 (setq date (calendar-gregorian-from-absolute d))
5194 (setq s (point))
5195 (setq rtn (apply 'org-agenda-get-day-entries
5196 entry date args))
5197 (if (or rtn (equal d today))
5198 (progn
5199 (insert (calendar-day-name date) " "
5200 (number-to-string (extract-calendar-day date)) " "
5201 (calendar-month-name (extract-calendar-month date)) " "
5202 (number-to-string (extract-calendar-year date)) "\n")
5203 (put-text-property s (1- (point)) 'face
5204 'org-level-3)
5205 (if (equal d today)
5206 (put-text-property s (1- (point)) 'org-today t))
5207 (insert (org-finalize-agenda-entries rtn) "\n")
5208 (put-text-property s (1- (point)) 'day d))))
5209 (goto-char (point-min))
5210 (setq buffer-read-only t)
5211 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5212 (point-min)))
5213 (when (not org-select-timeline-window)
5214 (select-window win)
5215 (goto-char pos1))))
5216
5217 ;;;###autoload
5218 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
5219 "Produce a weekly view from all files in variable `org-agenda-files'.
5220 The view will be for the current week, but from the overview buffer you
5221 will be able to go to other weeks.
5222 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
5223 also be shown, under the current date.
5224 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
5225 on the days are also shown. See the variable `org-log-done' for how
5226 to turn on logging.
5227 START-DAY defaults to TODAY, or to the most recent match for the weekday
5228 given in `org-agenda-start-on-weekday'.
5229 NDAYS defaults to `org-agenda-ndays'."
5230 (interactive "P")
5231 (org-agenda-maybe-reset-markers 'force)
5232 (org-compile-prefix-format org-agenda-prefix-format)
5233 (require 'calendar)
5234 (let* ((org-agenda-start-on-weekday
5235 (if (or (equal ndays 1)
5236 (and (null ndays) (equal 1 org-agenda-ndays)))
5237 nil org-agenda-start-on-weekday))
5238 (org-agenda-keep-modes keep-modes)
5239 (thefiles (org-agenda-files))
5240 (files thefiles)
5241 (win (selected-window))
5242 (today (time-to-days (current-time)))
5243 (sd (or start-day today))
5244 (start (if (or (null org-agenda-start-on-weekday)
5245 (< org-agenda-ndays 7))
5246 sd
5247 (let* ((nt (calendar-day-of-week
5248 (calendar-gregorian-from-absolute sd)))
5249 (n1 org-agenda-start-on-weekday)
5250 (d (- nt n1)))
5251 (- sd (+ (if (< d 0) 7 0) d)))))
5252 (day-numbers (list start))
5253 (inhibit-redisplay t)
5254 s e rtn rtnall file date d start-pos end-pos todayp nd)
5255 (setq org-agenda-redo-command
5256 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
5257 ;; Make the list of days
5258 (setq ndays (or ndays org-agenda-ndays)
5259 nd ndays)
5260 (while (> ndays 1)
5261 (push (1+ (car day-numbers)) day-numbers)
5262 (setq ndays (1- ndays)))
5263 (setq day-numbers (nreverse day-numbers))
5264 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5265 (progn
5266 (delete-other-windows)
5267 (switch-to-buffer-other-window
5268 (get-buffer-create org-agenda-buffer-name))))
5269 (setq buffer-read-only nil)
5270 (erase-buffer)
5271 (org-agenda-mode) (setq buffer-read-only nil)
5272 (set (make-local-variable 'org-agenda-type) 'agenda)
5273 (set (make-local-variable 'starting-day) (car day-numbers))
5274 (set (make-local-variable 'include-all-loc) include-all)
5275 (when (and (or include-all org-agenda-include-all-todo)
5276 (member today day-numbers))
5277 (setq files thefiles
5278 rtnall nil)
5279 (while (setq file (pop files))
5280 (catch 'nextfile
5281 (org-check-agenda-file file)
5282 (setq date (calendar-gregorian-from-absolute today)
5283 rtn (org-agenda-get-day-entries
5284 file date :todo))
5285 (setq rtnall (append rtnall rtn))))
5286 (when rtnall
5287 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
5288 (add-text-properties (point-min) (1- (point))
5289 (list 'face 'org-level-3))
5290 (insert (org-finalize-agenda-entries rtnall) "\n")))
5291 (while (setq d (pop day-numbers))
5292 (setq date (calendar-gregorian-from-absolute d)
5293 s (point))
5294 (if (or (setq todayp (= d today))
5295 (and (not start-pos) (= d sd)))
5296 (setq start-pos (point))
5297 (if (and start-pos (not end-pos))
5298 (setq end-pos (point))))
5299 (setq files thefiles
5300 rtnall nil)
5301 (while (setq file (pop files))
5302 (catch 'nextfile
5303 (org-check-agenda-file file)
5304 (if org-agenda-show-log
5305 (setq rtn (org-agenda-get-day-entries
5306 file date
5307 :deadline :scheduled :timestamp :closed))
5308 (setq rtn (org-agenda-get-day-entries
5309 file date
5310 :deadline :scheduled :timestamp)))
5311 (setq rtnall (append rtnall rtn))))
5312 (if org-agenda-include-diary
5313 (progn
5314 (require 'diary-lib)
5315 (setq rtn (org-get-entries-from-diary date))
5316 (setq rtnall (append rtnall rtn))))
5317 (if (or rtnall org-agenda-show-all-dates)
5318 (progn
5319 (insert (format "%-9s %2d %s %4d\n"
5320 (calendar-day-name date)
5321 (extract-calendar-day date)
5322 (calendar-month-name (extract-calendar-month date))
5323 (extract-calendar-year date)))
5324 (put-text-property s (1- (point)) 'face
5325 'org-level-3)
5326 (if rtnall (insert
5327 (org-finalize-agenda-entries
5328 (org-agenda-add-time-grid-maybe
5329 rtnall nd todayp))
5330 "\n"))
5331 (put-text-property s (1- (point)) 'day d))))
5332 (goto-char (point-min))
5333 (setq buffer-read-only t)
5334 (org-fit-agenda-window)
5335 (unless (and (pos-visible-in-window-p (point-min))
5336 (pos-visible-in-window-p (point-max)))
5337 (goto-char (1- (point-max)))
5338 (recenter -1)
5339 (if (not (pos-visible-in-window-p (or start-pos 1)))
5340 (progn
5341 (goto-char (or start-pos 1))
5342 (recenter 1))))
5343 (goto-char (or start-pos 1))
5344 (if (not org-select-agenda-window) (select-window win))
5345 (message "")))
5346
5347 (defvar org-select-this-todo-keyword nil)
5348
5349 ;;;###autoload
5350 (defun org-todo-list (arg &optional keep-modes)
5351 "Show all TODO entries from all agenda file in a single list.
5352 The prefix arg can be used to select a specific TODO keyword and limit
5353 the list to these. When using \\[universal-argument], you will be prompted
5354 for a keyword. A numeric prefix directly selects the Nth keyword in
5355 `org-todo-keywords'."
5356 (interactive "P")
5357 (org-agenda-maybe-reset-markers 'force)
5358 (org-compile-prefix-format org-agenda-prefix-format)
5359 (let* ((org-agenda-keep-modes keep-modes)
5360 (today (time-to-days (current-time)))
5361 (date (calendar-gregorian-from-absolute today))
5362 (win (selected-window))
5363 (kwds org-todo-keywords)
5364 (completion-ignore-case t)
5365 (org-select-this-todo-keyword
5366 (if (stringp arg) arg
5367 (and arg (integerp arg) (> arg 0)
5368 (nth (1- arg) org-todo-keywords))))
5369 rtn rtnall files file pos)
5370 (when (equal arg '(4))
5371 (setq org-select-this-todo-keyword
5372 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
5373 nil t)))
5374 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
5375 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
5376 (progn
5377 (delete-other-windows)
5378 (switch-to-buffer-other-window
5379 (get-buffer-create org-agenda-buffer-name))))
5380 (setq buffer-read-only nil)
5381 (erase-buffer)
5382 (org-agenda-mode) (setq buffer-read-only nil)
5383 (set (make-local-variable 'org-agenda-type) 'todo)
5384 (set (make-local-variable 'last-arg) arg)
5385 (set (make-local-variable 'org-todo-keywords) kwds)
5386 (set (make-local-variable 'org-agenda-redo-command)
5387 '(org-todo-list (or current-prefix-arg last-arg) t))
5388 (setq files (org-agenda-files)
5389 rtnall nil)
5390 (while (setq file (pop files))
5391 (catch 'nextfile
5392 (org-check-agenda-file file)
5393 (setq rtn (org-agenda-get-day-entries file date :todo))
5394 (setq rtnall (append rtnall rtn))))
5395 (insert "Global list of TODO items of type: ")
5396 (add-text-properties (point-min) (1- (point))
5397 (list 'face 'org-level-3))
5398 (setq pos (point))
5399 (insert (or org-select-this-todo-keyword "ALL") "\n")
5400 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
5401 (setq pos (point))
5402 (insert
5403 "Available with `N r': (0)ALL "
5404 (let ((n 0))
5405 (mapconcat (lambda (x)
5406 (format "(%d)%s" (setq n (1+ n)) x))
5407 org-todo-keywords " "))
5408 "\n")
5409 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
5410 (when rtnall
5411 (insert (org-finalize-agenda-entries rtnall) "\n"))
5412 (goto-char (point-min))
5413 (setq buffer-read-only t)
5414 (org-fit-agenda-window)
5415 (if (not org-select-agenda-window) (select-window win))))
5416
5417 (defun org-check-agenda-file (file)
5418 "Make sure FILE exists. If not, ask user what to do."
5419 (when (not (file-exists-p file))
5420 (message "non-existent file %s. [R]emove from list or [A]bort?"
5421 (abbreviate-file-name file))
5422 (let ((r (downcase (read-char-exclusive))))
5423 (cond
5424 ((equal r ?r)
5425 (org-remove-file file)
5426 (throw 'nextfile t))
5427 (t (error "Abort"))))))
5428
5429 (defun org-agenda-check-type (error &rest types)
5430 "Check if agenda buffer is of allowed type.
5431 If ERROR is non-nil, throw an error, otherwise just return nil."
5432 (if (memq org-agenda-type types)
5433 t
5434 (if error
5435 (error "Now allowed in %s-type agenda buffers" org-agenda-type)
5436 nil)))
5437
5438 (defun org-agenda-quit ()
5439 "Exit agenda by removing the window or the buffer."
5440 (interactive)
5441 (let ((buf (current-buffer)))
5442 (if (not (one-window-p)) (delete-window))
5443 (kill-buffer buf)
5444 (org-agenda-maybe-reset-markers 'force)))
5445
5446 (defun org-agenda-exit ()
5447 "Exit agenda by removing the window or the buffer.
5448 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
5449 Org-mode buffers visited directly by the user will not be touched."
5450 (interactive)
5451 (org-release-buffers org-agenda-new-buffers)
5452 (setq org-agenda-new-buffers nil)
5453 (org-agenda-quit))
5454
5455 (defun org-agenda-redo ()
5456 "Rebuild Agenda.
5457 When this is the global TODO list, a prefix argument will be interpreted."
5458 (interactive)
5459 (message "Rebuilding agenda buffer...")
5460 (eval org-agenda-redo-command)
5461 (message "Rebuilding agenda buffer...done"))
5462
5463 (defun org-agenda-goto-today ()
5464 "Go to today."
5465 (interactive)
5466 (org-agenda-check-type t 'timeline 'agenda)
5467 (if (boundp 'starting-day)
5468 (let ((cmd (car org-agenda-redo-command))
5469 (iall (nth 1 org-agenda-redo-command))
5470 (nday (nth 3 org-agenda-redo-command))
5471 (keep (nth 4 org-agenda-redo-command)))
5472 (eval (list cmd iall nil nday keep)))
5473 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
5474 (point-min)))))
5475
5476 (defun org-agenda-later (arg)
5477 "Go forward in time by `org-agenda-ndays' days.
5478 With prefix ARG, go forward that many times `org-agenda-ndays'."
5479 (interactive "p")
5480 (org-agenda-check-type t 'agenda)
5481 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5482 (+ starting-day (* arg org-agenda-ndays)) nil t))
5483
5484 (defun org-agenda-earlier (arg)
5485 "Go back in time by `org-agenda-ndays' days.
5486 With prefix ARG, go back that many times `org-agenda-ndays'."
5487 (interactive "p")
5488 (org-agenda-check-type t 'agenda)
5489 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
5490 (- starting-day (* arg org-agenda-ndays)) nil t))
5491
5492 (defun org-agenda-week-view ()
5493 "Switch to weekly view for agenda."
5494 (interactive)
5495 (org-agenda-check-type t 'agenda)
5496 (setq org-agenda-ndays 7)
5497 (org-agenda-list include-all-loc
5498 (or (get-text-property (point) 'day)
5499 starting-day)
5500 nil t)
5501 (org-agenda-set-mode-name)
5502 (message "Switched to week view"))
5503
5504 (defun org-agenda-day-view ()
5505 "Switch to daily view for agenda."
5506 (interactive)
5507 (org-agenda-check-type t 'agenda)
5508 (setq org-agenda-ndays 1)
5509 (org-agenda-list include-all-loc
5510 (or (get-text-property (point) 'day)
5511 starting-day)
5512 nil t)
5513 (org-agenda-set-mode-name)
5514 (message "Switched to day view"))
5515
5516 (defun org-agenda-next-date-line (&optional arg)
5517 "Jump to the next line indicating a date in agenda buffer."
5518 (interactive "p")
5519 (org-agenda-check-type t 'agenda 'timeline)
5520 (beginning-of-line 1)
5521 (if (looking-at "^\\S-") (forward-char 1))
5522 (if (not (re-search-forward "^\\S-" nil t arg))
5523 (progn
5524 (backward-char 1)
5525 (error "No next date after this line in this buffer")))
5526 (goto-char (match-beginning 0)))
5527
5528 (defun org-agenda-previous-date-line (&optional arg)
5529 "Jump to the previous line indicating a date in agenda buffer."
5530 (interactive "p")
5531 (org-agenda-check-type t 'agenda 'timeline)
5532 (beginning-of-line 1)
5533 (if (not (re-search-backward "^\\S-" nil t arg))
5534 (error "No previous date before this line in this buffer")))
5535
5536 ;; Initialize the highlight
5537 (defvar org-hl (org-make-overlay 1 1))
5538 (org-overlay-put org-hl 'face 'highlight)
5539
5540 (defun org-highlight (begin end &optional buffer)
5541 "Highlight a region with overlay."
5542 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
5543 org-hl begin end (or buffer (current-buffer))))
5544
5545 (defun org-unhighlight ()
5546 "Detach overlay INDEX."
5547 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
5548
5549
5550 (defun org-agenda-follow-mode ()
5551 "Toggle follow mode in an agenda buffer."
5552 (interactive)
5553 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
5554 (org-agenda-set-mode-name)
5555 (message "Follow mode is %s"
5556 (if org-agenda-follow-mode "on" "off")))
5557
5558 (defun org-agenda-log-mode ()
5559 "Toggle log mode in an agenda buffer."
5560 (interactive)
5561 (org-agenda-check-type t 'agenda 'timeline)
5562 (setq org-agenda-show-log (not org-agenda-show-log))
5563 (org-agenda-set-mode-name)
5564 (org-agenda-redo)
5565 (message "Log mode is %s"
5566 (if org-agenda-show-log "on" "off")))
5567
5568 (defun org-agenda-toggle-diary ()
5569 "Toggle diary inclusion in an agenda buffer."
5570 (interactive)
5571 (org-agenda-check-type t 'agenda)
5572 (setq org-agenda-include-diary (not org-agenda-include-diary))
5573 (org-agenda-redo)
5574 (org-agenda-set-mode-name)
5575 (message "Diary inclusion turned %s"
5576 (if org-agenda-include-diary "on" "off")))
5577
5578 (defun org-agenda-toggle-time-grid ()
5579 "Toggle time grid in an agenda buffer."
5580 (interactive)
5581 (org-agenda-check-type t 'agenda)
5582 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
5583 (org-agenda-redo)
5584 (org-agenda-set-mode-name)
5585 (message "Time-grid turned %s"
5586 (if org-agenda-use-time-grid "on" "off")))
5587
5588 (defun org-agenda-set-mode-name ()
5589 "Set the mode name to indicate all the small mode settings."
5590 (setq mode-name
5591 (concat "Org-Agenda"
5592 (if (equal org-agenda-ndays 1) " Day" "")
5593 (if (equal org-agenda-ndays 7) " Week" "")
5594 (if org-agenda-follow-mode " Follow" "")
5595 (if org-agenda-include-diary " Diary" "")
5596 (if org-agenda-use-time-grid " Grid" "")
5597 (if org-agenda-show-log " Log" "")))
5598 (force-mode-line-update))
5599
5600 (defun org-agenda-post-command-hook ()
5601 (and (eolp) (not (bolp)) (backward-char 1))
5602 (if (and org-agenda-follow-mode
5603 (get-text-property (point) 'org-marker))
5604 (org-agenda-show)))
5605
5606 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
5607
5608 (defun org-get-entries-from-diary (date)
5609 "Get the (Emacs Calendar) diary entries for DATE."
5610 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
5611 (diary-display-hook '(fancy-diary-display))
5612 (list-diary-entries-hook
5613 (cons 'org-diary-default-entry list-diary-entries-hook))
5614 (diary-file-name-prefix-function nil) ; turn this feature off
5615 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
5616 entries
5617 (org-disable-agenda-to-diary t))
5618 (save-excursion
5619 (save-window-excursion
5620 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
5621 (if (not (get-buffer fancy-diary-buffer))
5622 (setq entries nil)
5623 (with-current-buffer fancy-diary-buffer
5624 (setq buffer-read-only nil)
5625 (if (= (point-max) 1)
5626 ;; No entries
5627 (setq entries nil)
5628 ;; Omit the date and other unnecessary stuff
5629 (org-agenda-cleanup-fancy-diary)
5630 ;; Add prefix to each line and extend the text properties
5631 (if (= (point-max) 1)
5632 (setq entries nil)
5633 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
5634 (set-buffer-modified-p nil)
5635 (kill-buffer fancy-diary-buffer)))
5636 (when entries
5637 (setq entries (org-split-string entries "\n"))
5638 (setq entries
5639 (mapcar
5640 (lambda (x)
5641 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
5642 ;; Extend the text properties to the beginning of the line
5643 (org-add-props x (text-properties-at (1- (length x)) x)))
5644 entries)))))
5645
5646 (defun org-agenda-cleanup-fancy-diary ()
5647 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
5648 This gets rid of the date, the underline under the date, and
5649 the dummy entry installed by `org-mode' to ensure non-empty diary for each
5650 date. It also removes lines that contain only whitespace."
5651 (goto-char (point-min))
5652 (if (looking-at ".*?:[ \t]*")
5653 (progn
5654 (replace-match "")
5655 (re-search-forward "\n=+$" nil t)
5656 (replace-match "")
5657 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
5658 (re-search-forward "\n=+$" nil t)
5659 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
5660 (goto-char (point-min))
5661 (while (re-search-forward "^ +\n" nil t)
5662 (replace-match ""))
5663 (goto-char (point-min))
5664 (if (re-search-forward "^Org-mode dummy\n?" nil t)
5665 (replace-match "")))
5666
5667 ;; Make sure entries from the diary have the right text properties.
5668 (eval-after-load "diary-lib"
5669 '(if (boundp 'diary-modify-entry-list-string-function)
5670 ;; We can rely on the hook, nothing to do
5671 nil
5672 ;; Hook not avaiable, must use advice to make this work
5673 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
5674 "Make the position visible."
5675 (if (and org-disable-agenda-to-diary ;; called from org-agenda
5676 (stringp string)
5677 buffer-file-name)
5678 (setq string (org-modify-diary-entry-string string))))))
5679
5680 (defun org-modify-diary-entry-string (string)
5681 "Add text properties to string, allowing org-mode to act on it."
5682 (org-add-props string nil
5683 'mouse-face 'highlight
5684 'keymap org-agenda-keymap
5685 'help-echo (format "mouse-2 or RET jump to diary file %s"
5686 (abbreviate-file-name buffer-file-name))
5687 'org-agenda-diary-link t
5688 'org-marker (org-agenda-new-marker (point-at-bol))))
5689
5690 (defun org-diary-default-entry ()
5691 "Add a dummy entry to the diary.
5692 Needed to avoid empty dates which mess up holiday display."
5693 ;; Catch the error if dealing with the new add-to-diary-alist
5694 (when org-disable-agenda-to-diary
5695 (condition-case nil
5696 (add-to-diary-list original-date "Org-mode dummy" "")
5697 (error
5698 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
5699
5700 (defun org-cycle-agenda-files ()
5701 "Cycle through the files in `org-agenda-files'.
5702 If the current buffer visits an agenda file, find the next one in the list.
5703 If the current buffer does not, find the first agenda file."
5704 (interactive)
5705 (let* ((fs (org-agenda-files t))
5706 (files (append fs (list (car fs))))
5707 (tcf (if buffer-file-name (file-truename buffer-file-name)))
5708 file)
5709 (unless files (error "No agenda files"))
5710 (catch 'exit
5711 (while (setq file (pop files))
5712 (if (equal (file-truename file) tcf)
5713 (when (car files)
5714 (find-file (car files))
5715 (throw 'exit t))))
5716 (find-file (car fs)))))
5717
5718 (defun org-agenda-file-to-end ()
5719 "Move/add the current file to the end of the agenda file list.
5720 If the file is not present in the list, it is appended to the list. If it is
5721 present, it is moved there."
5722 (interactive)
5723 (org-agenda-file-to-front 'to-end))
5724
5725 (defun org-agenda-file-to-front (&optional to-end)
5726 "Move/add the current file to the top of the agenda file list.
5727 If the file is not present in the list, it is added to the front. If it is
5728 present, it is moved there. With optional argument TO-END, add/move to the
5729 end of the list."
5730 (interactive "P")
5731 (let ((file-alist (mapcar (lambda (x)
5732 (cons (file-truename x) x))
5733 (org-agenda-files t)))
5734 (ctf (file-truename buffer-file-name))
5735 x had)
5736 (setq x (assoc ctf file-alist) had x)
5737
5738 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
5739 (if to-end
5740 (setq file-alist (append (delq x file-alist) (list x)))
5741 (setq file-alist (cons x (delq x file-alist))))
5742 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
5743 (org-install-agenda-files-menu)
5744 (message "File %s to %s of agenda file list"
5745 (if had "moved" "added") (if to-end "end" "front"))))
5746
5747 (defun org-remove-file (&optional file)
5748 "Remove current file from the list of files in variable `org-agenda-files'.
5749 These are the files which are being checked for agenda entries.
5750 Optional argument FILE means, use this file instead of the current."
5751 (interactive)
5752 (let* ((file (or file buffer-file-name))
5753 (true-file (file-truename file))
5754 (afile (abbreviate-file-name file))
5755 (files (delq nil (mapcar
5756 (lambda (x)
5757 (if (equal true-file
5758 (file-truename x))
5759 nil x))
5760 (org-agenda-files t)))))
5761 (if (not (= (length files) (length (org-agenda-files t))))
5762 (progn
5763 (org-store-new-agenda-file-list files)
5764 (org-install-agenda-files-menu)
5765 (message "Removed file: %s" afile))
5766 (message "File was not in list: %s" afile))))
5767
5768 (defun org-file-menu-entry (file)
5769 (vector file (list 'find-file file) t))
5770
5771 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive)
5772 "Return a list of all relevant day numbers from BEG to END buffer positions.
5773 If NO-RANGES is non-nil, include only the start and end dates of a range,
5774 not every single day in the range. If FORCE-TODAY is non-nil, make
5775 sure that TODAY is included in the list. If INACTIVE is non-nil, also
5776 inactive time stamps (those in square brackets) are included."
5777 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
5778 dates date day day1 day2 ts1 ts2)
5779 (if force-today
5780 (setq dates (list (time-to-days (current-time)))))
5781 (save-excursion
5782 (goto-char beg)
5783 (while (re-search-forward re end t)
5784 (setq day (time-to-days (org-time-string-to-time
5785 (substring (match-string 1) 0 10))))
5786 (or (memq day dates) (push day dates)))
5787 (unless no-ranges
5788 (goto-char beg)
5789 (while (re-search-forward org-tr-regexp end t)
5790 (setq ts1 (substring (match-string 1) 0 10)
5791 ts2 (substring (match-string 2) 0 10)
5792 day1 (time-to-days (org-time-string-to-time ts1))
5793 day2 (time-to-days (org-time-string-to-time ts2)))
5794 (while (< (setq day1 (1+ day1)) day2)
5795 (or (memq day1 dates) (push day1 dates)))))
5796 (sort dates '<))))
5797
5798 ;;;###autoload
5799 (defun org-diary (&rest args)
5800 "Return diary information from org-files.
5801 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
5802 It accesses org files and extracts information from those files to be
5803 listed in the diary. The function accepts arguments specifying what
5804 items should be listed. The following arguments are allowed:
5805
5806 :timestamp List the headlines of items containing a date stamp or
5807 date range matching the selected date. Deadlines will
5808 also be listed, on the expiration day.
5809
5810 :deadline List any deadlines past due, or due within
5811 `org-deadline-warning-days'. The listing occurs only
5812 in the diary for *today*, not at any other date. If
5813 an entry is marked DONE, it is no longer listed.
5814
5815 :scheduled List all items which are scheduled for the given date.
5816 The diary for *today* also contains items which were
5817 scheduled earlier and are not yet marked DONE.
5818
5819 :todo List all TODO items from the org-file. This may be a
5820 long list - so this is not turned on by default.
5821 Like deadlines, these entries only show up in the
5822 diary for *today*, not at any other date.
5823
5824 The call in the diary file should look like this:
5825
5826 &%%(org-diary) ~/path/to/some/orgfile.org
5827
5828 Use a separate line for each org file to check. Or, if you omit the file name,
5829 all files listed in `org-agenda-files' will be checked automatically:
5830
5831 &%%(org-diary)
5832
5833 If you don't give any arguments (as in the example above), the default
5834 arguments (:deadline :scheduled :timestamp) are used. So the example above may
5835 also be written as
5836
5837 &%%(org-diary :deadline :timestamp :scheduled)
5838
5839 The function expects the lisp variables `entry' and `date' to be provided
5840 by the caller, because this is how the calendar works. Don't use this
5841 function from a program - use `org-agenda-get-day-entries' instead."
5842 (org-agenda-maybe-reset-markers)
5843 (org-compile-prefix-format org-agenda-prefix-format)
5844 (setq args (or args '(:deadline :scheduled :timestamp)))
5845 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
5846 (list entry)
5847 (org-agenda-files t)))
5848 file rtn results)
5849 ;; If this is called during org-agenda, don't return any entries to
5850 ;; the calendar. Org Agenda will list these entries itself.
5851 (if org-disable-agenda-to-diary (setq files nil))
5852 (while (setq file (pop files))
5853 (setq rtn (apply 'org-agenda-get-day-entries file date args))
5854 (setq results (append results rtn)))
5855 (if results
5856 (concat (org-finalize-agenda-entries results) "\n"))))
5857 (defvar org-category-table nil)
5858 (defun org-get-category-table ()
5859 "Get the table of categories and positions in current buffer."
5860 (let (tbl)
5861 (save-excursion
5862 (goto-char (point-min))
5863 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
5864 (push (cons (point) (org-trim (match-string 2))) tbl)))
5865 tbl))
5866 (defun org-get-category (&optional pos)
5867 "Get the category applying to position POS."
5868 (if (not org-category-table)
5869 (cond
5870 ((null org-category)
5871 (setq org-category
5872 (if buffer-file-name
5873 (file-name-sans-extension
5874 (file-name-nondirectory buffer-file-name))
5875 "???")))
5876 ((symbolp org-category) (symbol-name org-category))
5877 (t org-category))
5878 (let ((tbl org-category-table)
5879 (pos (or pos (point))))
5880 (while (and tbl (> (caar tbl) pos))
5881 (pop tbl))
5882 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
5883 org-category-table))))))
5884
5885 (defun org-agenda-get-day-entries (file date &rest args)
5886 "Does the work for `org-diary' and `org-agenda'.
5887 FILE is the path to a file to be checked for entries. DATE is date like
5888 the one returned by `calendar-current-date'. ARGS are symbols indicating
5889 which kind of entries should be extracted. For details about these, see
5890 the documentation of `org-diary'."
5891 (setq args (or args '(:deadline :scheduled :timestamp)))
5892 (let* ((org-startup-with-deadline-check nil)
5893 (org-startup-folded nil)
5894 (org-startup-align-all-tables nil)
5895 (buffer (if (file-exists-p file)
5896 (org-get-agenda-file-buffer file)
5897 (error "No such file %s" file)))
5898 arg results rtn)
5899 (if (not buffer)
5900 ;; If file does not exist, make sure an error message ends up in diary
5901 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
5902 (with-current-buffer buffer
5903 (unless (eq major-mode 'org-mode)
5904 (error "Agenda file %s is not in `org-mode'" file))
5905 (setq org-category-table (org-get-category-table))
5906 (let ((case-fold-search nil))
5907 (save-excursion
5908 (save-restriction
5909 (if org-respect-restriction
5910 (if (org-region-active-p)
5911 ;; Respect a region to restrict search
5912 (narrow-to-region (region-beginning) (region-end)))
5913 ;; If we work for the calendar or many files,
5914 ;; get rid of any restriction
5915 (widen))
5916 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
5917 (while (setq arg (pop args))
5918 (cond
5919 ((and (eq arg :todo)
5920 (equal date (calendar-current-date)))
5921 (setq rtn (org-agenda-get-todos))
5922 (setq results (append results rtn)))
5923 ((eq arg :timestamp)
5924 (setq rtn (org-agenda-get-blocks))
5925 (setq results (append results rtn))
5926 (setq rtn (org-agenda-get-timestamps))
5927 (setq results (append results rtn)))
5928 ((eq arg :scheduled)
5929 (setq rtn (org-agenda-get-scheduled))
5930 (setq results (append results rtn)))
5931 ((eq arg :closed)
5932 (setq rtn (org-agenda-get-closed))
5933 (setq results (append results rtn)))
5934 ((and (eq arg :deadline)
5935 (equal date (calendar-current-date)))
5936 (setq rtn (org-agenda-get-deadlines))
5937 (setq results (append results rtn))))))))
5938 results))))
5939
5940 (defun org-entry-is-done-p ()
5941 "Is the current entry marked DONE?"
5942 (save-excursion
5943 (and (re-search-backward "[\r\n]\\*" nil t)
5944 (looking-at org-nl-done-regexp))))
5945
5946 (defun org-at-date-range-p ()
5947 "Is the cursor inside a date range?"
5948 (interactive)
5949 (save-excursion
5950 (catch 'exit
5951 (let ((pos (point)))
5952 (skip-chars-backward "^<\r\n")
5953 (skip-chars-backward "<")
5954 (and (looking-at org-tr-regexp)
5955 (>= (match-end 0) pos)
5956 (throw 'exit t))
5957 (skip-chars-backward "^<\r\n")
5958 (skip-chars-backward "<")
5959 (and (looking-at org-tr-regexp)
5960 (>= (match-end 0) pos)
5961 (throw 'exit t)))
5962 nil)))
5963
5964 (defun org-agenda-get-todos ()
5965 "Return the TODO information for agenda display."
5966 (let* ((props (list 'face nil
5967 'done-face 'org-done
5968 'org-not-done-regexp org-not-done-regexp
5969 'mouse-face 'highlight
5970 'keymap org-agenda-keymap
5971 'help-echo
5972 (format "mouse-2 or RET jump to org file %s"
5973 (abbreviate-file-name buffer-file-name))))
5974 (regexp (concat "[\n\r]\\*+ *\\("
5975 (if org-select-this-todo-keyword
5976 (concat "\\<\\(" org-select-this-todo-keyword
5977 "\\)\\>")
5978 org-not-done-regexp)
5979 "[^\n\r]*\\)"))
5980 marker priority category tags
5981 ee txt)
5982 (goto-char (point-min))
5983 (while (re-search-forward regexp nil t)
5984 (goto-char (match-beginning 1))
5985 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
5986 category (org-get-category)
5987 tags (org-get-tags-at (point))
5988 txt (org-format-agenda-item "" (match-string 1) category tags)
5989 priority
5990 (+ (org-get-priority txt)
5991 (if org-todo-kwd-priority-p
5992 (- org-todo-kwd-max-priority -2
5993 (length
5994 (member (match-string 2) org-todo-keywords)))
5995 1)))
5996 (org-add-props txt props
5997 'org-marker marker 'org-hd-marker marker
5998 'priority priority 'category category)
5999 (push txt ee)
6000 (goto-char (match-end 1)))
6001 (nreverse ee)))
6002
6003 (defconst org-agenda-no-heading-message
6004 "No heading for this item in buffer or region.")
6005
6006 (defun org-agenda-get-timestamps ()
6007 "Return the date stamp information for agenda display."
6008 (let* ((props (list 'face nil
6009 'org-not-done-regexp org-not-done-regexp
6010 'mouse-face 'highlight
6011 'keymap org-agenda-keymap
6012 'help-echo
6013 (format "mouse-2 or RET jump to org file %s"
6014 (abbreviate-file-name buffer-file-name))))
6015 (regexp (regexp-quote
6016 (substring
6017 (format-time-string
6018 (car org-time-stamp-formats)
6019 (apply 'encode-time ; DATE bound by calendar
6020 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6021 0 11)))
6022 marker hdmarker deadlinep scheduledp donep tmp priority category
6023 ee txt timestr tags)
6024 (goto-char (point-min))
6025 (while (re-search-forward regexp nil t)
6026 (if (not (save-match-data (org-at-date-range-p)))
6027 (progn
6028 (setq marker (org-agenda-new-marker (match-beginning 0))
6029 category (org-get-category (match-beginning 0))
6030 tmp (buffer-substring (max (point-min)
6031 (- (match-beginning 0)
6032 org-ds-keyword-length))
6033 (match-beginning 0))
6034 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6035 deadlinep (string-match org-deadline-regexp tmp)
6036 scheduledp (string-match org-scheduled-regexp tmp)
6037 donep (org-entry-is-done-p))
6038 (if (string-match ">" timestr)
6039 ;; substring should only run to end of time stamp
6040 (setq timestr (substring timestr 0 (match-end 0))))
6041 (save-excursion
6042 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6043 (progn
6044 (goto-char (match-end 1))
6045 (setq hdmarker (org-agenda-new-marker)
6046 tags (org-get-tags-at))
6047 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6048 (setq txt (org-format-agenda-item
6049 (format "%s%s"
6050 (if deadlinep "Deadline: " "")
6051 (if scheduledp "Scheduled: " ""))
6052 (match-string 1) category tags timestr)))
6053 (setq txt org-agenda-no-heading-message))
6054 (setq priority (org-get-priority txt))
6055 (org-add-props txt props
6056 'org-marker marker 'org-hd-marker hdmarker)
6057 (if deadlinep
6058 (org-add-props txt nil
6059 'face (if donep 'org-done 'org-warning)
6060 'undone-face 'org-warning 'done-face 'org-done
6061 'category category 'priority (+ 100 priority))
6062 (if scheduledp
6063 (org-add-props txt nil
6064 'face 'org-scheduled-today
6065 'undone-face 'org-scheduled-today 'done-face 'org-done
6066 'category category 'priority (+ 99 priority))
6067 (org-add-props txt nil 'priority priority 'category category)))
6068 (push txt ee))
6069 (outline-next-heading))))
6070 (nreverse ee)))
6071
6072 (defun org-agenda-get-closed ()
6073 "Return the logged TODO entries for agenda display."
6074 (let* ((props (list 'mouse-face 'highlight
6075 'org-not-done-regexp org-not-done-regexp
6076 'keymap org-agenda-keymap
6077 'help-echo
6078 (format "mouse-2 or RET jump to org file %s"
6079 (abbreviate-file-name buffer-file-name))))
6080 (regexp (concat
6081 "\\<" org-closed-string " *\\["
6082 (regexp-quote
6083 (substring
6084 (format-time-string
6085 (car org-time-stamp-formats)
6086 (apply 'encode-time ; DATE bound by calendar
6087 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
6088 1 11))))
6089 marker hdmarker priority category tags
6090 ee txt timestr)
6091 (goto-char (point-min))
6092 (while (re-search-forward regexp nil t)
6093 (if (not (save-match-data (org-at-date-range-p)))
6094 (progn
6095 (setq marker (org-agenda-new-marker (match-beginning 0))
6096 category (org-get-category (match-beginning 0))
6097 timestr (buffer-substring (match-beginning 0) (point-at-eol))
6098 ;; donep (org-entry-is-done-p)
6099 )
6100 (if (string-match "\\]" timestr)
6101 ;; substring should only run to end of time stamp
6102 (setq timestr (substring timestr 0 (match-end 0))))
6103 (save-excursion
6104 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6105 (progn
6106 (goto-char (match-end 1))
6107 (setq hdmarker (org-agenda-new-marker)
6108 tags (org-get-tags-at))
6109 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6110 (setq txt (org-format-agenda-item
6111 "Closed: "
6112 (match-string 1) category tags timestr)))
6113 (setq txt org-agenda-no-heading-message))
6114 (setq priority 100000)
6115 (org-add-props txt props
6116 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
6117 'priority priority 'category category
6118 'undone-face 'org-warning 'done-face 'org-done)
6119 (push txt ee))
6120 (outline-next-heading))))
6121 (nreverse ee)))
6122
6123 (defun org-agenda-get-deadlines ()
6124 "Return the deadline information for agenda display."
6125 (let* ((wdays org-deadline-warning-days)
6126 (props (list 'mouse-face 'highlight
6127 'org-not-done-regexp org-not-done-regexp
6128 'keymap org-agenda-keymap
6129 'help-echo
6130 (format "mouse-2 or RET jump to org file %s"
6131 (abbreviate-file-name buffer-file-name))))
6132 (regexp org-deadline-time-regexp)
6133 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6134 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6135 d2 diff pos pos1 category tags
6136 ee txt head)
6137 (goto-char (point-min))
6138 (while (re-search-forward regexp nil t)
6139 (setq pos (1- (match-beginning 1))
6140 d2 (time-to-days
6141 (org-time-string-to-time (match-string 1)))
6142 diff (- d2 d1))
6143 ;; When to show a deadline in the calendar:
6144 ;; If the expiration is within wdays warning time.
6145 ;; Past-due deadlines are only shown on the current date
6146 (if (and (< diff wdays) todayp (not (= diff 0)))
6147 (save-excursion
6148 (setq category (org-get-category))
6149 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6150 (progn
6151 (goto-char (match-end 0))
6152 (setq pos1 (match-end 1))
6153 (setq tags (org-get-tags-at pos1))
6154 (setq head (buffer-substring-no-properties
6155 (point)
6156 (progn (skip-chars-forward "^\r\n")
6157 (point))))
6158 (if (string-match org-looking-at-done-regexp head)
6159 (setq txt nil)
6160 (setq txt (org-format-agenda-item
6161 (format "In %3d d.: " diff) head category tags))))
6162 (setq txt org-agenda-no-heading-message))
6163 (when txt
6164 (org-add-props txt props
6165 'org-marker (org-agenda-new-marker pos)
6166 'org-hd-marker (org-agenda-new-marker pos1)
6167 'priority (+ (- 10 diff) (org-get-priority txt))
6168 'category category
6169 'face (cond ((<= diff 0) 'org-warning)
6170 ((<= diff 5) 'org-scheduled-previously)
6171 (t nil))
6172 'undone-face (cond
6173 ((<= diff 0) 'org-warning)
6174 ((<= diff 5) 'org-scheduled-previously)
6175 (t nil))
6176 'done-face 'org-done)
6177 (push txt ee)))))
6178 ee))
6179
6180 (defun org-agenda-get-scheduled ()
6181 "Return the scheduled information for agenda display."
6182 (let* ((props (list 'face 'org-scheduled-previously
6183 'org-not-done-regexp org-not-done-regexp
6184 'undone-face 'org-scheduled-previously
6185 'done-face 'org-done
6186 'mouse-face 'highlight
6187 'keymap org-agenda-keymap
6188 'help-echo
6189 (format "mouse-2 or RET jump to org file %s"
6190 (abbreviate-file-name buffer-file-name))))
6191 (regexp org-scheduled-time-regexp)
6192 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
6193 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
6194 d2 diff pos pos1 category tags
6195 ee txt head)
6196 (goto-char (point-min))
6197 (while (re-search-forward regexp nil t)
6198 (setq pos (1- (match-beginning 1))
6199 d2 (time-to-days
6200 (org-time-string-to-time (match-string 1)))
6201 diff (- d2 d1))
6202 ;; When to show a scheduled item in the calendar:
6203 ;; If it is on or past the date.
6204 (if (and (< diff 0) todayp)
6205 (save-excursion
6206 (setq category (org-get-category))
6207 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
6208 (progn
6209 (goto-char (match-end 0))
6210 (setq pos1 (match-end 1))
6211 (setq tags (org-get-tags-at))
6212 (setq head (buffer-substring-no-properties
6213 (point)
6214 (progn (skip-chars-forward "^\r\n") (point))))
6215 (if (string-match org-looking-at-done-regexp head)
6216 (setq txt nil)
6217 (setq txt (org-format-agenda-item
6218 (format "Sched.%2dx: " (- 1 diff)) head
6219 category tags))))
6220 (setq txt org-agenda-no-heading-message))
6221 (when txt
6222 (org-add-props txt props
6223 'org-marker (org-agenda-new-marker pos)
6224 'org-hd-marker (org-agenda-new-marker pos1)
6225 'priority (+ (- 5 diff) (org-get-priority txt))
6226 'category category)
6227 (push txt ee)))))
6228 ee))
6229
6230 (defun org-agenda-get-blocks ()
6231 "Return the date-range information for agenda display."
6232 (let* ((props (list 'face nil
6233 'org-not-done-regexp org-not-done-regexp
6234 'mouse-face 'highlight
6235 'keymap org-agenda-keymap
6236 'help-echo
6237 (format "mouse-2 or RET jump to org file %s"
6238 (abbreviate-file-name buffer-file-name))))
6239 (regexp org-tr-regexp)
6240 (d0 (calendar-absolute-from-gregorian date))
6241 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags)
6242 (goto-char (point-min))
6243 (while (re-search-forward regexp nil t)
6244 (setq timestr (match-string 0)
6245 s1 (match-string 1)
6246 s2 (match-string 2)
6247 d1 (time-to-days (org-time-string-to-time s1))
6248 d2 (time-to-days (org-time-string-to-time s2)))
6249 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
6250 ;; Only allow days between the limits, because the normal
6251 ;; date stamps will catch the limits.
6252 (save-excursion
6253 (setq marker (org-agenda-new-marker (point)))
6254 (setq category (org-get-category))
6255 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
6256 (progn
6257 (setq hdmarker (org-agenda-new-marker (match-end 1)))
6258 (goto-char (match-end 1))
6259 (setq tags (org-get-tags-at))
6260 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
6261 (setq txt (org-format-agenda-item
6262 (format (if (= d1 d2) "" "(%d/%d): ")
6263 (1+ (- d0 d1)) (1+ (- d2 d1)))
6264 (match-string 1) category tags
6265 (if (= d0 d1) timestr))))
6266 (setq txt org-agenda-no-heading-message))
6267 (org-add-props txt props
6268 'org-marker marker 'org-hd-marker hdmarker
6269 'priority (org-get-priority txt) 'category category)
6270 (push txt ee)))
6271 (outline-next-heading))
6272 ;; Sort the entries by expiration date.
6273 (nreverse ee)))
6274
6275 (defconst org-plain-time-of-day-regexp
6276 (concat
6277 "\\(\\<[012]?[0-9]"
6278 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6279 "\\(--?"
6280 "\\(\\<[012]?[0-9]"
6281 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
6282 "\\)?")
6283 "Regular expression to match a plain time or time range.
6284 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
6285 groups carry important information:
6286 0 the full match
6287 1 the first time, range or not
6288 8 the second time, if it is a range.")
6289
6290 (defconst org-stamp-time-of-day-regexp
6291 (concat
6292 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +[a-zA-Z]+ +\\)"
6293 "\\([012][0-9]:[0-5][0-9]\\)>"
6294 "\\(--?"
6295 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
6296 "Regular expression to match a timestamp time or time range.
6297 After a match, the following groups carry important information:
6298 0 the full match
6299 1 date plus weekday, for backreferencing to make sure both times on same day
6300 2 the first time, range or not
6301 4 the second time, if it is a range.")
6302
6303 (defvar org-prefix-has-time nil
6304 "A flag, set by `org-compile-prefix-format'.
6305 The flag is set if the currently compiled format contains a `%t'.")
6306 (defvar org-prefix-has-tag nil
6307 "A flag, set by `org-compile-prefix-format'.
6308 The flag is set if the currently compiled format contains a `%T'.")
6309
6310 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
6311 "Format TXT to be inserted into the agenda buffer.
6312 In particular, it adds the prefix and corresponding text properties. EXTRA
6313 must be a string and replaces the `%s' specifier in the prefix format.
6314 CATEGORY (string, symbol or nil) may be used to overrule the default
6315 category taken from local variable or file name. It will replace the `%c'
6316 specifier in the format. DOTIME, when non-nil, indicates that a
6317 time-of-day should be extracted from TXT for sorting of this entry, and for
6318 the `%t' specifier in the format. When DOTIME is a string, this string is
6319 searched for a time before TXT is. NOPREFIX is a flag and indicates that
6320 only the correctly processes TXT should be returned - this is used by
6321 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
6322 (save-match-data
6323 ;; Diary entries sometimes have extra whitespace at the beginning
6324 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
6325 (let* ((category (or category
6326 org-category
6327 (if buffer-file-name
6328 (file-name-sans-extension
6329 (file-name-nondirectory buffer-file-name))
6330 "")))
6331 (tag (if tags (nth (1- (length tags)) tags) ""))
6332 time ;; needed for the eval of the prefix format
6333 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
6334 (time-of-day (and dotime (org-get-time-of-day ts)))
6335 stamp plain s0 s1 s2 rtn)
6336 (when (and dotime time-of-day org-prefix-has-time)
6337 ;; Extract starting and ending time and move them to prefix
6338 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
6339 (setq plain (string-match org-plain-time-of-day-regexp ts)))
6340 (setq s0 (match-string 0 ts)
6341 s1 (match-string (if plain 1 2) ts)
6342 s2 (match-string (if plain 8 4) ts))
6343
6344 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
6345 ;; them, we might want to remove them there to avoid duplication.
6346 ;; The user can turn this off with a variable.
6347 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
6348 (string-match (concat (regexp-quote s0) " *") txt)
6349 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
6350 (= (match-beginning 0) 0)
6351 t))
6352 (setq txt (replace-match "" nil nil txt))))
6353 ;; Normalize the time(s) to 24 hour
6354 (if s1 (setq s1 (org-get-time-of-day s1 'string)))
6355 (if s2 (setq s2 (org-get-time-of-day s2 'string))))
6356
6357 (when (and (or (eq org-agenda-remove-tags-when-in-prefix t)
6358 (and org-agenda-remove-tags-when-in-prefix
6359 org-prefix-has-tag))
6360 (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" txt))
6361 (setq txt (replace-match "" t t txt)))
6362
6363 ;; Create the final string
6364 (if noprefix
6365 (setq rtn txt)
6366 ;; Prepare the variables needed in the eval of the compiled format
6367 (setq time (cond (s2 (concat s1 "-" s2))
6368 (s1 (concat s1 "......"))
6369 (t ""))
6370 extra (or extra "")
6371 category (if (symbolp category) (symbol-name category) category))
6372 ;; Evaluate the compiled format
6373 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
6374
6375 ;; And finally add the text properties
6376 (org-add-props rtn nil
6377 'category (downcase category) 'tags tags
6378 'prefix-length (- (length rtn) (length txt))
6379 'time-of-day time-of-day
6380 'dotime dotime))))
6381
6382 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
6383 (catch 'exit
6384 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
6385 ((and todayp (member 'today (car org-agenda-time-grid))))
6386 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
6387 ((member 'weekly (car org-agenda-time-grid)))
6388 (t (throw 'exit list)))
6389 (let* ((have (delq nil (mapcar
6390 (lambda (x) (get-text-property 1 'time-of-day x))
6391 list)))
6392 (string (nth 1 org-agenda-time-grid))
6393 (gridtimes (nth 2 org-agenda-time-grid))
6394 (req (car org-agenda-time-grid))
6395 (remove (member 'remove-match req))
6396 new time)
6397 (if (and (member 'require-timed req) (not have))
6398 ;; don't show empty grid
6399 (throw 'exit list))
6400 (while (setq time (pop gridtimes))
6401 (unless (and remove (member time have))
6402 (setq time (int-to-string time))
6403 (push (org-format-agenda-item
6404 nil string "" nil
6405 (concat (substring time 0 -2) ":" (substring time -2)))
6406 new)
6407 (put-text-property
6408 1 (length (car new)) 'face 'org-time-grid (car new))))
6409 (if (member 'time-up org-agenda-sorting-strategy)
6410 (append new list)
6411 (append list new)))))
6412
6413 (defun org-compile-prefix-format (format)
6414 "Compile the prefix format into a Lisp form that can be evaluated.
6415 The resulting form is returned and stored in the variable
6416 `org-prefix-format-compiled'."
6417 (setq org-prefix-has-time nil org-prefix-has-tag nil)
6418 (let ((start 0) varform vars var (s format)e c f opt)
6419 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
6420 s start)
6421 (setq var (cdr (assoc (match-string 4 s)
6422 '(("c" . category) ("t" . time) ("s" . extra)
6423 ("T" . tag))))
6424 c (or (match-string 3 s) "")
6425 opt (match-beginning 1)
6426 start (1+ (match-beginning 0)))
6427 (if (equal var 'time) (setq org-prefix-has-time t))
6428 (if (equal var 'tag) (setq org-prefix-has-tag t))
6429 (setq f (concat "%" (match-string 2 s) "s"))
6430 (if opt
6431 (setq varform
6432 `(if (equal "" ,var)
6433 ""
6434 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
6435 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
6436 (setq s (replace-match "%s" t nil s))
6437 (push varform vars))
6438 (setq vars (nreverse vars))
6439 (setq org-prefix-format-compiled `(format ,s ,@vars))))
6440
6441 (defun org-get-time-of-day (s &optional string)
6442 "Check string S for a time of day.
6443 If found, return it as a military time number between 0 and 2400.
6444 If not found, return nil.
6445 The optional STRING argument forces conversion into a 5 character wide string
6446 HH:MM."
6447 (save-match-data
6448 (when
6449 (or
6450 (string-match
6451 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
6452 (string-match
6453 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
6454 (let* ((t0 (+ (* 100
6455 (+ (string-to-number (match-string 1 s))
6456 (if (and (match-beginning 4)
6457 (equal (downcase (match-string 4 s)) "pm"))
6458 12 0)))
6459 (if (match-beginning 3)
6460 (string-to-number (match-string 3 s))
6461 0)))
6462 (t1 (concat " "
6463 (if (< t0 100) "0" "") (if (< t0 10) "0" "")
6464 (int-to-string t0))))
6465 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
6466
6467 (defun org-finalize-agenda-entries (list)
6468 "Sort and concatenate the agenda items."
6469 (setq list (mapcar 'org-agenda-highlight-todo list))
6470 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
6471
6472 (defun org-agenda-highlight-todo (x)
6473 (let (re)
6474 (if (eq x 'line)
6475 (save-excursion
6476 (beginning-of-line 1)
6477 (setq re (get-text-property (point) 'org-not-done-regexp))
6478 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
6479 (and (looking-at (concat "[ \t]*" re))
6480 (add-text-properties (match-beginning 0) (match-end 0)
6481 '(face org-todo))))
6482 (setq re (get-text-property 0 'org-not-done-regexp x))
6483 (and re (string-match re x)
6484 (add-text-properties (match-beginning 0) (match-end 0)
6485 '(face org-todo) x))
6486 x)))
6487
6488 (defsubst org-cmp-priority (a b)
6489 "Compare the priorities of string A and B."
6490 (let ((pa (or (get-text-property 1 'priority a) 0))
6491 (pb (or (get-text-property 1 'priority b) 0)))
6492 (cond ((> pa pb) +1)
6493 ((< pa pb) -1)
6494 (t nil))))
6495
6496 (defsubst org-cmp-category (a b)
6497 "Compare the string values of categories of strings A and B."
6498 (let ((ca (or (get-text-property 1 'category a) ""))
6499 (cb (or (get-text-property 1 'category b) "")))
6500 (cond ((string-lessp ca cb) -1)
6501 ((string-lessp cb ca) +1)
6502 (t nil))))
6503
6504 (defsubst org-cmp-time (a b)
6505 "Compare the time-of-day values of strings A and B."
6506 (let* ((def (if org-sort-agenda-notime-is-late 2401 -1))
6507 (ta (or (get-text-property 1 'time-of-day a) def))
6508 (tb (or (get-text-property 1 'time-of-day b) def)))
6509 (cond ((< ta tb) -1)
6510 ((< tb ta) +1)
6511 (t nil))))
6512
6513 (defun org-entries-lessp (a b)
6514 "Predicate for sorting agenda entries."
6515 ;; The following variables will be used when the form is evaluated.
6516 (let* ((time-up (org-cmp-time a b))
6517 (time-down (if time-up (- time-up) nil))
6518 (priority-up (org-cmp-priority a b))
6519 (priority-down (if priority-up (- priority-up) nil))
6520 (category-up (org-cmp-category a b))
6521 (category-down (if category-up (- category-up) nil))
6522 (category-keep (if category-up +1 nil)))
6523 (cdr (assoc
6524 (eval (cons 'or org-agenda-sorting-strategy))
6525 '((-1 . t) (1 . nil) (nil . nil))))))
6526
6527 (defun org-agenda-show-priority ()
6528 "Show the priority of the current item.
6529 This priority is composed of the main priority given with the [#A] cookies,
6530 and by additional input from the age of a schedules or deadline entry."
6531 (interactive)
6532 (let* ((pri (get-text-property (point-at-bol) 'priority)))
6533 (message "Priority is %d" (if pri pri -1000))))
6534
6535 (defun org-agenda-show-tags ()
6536 "Show the tags applicable to the current item."
6537 (interactive)
6538 (let* ((tags (get-text-property (point-at-bol) 'tags)))
6539 (if tags
6540 (message "Tags are :%s:" (mapconcat 'identity tags ":"))
6541 (message "No tags associated with this line"))))
6542
6543 (defun org-agenda-goto (&optional highlight)
6544 "Go to the Org-mode file which contains the item at point."
6545 (interactive)
6546 (let* ((marker (or (get-text-property (point) 'org-marker)
6547 (org-agenda-error)))
6548 (buffer (marker-buffer marker))
6549 (pos (marker-position marker)))
6550 (switch-to-buffer-other-window buffer)
6551 (widen)
6552 (goto-char pos)
6553 (when (eq major-mode 'org-mode)
6554 (org-show-hidden-entry)
6555 (save-excursion
6556 (and (outline-next-heading)
6557 (org-flag-heading nil)))) ; show the next heading
6558 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
6559
6560 (defun org-agenda-switch-to ()
6561 "Go to the Org-mode file which contains the item at point."
6562 (interactive)
6563 (let* ((marker (or (get-text-property (point) 'org-marker)
6564 (org-agenda-error)))
6565 (buffer (marker-buffer marker))
6566 (pos (marker-position marker)))
6567 (switch-to-buffer buffer)
6568 (delete-other-windows)
6569 (widen)
6570 (goto-char pos)
6571 (when (eq major-mode 'org-mode)
6572 (org-show-hidden-entry)
6573 (save-excursion
6574 (and (outline-next-heading)
6575 (org-flag-heading nil)))))) ; show the next heading
6576
6577 (defun org-agenda-goto-mouse (ev)
6578 "Go to the Org-mode file which contains the item at the mouse click."
6579 (interactive "e")
6580 (mouse-set-point ev)
6581 (org-agenda-goto))
6582
6583 (defun org-agenda-show ()
6584 "Display the Org-mode file which contains the item at point."
6585 (interactive)
6586 (let ((win (selected-window)))
6587 (org-agenda-goto t)
6588 (select-window win)))
6589
6590 (defun org-agenda-recenter (arg)
6591 "Display the Org-mode file which contains the item at point and recenter."
6592 (interactive "P")
6593 (let ((win (selected-window)))
6594 (org-agenda-goto t)
6595 (recenter arg)
6596 (select-window win)))
6597
6598 (defun org-agenda-show-mouse (ev)
6599 "Display the Org-mode file which contains the item at the mouse click."
6600 (interactive "e")
6601 (mouse-set-point ev)
6602 (org-agenda-show))
6603
6604 (defun org-agenda-check-no-diary ()
6605 "Check if the entry is a diary link and abort if yes."
6606 (if (get-text-property (point) 'org-agenda-diary-link)
6607 (org-agenda-error)))
6608
6609 (defun org-agenda-error ()
6610 (error "Command not allowed in this line"))
6611
6612 (defvar org-last-heading-marker (make-marker)
6613 "Marker pointing to the headline that last changed its TODO state
6614 by a remote command from the agenda.")
6615
6616 (defun org-agenda-todo (&optional arg)
6617 "Cycle TODO state of line at point, also in Org-mode file.
6618 This changes the line at point, all other lines in the agenda referring to
6619 the same tree node, and the headline of the tree node in the Org-mode file."
6620 (interactive "P")
6621 (org-agenda-check-no-diary)
6622 (let* ((col (current-column))
6623 (marker (or (get-text-property (point) 'org-marker)
6624 (org-agenda-error)))
6625 (buffer (marker-buffer marker))
6626 (pos (marker-position marker))
6627 (hdmarker (get-text-property (point) 'org-hd-marker))
6628 (buffer-read-only nil)
6629 newhead)
6630 (with-current-buffer buffer
6631 (widen)
6632 (goto-char pos)
6633 (org-show-hidden-entry)
6634 (save-excursion
6635 (and (outline-next-heading)
6636 (org-flag-heading nil))) ; show the next heading
6637 (org-todo arg)
6638 (and (bolp) (forward-char 1))
6639 (setq newhead (org-get-heading))
6640 (save-excursion
6641 (org-back-to-heading)
6642 (move-marker org-last-heading-marker (point))))
6643 (beginning-of-line 1)
6644 (save-excursion
6645 (org-agenda-change-all-lines newhead hdmarker 'fixface))
6646 (move-to-column col)))
6647
6648 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
6649 "Change all lines in the agenda buffer which match HDMARKER.
6650 The new content of the line will be NEWHEAD (as modified by
6651 `org-format-agenda-item'). HDMARKER is checked with
6652 `equal' against all `org-hd-marker' text properties in the file.
6653 If FIXFACE is non-nil, the face of each item is modified acording to
6654 the new TODO state."
6655 (let* (props m pl undone-face done-face finish new dotime cat tags)
6656 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
6657 (save-excursion
6658 (goto-char (point-max))
6659 (beginning-of-line 1)
6660 (while (not finish)
6661 (setq finish (bobp))
6662 (when (and (setq m (get-text-property (point) 'org-hd-marker))
6663 (equal m hdmarker))
6664 (setq props (text-properties-at (point))
6665 dotime (get-text-property (point) 'dotime)
6666 cat (get-text-property (point) 'category)
6667 tags (get-text-property (point) 'tags)
6668 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
6669 pl (get-text-property (point) 'prefix-length)
6670 undone-face (get-text-property (point) 'undone-face)
6671 done-face (get-text-property (point) 'done-face))
6672 (move-to-column pl)
6673 (if (looking-at ".*")
6674 (progn
6675 (replace-match new t t)
6676 (beginning-of-line 1)
6677 (add-text-properties (point-at-bol) (point-at-eol) props)
6678 (when fixface
6679 (add-text-properties
6680 (point-at-bol) (point-at-eol)
6681 (list 'face
6682 (if org-last-todo-state-is-todo
6683 undone-face done-face)))
6684 (org-agenda-highlight-todo 'line))
6685 (beginning-of-line 1))
6686 (error "Line update did not work")))
6687 (beginning-of-line 0)))))
6688
6689 (defun org-agenda-priority-up ()
6690 "Increase the priority of line at point, also in Org-mode file."
6691 (interactive)
6692 (org-agenda-priority 'up))
6693
6694 (defun org-agenda-priority-down ()
6695 "Decrease the priority of line at point, also in Org-mode file."
6696 (interactive)
6697 (org-agenda-priority 'down))
6698
6699 (defun org-agenda-priority (&optional force-direction)
6700 "Set the priority of line at point, also in Org-mode file.
6701 This changes the line at point, all other lines in the agenda referring to
6702 the same tree node, and the headline of the tree node in the Org-mode file."
6703 (interactive)
6704 (org-agenda-check-no-diary)
6705 (let* ((marker (or (get-text-property (point) 'org-marker)
6706 (org-agenda-error)))
6707 (buffer (marker-buffer marker))
6708 (pos (marker-position marker))
6709 (hdmarker (get-text-property (point) 'org-hd-marker))
6710 (buffer-read-only nil)
6711 newhead)
6712 (with-current-buffer buffer
6713 (widen)
6714 (goto-char pos)
6715 (org-show-hidden-entry)
6716 (save-excursion
6717 (and (outline-next-heading)
6718 (org-flag-heading nil))) ; show the next heading
6719 (funcall 'org-priority force-direction)
6720 (end-of-line 1)
6721 (setq newhead (org-get-heading)))
6722 (org-agenda-change-all-lines newhead hdmarker)
6723 (beginning-of-line 1)))
6724
6725 (defun org-get-tags-at (&optional pos)
6726 "Get a list of all headline targs applicable at POS.
6727 POS defaults to point. If tags are inherited, the list contains
6728 the targets in the same sequence as the headlines appear, i.e.
6729 the tags of the current headline come last."
6730 (interactive)
6731 (let (tags)
6732 (save-excursion
6733 (goto-char (or pos (point)))
6734 (save-match-data
6735 (org-back-to-heading t)
6736 (condition-case nil
6737 (while t
6738 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
6739 (setq tags (append (org-split-string (match-string 1) ":") tags)))
6740 (or org-use-tag-inheritance (error ""))
6741 (org-up-heading-all 1))
6742 (error nil))))
6743 (message "%s" tags)
6744 tags))
6745
6746 (defun org-agenda-set-tags ()
6747 "Set tags for the current headline."
6748 (interactive)
6749 (org-agenda-check-no-diary)
6750 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
6751 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
6752 (org-agenda-error)))
6753 (buffer (marker-buffer hdmarker))
6754 (pos (marker-position hdmarker))
6755 (buffer-read-only nil)
6756 newhead)
6757 (with-current-buffer buffer
6758 (widen)
6759 (goto-char pos)
6760 (org-show-hidden-entry)
6761 (save-excursion
6762 (and (outline-next-heading)
6763 (org-flag-heading nil))) ; show the next heading
6764 (call-interactively 'org-set-tags)
6765 (end-of-line 1)
6766 (setq newhead (org-get-heading)))
6767 (org-agenda-change-all-lines newhead hdmarker)
6768 (beginning-of-line 1)))
6769
6770 (defun org-agenda-date-later (arg &optional what)
6771 "Change the date of this item to one day later."
6772 (interactive "p")
6773 (org-agenda-check-type t 'agenda 'timeline)
6774 (org-agenda-check-no-diary)
6775 (let* ((marker (or (get-text-property (point) 'org-marker)
6776 (org-agenda-error)))
6777 (buffer (marker-buffer marker))
6778 (pos (marker-position marker)))
6779 (with-current-buffer buffer
6780 (widen)
6781 (goto-char pos)
6782 (if (not (org-at-timestamp-p))
6783 (error "Cannot find time stamp"))
6784 (org-timestamp-change arg (or what 'day))
6785 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6786
6787 (defun org-agenda-date-earlier (arg &optional what)
6788 "Change the date of this item to one day earlier."
6789 (interactive "p")
6790 (org-agenda-date-later (- arg) what))
6791
6792 (defun org-agenda-date-prompt (arg)
6793 "Change the date of this item. Date is prompted for, with default today.
6794 The prefix ARG is passed to the `org-time-stamp' command and can therefore
6795 be used to request time specification in the time stamp."
6796 (interactive "P")
6797 (org-agenda-check-type t 'agenda 'timeline)
6798 (org-agenda-check-no-diary)
6799 (let* ((marker (or (get-text-property (point) 'org-marker)
6800 (org-agenda-error)))
6801 (buffer (marker-buffer marker))
6802 (pos (marker-position marker)))
6803 (with-current-buffer buffer
6804 (widen)
6805 (goto-char pos)
6806 (if (not (org-at-timestamp-p))
6807 (error "Cannot find time stamp"))
6808 (org-time-stamp arg)
6809 (message "Time stamp changed to %s" org-last-changed-timestamp))))
6810
6811 (defun org-get-heading ()
6812 "Return the heading of the current entry, without the stars."
6813 (save-excursion
6814 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
6815 (if (and (re-search-backward "[\r\n]\\*" nil t)
6816 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
6817 (match-string 1)
6818 "")))
6819
6820 (defun org-agenda-diary-entry ()
6821 "Make a diary entry, like the `i' command from the calendar.
6822 All the standard commands work: block, weekly etc."
6823 (interactive)
6824 (org-agenda-check-type t 'agenda 'timeline)
6825 (require 'diary-lib)
6826 (let* ((char (progn
6827 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
6828 (read-char-exclusive)))
6829 (cmd (cdr (assoc char
6830 '((?d . insert-diary-entry)
6831 (?w . insert-weekly-diary-entry)
6832 (?m . insert-monthly-diary-entry)
6833 (?y . insert-yearly-diary-entry)
6834 (?a . insert-anniversary-diary-entry)
6835 (?b . insert-block-diary-entry)
6836 (?c . insert-cyclic-diary-entry)))))
6837 (oldf (symbol-function 'calendar-cursor-to-date))
6838 (point (point))
6839 (mark (or (mark t) (point))))
6840 (unless cmd
6841 (error "No command associated with <%c>" char))
6842 (unless (and (get-text-property point 'day)
6843 (or (not (equal ?b char))
6844 (get-text-property mark 'day)))
6845 (error "Don't know which date to use for diary entry"))
6846 ;; We implement this by hacking the `calendar-cursor-to-date' function
6847 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
6848 (let ((calendar-mark-ring
6849 (list (calendar-gregorian-from-absolute
6850 (or (get-text-property mark 'day)
6851 (get-text-property point 'day))))))
6852 (unwind-protect
6853 (progn
6854 (fset 'calendar-cursor-to-date
6855 (lambda (&optional error)
6856 (calendar-gregorian-from-absolute
6857 (get-text-property point 'day))))
6858 (call-interactively cmd))
6859 (fset 'calendar-cursor-to-date oldf)))))
6860
6861
6862 (defun org-agenda-execute-calendar-command (cmd)
6863 "Execute a calendar command from the agenda, with the date associated to
6864 the cursor position."
6865 (org-agenda-check-type t 'agenda 'timeline)
6866 (require 'diary-lib)
6867 (unless (get-text-property (point) 'day)
6868 (error "Don't know which date to use for calendar command"))
6869 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
6870 (point (point))
6871 (date (calendar-gregorian-from-absolute
6872 (get-text-property point 'day)))
6873 (displayed-day (extract-calendar-day date))
6874 (displayed-month (extract-calendar-month date))
6875 (displayed-year (extract-calendar-year date)))
6876 (unwind-protect
6877 (progn
6878 (fset 'calendar-cursor-to-date
6879 (lambda (&optional error)
6880 (calendar-gregorian-from-absolute
6881 (get-text-property point 'day))))
6882 (call-interactively cmd))
6883 (fset 'calendar-cursor-to-date oldf))))
6884
6885 (defun org-agenda-phases-of-moon ()
6886 "Display the phases of the moon for the 3 months around the cursor date."
6887 (interactive)
6888 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
6889
6890 (defun org-agenda-holidays ()
6891 "Display the holidays for the 3 months around the cursor date."
6892 (interactive)
6893 (org-agenda-execute-calendar-command 'list-calendar-holidays))
6894
6895 (defun org-agenda-sunrise-sunset (arg)
6896 "Display sunrise and sunset for the cursor date.
6897 Latitude and longitude can be specified with the variables
6898 `calendar-latitude' and `calendar-longitude'. When called with prefix
6899 argument, latitude and longitude will be prompted for."
6900 (interactive "P")
6901 (let ((calendar-longitude (if arg nil calendar-longitude))
6902 (calendar-latitude (if arg nil calendar-latitude))
6903 (calendar-location-name
6904 (if arg "the given coordinates" calendar-location-name)))
6905 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
6906
6907 (defun org-agenda-goto-calendar ()
6908 "Open the Emacs calendar with the date at the cursor."
6909 (interactive)
6910 (org-agenda-check-type t 'agenda 'timeline)
6911 (let* ((day (or (get-text-property (point) 'day)
6912 (error "Don't know which date to open in calendar")))
6913 (date (calendar-gregorian-from-absolute day))
6914 (calendar-move-hook nil)
6915 (view-calendar-holidays-initially nil)
6916 (view-diary-entries-initially nil))
6917 (calendar)
6918 (calendar-goto-date date)))
6919
6920 (defun org-calendar-goto-agenda ()
6921 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
6922 This is a command that has to be installed in `calendar-mode-map'."
6923 (interactive)
6924 (org-agenda-list nil (calendar-absolute-from-gregorian
6925 (calendar-cursor-to-date))
6926 nil t))
6927
6928 (defun org-agenda-convert-date ()
6929 (interactive)
6930 (org-agenda-check-type t 'agenda 'timeline)
6931 (let ((day (get-text-property (point) 'day))
6932 date s)
6933 (unless day
6934 (error "Don't know which date to convert"))
6935 (setq date (calendar-gregorian-from-absolute day))
6936 (setq s (concat
6937 "Gregorian: " (calendar-date-string date) "\n"
6938 "ISO: " (calendar-iso-date-string date) "\n"
6939 "Day of Yr: " (calendar-day-of-year-string date) "\n"
6940 "Julian: " (calendar-julian-date-string date) "\n"
6941 "Astron. JD: " (calendar-astro-date-string date)
6942 " (Julian date number at noon UTC)\n"
6943 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
6944 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
6945 "French: " (calendar-french-date-string date) "\n"
6946 "Mayan: " (calendar-mayan-date-string date) "\n"
6947 "Coptic: " (calendar-coptic-date-string date) "\n"
6948 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
6949 "Persian: " (calendar-persian-date-string date) "\n"
6950 "Chinese: " (calendar-chinese-date-string date) "\n"))
6951 (with-output-to-temp-buffer "*Dates*"
6952 (princ s))
6953 (if (fboundp 'fit-window-to-buffer)
6954 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
6955
6956 ;;; Tags
6957
6958 (defun org-scan-tags (action matcher &optional todo-only)
6959 "Scan headline tags with inheritance and produce output ACTION.
6960 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
6961 evaluated, testing if a given set of tags qualifies a headline for
6962 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
6963 are included in the output."
6964 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
6965 (mapconcat 'regexp-quote
6966 (nreverse (cdr (reverse org-todo-keywords)))
6967 "\\|")
6968 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
6969 (props (list 'face nil
6970 'done-face 'org-done
6971 'undone-face nil
6972 'mouse-face 'highlight
6973 'keymap org-agenda-keymap
6974 'help-echo
6975 (format "mouse-2 or RET jump to org file %s"
6976 (abbreviate-file-name buffer-file-name))))
6977 lspos
6978 tags tags-list tags-alist (llast 0) rtn level category i txt
6979 todo marker)
6980
6981 (save-excursion
6982 (goto-char (point-min))
6983 (when (eq action 'sparse-tree) (hide-sublevels 1))
6984 (while (re-search-forward re nil t)
6985 (setq todo (if (match-end 1) (match-string 2))
6986 tags (if (match-end 4) (match-string 4)))
6987 (goto-char (setq lspos (1+ (match-beginning 0))))
6988 (setq level (funcall outline-level)
6989 category (org-get-category))
6990 (setq i llast llast level)
6991 ;; remove tag lists from same and sublevels
6992 (while (>= i level)
6993 (when (setq entry (assoc i tags-alist))
6994 (setq tags-alist (delete entry tags-alist)))
6995 (setq i (1- i)))
6996 ;; add the nex tags
6997 (when tags
6998 (setq tags (mapcar 'downcase (org-split-string tags ":"))
6999 tags-alist
7000 (cons (cons level tags) tags-alist)))
7001 ;; compile tags for current headline
7002 (setq tags-list
7003 (if org-use-tag-inheritance
7004 (apply 'append (mapcar 'cdr tags-alist))
7005 tags))
7006 (when (and (or (not todo-only) todo)
7007 (eval matcher))
7008 ;; list this headline
7009 (if (eq action 'sparse-tree)
7010 (progn
7011 (org-show-hierarchy-above))
7012 (setq txt (org-format-agenda-item
7013 ""
7014 (concat
7015 (if org-tags-match-list-sublevels
7016 (make-string (1- level) ?.) "")
7017 (org-get-heading))
7018 category tags-list))
7019 (goto-char lspos)
7020 (setq marker (org-agenda-new-marker))
7021 (org-add-props txt props
7022 'org-marker marker 'org-hd-marker marker 'category category)
7023 (push txt rtn))
7024 ;; if we are to skip sublevels, jump to end of subtree
7025 (point)
7026 (or org-tags-match-list-sublevels (org-end-of-subtree)))))
7027 (nreverse rtn)))
7028
7029 (defun org-tags-sparse-tree (&optional arg match)
7030 "Create a sparse tree according to tags search string MATCH.
7031 MATCH can contain positive and negative selection of tags, like
7032 \"+WORK+URGENT-WITHBOSS\"."
7033 (interactive "P")
7034 (let ((org-show-following-heading nil)
7035 (org-show-hierarchy-above nil))
7036 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
7037
7038 (defun org-make-tags-matcher (match)
7039 "Create the TAGS matcher form for the tags-selecting string MATCH."
7040 (unless match
7041 ;; Get a new match request, with completion
7042 (setq org-last-tags-completion-table
7043 (or (org-get-buffer-tags)
7044 org-last-tags-completion-table))
7045 (setq match (completing-read
7046 "Tags: " 'org-tags-completion-function nil nil nil
7047 'org-tags-history)))
7048 ;; parse the string and create a lisp form
7049 (let ((match0 match) minus tag mm matcher orterms term orlist)
7050 (setq orterms (org-split-string match "|"))
7051 (while (setq term (pop orterms))
7052 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
7053 (setq minus (and (match-end 1)
7054 (equal (match-string 1 term) "-"))
7055 tag (match-string 2 term)
7056 term (substring term (match-end 0))
7057 mm (list 'member (downcase tag) 'tags-list)
7058 mm (if minus (list 'not mm) mm))
7059 (push mm matcher))
7060 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
7061 orlist)
7062 (setq matcher nil))
7063 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
7064 ;; Return the string and lisp forms of the matcher
7065 (cons match0 matcher)))
7066
7067 ;;;###autoload
7068 (defun org-tags-view (&optional todo-only match keep-modes)
7069 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
7070 The prefix arg TODO-ONLY limits the search to TODO entries."
7071 (interactive "P")
7072 (org-agenda-maybe-reset-markers 'force)
7073 (org-compile-prefix-format org-agenda-prefix-format)
7074 (let* ((org-agenda-keep-modes keep-modes)
7075 (org-tags-match-list-sublevels
7076 (if todo-only t org-tags-match-list-sublevels))
7077 (win (selected-window))
7078 (completion-ignore-case t)
7079 rtn rtnall files file pos matcher
7080 buffer)
7081 (setq matcher (org-make-tags-matcher match)
7082 match (car matcher) matcher (cdr matcher))
7083 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
7084 (progn
7085 (delete-other-windows)
7086 (switch-to-buffer-other-window
7087 (get-buffer-create org-agenda-buffer-name))))
7088 (setq buffer-read-only nil)
7089 (erase-buffer)
7090 (org-agenda-mode) (setq buffer-read-only nil)
7091 (set (make-local-variable 'org-agenda-type) 'tags)
7092 (set (make-local-variable 'org-agenda-redo-command)
7093 (list 'org-tags-view (list 'quote todo-only)
7094 (list 'if 'current-prefix-arg nil match) t))
7095 (setq files (org-agenda-files)
7096 rtnall nil)
7097 (while (setq file (pop files))
7098 (catch 'nextfile
7099 (org-check-agenda-file file)
7100 (setq buffer (if (file-exists-p file)
7101 (org-get-agenda-file-buffer file)
7102 (error "No such file %s" file)))
7103 (if (not buffer)
7104 ;; If file does not exist, merror message to agenda
7105 (setq rtn (list
7106 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7107 rtnall (append rtnall rtn))
7108 (with-current-buffer buffer
7109 (unless (eq major-mode 'org-mode)
7110 (error "Agenda file %s is not in `org-mode'" file))
7111 (save-excursion
7112 (save-restriction
7113 (if org-respect-restriction
7114 (if (org-region-active-p)
7115 ;; Respect a region to restrict search
7116 (narrow-to-region (region-beginning) (region-end)))
7117 ;; If we work for the calendar or many files,
7118 ;; get rid of any restriction
7119 (widen))
7120 (setq rtn (org-scan-tags 'agenda matcher todo-only))
7121 (setq rtnall (append rtnall rtn))))))))
7122 (insert "Headlines with TAGS match: ")
7123 (add-text-properties (point-min) (1- (point))
7124 (list 'face 'org-level-3))
7125 (setq pos (point))
7126 (insert match "\n")
7127 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7128 (setq pos (point))
7129 (insert "Press `C-u r' to search again with new search string\n")
7130 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7131 (when rtnall
7132 (insert (mapconcat 'identity rtnall "\n")))
7133 (goto-char (point-min))
7134 (setq buffer-read-only t)
7135 (org-fit-agenda-window)
7136 (if (not org-select-agenda-window) (select-window win))))
7137
7138 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
7139 (defun org-set-tags (&optional arg just-align)
7140 "Set the tags for the current headline.
7141 With prefix ARG, realign all tags in headings in the current buffer."
7142 (interactive)
7143 (let* (;(inherit (org-get-inherited-tags))
7144 (re (concat "^" outline-regexp))
7145 (col (current-column))
7146 (current (org-get-tags))
7147 tags hd empty invis)
7148 (if arg
7149 (save-excursion
7150 (goto-char (point-min))
7151 (while (re-search-forward re nil t)
7152 (org-set-tags nil t))
7153 (message "All tags realigned to column %d" org-tags-column))
7154 (if just-align
7155 (setq tags current)
7156 (setq org-last-tags-completion-table
7157 (or (org-get-buffer-tags)
7158 org-last-tags-completion-table))
7159 (setq tags
7160 (let ((org-add-colon-after-tag-completion t))
7161 (completing-read "Tags: " 'org-tags-completion-function
7162 nil nil current 'org-tags-history)))
7163 (while (string-match "[-+&]+" tags)
7164 (setq tags (replace-match ":" t t tags))))
7165 ;; FIXME: still optimize this by not checking when JUST-ALIGN?
7166 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
7167 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
7168 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
7169 (if (equal current "")
7170 (progn
7171 (end-of-line 1)
7172 (or empty (insert-before-markers " ")))
7173 (beginning-of-line 1)
7174 (setq invis (org-invisible-p))
7175 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
7176 (setq hd (match-string 1))
7177 (delete-region (match-beginning 0) (match-end 0))
7178 (insert-before-markers (org-trim hd) (if empty "" " ")))
7179 (unless (equal tags "")
7180 (move-to-column (max (current-column)
7181 (if (> org-tags-column 0)
7182 org-tags-column
7183 (- (- org-tags-column) (length tags))))
7184 t)
7185 (insert-before-markers tags)
7186 (if (and (not invis) (org-invisible-p))
7187 (outline-flag-region (point-at-bol) (point) nil)))
7188 (move-to-column col))))
7189
7190 (defun org-tags-completion-function (string predicate &optional flag)
7191 (let (s1 s2 rtn (ctable org-last-tags-completion-table))
7192 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
7193 (setq s1 (match-string 1 string)
7194 s2 (match-string 2 string))
7195 (setq s1 "" s2 string))
7196 (cond
7197 ((eq flag nil)
7198 ;; try completion
7199 (setq rtn (try-completion s2 ctable))
7200 (if (stringp rtn)
7201 (concat s1 s2 (substring rtn (length s2))
7202 (if (and org-add-colon-after-tag-completion
7203 (assoc rtn ctable))
7204 ":" "")))
7205 )
7206 ((eq flag t)
7207 ;; all-completions
7208 (all-completions s2 ctable)
7209 )
7210 ((eq flag 'lambda)
7211 ;; exact match?
7212 (assoc s2 ctable)))
7213 ))
7214
7215 (defun org-get-tags ()
7216 "Get the TAGS string in the current headline."
7217 (unless (org-on-heading-p)
7218 (error "Not on a heading"))
7219 (save-excursion
7220 (beginning-of-line 1)
7221 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
7222 (org-match-string-no-properties 1)
7223 "")))
7224
7225 (defun org-get-buffer-tags ()
7226 "Get a table of all tags used in the buffer, for completion."
7227 (let (tags)
7228 (save-excursion
7229 (goto-char (point-min))
7230 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
7231 (mapc (lambda (x) (add-to-list 'tags x))
7232 (org-split-string (org-match-string-no-properties 1) ":"))))
7233 (mapcar 'list tags)))
7234
7235 ;;; Link Stuff
7236
7237 (defun org-find-file-at-mouse (ev)
7238 "Open file link or URL at mouse."
7239 (interactive "e")
7240 (mouse-set-point ev)
7241 (org-open-at-point 'in-emacs))
7242
7243 (defun org-open-at-mouse (ev)
7244 "Open file link or URL at mouse."
7245 (interactive "e")
7246 (mouse-set-point ev)
7247 (org-open-at-point))
7248
7249 (defun org-open-at-point (&optional in-emacs)
7250 "Open link at or after point.
7251 If there is no link at point, this function will search forward up to
7252 the end of the current subtree.
7253 Normally, files will be opened by an appropriate application. If the
7254 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7255 (interactive "P")
7256 (org-remove-occur-highlights nil nil t)
7257 (if (org-at-timestamp-p)
7258 (org-agenda-list nil (time-to-days (org-time-string-to-time
7259 (substring (match-string 1) 0 10)))
7260 1)
7261 (let (type path link line search (pos (point)))
7262 (catch 'match
7263 (save-excursion
7264 (skip-chars-forward "^]\n\r")
7265 (when (and (re-search-backward "\\[\\[" nil t)
7266 (looking-at org-bracket-link-regexp)
7267 (<= (match-beginning 0) pos)
7268 (>= (match-end 0) pos))
7269 (setq link (org-link-unescape (org-match-string-no-properties 1)))
7270 (while (string-match " *\n *" link)
7271 (setq link (replace-match " " t t link)))
7272 (if (string-match org-link-re-with-space2 link)
7273 (setq type (match-string 1 link)
7274 path (match-string 2 link))
7275 (setq type "thisfile"
7276 path link))
7277 (throw 'match t)))
7278
7279 (when (get-text-property (point) 'org-linked-text)
7280 (setq type "thisfile"
7281 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7282 (1+ (point)) (point))
7283 path (buffer-substring
7284 (previous-single-property-change pos 'org-linked-text)
7285 (next-single-property-change pos 'org-linked-text)))
7286 (throw 'match t))
7287
7288 (save-excursion
7289 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
7290 (if (equal (char-before) ?<) (backward-char 1))
7291 (when (or (looking-at org-angle-link-re)
7292 (looking-at org-plain-link-re)
7293 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
7294 (re-search-forward org-plain-link-re (point-at-eol) t))
7295 (<= (match-beginning 0) pos)
7296 (>= (match-end 0) pos)))
7297 (setq type (match-string 1)
7298 path (match-string 2))
7299 (throw 'match t)))
7300 (save-excursion
7301 (skip-chars-backward "^ \t\n\r")
7302 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
7303 (setq type "tags"
7304 path (match-string 1))
7305 (while (string-match ":" path)
7306 (setq path (replace-match "+" t t path)))
7307 (throw 'match t)))
7308 (save-excursion
7309 (skip-chars-backward "a-zA-Z_")
7310 (when (and (memq 'camel org-activate-links)
7311 (looking-at org-camel-regexp))
7312 (setq type "camel" path (match-string 0))
7313 (if (equal (char-before) ?*)
7314 (setq path (concat "*" path))))
7315 (throw 'match t)))
7316 (unless path
7317 (error "No link found"))
7318 ;; Remove any trailing spaces in path
7319 (if (string-match " +\\'" path)
7320 (setq path (replace-match "" t t path)))
7321
7322 (cond
7323
7324 ((member type '("http" "https" "ftp" "mailto" "news"))
7325 (browse-url (concat type ":" path)))
7326
7327 ((string= type "tags")
7328 (org-tags-view in-emacs path))
7329 ((or (string= type "camel")
7330 (string= type "thisfile"))
7331 (org-mark-ring-push)
7332 (org-link-search
7333 path
7334 (cond ((equal in-emacs '(4)) 'occur)
7335 ((equal in-emacs '(16)) 'org-occur)
7336 (t nil))))
7337
7338 ((string= type "file")
7339 (if (string-match "::?\\([0-9]+\\)\\'" path) ;; second : optional
7340 (setq line (string-to-number (match-string 1 path))
7341 path (substring path 0 (match-beginning 0)))
7342 (if (string-match "::\\(.+\\)\\'" path)
7343 (setq search (match-string 1 path)
7344 path (substring path 0 (match-beginning 0)))))
7345 (org-open-file path in-emacs line search))
7346
7347 ((string= type "news")
7348 (org-follow-gnus-link path))
7349
7350 ((string= type "bbdb")
7351 (org-follow-bbdb-link path))
7352
7353 ((string= type "gnus")
7354 (let (group article)
7355 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7356 (error "Error in Gnus link"))
7357 (setq group (match-string 1 path)
7358 article (match-string 3 path))
7359 (org-follow-gnus-link group article)))
7360
7361 ((string= type "vm")
7362 (let (folder article)
7363 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7364 (error "Error in VM link"))
7365 (setq folder (match-string 1 path)
7366 article (match-string 3 path))
7367 ;; in-emacs is the prefix arg, will be interpreted as read-only
7368 (org-follow-vm-link folder article in-emacs)))
7369
7370 ((string= type "wl")
7371 (let (folder article)
7372 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7373 (error "Error in Wanderlust link"))
7374 (setq folder (match-string 1 path)
7375 article (match-string 3 path))
7376 (org-follow-wl-link folder article)))
7377
7378 ((string= type "mhe")
7379 (let (folder article)
7380 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7381 (error "Error in MHE link"))
7382 (setq folder (match-string 1 path)
7383 article (match-string 3 path))
7384 (org-follow-mhe-link folder article)))
7385
7386 ((string= type "rmail")
7387 (let (folder article)
7388 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
7389 (error "Error in RMAIL link"))
7390 (setq folder (match-string 1 path)
7391 article (match-string 3 path))
7392 (org-follow-rmail-link folder article)))
7393
7394 ((string= type "shell")
7395 (let ((cmd path))
7396 (while (string-match "@{" cmd)
7397 (setq cmd (replace-match "<" t t cmd)))
7398 (while (string-match "@}" cmd)
7399 (setq cmd (replace-match ">" t t cmd)))
7400 (if (or (not org-confirm-shell-links)
7401 (funcall org-confirm-shell-links
7402 (format "Execute \"%s\" in shell? "
7403 (org-add-props cmd nil
7404 'face 'org-warning))))
7405 (progn
7406 (message "Executing %s" cmd)
7407 (shell-command cmd))
7408 (error "Abort"))))
7409
7410 (t
7411 (browse-url-at-point))))))
7412
7413 (defun org-link-search (s &optional type)
7414 "Search for a link search option.
7415 When S is a CamelCaseWord, search for a target, or for a sentence containing
7416 the words. If S is surrounded by forward slashes, it is interpreted as a
7417 regular expression. In org-mode files, this will create an `org-occur'
7418 sparse tree. In ordinary files, `occur' will be used to list matches.
7419 If the current buffer is in `dired-mode', grep will be used to search
7420 in all files."
7421 (let ((case-fold-search t)
7422 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7423 (pos (point))
7424 (pre "") (post "")
7425 words re0 re1 re2 re3 re4 re5 re2a reall camel)
7426 (cond ((save-excursion
7427 (goto-char (point-min))
7428 (and
7429 (re-search-forward
7430 (concat "<<" (regexp-quote s0) ">>") nil t)
7431 (setq pos (match-beginning 0))))
7432 ;; There is an exact target for this
7433 (goto-char pos))
7434 ((string-match "^/\\(.*\\)/$" s)
7435 ;; A regular expression
7436 (cond
7437 ((eq major-mode 'org-mode)
7438 (org-occur (match-string 1 s)))
7439 ;;((eq major-mode 'dired-mode)
7440 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7441 (t (org-do-occur (match-string 1 s)))))
7442 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
7443 t)
7444 ;; A camel or a normal search string
7445 (when (equal (string-to-char s) ?*)
7446 ;; Anchor on headlines, post may include tags.
7447 (setq pre "^\\*+[ \t]*\\(\\sw+\\)?[ \t]*"
7448 post "[ \t]*\\([ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
7449 s (substring s 1)))
7450 (remove-text-properties
7451 0 (length s)
7452 '(face nil mouse-face nil keymap nil fontified nil) s)
7453 ;; Make a series of regular expressions to find a match
7454 (setq words
7455 (if camel
7456 (org-camel-to-words s)
7457 (org-split-string s "[ \n\r\t]+"))
7458 re0 (concat "<<" (regexp-quote s0) ">>")
7459 re2 (concat "\\<" (mapconcat 'downcase words "[ \t]+") "\\>")
7460 re2a (concat "\\<" (mapconcat 'downcase words "[ \t\r\n]+") "\\>")
7461 re4 (concat "\\<" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\>")
7462 re1 (concat pre re2 post)
7463 re3 (concat pre re4 post)
7464 re5 (concat pre ".*" re4)
7465 re2 (concat pre re2)
7466 re2a (concat pre re2a)
7467 re4 (concat pre re4)
7468 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7469 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7470 re5 "\\)"
7471 ))
7472 (cond
7473 ((eq type 'org-occur) (org-occur reall))
7474 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7475 (t (goto-char (point-min))
7476 (if (or (org-search-not-link re0 nil t)
7477 (org-search-not-link re1 nil t)
7478 (org-search-not-link re2 nil t)
7479 (org-search-not-link re2a nil t)
7480 (org-search-not-link re3 nil t)
7481 (org-search-not-link re4 nil t)
7482 (org-search-not-link re5 nil t)
7483 )
7484 (goto-char (match-beginning 0))
7485 (goto-char pos)
7486 (error "No match")))))
7487 (t
7488 ;; Normal string-search
7489 (goto-char (point-min))
7490 (if (search-forward s nil t)
7491 (goto-char (match-beginning 0))
7492 (error "No match"))))
7493 (and (eq major-mode 'org-mode) (org-show-hierarchy-above))))
7494
7495 (defun org-search-not-link (&rest args)
7496 "Execute `re-search-forward', but only accept matches that are not a link."
7497 (catch 'exit
7498 (let ((pos (point)) p1)
7499 (while (apply 're-search-forward args)
7500 (setq p1 (point))
7501 (if (not (save-match-data
7502 (and (re-search-backward "\\[\\[" nil t)
7503 (looking-at org-bracket-link-regexp)
7504 (<= (match-beginning 0) p1)
7505 (>= (match-end 0) p1))))
7506 (progn (goto-char (match-end 0))
7507 (throw 'exit (point)))
7508 (goto-char (match-end 0)))))))
7509
7510 (defun org-do-occur (regexp &optional cleanup)
7511 "Call the Emacs command `occur'.
7512 If CLEANUP is non-nil, remove the printout of the regular expression
7513 in the *Occur* buffer. This is useful if the regex is long and not useful
7514 to read."
7515 (occur regexp)
7516 (when cleanup
7517 (let ((cwin (selected-window)) win beg end)
7518 (when (setq win (get-buffer-window "*Occur*"))
7519 (select-window win))
7520 (goto-char (point-min))
7521 (when (re-search-forward "match[a-z]+" nil t)
7522 (setq beg (match-end 0))
7523 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7524 (setq end (1- (match-beginning 0)))))
7525 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
7526 (goto-char (point-min))
7527 (select-window cwin))))
7528
7529 (defvar org-mark-ring nil
7530 "Mark ring for positions before jumps in Org-mode.")
7531 (defvar org-mark-ring-last-goto nil
7532 "Last position in the mark ring used to go back.")
7533 ;; Fill and close the ring
7534 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7535 (loop for i from 1 to org-mark-ring-length do
7536 (push (make-marker) org-mark-ring))
7537 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7538 org-mark-ring)
7539
7540 (defun org-mark-ring-push (&optional pos buffer)
7541 "Put the current position or POS into the mark ring and rotate it."
7542 (interactive)
7543 (setq pos (or pos (point)))
7544 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7545 (move-marker (car org-mark-ring)
7546 (or pos (point))
7547 (or buffer (current-buffer)))
7548 (message
7549 (substitute-command-keys
7550 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7551
7552 (defun org-mark-ring-goto (&optional n)
7553 "Jump to the previous position in the mark ring.
7554 With prefix arg N, jump back that many stored positions. When
7555 called several times in succession, walk through the entire ring.
7556 Org-mode commands jumping to a different position in the current file,
7557 or to another Org-mode file, automatically push the old position
7558 onto the ring."
7559 (interactive "p")
7560 (let (p m)
7561 (if (eq last-command this-command)
7562 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7563 (setq p org-mark-ring))
7564 (setq org-mark-ring-last-goto p)
7565 (setq m (car p))
7566 (switch-to-buffer (marker-buffer m))
7567 (goto-char m)
7568 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
7569
7570 (defun org-camel-to-words (s)
7571 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
7572 (let ((case-fold-search nil)
7573 words)
7574 (while (string-match "[a-z][A-Z]" s)
7575 (push (substring s 0 (1+ (match-beginning 0))) words)
7576 (setq s (substring s (1+ (match-beginning 0)))))
7577 (nreverse (cons s words))))
7578
7579 (defun org-remove-angle-brackets (s)
7580 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7581 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7582 s)
7583 (defun org-add-angle-brackets (s)
7584 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7585 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7586 s)
7587
7588 (defun org-follow-bbdb-link (name)
7589 "Follow a BBDB link to NAME."
7590 (require 'bbdb)
7591 (let ((inhibit-redisplay t)
7592 (bbdb-electric-p nil))
7593 (catch 'exit
7594 ;; Exact match on name
7595 (bbdb-name (concat "\\`" name "\\'") nil)
7596 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7597 ;; Exact match on name
7598 (bbdb-company (concat "\\`" name "\\'") nil)
7599 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7600 ;; Partial match on name
7601 (bbdb-name name nil)
7602 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7603 ;; Partial match on company
7604 (bbdb-company name nil)
7605 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
7606 ;; General match including network address and notes
7607 (bbdb name nil)
7608 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
7609 (delete-window (get-buffer-window "*BBDB*"))
7610 (error "No matching BBDB record")))))
7611
7612 (defun org-follow-gnus-link (&optional group article)
7613 "Follow a Gnus link to GROUP and ARTICLE."
7614 (require 'gnus)
7615 (funcall (cdr (assq 'gnus org-link-frame-setup)))
7616 (if group (gnus-fetch-group group))
7617 (if article
7618 (or (gnus-summary-goto-article article nil 'force)
7619 (if (fboundp 'gnus-summary-insert-cached-articles)
7620 (progn
7621 (gnus-summary-insert-cached-articles)
7622 (gnus-summary-goto-article article nil 'force))
7623 (message "Message could not be found.")))))
7624
7625 (defun org-follow-vm-link (&optional folder article readonly)
7626 "Follow a VM link to FOLDER and ARTICLE."
7627 (require 'vm)
7628 (setq article (org-add-angle-brackets article))
7629 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
7630 ;; ange-ftp or efs or tramp access
7631 (let ((user (or (match-string 1 folder) (user-login-name)))
7632 (host (match-string 2 folder))
7633 (file (match-string 3 folder)))
7634 (cond
7635 ((featurep 'tramp)
7636 ;; use tramp to access the file
7637 (if (featurep 'xemacs)
7638 (setq folder (format "[%s@%s]%s" user host file))
7639 (setq folder (format "/%s@%s:%s" user host file))))
7640 (t
7641 ;; use ange-ftp or efs
7642 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
7643 (setq folder (format "/%s@%s:%s" user host file))))))
7644 (when folder
7645 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
7646 (sit-for 0.1)
7647 (when article
7648 (vm-select-folder-buffer)
7649 (widen)
7650 (let ((case-fold-search t))
7651 (goto-char (point-min))
7652 (if (not (re-search-forward
7653 (concat "^" "message-id: *" (regexp-quote article))))
7654 (error "Could not find the specified message in this folder"))
7655 (vm-isearch-update)
7656 (vm-isearch-narrow)
7657 (vm-beginning-of-message)
7658 (vm-summarize)))))
7659
7660 (defun org-follow-wl-link (folder article)
7661 "Follow a Wanderlust link to FOLDER and ARTICLE."
7662 (setq article (org-add-angle-brackets article))
7663 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
7664 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
7665 (wl-summary-redisplay))
7666
7667 (defun org-follow-rmail-link (folder article)
7668 "Follow an RMAIL link to FOLDER and ARTICLE."
7669 (setq article (org-add-angle-brackets article))
7670 (let (message-number)
7671 (save-excursion
7672 (save-window-excursion
7673 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7674 (setq message-number
7675 (save-restriction
7676 (widen)
7677 (goto-char (point-max))
7678 (if (re-search-backward
7679 (concat "^Message-ID:\\s-+" (regexp-quote
7680 (or article "")))
7681 nil t)
7682 (rmail-what-message))))))
7683 (if message-number
7684 (progn
7685 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
7686 (rmail-show-message message-number)
7687 message-number)
7688 (error "Message not found"))))
7689
7690 ;; mh-e integration based on planner-mode
7691 (defun org-mhe-get-message-real-folder ()
7692 "Return the name of the current message real folder, so if you use
7693 sequences, it will now work."
7694 (save-excursion
7695 (let* ((folder
7696 (if (equal major-mode 'mh-folder-mode)
7697 mh-current-folder
7698 ;; Refer to the show buffer
7699 mh-show-folder-buffer))
7700 (end-index
7701 (if (boundp 'mh-index-folder)
7702 (min (length mh-index-folder) (length folder))))
7703 )
7704 ;; a simple test on mh-index-data does not work, because
7705 ;; mh-index-data is always nil in a show buffer.
7706 (if (and (boundp 'mh-index-folder)
7707 (string= mh-index-folder (substring folder 0 end-index)))
7708 (if (equal major-mode 'mh-show-mode)
7709 (save-window-excursion
7710 (when (buffer-live-p (get-buffer folder))
7711 (progn
7712 (pop-to-buffer folder)
7713 (org-mhe-get-message-folder-from-index)
7714 )
7715 ))
7716 (org-mhe-get-message-folder-from-index)
7717 )
7718 folder
7719 )
7720 )))
7721
7722 (defun org-mhe-get-message-folder-from-index ()
7723 "Returns the name of the message folder in a index folder buffer."
7724 (save-excursion
7725 (mh-index-previous-folder)
7726 (re-search-forward "^\\(+.*\\)$" nil t)
7727 (message (match-string 1))))
7728
7729 (defun org-mhe-get-message-folder ()
7730 "Return the name of the current message folder. Be careful if you
7731 use sequences."
7732 (save-excursion
7733 (if (equal major-mode 'mh-folder-mode)
7734 mh-current-folder
7735 ;; Refer to the show buffer
7736 mh-show-folder-buffer)))
7737
7738 (defun org-mhe-get-message-num ()
7739 "Return the number of the current message. Be careful if you
7740 use sequences."
7741 (save-excursion
7742 (if (equal major-mode 'mh-folder-mode)
7743 (mh-get-msg-num nil)
7744 ;; Refer to the show buffer
7745 (mh-show-buffer-message-number))))
7746
7747 (defun org-mhe-get-header (header)
7748 "Return a header of the message in folder mode. This will create a
7749 show buffer for the corresponding message. If you have a more clever
7750 idea..."
7751 (let* ((folder (org-mhe-get-message-folder))
7752 (num (org-mhe-get-message-num))
7753 (buffer (get-buffer-create (concat "show-" folder)))
7754 (header-field))
7755 (with-current-buffer buffer
7756 (mh-display-msg num folder)
7757 (if (equal major-mode 'mh-folder-mode)
7758 (mh-header-display)
7759 (mh-show-header-display))
7760 (set-buffer buffer)
7761 (setq header-field (mh-get-header-field header))
7762 (if (equal major-mode 'mh-folder-mode)
7763 (mh-show)
7764 (mh-show-show))
7765 header-field)))
7766
7767 (defun org-follow-mhe-link (folder article)
7768 "Follow an MHE link to FOLDER and ARTICLE.
7769 If ARTICLE is nil FOLDER is shown. If the configuration variable
7770 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
7771 ARTICLE is searched in all folders. Indexed searches (swish++,
7772 namazu, and others supported by MH-E) will always search in all
7773 folders."
7774 (require 'mh-e)
7775 (require 'mh-search)
7776 (require 'mh-utils)
7777 (mh-find-path)
7778 (if (not article)
7779 (mh-visit-folder (mh-normalize-folder-name folder))
7780 (setq article (org-add-angle-brackets article))
7781 (mh-search-choose)
7782 (if (equal mh-searcher 'pick)
7783 (progn
7784 (mh-search folder (list "--message-id" article))
7785 (when (and org-mhe-search-all-folders
7786 (not (org-mhe-get-message-real-folder)))
7787 (kill-this-buffer)
7788 (mh-search "+" (list "--message-id" article))))
7789 (mh-search "+" article))
7790 (if (org-mhe-get-message-real-folder)
7791 (mh-show-msg 1)
7792 (kill-this-buffer)
7793 (error "Message not found"))))
7794
7795 (defun org-upgrade-old-links (&optional query-description)
7796 "Transfer old <...> style links to new [[...]] style links.
7797 With arg query-description, ask at each match for a description text to use
7798 for this link."
7799 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
7800 (save-excursion
7801 (goto-char (point-min))
7802 (let ((re (concat "\\([^[]\\)<\\("
7803 "\\(" (mapconcat 'identity org-link-types "\\|")
7804 "\\):"
7805 "[^" org-non-link-chars "]+\\)>"))
7806 l1 l2 (cnt 0))
7807 (while (re-search-forward re nil t)
7808 (setq cnt (1+ cnt)
7809 l1 (org-match-string-no-properties 2)
7810 l2 (save-match-data (org-link-escape l1)))
7811 (when query-description (setq l1 (read-string "Desc: " l1)))
7812 (if (equal l1 l2)
7813 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
7814 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
7815 (message "%d matches have beed treated" cnt))))
7816
7817 (defun org-open-file (path &optional in-emacs line search)
7818 "Open the file at PATH.
7819 First, this expands any special file name abbreviations. Then the
7820 configuration variable `org-file-apps' is checked if it contains an
7821 entry for this file type, and if yes, the corresponding command is launched.
7822 If no application is found, Emacs simply visits the file.
7823 With optional argument IN-EMACS, Emacs will visit the file.
7824 Optional LINE specifies a line to go to, optional SEARCH a string to
7825 search for. If LINE or SEARCH is given, the file will always be
7826 opened in Emacs.
7827 If the file does not exist, an error is thrown."
7828 (setq in-emacs (or in-emacs line search))
7829 (let* ((file (if (equal path "")
7830 buffer-file-name
7831 (convert-standard-filename (org-expand-file-name path))))
7832 (dirp (file-directory-p file))
7833 (dfile (downcase file))
7834 (old-buffer (current-buffer))
7835 (old-pos (point))
7836 (old-mode major-mode)
7837 ext cmd apps)
7838 (if (and (not (file-exists-p file))
7839 (not org-open-non-existing-files))
7840 (error "No such file: %s" file))
7841 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7842 (setq ext (match-string 1 dfile))
7843 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7844 (setq ext (match-string 1 dfile))))
7845 (setq apps (append org-file-apps (org-default-apps)))
7846 (if in-emacs
7847 (setq cmd 'emacs)
7848 (setq cmd (or (and dirp (cdr (assoc 'directory apps)))
7849 (cdr (assoc ext apps))
7850 (cdr (assoc t apps)))))
7851 (when (eq cmd 'mailcap)
7852 (require 'mailcap)
7853 (mailcap-parse-mailcaps)
7854 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7855 (command (mailcap-mime-info mime-type)))
7856 (if (stringp command)
7857 (setq cmd command)
7858 (setq cmd 'emacs))))
7859 (cond
7860 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7861 ;; Normalize use of quote, this can vary.
7862 (if (string-match "['\"]%s['\"]" cmd)
7863 (setq cmd (replace-match "'%s'" t t cmd)))
7864 (setq cmd (format cmd file))
7865 (save-window-excursion
7866 (shell-command (concat cmd " &"))))
7867 ((or (stringp cmd)
7868 (eq cmd 'emacs))
7869 (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
7870 (funcall (cdr (assq 'file org-link-frame-setup)) file))
7871 (if line (goto-line line)
7872 (if search (org-link-search search))))
7873 ((consp cmd)
7874 (eval cmd))
7875 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7876 (and (eq major-mode 'org-mode) (eq old-mode 'org-mode)
7877 (or (not (equal old-buffer (current-buffer)))
7878 (not (equal old-pos (point))))
7879 (org-mark-ring-push old-pos old-buffer))))
7880
7881 (defun org-default-apps ()
7882 "Return the default applications for this operating system."
7883 (cond
7884 ((eq system-type 'darwin)
7885 org-file-apps-defaults-macosx)
7886 ((eq system-type 'windows-nt)
7887 org-file-apps-defaults-windowsnt)
7888 (t org-file-apps-defaults-gnu)))
7889
7890 (defun org-expand-file-name (path)
7891 "Replace special path abbreviations and expand the file name."
7892 (expand-file-name path))
7893
7894
7895 (defvar org-insert-link-history nil
7896 "Minibuffer history for links inserted with `org-insert-link'.")
7897
7898 (defvar org-stored-links nil
7899 "Contains the links stored with `org-store-link'.")
7900
7901 ;;;###autoload
7902 (defun org-store-link (arg)
7903 "\\<org-mode-map>Store an org-link to the current location.
7904 This link can later be inserted into an org-buffer with
7905 \\[org-insert-link].
7906 For some link types, a prefix arg is interpreted:
7907 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
7908 For file links, arg negates `org-context-in-file-links'."
7909 (interactive "P")
7910 (let (link cpltxt desc txt (pos (point)))
7911 (cond
7912
7913 ((eq major-mode 'bbdb-mode)
7914 (setq cpltxt (concat
7915 "bbdb:"
7916 (or (bbdb-record-name (bbdb-current-record))
7917 (bbdb-record-company (bbdb-current-record))))
7918 link (org-make-link cpltxt)))
7919
7920 ((eq major-mode 'calendar-mode)
7921 (let ((cd (calendar-cursor-to-date)))
7922 (setq link
7923 (format-time-string
7924 (car org-time-stamp-formats)
7925 (apply 'encode-time
7926 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7927 nil nil nil))))))
7928
7929 ((or (eq major-mode 'vm-summary-mode)
7930 (eq major-mode 'vm-presentation-mode))
7931 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
7932 (vm-follow-summary-cursor)
7933 (save-excursion
7934 (vm-select-folder-buffer)
7935 (let* ((message (car vm-message-pointer))
7936 (folder buffer-file-name)
7937 (subject (vm-su-subject message))
7938 (author (vm-su-full-name message))
7939 (message-id (vm-su-message-id message)))
7940 (setq message-id (org-remove-angle-brackets message-id))
7941 (setq folder (abbreviate-file-name folder))
7942 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
7943 folder)
7944 (setq folder (replace-match "" t t folder)))
7945 (setq cpltxt (concat author " on: " subject))
7946 (setq link (org-make-link "vm:" folder "#" message-id)))))
7947
7948 ((eq major-mode 'wl-summary-mode)
7949 (let* ((msgnum (wl-summary-message-number))
7950 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
7951 msgnum 'message-id))
7952 (wl-message-entity (elmo-msgdb-overview-get-entity
7953 msgnum (wl-summary-buffer-msgdb)))
7954 (author (wl-summary-line-from)) ; FIXME: correct?
7955 (subject "???")) ; FIXME:
7956 (setq message-id (org-remove-angle-brackets message-id))
7957 (setq cpltxt (concat author " on: " subject))
7958 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
7959 "#" message-id))))
7960
7961 ((or (equal major-mode 'mh-folder-mode)
7962 (equal major-mode 'mh-show-mode))
7963 (let ((from-header (org-mhe-get-header "From:"))
7964 (to-header (org-mhe-get-header "To:"))
7965 (subject (org-mhe-get-header "Subject:")))
7966 (setq cpltxt (concat from-header " on: " subject))
7967 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
7968 (org-remove-angle-brackets
7969 (org-mhe-get-header "Message-Id:"))))))
7970
7971 ((eq major-mode 'rmail-mode)
7972 (save-excursion
7973 (save-restriction
7974 (rmail-narrow-to-non-pruned-header)
7975 (let ((folder buffer-file-name)
7976 (message-id (mail-fetch-field "message-id"))
7977 (author (mail-fetch-field "from"))
7978 (subject (mail-fetch-field "subject")))
7979 (setq message-id (org-remove-angle-brackets message-id))
7980 (setq cpltxt (concat author " on: " subject))
7981 (setq link (org-make-link "rmail:" folder "#" message-id))))))
7982
7983 ((eq major-mode 'gnus-group-mode)
7984 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
7985 (gnus-group-group-name)) ; version
7986 ((fboundp 'gnus-group-name)
7987 (gnus-group-name))
7988 (t "???"))))
7989 (setq cpltxt (concat
7990 (if (org-xor arg org-usenet-links-prefer-google)
7991 "http://groups.google.com/groups?group="
7992 "gnus:")
7993 group)
7994 link (org-make-link cpltxt))))
7995
7996 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
7997 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
7998 (gnus-summary-beginning-of-article)
7999 (let* ((group (car gnus-article-current))
8000 (article (cdr gnus-article-current))
8001 (header (gnus-summary-article-header article))
8002 (author (mail-header-from header))
8003 (message-id (mail-header-id header))
8004 (date (mail-header-date header))
8005 (subject (gnus-summary-subject-string)))
8006 (setq cpltxt (concat author " on: " subject))
8007 (if (org-xor arg org-usenet-links-prefer-google)
8008 (setq link
8009 (concat
8010 cpltxt "\n "
8011 (format "http://groups.google.com/groups?as_umsgid=%s"
8012 (org-fixup-message-id-for-http message-id))))
8013 (setq link (org-make-link "gnus:" group
8014 "#" (number-to-string article))))))
8015
8016 ((eq major-mode 'w3-mode)
8017 (setq cpltxt (url-view-url t)
8018 link (org-make-link cpltxt)))
8019 ((eq major-mode 'w3m-mode)
8020 (setq cpltxt w3m-current-url
8021 link (org-make-link cpltxt)))
8022
8023 ((eq major-mode 'org-mode)
8024 ;; Just link to current headline
8025 (setq cpltxt (concat "file:"
8026 (abbreviate-file-name buffer-file-name)))
8027 ;; Add a context search string
8028 (when (org-xor org-context-in-file-links arg)
8029 ;; Check if we are on a target
8030 (if (save-excursion
8031 (skip-chars-forward "^>\n\r")
8032 (and (re-search-backward "<<" nil t)
8033 (looking-at "<<\\(.*?\\)>>")
8034 (<= (match-beginning 0) pos)
8035 (>= (match-end 0) pos)))
8036 (setq cpltxt (concat cpltxt "::" (match-string 1)))
8037 (setq txt (cond
8038 ((org-on-heading-p) nil)
8039 ((org-region-active-p)
8040 (buffer-substring (region-beginning) (region-end)))
8041 (t (buffer-substring (point-at-bol) (point-at-eol)))))
8042 (setq cpltxt
8043 (concat cpltxt "::"
8044 (if org-file-link-context-use-camel-case
8045 (org-make-org-heading-camel txt)
8046 (org-make-org-heading-search-string txt)))
8047 desc "NONE")))
8048 (if (string-match "::\\'" cpltxt)
8049 (setq cpltxt (substring cpltxt 0 -2)))
8050 (setq link (org-make-link cpltxt)))
8051
8052 (buffer-file-name
8053 ;; Just link to this file here.
8054 (setq cpltxt (concat "file:"
8055 (abbreviate-file-name buffer-file-name)))
8056 ;; Add a context string
8057 (when (org-xor org-context-in-file-links arg)
8058 (setq txt (if (org-region-active-p)
8059 (buffer-substring (region-beginning) (region-end))
8060 (buffer-substring (point-at-bol) (point-at-eol))))
8061 (setq cpltxt
8062 (concat cpltxt "::"
8063 (if org-file-link-context-use-camel-case
8064 (org-make-org-heading-camel txt)
8065 (org-make-org-heading-search-string txt)))
8066 desc "NONE"))
8067 (setq link (org-make-link cpltxt)))
8068
8069 ((interactive-p)
8070 (error "Cannot link to a buffer which is not visiting a file"))
8071
8072 (t (setq link nil)))
8073
8074 (if (consp link) (setq cpltxt (car link) link (cdr link)))
8075 (setq link (or link cpltxt)
8076 desc (or desc cpltxt))
8077 (if (equal desc "NONE") (setq desc nil))
8078
8079 (if (and (interactive-p) link)
8080 (progn
8081 (setq org-stored-links
8082 (cons (list cpltxt link desc) org-stored-links))
8083 (message "Stored: %s" (or cpltxt link)))
8084 (org-make-link-string link desc))))
8085
8086 (defun org-make-org-heading-search-string (&optional string heading)
8087 "Make search string for STRING or current headline."
8088 (interactive)
8089 (let ((s (or string (org-get-heading))))
8090 (unless (and string (not heading))
8091 ;; We are using a headline, clean up garbage in there.
8092 (if (string-match org-todo-regexp s)
8093 (setq s (replace-match "" t t s)))
8094 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8095 (setq s (replace-match "" t t s)))
8096 (setq s (org-trim s))
8097 (if (string-match (concat "^\\(" org-quote-string "\\|"
8098 org-comment-string "\\)") s)
8099 (setq s (replace-match "" t t s)))
8100 (while (string-match org-ts-regexp s)
8101 (setq s (replace-match "" t t s))))
8102 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8103 (setq s (replace-match " " t t s)))
8104 (or string (setq s (concat "*" s))) ; Add * for headlines
8105 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8106
8107 (defun org-make-org-heading-camel (&optional string heading)
8108 "Make a CamelCase string for STRING or the current headline."
8109 (interactive)
8110 (let ((s (or string (org-get-heading))))
8111 (unless (and string (not heading))
8112 ;; We are using a headline, clean up garbage in there.
8113 (if (string-match org-todo-regexp s)
8114 (setq s (replace-match "" t t s)))
8115 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
8116 (setq s (replace-match "" t t s)))
8117 (setq s (org-trim s))
8118 (if (string-match (concat "^\\(" org-quote-string "\\|"
8119 org-comment-string "\\)") s)
8120 (setq s (replace-match "" t t s)))
8121 (while (string-match org-ts-regexp s)
8122 (setq s (replace-match "" t t s))))
8123 (while (string-match "[^a-zA-Z_ \t]+" s)
8124 (setq s (replace-match " " t t s)))
8125 (or string (setq s (concat "*" s))) ; Add * for headlines
8126 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
8127
8128 (defun org-make-link (&rest strings)
8129 "Concatenate STRINGS, format resulting string with `org-link-format'."
8130 (format org-link-format (apply 'concat strings)))
8131
8132 (defun org-make-link-string (link &optional description)
8133 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8134 (if (eq org-link-style 'plain)
8135 (if (equal description link)
8136 link
8137 (concat description "\n" link))
8138 (when (stringp description)
8139 ;; Remove brackets from the description, they are fatal.
8140 (while (string-match "\\[\\|\\]" description)
8141 (setq description (replace-match "" t t description))))
8142 (when (equal (org-link-escape link) description)
8143 ;; No description needed, it is identical
8144 (setq description nil))
8145 (when (and (not description)
8146 (not (equal link (org-link-escape link))))
8147 (setq description link))
8148 (concat "[[" (org-link-escape link) "]"
8149 (if description (concat "[" description "]") "")
8150 "]")))
8151
8152 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
8153 "Association list of escapes for some characters problematic in links.")
8154
8155 (defun org-link-escape (text)
8156 "Escape charaters in TEXT that are problematic for links."
8157 (when text
8158 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
8159 org-link-escape-chars "\\|")))
8160 (while (string-match re text)
8161 (setq text
8162 (replace-match
8163 (cdr (assoc (match-string 0 text) org-link-escape-chars))
8164 t t text)))
8165 text)))
8166
8167 (defun org-link-unescape (text)
8168 "Reverse the action of `org-link-escape'."
8169 (when text
8170 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
8171 org-link-escape-chars "\\|")))
8172 (while (string-match re text)
8173 (setq text
8174 (replace-match
8175 (car (rassoc (match-string 0 text) org-link-escape-chars))
8176 t t text)))
8177 text)))
8178
8179 (defun org-xor (a b)
8180 "Exclusive or."
8181 (if a (not b) b))
8182
8183 (defun org-get-header (header)
8184 "Find a header field in the current buffer."
8185 (save-excursion
8186 (goto-char (point-min))
8187 (let ((case-fold-search t) s)
8188 (cond
8189 ((eq header 'from)
8190 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
8191 (setq s (match-string 1)))
8192 (while (string-match "\"" s)
8193 (setq s (replace-match "" t t s)))
8194 (if (string-match "[<(].*" s)
8195 (setq s (replace-match "" t t s))))
8196 ((eq header 'message-id)
8197 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
8198 (setq s (match-string 1))))
8199 ((eq header 'subject)
8200 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
8201 (setq s (match-string 1)))))
8202 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
8203 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
8204 s)))
8205
8206
8207 (defun org-fixup-message-id-for-http (s)
8208 "Replace special characters in a message id, so it can be used in an http query."
8209 (while (string-match "<" s)
8210 (setq s (replace-match "%3C" t t s)))
8211 (while (string-match ">" s)
8212 (setq s (replace-match "%3E" t t s)))
8213 (while (string-match "@" s)
8214 (setq s (replace-match "%40" t t s)))
8215 s)
8216
8217 (defun org-insert-link (&optional complete-file)
8218 "Insert a link. At the prompt, enter the link.
8219
8220 Completion can be used to select a link previously stored with
8221 `org-store-link'. When the empty string is entered (i.e. if you just
8222 press RET at the prompt), the link defaults to the most recently
8223 stored link. As SPC triggers completion in the minibuffer, you need to
8224 use M-SPC or C-q SPC to force the insertion of a space character.
8225
8226 You will also be prompted for a description, and if one is given, it will
8227 be displayed in the buffer instead of the link.
8228
8229 If there is already a link at point, this command will allow you to edit link
8230 and description parts.
8231
8232 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
8233 selected using completion. The path to the file will be relative to
8234 the current directory if the file is in the current directory or a
8235 subdirectory. Otherwise, the link will be the absolute path as
8236 completed in the minibuffer (i.e. normally ~/path/to/file).
8237
8238 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
8239 is in the current directory or below."
8240 (interactive "P")
8241 (let (link desc entry remove file (pos (point)))
8242 (cond
8243 ((save-excursion
8244 (skip-chars-forward "^]\n\r")
8245 (and (re-search-backward "\\[\\[" nil t)
8246 (looking-at org-bracket-link-regexp)
8247 (<= (match-beginning 0) pos)
8248 (>= (match-end 0) pos)))
8249 ;; We do have a link at point, and we are going to edit it.
8250 (setq remove (list (match-beginning 0) (match-end 0)))
8251 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8252 (setq link (read-string "Link: "
8253 (org-link-unescape
8254 (org-match-string-no-properties 1)))))
8255 (complete-file
8256 ;; Completing read for file names.
8257 (setq file (read-file-name "File: "))
8258 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8259 (pwd1 (file-name-as-directory (abbreviate-file-name
8260 (expand-file-name ".")))))
8261 (cond
8262 ((equal complete-file '(16))
8263 (setq link (org-make-link
8264 "file:"
8265 (abbreviate-file-name (expand-file-name file)))))
8266 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8267 (setq link (org-make-link "file:" (match-string 1 file))))
8268 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8269 (expand-file-name file))
8270 (setq link (org-make-link
8271 "file:" (match-string 1 (expand-file-name file)))))
8272 (t (setq link (org-make-link "file:" file))))))
8273 (t
8274 ;; Read link, with completion for stored links.
8275 (setq link (org-completing-read
8276 "Link: " org-stored-links nil nil nil
8277 org-insert-link-history
8278 (or (car (car org-stored-links)))))
8279 (setq entry (assoc link org-stored-links))
8280 (if (not org-keep-stored-link-after-insertion)
8281 (setq org-stored-links (delq (assoc link org-stored-links)
8282 org-stored-links)))
8283 (setq link (if entry (nth 1 entry) link)
8284 desc (or desc (nth 2 entry)))))
8285
8286 (if (string-match org-plain-link-re link)
8287 ;; URL-like link, normalize the use of angular brackets.
8288 (setq link (org-make-link (org-remove-angle-brackets link))))
8289
8290 ;; Check if we are linking to the current file. If yes, simplify the link.
8291 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
8292 (let* ((path (match-string 1 link))
8293 (case-fold-search nil)
8294 (search (match-string 2 link)))
8295 (when (save-match-data
8296 (equal (file-truename buffer-file-name)
8297 (file-truename path)))
8298 ;; We are linking to this same file, with a search option
8299 (setq link search))))
8300 (setq desc (read-string "Description: " desc))
8301 (unless (string-match "\\S-" desc) (setq desc nil))
8302 (if remove (apply 'delete-region remove))
8303 (insert (org-make-link-string link desc))))
8304
8305 (defun org-completing-read (&rest args)
8306 (let ((minibuffer-local-completion-map
8307 (copy-keymap minibuffer-local-completion-map)))
8308 (define-key minibuffer-local-completion-map " " 'self-insert-command)
8309 (apply 'completing-read args)))
8310
8311 ;;; Hooks for remember.el
8312
8313 (defvar org-finish-function nil)
8314
8315 ;;;###autoload
8316 (defun org-remember-annotation ()
8317 "Return a link to the current location as an annotation for remember.el.
8318 If you are using Org-mode files as target for data storage with
8319 remember.el, then the annotations should include a link compatible with the
8320 conventions in Org-mode. This function returns such a link."
8321 (org-store-link nil))
8322
8323 (defconst org-remember-help
8324 "Select a destination location for the note.
8325 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
8326 RET at beg-of-buf -> Append to file as level 2 headline
8327 RET on headline -> Store as sublevel entry to current headline
8328 <left>/<right> -> before/after current headline, same headings level")
8329
8330 ;;;###autoload
8331 (defun org-remember-apply-template ()
8332 "Initialize *remember* buffer with template, invode `org-mode'.
8333 This function should be placed into `remember-mode-hook' and in fact requires
8334 to be run from that hook to fucntion properly."
8335 (when org-remember-templates
8336 (let* ((entry (if (= (length org-remember-templates) 1)
8337 (cdar org-remember-templates)
8338 (message "Select template: %s"
8339 (mapconcat
8340 (lambda (x) (char-to-string (car x)))
8341 org-remember-templates " "))
8342 (cdr (assoc (read-char-exclusive) org-remember-templates))))
8343 (tpl (if (consp (cdr entry)) (cadr entry) (cdr entry)))
8344 (file (if (consp (cdr entry)) (nth 2 entry)))
8345 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
8346 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
8347 (v-u (concat "[" (substring v-t 1 -1) "]"))
8348 (v-U (concat "[" (substring v-T 1 -1) "]"))
8349 (v-a annotation) ; defined in `remember-mode'
8350 (v-i initial) ; defined in `remember-mode'
8351 (v-n user-full-name)
8352 )
8353 (unless tpl (setq tpl "") (message "No template") (ding))
8354 (insert tpl) (goto-char (point-min))
8355 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
8356 (when (and initial (equal (match-string 0) "%i"))
8357 (save-match-data
8358 (let* ((lead (buffer-substring
8359 (point-at-bol) (match-beginning 0))))
8360 (setq v-i (mapconcat 'identity
8361 (org-split-string initial "\n")
8362 (concat "\n" lead))))))
8363 (replace-match
8364 (or (eval (intern (concat "v-" (match-string 1)))) "")
8365 t t))
8366 (let ((org-startup-folded nil)
8367 (org-startup-with-deadline-check nil))
8368 (org-mode))
8369 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
8370 (set (make-local-variable 'org-default-notes-file) file))
8371 (goto-char (point-min))
8372 (if (re-search-forward "%\\?" nil t) (replace-match ""))
8373 (set (make-local-variable 'org-finish-function) 'remember-buffer))))
8374
8375 ;;;###autoload
8376 (defun org-remember-handler ()
8377 "Store stuff from remember.el into an org file.
8378 First prompts for an org file. If the user just presses return, the value
8379 of `org-default-notes-file' is used.
8380 Then the command offers the headings tree of the selected file in order to
8381 file the text at a specific location.
8382 You can either immediately press RET to get the note appended to the
8383 file, or you can use vertical cursor motion and visibility cycling (TAB) to
8384 find a better place. Then press RET or <left> or <right> in insert the note.
8385
8386 Key Cursor position Note gets inserted
8387 -----------------------------------------------------------------------------
8388 RET buffer-start as level 2 heading at end of file
8389 RET on headline as sublevel of the heading at cursor
8390 RET no heading at cursor position, level taken from context.
8391 Or use prefix arg to specify level manually.
8392 <left> on headline as same level, before current heading
8393 <right> on headline as same level, after current heading
8394
8395 So the fastest way to store the note is to press RET RET to append it to
8396 the default file. This way your current train of thought is not
8397 interrupted, in accordance with the principles of remember.el. But with
8398 little extra effort, you can push it directly to the correct location.
8399
8400 Before being stored away, the function ensures that the text has a
8401 headline, i.e. a first line that starts with a \"*\". If not, a headline
8402 is constructed from the current date and some additional data.
8403
8404 If the variable `org-adapt-indentation' is non-nil, the entire text is
8405 also indented so that it starts in the same column as the headline
8406 \(i.e. after the stars).
8407
8408 See also the variable `org-reverse-note-order'."
8409 (catch 'quit
8410 (let* ((txt (buffer-substring (point-min) (point-max)))
8411 (fastp current-prefix-arg)
8412 (file (if fastp org-default-notes-file (org-get-org-file)))
8413 (visiting (find-buffer-visiting file))
8414 (org-startup-with-deadline-check nil)
8415 (org-startup-folded nil)
8416 (org-startup-align-all-tables nil)
8417 spos level indent reversed)
8418 ;; Modify text so that it becomes a nice subtree which can be inserted
8419 ;; into an org tree.
8420 (let* ((lines (split-string txt "\n"))
8421 first)
8422 ;; remove empty lines at the beginning
8423 (while (and lines (string-match "^[ \t]*\n" (car lines)))
8424 (setq lines (cdr lines)))
8425 (setq first (car lines) lines (cdr lines))
8426 (if (string-match "^\\*+" first)
8427 ;; Is already a headline
8428 (setq indent nil)
8429 ;; We need to add a headline: Use time and first buffer line
8430 (setq lines (cons first lines)
8431 first (concat "* " (current-time-string)
8432 " (" (remember-buffer-desc) ")")
8433 indent " "))
8434 (if (and org-adapt-indentation indent)
8435 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
8436 (setq txt (concat first "\n"
8437 (mapconcat 'identity lines "\n"))))
8438 ;; Find the file
8439 (if (not visiting)
8440 (find-file-noselect file))
8441 (with-current-buffer (get-file-buffer file)
8442 (setq reversed (org-notes-order-reversed-p))
8443 (save-excursion
8444 (save-restriction
8445 (widen)
8446 ;; Ask the User for a location
8447 (setq spos (if fastp 1 (org-get-location
8448 (current-buffer)
8449 org-remember-help)))
8450 (if (not spos) (throw 'quit nil)) ; return nil to show we did
8451 ; not handle this note
8452 (goto-char spos)
8453 (cond ((bobp)
8454 ;; Put it at the start or end, as level 2
8455 (save-restriction
8456 (widen)
8457 (goto-char (if reversed (point-min) (point-max)))
8458 (if (not (bolp)) (newline))
8459 (org-paste-subtree 2 txt)))
8460 ((and (org-on-heading-p nil) (not current-prefix-arg))
8461 ;; Put it below this entry, at the beg/end of the subtree
8462 (org-back-to-heading)
8463 (setq level (funcall outline-level))
8464 (if reversed
8465 (outline-end-of-heading)
8466 (outline-end-of-subtree))
8467 (if (not (bolp)) (newline))
8468 (beginning-of-line 1)
8469 (org-paste-subtree (1+ level) txt))
8470 (t
8471 ;; Put it right there, with automatic level determined by
8472 ;; org-paste-subtree or from prefix arg
8473 (org-paste-subtree current-prefix-arg txt)))
8474 (when remember-save-after-remembering
8475 (save-buffer)
8476 (if (not visiting) (kill-buffer (current-buffer)))))))))
8477 t) ;; return t to indicate that we took care of this note.
8478
8479 (defun org-get-org-file ()
8480 "Read a filename, with default directory `org-directory'."
8481 (let ((default (or org-default-notes-file remember-data-file)))
8482 (read-file-name (format "File name [%s]: " default)
8483 (file-name-as-directory org-directory)
8484 default)))
8485
8486 (defun org-notes-order-reversed-p ()
8487 "Check if the current file should receive notes in reversed order."
8488 (cond
8489 ((not org-reverse-note-order) nil)
8490 ((eq t org-reverse-note-order) t)
8491 ((not (listp org-reverse-note-order)) nil)
8492 (t (catch 'exit
8493 (let ((all org-reverse-note-order)
8494 entry)
8495 (while (setq entry (pop all))
8496 (if (string-match (car entry) buffer-file-name)
8497 (throw 'exit (cdr entry))))
8498 nil)))))
8499
8500 ;;; Tables
8501
8502 ;; Watch out: Here we are talking about two different kind of tables.
8503 ;; Most of the code is for the tables created with the Org-mode table editor.
8504 ;; Sometimes, we talk about tables created and edited with the table.el
8505 ;; Emacs package. We call the former org-type tables, and the latter
8506 ;; table.el-type tables.
8507
8508
8509 (defun org-before-change-function (beg end)
8510 "Every change indicates that a table might need an update."
8511 (setq org-table-may-need-update t))
8512
8513 (defconst org-table-line-regexp "^[ \t]*|"
8514 "Detects an org-type table line.")
8515 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
8516 "Detects an org-type table line.")
8517 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
8518 "Detects a table line marked for automatic recalculation.")
8519 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
8520 "Detects a table line marked for automatic recalculation.")
8521 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
8522 "Detects a table line marked for automatic recalculation.")
8523 (defconst org-table-hline-regexp "^[ \t]*|-"
8524 "Detects an org-type table hline.")
8525 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
8526 "Detects a table-type table hline.")
8527 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
8528 "Detects an org-type or table-type table.")
8529 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
8530 "Searching from within a table (any type) this finds the first line
8531 outside the table.")
8532 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
8533 "Searching from within a table (any type) this finds the first line
8534 outside the table.")
8535
8536 (defun org-table-create-with-table.el ()
8537 "Use the table.el package to insert a new table.
8538 If there is already a table at point, convert between Org-mode tables
8539 and table.el tables."
8540 (interactive)
8541 (require 'table)
8542 (cond
8543 ((org-at-table.el-p)
8544 (if (y-or-n-p "Convert table to Org-mode table? ")
8545 (org-table-convert)))
8546 ((org-at-table-p)
8547 (if (y-or-n-p "Convert table to table.el table? ")
8548 (org-table-convert)))
8549 (t (call-interactively 'table-insert))))
8550
8551 (defun org-table-create-or-convert-from-region (arg)
8552 "Convert region to table, or create an empty table.
8553 If there is an active region, convert it to a table. If there is no such
8554 region, create an empty table."
8555 (interactive "P")
8556 (if (org-region-active-p)
8557 (org-table-convert-region (region-beginning) (region-end) arg)
8558 (org-table-create arg)))
8559
8560 (defun org-table-create (&optional size)
8561 "Query for a size and insert a table skeleton.
8562 SIZE is a string Columns x Rows like for example \"3x2\"."
8563 (interactive "P")
8564 (unless size
8565 (setq size (read-string
8566 (concat "Table size Columns x Rows [e.g. "
8567 org-table-default-size "]: ")
8568 "" nil org-table-default-size)))
8569
8570 (let* ((pos (point))
8571 (indent (make-string (current-column) ?\ ))
8572 (split (org-split-string size " *x *"))
8573 (rows (string-to-number (nth 1 split)))
8574 (columns (string-to-number (car split)))
8575 (line (concat (apply 'concat indent "|" (make-list columns " |"))
8576 "\n")))
8577 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
8578 (point-at-bol) (point)))
8579 (beginning-of-line 1)
8580 (newline))
8581 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
8582 (dotimes (i rows) (insert line))
8583 (goto-char pos)
8584 (if (> rows 1)
8585 ;; Insert a hline after the first row.
8586 (progn
8587 (end-of-line 1)
8588 (insert "\n|-")
8589 (goto-char pos)))
8590 (org-table-align)))
8591
8592 (defun org-table-convert-region (beg0 end0 &optional nspace)
8593 "Convert region to a table.
8594 The region goes from BEG0 to END0, but these borders will be moved
8595 slightly, to make sure a beginning of line in the first line is included.
8596 When NSPACE is non-nil, it indicates the minimum number of spaces that
8597 separate columns (default: just one space)."
8598 (interactive "rP")
8599 (let* ((beg (min beg0 end0))
8600 (end (max beg0 end0))
8601 (tabsep t)
8602 re)
8603 (goto-char beg)
8604 (beginning-of-line 1)
8605 (setq beg (move-marker (make-marker) (point)))
8606 (goto-char end)
8607 (if (bolp) (backward-char 1) (end-of-line 1))
8608 (setq end (move-marker (make-marker) (point)))
8609 ;; Lets see if this is tab-separated material. If every nonempty line
8610 ;; contains a tab, we will assume that it is tab-separated material
8611 (if nspace
8612 (setq tabsep nil)
8613 (goto-char beg)
8614 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
8615 (if nspace (setq tabsep nil))
8616 (if tabsep
8617 (setq re "^\\|\t")
8618 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
8619 (max 1 (prefix-numeric-value nspace)))))
8620 (goto-char beg)
8621 (while (re-search-forward re end t)
8622 (replace-match "|" t t))
8623 (goto-char beg)
8624 (insert " ")
8625 (org-table-align)))
8626
8627 (defun org-table-import (file arg)
8628 "Import FILE as a table.
8629 The file is assumed to be tab-separated. Such files can be produced by most
8630 spreadsheet and database applications. If no tabs (at least one per line)
8631 are found, lines will be split on whitespace into fields."
8632 (interactive "f\nP")
8633 (or (bolp) (newline))
8634 (let ((beg (point))
8635 (pm (point-max)))
8636 (insert-file-contents file)
8637 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
8638
8639 (defun org-table-export ()
8640 "Export table as a tab-separated file.
8641 Such a file can be imported into a spreadsheet program like Excel."
8642 (interactive)
8643 (let* ((beg (org-table-begin))
8644 (end (org-table-end))
8645 (table (buffer-substring beg end))
8646 (file (read-file-name "Export table to: "))
8647 buf)
8648 (unless (or (not (file-exists-p file))
8649 (y-or-n-p (format "Overwrite file %s? " file)))
8650 (error "Abort"))
8651 (with-current-buffer (find-file-noselect file)
8652 (setq buf (current-buffer))
8653 (erase-buffer)
8654 (fundamental-mode)
8655 (insert table)
8656 (goto-char (point-min))
8657 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
8658 (replace-match "" t t)
8659 (end-of-line 1))
8660 (goto-char (point-min))
8661 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
8662 (replace-match "" t t)
8663 (goto-char (min (1+ (point)) (point-max))))
8664 (goto-char (point-min))
8665 (while (re-search-forward "^-[-+]*$" nil t)
8666 (replace-match "")
8667 (if (looking-at "\n")
8668 (delete-char 1)))
8669 (goto-char (point-min))
8670 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
8671 (replace-match "\t" t t))
8672 (save-buffer))
8673 (kill-buffer buf)))
8674
8675 (defvar org-table-aligned-begin-marker (make-marker)
8676 "Marker at the beginning of the table last aligned.
8677 Used to check if cursor still is in that table, to minimize realignment.")
8678 (defvar org-table-aligned-end-marker (make-marker)
8679 "Marker at the end of the table last aligned.
8680 Used to check if cursor still is in that table, to minimize realignment.")
8681 (defvar org-table-last-alignment nil
8682 "List of flags for flushright alignment, from the last re-alignment.
8683 This is being used to correctly align a single field after TAB or RET.")
8684 (defvar org-table-last-column-widths nil
8685 "List of max width of fields in each column.
8686 This is being used to correctly align a single field after TAB or RET.")
8687
8688 (defvar org-last-recalc-line nil)
8689 (defconst org-narrow-column-arrow "=>"
8690 "Used as display property in narrowed table columns.")
8691
8692 (defun org-table-align ()
8693 "Align the table at point by aligning all vertical bars."
8694 (interactive)
8695 (let* (
8696 ;; Limits of table
8697 (beg (org-table-begin))
8698 (end (org-table-end))
8699 ;; Current cursor position
8700 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
8701 (colpos (org-table-current-column))
8702 (winstart (window-start))
8703 text lines (new "") lengths l typenums ty fields maxfields i
8704 column
8705 (indent "") cnt frac
8706 rfmt hfmt
8707 (spaces '(1 . 1))
8708 (sp1 (car spaces))
8709 (sp2 (cdr spaces))
8710 (rfmt1 (concat
8711 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
8712 (hfmt1 (concat
8713 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
8714 emptystrings xx links narrow fmax fmin f1 len c e)
8715 (untabify beg end)
8716 (remove-text-properties beg end '(org-cwidth t display t))
8717 ;; Check if we have links
8718 (goto-char beg)
8719 (setq links (re-search-forward org-bracket-link-regexp end t))
8720 ;; Make sure the link properties are right FIXME: Can this be optimized????
8721 (when links (goto-char beg) (while (org-activate-bracket-links end)))
8722 ;; Check if we are narrowing any columns
8723 (goto-char beg)
8724 (setq narrow (and org-format-transports-properties-p
8725 (re-search-forward "<[0-9]+>" end t)))
8726 ;; Get the rows
8727 (setq lines (org-split-string
8728 (buffer-substring beg end) "\n"))
8729 ;; Store the indentation of the first line
8730 (if (string-match "^ *" (car lines))
8731 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
8732 ;; Mark the hlines by setting the corresponding element to nil
8733 ;; At the same time, we remove trailing space.
8734 (setq lines (mapcar (lambda (l)
8735 (if (string-match "^ *|-" l)
8736 nil
8737 (if (string-match "[ \t]+$" l)
8738 (substring l 0 (match-beginning 0))
8739 l)))
8740 lines))
8741 ;; Get the data fields by splitting the lines.
8742 (setq fields (mapcar
8743 (lambda (l)
8744 (org-split-string l " *| *"))
8745 (delq nil (copy-sequence lines))))
8746 ;; How many fields in the longest line?
8747 (condition-case nil
8748 (setq maxfields (apply 'max (mapcar 'length fields)))
8749 (error
8750 (kill-region beg end)
8751 (org-table-create org-table-default-size)
8752 (error "Empty table - created default table")))
8753 ;; A list of empty string to fill any short rows on output
8754 (setq emptystrings (make-list maxfields ""))
8755 ;; Check for special formatting.
8756 (setq i -1)
8757 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
8758 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
8759 ;; Check if there is an explicit width specified
8760 (when (and org-table-limit-column-width narrow)
8761 (setq c column fmax nil)
8762 (while c
8763 (setq e (pop c))
8764 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
8765 (setq fmax (string-to-number (match-string 1 e)) c nil)))
8766 ;; Find fields that are wider than fmax, and shorten them
8767 (when fmax
8768 (loop for xx in column do
8769 (when (and (stringp xx)
8770 (> (org-string-width xx) fmax))
8771 (org-add-props xx nil
8772 'help-echo
8773 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
8774 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
8775 (unless (> f1 1)
8776 (error "Cannot narrow field starting with wide link \"%s\""
8777 (match-string 0 xx)))
8778 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
8779 (add-text-properties (- f1 2) f1
8780 (list 'display org-narrow-column-arrow)
8781 xx)))))
8782 ;; Get the maximum width for each column
8783 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
8784 ;; Get the fraction of numbers, to decide about alignment of the column
8785 (setq cnt 0 frac 0.0)
8786 (loop for x in column do
8787 (if (equal x "")
8788 nil
8789 (setq frac ( / (+ (* frac cnt)
8790 (if (string-match org-table-number-regexp x) 1 0))
8791 (setq cnt (1+ cnt))))))
8792 (push (>= frac org-table-number-fraction) typenums))
8793 (setq lengths (nreverse lengths) typenums (nreverse typenums))
8794
8795 ;; Store the alignment of this table, for later editing of single fields
8796 (setq org-table-last-alignment typenums
8797 org-table-last-column-widths lengths)
8798
8799 ;; With invisible characters, `format' does not get the field width right
8800 ;; So we need to make these fields wide by hand.
8801 (when links
8802 (loop for i from 0 upto (1- maxfields) do
8803 (setq len (nth i lengths))
8804 (loop for j from 0 upto (1- (length fields)) do
8805 (setq c (nthcdr i (car (nthcdr j fields))))
8806 (if (and (stringp (car c))
8807 (string-match org-bracket-link-regexp (car c))
8808 (< (org-string-width (car c)) len))
8809 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
8810
8811 ;; Compute the formats needed for output of the table
8812 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
8813 (while (setq l (pop lengths))
8814 (setq ty (if (pop typenums) "" "-")) ; number types flushright
8815 (setq rfmt (concat rfmt (format rfmt1 ty l))
8816 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
8817 (setq rfmt (concat rfmt "\n")
8818 hfmt (concat (substring hfmt 0 -1) "|\n"))
8819
8820 (setq new (mapconcat
8821 (lambda (l)
8822 (if l (apply 'format rfmt
8823 (append (pop fields) emptystrings))
8824 hfmt))
8825 lines ""))
8826 ;; Replace the old one
8827 (delete-region beg end)
8828 (move-marker end nil)
8829 (move-marker org-table-aligned-begin-marker (point))
8830 (insert new)
8831 (move-marker org-table-aligned-end-marker (point))
8832 (when (and orgtbl-mode (not (eq major-mode 'org-mode)))
8833 (goto-char org-table-aligned-begin-marker)
8834 (while (org-hide-wide-columns org-table-aligned-end-marker)))
8835 ;; Try to move to the old location (approximately)
8836 (goto-line linepos)
8837 (set-window-start (selected-window) winstart 'noforce)
8838 (org-table-goto-column colpos)
8839 (setq org-table-may-need-update nil)
8840 ))
8841
8842 (defun org-string-width (s)
8843 "Compute width of string, ignoring invisible characters.
8844 This ignores character with invisibility property `org-link', and also
8845 characters with property `org-cwidth', because these will become invisible
8846 upon the next fontification round."
8847 (let (b)
8848 (when (or (eq t buffer-invisibility-spec)
8849 (assq 'org-link buffer-invisibility-spec))
8850 (while (setq b (text-property-any 0 (length s)
8851 'invisible 'org-link s))
8852 (setq s (concat (substring s 0 b)
8853 (substring s (or (next-single-property-change
8854 b 'invisible s) (length s)))))))
8855 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
8856 (setq s (concat (substring s 0 b)
8857 (substring s (or (next-single-property-change
8858 b 'org-cwidth s) (length s))))))
8859 (string-width s)))
8860
8861 (defun org-table-begin (&optional table-type)
8862 "Find the beginning of the table and return its position.
8863 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
8864 (save-excursion
8865 (if (not (re-search-backward
8866 (if table-type org-table-any-border-regexp
8867 org-table-border-regexp)
8868 nil t))
8869 (error "Can't find beginning of table")
8870 (goto-char (match-beginning 0))
8871 (beginning-of-line 2)
8872 (point))))
8873
8874 (defun org-table-end (&optional table-type)
8875 "Find the end of the table and return its position.
8876 With argument TABLE-TYPE, go to the end of a table.el-type table."
8877 (save-excursion
8878 (if (not (re-search-forward
8879 (if table-type org-table-any-border-regexp
8880 org-table-border-regexp)
8881 nil t))
8882 (goto-char (point-max))
8883 (goto-char (match-beginning 0)))
8884 (point-marker)))
8885
8886 (defun org-table-justify-field-maybe (&optional new)
8887 "Justify the current field, text to left, number to right.
8888 Optional argument NEW may specify text to replace the current field content."
8889 (cond
8890 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
8891 ((org-at-table-hline-p))
8892 ((and (not new)
8893 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
8894 (current-buffer)))
8895 (< (point) org-table-aligned-begin-marker)
8896 (>= (point) org-table-aligned-end-marker)))
8897 ;; This is not the same table, force a full re-align
8898 (setq org-table-may-need-update t))
8899 (t ;; realign the current field, based on previous full realign
8900 (let* ((pos (point)) s
8901 (col (org-table-current-column))
8902 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
8903 l f n o e)
8904 (when (> col 0)
8905 (skip-chars-backward "^|\n")
8906 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
8907 (progn
8908 (setq s (match-string 1)
8909 o (match-string 0)
8910 l (max 1 (- (match-end 0) (match-beginning 0) 3))
8911 e (not (= (match-beginning 2) (match-end 2))))
8912 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
8913 l (if e "|" (setq org-table-may-need-update t) ""))
8914 n (format f s))
8915 (if new
8916 (if (<= (length new) l) ;; FIXME: length -> str-width?
8917 (setq n (format f new t t)) ;; FIXME: t t?
8918 (setq n (concat new "|") org-table-may-need-update t)))
8919 (or (equal n o)
8920 (let (org-table-may-need-update)
8921 (replace-match n))))
8922 (setq org-table-may-need-update t))
8923 (goto-char pos))))))
8924
8925 (defun org-table-next-field ()
8926 "Go to the next field in the current table, creating new lines as needed.
8927 Before doing so, re-align the table if necessary."
8928 (interactive)
8929 (org-table-maybe-eval-formula)
8930 (org-table-maybe-recalculate-line)
8931 (if (and org-table-automatic-realign
8932 org-table-may-need-update)
8933 (org-table-align))
8934 (let ((end (org-table-end)))
8935 (if (org-at-table-hline-p)
8936 (end-of-line 1))
8937 (condition-case nil
8938 (progn
8939 (re-search-forward "|" end)
8940 (if (looking-at "[ \t]*$")
8941 (re-search-forward "|" end))
8942 (if (and (looking-at "-")
8943 org-table-tab-jumps-over-hlines
8944 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
8945 (goto-char (match-beginning 1)))
8946 (if (looking-at "-")
8947 (progn
8948 (beginning-of-line 0)
8949 (org-table-insert-row 'below))
8950 (if (looking-at " ") (forward-char 1))))
8951 (error
8952 (org-table-insert-row 'below)))))
8953
8954 (defun org-table-previous-field ()
8955 "Go to the previous field in the table.
8956 Before doing so, re-align the table if necessary."
8957 (interactive)
8958 (org-table-justify-field-maybe)
8959 (org-table-maybe-recalculate-line)
8960 (if (and org-table-automatic-realign
8961 org-table-may-need-update)
8962 (org-table-align))
8963 (if (org-at-table-hline-p)
8964 (end-of-line 1))
8965 (re-search-backward "|" (org-table-begin))
8966 (re-search-backward "|" (org-table-begin))
8967 (while (looking-at "|\\(-\\|[ \t]*$\\)")
8968 (re-search-backward "|" (org-table-begin)))
8969 (if (looking-at "| ?")
8970 (goto-char (match-end 0))))
8971
8972 (defun org-table-next-row ()
8973 "Go to the next row (same column) in the current table.
8974 Before doing so, re-align the table if necessary."
8975 (interactive)
8976 (org-table-maybe-eval-formula)
8977 (org-table-maybe-recalculate-line)
8978 (if (or (looking-at "[ \t]*$")
8979 (save-excursion (skip-chars-backward " \t") (bolp)))
8980 (newline)
8981 (if (and org-table-automatic-realign
8982 org-table-may-need-update)
8983 (org-table-align))
8984 (let ((col (org-table-current-column)))
8985 (beginning-of-line 2)
8986 (if (or (not (org-at-table-p))
8987 (org-at-table-hline-p))
8988 (progn
8989 (beginning-of-line 0)
8990 (org-table-insert-row 'below)))
8991 (org-table-goto-column col)
8992 (skip-chars-backward "^|\n\r")
8993 (if (looking-at " ") (forward-char 1)))))
8994
8995 (defun org-table-copy-down (n)
8996 "Copy a field down in the current column.
8997 If the field at the cursor is empty, copy into it the content of the nearest
8998 non-empty field above. With argument N, use the Nth non-empty field.
8999 If the current field is not empty, it is copied down to the next row, and
9000 the cursor is moved with it. Therefore, repeating this command causes the
9001 column to be filled row-by-row.
9002 If the variable `org-table-copy-increment' is non-nil and the field is an
9003 integer, it will be incremented while copying."
9004 (interactive "p")
9005 (let* ((colpos (org-table-current-column))
9006 (field (org-table-get-field))
9007 (non-empty (string-match "[^ \t]" field))
9008 (beg (org-table-begin))
9009 txt)
9010 (org-table-check-inside-data-field)
9011 (if non-empty
9012 (progn
9013 (setq txt (org-trim field))
9014 (org-table-next-row)
9015 (org-table-blank-field))
9016 (save-excursion
9017 (setq txt
9018 (catch 'exit
9019 (while (progn (beginning-of-line 1)
9020 (re-search-backward org-table-dataline-regexp
9021 beg t))
9022 (org-table-goto-column colpos t)
9023 (if (and (looking-at
9024 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
9025 (= (setq n (1- n)) 0))
9026 (throw 'exit (match-string 1))))))))
9027 (if txt
9028 (progn
9029 (if (and org-table-copy-increment
9030 (string-match "^[0-9]+$" txt))
9031 (setq txt (format "%d" (+ (string-to-number txt) 1))))
9032 (insert txt)
9033 (org-table-maybe-recalculate-line)
9034 (org-table-align))
9035 (error "No non-empty field found"))))
9036
9037 (defun org-table-check-inside-data-field ()
9038 "Is point inside a table data field?
9039 I.e. not on a hline or before the first or after the last column?
9040 This actually throws an error, so it aborts the current command."
9041 (if (or (not (org-at-table-p))
9042 (= (org-table-current-column) 0)
9043 (org-at-table-hline-p)
9044 (looking-at "[ \t]*$"))
9045 (error "Not in table data field")))
9046
9047 (defvar org-table-clip nil
9048 "Clipboard for table regions.")
9049
9050 (defun org-table-blank-field ()
9051 "Blank the current table field or active region."
9052 (interactive)
9053 (org-table-check-inside-data-field)
9054 (if (and (interactive-p) (org-region-active-p))
9055 (let (org-table-clip)
9056 (org-table-cut-region (region-beginning) (region-end)))
9057 (skip-chars-backward "^|")
9058 (backward-char 1)
9059 (if (looking-at "|[^|\n]+")
9060 (let* ((pos (match-beginning 0))
9061 (match (match-string 0))
9062 (len (org-string-width match)))
9063 (replace-match (concat "|" (make-string (1- len) ?\ )))
9064 (goto-char (+ 2 pos))
9065 (substring match 1)))))
9066
9067 (defun org-table-get-field (&optional n replace)
9068 "Return the value of the field in column N of current row.
9069 N defaults to current field.
9070 If REPLACE is a string, replace field with this value. The return value
9071 is always the old value."
9072 (and n (org-table-goto-column n))
9073 (skip-chars-backward "^|\n")
9074 (backward-char 1)
9075 (if (looking-at "|[^|\r\n]*")
9076 (let* ((pos (match-beginning 0))
9077 (val (buffer-substring (1+ pos) (match-end 0))))
9078 (if replace
9079 (replace-match (concat "|" replace)))
9080 (goto-char (min (point-at-eol) (+ 2 pos)))
9081 val)
9082 (forward-char 1) ""))
9083
9084 (defun org-table-current-column ()
9085 "Find out which column we are in.
9086 When called interactively, column is also displayed in echo area."
9087 (interactive)
9088 (if (interactive-p) (org-table-check-inside-data-field))
9089 (save-excursion
9090 (let ((cnt 0) (pos (point)))
9091 (beginning-of-line 1)
9092 (while (search-forward "|" pos t)
9093 (setq cnt (1+ cnt)))
9094 (if (interactive-p) (message "This is table column %d" cnt))
9095 cnt)))
9096
9097 (defun org-table-goto-column (n &optional on-delim force)
9098 "Move the cursor to the Nth column in the current table line.
9099 With optional argument ON-DELIM, stop with point before the left delimiter
9100 of the field.
9101 If there are less than N fields, just go to after the last delimiter.
9102 However, when FORCE is non-nil, create new columns if necessary."
9103 (interactive "p")
9104 (let ((pos (point-at-eol)))
9105 (beginning-of-line 1)
9106 (when (> n 0)
9107 (while (and (> (setq n (1- n)) -1)
9108 (or (search-forward "|" pos t)
9109 (and force
9110 (progn (end-of-line 1)
9111 (skip-chars-backward "^|")
9112 (insert " | "))))))
9113 ; (backward-char 2) t)))))
9114 (when (and force (not (looking-at ".*|")))
9115 (save-excursion (end-of-line 1) (insert " | ")))
9116 (if on-delim
9117 (backward-char 1)
9118 (if (looking-at " ") (forward-char 1))))))
9119
9120 (defun org-at-table-p (&optional table-type)
9121 "Return t if the cursor is inside an org-type table.
9122 If TABLE-TYPE is non-nil, also check for table.el-type tables."
9123 (if org-enable-table-editor
9124 (save-excursion
9125 (beginning-of-line 1)
9126 (looking-at (if table-type org-table-any-line-regexp
9127 org-table-line-regexp)))
9128 nil))
9129
9130 (defun org-at-table.el-p ()
9131 "Return t if and only if we are at a table.el table."
9132 (and (org-at-table-p 'any)
9133 (save-excursion
9134 (goto-char (org-table-begin 'any))
9135 (looking-at org-table1-hline-regexp))))
9136
9137 (defun org-table-recognize-table.el ()
9138 "If there is a table.el table nearby, recognize it and move into it."
9139 (if org-table-tab-recognizes-table.el
9140 (if (org-at-table.el-p)
9141 (progn
9142 (beginning-of-line 1)
9143 (if (looking-at org-table-dataline-regexp)
9144 nil
9145 (if (looking-at org-table1-hline-regexp)
9146 (progn
9147 (beginning-of-line 2)
9148 (if (looking-at org-table-any-border-regexp)
9149 (beginning-of-line -1)))))
9150 (if (re-search-forward "|" (org-table-end t) t)
9151 (progn
9152 (require 'table)
9153 (if (table--at-cell-p (point))
9154 t
9155 (message "recognizing table.el table...")
9156 (table-recognize-table)
9157 (message "recognizing table.el table...done")))
9158 (error "This should not happen..."))
9159 t)
9160 nil)
9161 nil))
9162
9163 (defun org-at-table-hline-p ()
9164 "Return t if the cursor is inside a hline in a table."
9165 (if org-enable-table-editor
9166 (save-excursion
9167 (beginning-of-line 1)
9168 (looking-at org-table-hline-regexp))
9169 nil))
9170
9171 (defun org-table-insert-column ()
9172 "Insert a new column into the table."
9173 (interactive)
9174 (if (not (org-at-table-p))
9175 (error "Not at a table"))
9176 (org-table-find-dataline)
9177 (let* ((col (max 1 (org-table-current-column)))
9178 (beg (org-table-begin))
9179 (end (org-table-end))
9180 ;; Current cursor position
9181 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9182 (colpos col))
9183 (goto-char beg)
9184 (while (< (point) end)
9185 (if (org-at-table-hline-p)
9186 nil
9187 (org-table-goto-column col t)
9188 (insert "| "))
9189 (beginning-of-line 2))
9190 (move-marker end nil)
9191 (goto-line linepos)
9192 (org-table-goto-column colpos)
9193 (org-table-align)
9194 (org-table-modify-formulas 'insert col)))
9195
9196 (defun org-table-find-dataline ()
9197 "Find a dataline in the current table, which is needed for column commands."
9198 (if (and (org-at-table-p)
9199 (not (org-at-table-hline-p)))
9200 t
9201 (let ((col (current-column))
9202 (end (org-table-end)))
9203 (move-to-column col)
9204 (while (and (< (point) end)
9205 (or (not (= (current-column) col))
9206 (org-at-table-hline-p)))
9207 (beginning-of-line 2)
9208 (move-to-column col))
9209 (if (and (org-at-table-p)
9210 (not (org-at-table-hline-p)))
9211 t
9212 (error
9213 "Please position cursor in a data line for column operations")))))
9214
9215 (defun org-table-delete-column ()
9216 "Delete a column into the table."
9217 (interactive)
9218 (if (not (org-at-table-p))
9219 (error "Not at a table"))
9220 (org-table-find-dataline)
9221 (org-table-check-inside-data-field)
9222 (let* ((col (org-table-current-column))
9223 (beg (org-table-begin))
9224 (end (org-table-end))
9225 ;; Current cursor position
9226 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9227 (colpos col))
9228 (goto-char beg)
9229 (while (< (point) end)
9230 (if (org-at-table-hline-p)
9231 nil
9232 (org-table-goto-column col t)
9233 (and (looking-at "|[^|\n]+|")
9234 (replace-match "|")))
9235 (beginning-of-line 2))
9236 (move-marker end nil)
9237 (goto-line linepos)
9238 (org-table-goto-column colpos)
9239 (org-table-align)
9240 (org-table-modify-formulas 'remove col)))
9241
9242 (defun org-table-move-column-right ()
9243 "Move column to the right."
9244 (interactive)
9245 (org-table-move-column nil))
9246 (defun org-table-move-column-left ()
9247 "Move column to the left."
9248 (interactive)
9249 (org-table-move-column 'left))
9250
9251 (defun org-table-move-column (&optional left)
9252 "Move the current column to the right. With arg LEFT, move to the left."
9253 (interactive "P")
9254 (if (not (org-at-table-p))
9255 (error "Not at a table"))
9256 (org-table-find-dataline)
9257 (org-table-check-inside-data-field)
9258 (let* ((col (org-table-current-column))
9259 (col1 (if left (1- col) col))
9260 (beg (org-table-begin))
9261 (end (org-table-end))
9262 ;; Current cursor position
9263 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
9264 (colpos (if left (1- col) (1+ col))))
9265 (if (and left (= col 1))
9266 (error "Cannot move column further left"))
9267 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
9268 (error "Cannot move column further right"))
9269 (goto-char beg)
9270 (while (< (point) end)
9271 (if (org-at-table-hline-p)
9272 nil
9273 (org-table-goto-column col1 t)
9274 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
9275 (replace-match "|\\2|\\1|")))
9276 (beginning-of-line 2))
9277 (move-marker end nil)
9278 (goto-line linepos)
9279 (org-table-goto-column colpos)
9280 (org-table-align)
9281 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
9282
9283 (defun org-table-move-row-down ()
9284 "Move table row down."
9285 (interactive)
9286 (org-table-move-row nil))
9287 (defun org-table-move-row-up ()
9288 "Move table row up."
9289 (interactive)
9290 (org-table-move-row 'up))
9291
9292 (defun org-table-move-row (&optional up)
9293 "Move the current table line down. With arg UP, move it up."
9294 (interactive "P")
9295 (let ((col (current-column))
9296 (pos (point))
9297 (tonew (if up 0 2))
9298 txt)
9299 (beginning-of-line tonew)
9300 (if (not (org-at-table-p))
9301 (progn
9302 (goto-char pos)
9303 (error "Cannot move row further")))
9304 (goto-char pos)
9305 (beginning-of-line 1)
9306 (setq pos (point))
9307 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
9308 (delete-region (point) (1+ (point-at-eol)))
9309 (beginning-of-line tonew)
9310 (insert txt)
9311 (beginning-of-line 0)
9312 (move-to-column col)))
9313
9314 (defun org-table-insert-row (&optional arg)
9315 "Insert a new row above the current line into the table.
9316 With prefix ARG, insert below the current line."
9317 (interactive "P")
9318 (if (not (org-at-table-p))
9319 (error "Not at a table"))
9320 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
9321 (new (org-table-clean-line line)))
9322 ;; Fix the first field if necessary
9323 (if (string-match "^[ \t]*| *[#$] *|" line)
9324 (setq new (replace-match (match-string 0 line) t t new)))
9325 (beginning-of-line (if arg 2 1))
9326 (let (org-table-may-need-update) (insert-before-markers new "\n"))
9327 (beginning-of-line 0)
9328 (re-search-forward "| ?" (point-at-eol) t)
9329 (and org-table-may-need-update (org-table-align))))
9330
9331 (defun org-table-insert-hline (&optional arg)
9332 "Insert a horizontal-line below the current line into the table.
9333 With prefix ARG, insert above the current line."
9334 (interactive "P")
9335 (if (not (org-at-table-p))
9336 (error "Not at a table"))
9337 (let ((line (org-table-clean-line
9338 (buffer-substring (point-at-bol) (point-at-eol))))
9339 (col (current-column)))
9340 (while (string-match "|\\( +\\)|" line)
9341 (setq line (replace-match
9342 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
9343 ?-) "|") t t line)))
9344 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
9345 (beginning-of-line (if arg 1 2))
9346 (insert line "\n")
9347 (beginning-of-line (if arg 1 -1))
9348 (move-to-column col)))
9349
9350 (defun org-table-clean-line (s)
9351 "Convert a table line S into a string with only \"|\" and space.
9352 In particular, this does handle wide and invisible characters."
9353 (if (string-match "^[ \t]*|-" s)
9354 ;; It's a hline, just map the characters
9355 (setq s (mapcar (lambda (x) (if (member x '(?| ?+)) ?| ?\ )) s))
9356 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
9357 (setq s (replace-match
9358 (concat "|" (make-string (org-string-width (match-string 1 s))
9359 ?\ ) "|")
9360 t t s)))
9361 s))
9362
9363 (defun org-table-kill-row ()
9364 "Delete the current row or horizontal line from the table."
9365 (interactive)
9366 (if (not (org-at-table-p))
9367 (error "Not at a table"))
9368 (let ((col (current-column)))
9369 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
9370 (if (not (org-at-table-p)) (beginning-of-line 0))
9371 (move-to-column col)))
9372
9373 (defun org-table-sort-lines (beg end numericp)
9374 "Sort table lines in region.
9375 Point and mark define the first and last line to include. Both point and
9376 mark should be in the column that is used for sorting. For example, to
9377 sort according to column 3, put the mark in the first line to sort, in
9378 table column 3. Put point into the last line to be included in the sorting,
9379 also in table column 3. The command will prompt for the sorting method
9380 \(n for numerical, a for alphanumeric)."
9381 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
9382 (setq numericp (string-match "[nN]" numericp))
9383 (org-table-align) ;; Just to be safe
9384 (let* (bcol ecol cmp column lns)
9385 (goto-char beg)
9386 (org-table-check-inside-data-field)
9387 (setq column (org-table-current-column)
9388 beg (move-marker (make-marker) (point-at-bol)))
9389 (goto-char end)
9390 (org-table-check-inside-data-field)
9391 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
9392 (untabify beg end)
9393 (goto-char beg)
9394 (org-table-goto-column column)
9395 (skip-chars-backward "^|")
9396 (setq bcol (current-column))
9397 (org-table-goto-column (1+ column))
9398 (skip-chars-backward "^|")
9399 (setq ecol (1- (current-column)))
9400 (setq cmp (if numericp
9401 (lambda (a b) (< (car a) (car b)))
9402 (lambda (a b) (string< (car a) (car b)))))
9403 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
9404 (split-string (buffer-substring beg end) "\n")))
9405 (if numericp
9406 (setq lns (mapcar (lambda(x)
9407 (cons (string-to-number (car x)) (cdr x)))
9408 lns)))
9409 (delete-region beg end)
9410 (move-marker beg nil)
9411 (move-marker end nil)
9412 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
9413 (message "%d lines sorted %s based on column %d"
9414 (length lns)
9415 (if numericp "numerically" "alphabetically") column)))
9416
9417 (defun org-table-cut-region (beg end)
9418 "Copy region in table to the clipboard and blank all relevant fields."
9419 (interactive "r")
9420 (org-table-copy-region beg end 'cut))
9421
9422 (defun org-table-copy-region (beg end &optional cut)
9423 "Copy rectangular region in table to clipboard.
9424 A special clipboard is used which can only be accessed
9425 with `org-table-paste-rectangle'."
9426 (interactive "rP")
9427 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
9428 region cols
9429 (rpl (if cut " " nil)))
9430 (goto-char beg)
9431 (org-table-check-inside-data-field)
9432 (setq l01 (count-lines (point-min) (point))
9433 c01 (org-table-current-column))
9434 (goto-char end)
9435 (org-table-check-inside-data-field)
9436 (setq l02 (count-lines (point-min) (point))
9437 c02 (org-table-current-column))
9438 (setq l1 (min l01 l02) l2 (max l01 l02)
9439 c1 (min c01 c02) c2 (max c01 c02))
9440 (catch 'exit
9441 (while t
9442 (catch 'nextline
9443 (if (> l1 l2) (throw 'exit t))
9444 (goto-line l1)
9445 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
9446 (setq cols nil ic1 c1 ic2 c2)
9447 (while (< ic1 (1+ ic2))
9448 (push (org-table-get-field ic1 rpl) cols)
9449 (setq ic1 (1+ ic1)))
9450 (push (nreverse cols) region)
9451 (setq l1 (1+ l1)))))
9452 (setq org-table-clip (nreverse region))
9453 (if cut (org-table-align))
9454 org-table-clip))
9455
9456 (defun org-table-paste-rectangle ()
9457 "Paste a rectangular region into a table.
9458 The upper right corner ends up in the current field. All involved fields
9459 will be overwritten. If the rectangle does not fit into the present table,
9460 the table is enlarged as needed. The process ignores horizontal separator
9461 lines."
9462 (interactive)
9463 (unless (and org-table-clip (listp org-table-clip))
9464 (error "First cut/copy a region to paste!"))
9465 (org-table-check-inside-data-field)
9466 (let* ((clip org-table-clip)
9467 (line (count-lines (point-min) (point)))
9468 (col (org-table-current-column))
9469 (org-enable-table-editor t)
9470 (org-table-automatic-realign nil)
9471 c cols field)
9472 (while (setq cols (pop clip))
9473 (while (org-at-table-hline-p) (beginning-of-line 2))
9474 (if (not (org-at-table-p))
9475 (progn (end-of-line 0) (org-table-next-field)))
9476 (setq c col)
9477 (while (setq field (pop cols))
9478 (org-table-goto-column c nil 'force)
9479 (org-table-get-field nil field)
9480 (setq c (1+ c)))
9481 (beginning-of-line 2))
9482 (goto-line line)
9483 (org-table-goto-column col)
9484 (org-table-align)))
9485
9486 (defun org-table-convert ()
9487 "Convert from `org-mode' table to table.el and back.
9488 Obviously, this only works within limits. When an Org-mode table is
9489 converted to table.el, all horizontal separator lines get lost, because
9490 table.el uses these as cell boundaries and has no notion of horizontal lines.
9491 A table.el table can be converted to an Org-mode table only if it does not
9492 do row or column spanning. Multiline cells will become multiple cells.
9493 Beware, Org-mode does not test if the table can be successfully converted - it
9494 blindly applies a recipe that works for simple tables."
9495 (interactive)
9496 (require 'table)
9497 (if (org-at-table.el-p)
9498 ;; convert to Org-mode table
9499 (let ((beg (move-marker (make-marker) (org-table-begin t)))
9500 (end (move-marker (make-marker) (org-table-end t))))
9501 (table-unrecognize-region beg end)
9502 (goto-char beg)
9503 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
9504 (replace-match ""))
9505 (goto-char beg))
9506 (if (org-at-table-p)
9507 ;; convert to table.el table
9508 (let ((beg (move-marker (make-marker) (org-table-begin)))
9509 (end (move-marker (make-marker) (org-table-end))))
9510 ;; first, get rid of all horizontal lines
9511 (goto-char beg)
9512 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
9513 (replace-match ""))
9514 ;; insert a hline before first
9515 (goto-char beg)
9516 (org-table-insert-hline 'above)
9517 (beginning-of-line -1)
9518 ;; insert a hline after each line
9519 (while (progn (beginning-of-line 3) (< (point) end))
9520 (org-table-insert-hline))
9521 (goto-char beg)
9522 (setq end (move-marker end (org-table-end)))
9523 ;; replace "+" at beginning and ending of hlines
9524 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
9525 (replace-match "\\1+-"))
9526 (goto-char beg)
9527 (while (re-search-forward "-|[ \t]*$" end t)
9528 (replace-match "-+"))
9529 (goto-char beg)))))
9530
9531 (defun org-table-wrap-region (arg)
9532 "Wrap several fields in a column like a paragraph.
9533 This is useful if you'd like to spread the contents of a field over several
9534 lines, in order to keep the table compact.
9535
9536 If there is an active region, and both point and mark are in the same column,
9537 the text in the column is wrapped to minimum width for the given number of
9538 lines. Generally, this makes the table more compact. A prefix ARG may be
9539 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
9540 formats the selected text to two lines. If the region was longer than two
9541 lines, the remaining lines remain empty. A negative prefix argument reduces
9542 the current number of lines by that amount. The wrapped text is pasted back
9543 into the table. If you formatted it to more lines than it was before, fields
9544 further down in the table get overwritten - so you might need to make space in
9545 the table first.
9546
9547 If there is no region, the current field is split at the cursor position and
9548 the text fragment to the right of the cursor is prepended to the field one
9549 line down.
9550
9551 If there is no region, but you specify a prefix ARG, the current field gets
9552 blank, and the content is appended to the field above."
9553 (interactive "P")
9554 (org-table-check-inside-data-field)
9555 (if (org-region-active-p)
9556 ;; There is a region: fill as a paragraph
9557 (let ((beg (region-beginning))
9558 nlines)
9559 (org-table-cut-region (region-beginning) (region-end))
9560 (if (> (length (car org-table-clip)) 1)
9561 (error "Region must be limited to single column"))
9562 (setq nlines (if arg
9563 (if (< arg 1)
9564 (+ (length org-table-clip) arg)
9565 arg)
9566 (length org-table-clip)))
9567 (setq org-table-clip
9568 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
9569 nil nlines)))
9570 (goto-char beg)
9571 (org-table-paste-rectangle))
9572 ;; No region, split the current field at point
9573 (if arg
9574 ;; combine with field above
9575 (let ((s (org-table-blank-field))
9576 (col (org-table-current-column)))
9577 (beginning-of-line 0)
9578 (while (org-at-table-hline-p) (beginning-of-line 0))
9579 (org-table-goto-column col)
9580 (skip-chars-forward "^|")
9581 (skip-chars-backward " ")
9582 (insert " " (org-trim s))
9583 (org-table-align))
9584 ;; split field
9585 (when (looking-at "\\([^|]+\\)+|")
9586 (let ((s (match-string 1)))
9587 (replace-match " |")
9588 (goto-char (match-beginning 0))
9589 (org-table-next-row)
9590 (insert (org-trim s) " ")
9591 (org-table-align))))))
9592
9593 (defvar org-field-marker nil)
9594
9595 (defun org-table-edit-field (arg)
9596 "Edit table field in a different window.
9597 This is mainly useful for fields that contain hidden parts.
9598 When called with a \\[universal-argument] prefix, just make the full field visible so that
9599 it can be edited in place."
9600 (interactive "P")
9601 (if arg
9602 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
9603 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
9604 (remove-text-properties b e '(org-cwidth t invisible t
9605 display t intangible t))
9606 (if (and (boundp 'font-lock-mode) font-lock-mode)
9607 (font-lock-fontify-block)))
9608 (let ((pos (move-marker (make-marker) (point)))
9609 (field (org-table-get-field))
9610 (cw (current-window-configuration))
9611 p)
9612 (switch-to-buffer-other-window "*Org tmp*")
9613 (erase-buffer)
9614 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
9615 (org-mode)
9616 (goto-char (setq p (point-max)))
9617 (insert (org-trim field))
9618 (remove-text-properties p (point-max)
9619 '(invisible t org-cwidth t display t
9620 intangible t))
9621 (goto-char p)
9622 (set (make-local-variable 'org-finish-function)
9623 'org-table-finish-edit-field)
9624 (set (make-local-variable 'org-window-configuration) cw)
9625 (set (make-local-variable 'org-field-marker) pos)
9626 (message "Edit and finish with C-c C-c"))))
9627
9628 (defun org-table-finish-edit-field ()
9629 "Finish editing a table data field.
9630 Remove all newline characters, insert the result into the table, realign
9631 the table and kill the editing buffer."
9632 (let ((pos org-field-marker)
9633 (cw org-window-configuration)
9634 (cb (current-buffer))
9635 text)
9636 (goto-char (point-min))
9637 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
9638 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
9639 (replace-match " "))
9640 (setq text (org-trim (buffer-string)))
9641 (set-window-configuration cw)
9642 (kill-buffer cb)
9643 (select-window (get-buffer-window (marker-buffer pos)))
9644 (goto-char pos)
9645 (move-marker pos nil)
9646 (org-table-check-inside-data-field)
9647 (org-table-get-field nil text)
9648 (org-table-align)
9649 (message "New field value inserted")))
9650
9651 (defun org-trim (s)
9652 "Remove whitespace at beginning and end of string."
9653 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
9654 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
9655 s)
9656
9657 (defun org-wrap (string &optional width lines)
9658 "Wrap string to either a number of lines, or a width in characters.
9659 If WIDTH is non-nil, the string is wrapped to that width, however many lines
9660 that costs. If there is a word longer than WIDTH, the text is actually
9661 wrapped to the length of that word.
9662 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
9663 many lines, whatever width that takes.
9664 The return value is a list of lines, without newlines at the end."
9665 (let* ((words (org-split-string string "[ \t\n]+"))
9666 (maxword (apply 'max (mapcar 'org-string-width words)))
9667 w ll)
9668 (cond (width
9669 (org-do-wrap words (max maxword width)))
9670 (lines
9671 (setq w maxword)
9672 (setq ll (org-do-wrap words maxword))
9673 (if (<= (length ll) lines)
9674 ll
9675 (setq ll words)
9676 (while (> (length ll) lines)
9677 (setq w (1+ w))
9678 (setq ll (org-do-wrap words w)))
9679 ll))
9680 (t (error "Cannot wrap this")))))
9681
9682
9683 (defun org-do-wrap (words width)
9684 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
9685 (let (lines line)
9686 (while words
9687 (setq line (pop words))
9688 (while (and words (< (+ (length line) (length (car words))) width))
9689 (setq line (concat line " " (pop words))))
9690 (setq lines (push line lines)))
9691 (nreverse lines)))
9692
9693 (defun org-split-string (string &optional separators)
9694 "Splits STRING into substrings at SEPARATORS.
9695 No empty strings are returned if there are matches at the beginning
9696 and end of string."
9697 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
9698 (start 0)
9699 notfirst
9700 (list nil))
9701 (while (and (string-match rexp string
9702 (if (and notfirst
9703 (= start (match-beginning 0))
9704 (< start (length string)))
9705 (1+ start) start))
9706 (< (match-beginning 0) (length string)))
9707 (setq notfirst t)
9708 (or (eq (match-beginning 0) 0)
9709 (and (eq (match-beginning 0) (match-end 0))
9710 (eq (match-beginning 0) start))
9711 (setq list
9712 (cons (substring string start (match-beginning 0))
9713 list)))
9714 (setq start (match-end 0)))
9715 (or (eq start (length string))
9716 (setq list
9717 (cons (substring string start)
9718 list)))
9719 (nreverse list)))
9720
9721 (defun org-table-map-tables (function)
9722 "Apply FUNCTION to the start of all tables in the buffer."
9723 (save-excursion
9724 (save-restriction
9725 (widen)
9726 (goto-char (point-min))
9727 (while (re-search-forward org-table-any-line-regexp nil t)
9728 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
9729 (beginning-of-line 1)
9730 (if (looking-at org-table-line-regexp)
9731 (save-excursion (funcall function)))
9732 (re-search-forward org-table-any-border-regexp nil 1))))
9733 (message "Mapping tables: done"))
9734
9735 (defun org-table-sum (&optional beg end nlast)
9736 "Sum numbers in region of current table column.
9737 The result will be displayed in the echo area, and will be available
9738 as kill to be inserted with \\[yank].
9739
9740 If there is an active region, it is interpreted as a rectangle and all
9741 numbers in that rectangle will be summed. If there is no active
9742 region and point is located in a table column, sum all numbers in that
9743 column.
9744
9745 If at least one number looks like a time HH:MM or HH:MM:SS, all other
9746 numbers are assumed to be times as well (in decimal hours) and the
9747 numbers are added as such.
9748
9749 If NLAST is a number, only the NLAST fields will actually be summed."
9750 (interactive)
9751 (save-excursion
9752 (let (col (timecnt 0) diff h m s org-table-clip)
9753 (cond
9754 ((and beg end)) ; beg and end given explicitly
9755 ((org-region-active-p)
9756 (setq beg (region-beginning) end (region-end)))
9757 (t
9758 (setq col (org-table-current-column))
9759 (goto-char (org-table-begin))
9760 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
9761 (error "No table data"))
9762 (org-table-goto-column col)
9763 ;not needed? (skip-chars-backward "^|")
9764 (setq beg (point))
9765 (goto-char (org-table-end))
9766 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
9767 (error "No table data"))
9768 (org-table-goto-column col)
9769 ;not needed? (skip-chars-forward "^|")
9770 (setq end (point))))
9771 (let* ((items (apply 'append (org-table-copy-region beg end)))
9772 (items1 (cond ((not nlast) items)
9773 ((>= nlast (length items)) items)
9774 (t (setq items (reverse items))
9775 (setcdr (nthcdr (1- nlast) items) nil)
9776 (nreverse items))))
9777 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
9778 items1)))
9779 (res (apply '+ numbers))
9780 (sres (if (= timecnt 0)
9781 (format "%g" res)
9782 (setq diff (* 3600 res)
9783 h (floor (/ diff 3600)) diff (mod diff 3600)
9784 m (floor (/ diff 60)) diff (mod diff 60)
9785 s diff)
9786 (format "%d:%02d:%02d" h m s))))
9787 (kill-new sres)
9788 (if (interactive-p)
9789 (message "%s"
9790 (substitute-command-keys
9791 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
9792 (length numbers) sres))))
9793 sres))))
9794
9795 (defun org-table-get-number-for-summing (s)
9796 (let (n)
9797 (if (string-match "^ *|? *" s)
9798 (setq s (replace-match "" nil nil s)))
9799 (if (string-match " *|? *$" s)
9800 (setq s (replace-match "" nil nil s)))
9801 (setq n (string-to-number s))
9802 (cond
9803 ((and (string-match "0" s)
9804 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
9805 ((string-match "\\`[ \t]+\\'" s) nil)
9806 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
9807 (let ((h (string-to-number (or (match-string 1 s) "0")))
9808 (m (string-to-number (or (match-string 2 s) "0")))
9809 (s (string-to-number (or (match-string 4 s) "0"))))
9810 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
9811 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
9812 ((equal n 0) nil)
9813 (t n))))
9814
9815 (defun org-table-get-vertical-vector (desc &optional tbeg col)
9816 "Get a calc vector from a column, accorting to descriptor DESC.
9817 Optional arguments TBEG and COL can give the beginning of the table and
9818 the current column, to avoid unnecessary parsing."
9819 (save-excursion
9820 (or tbeg (setq tbeg (org-table-begin)))
9821 (or col (setq col (org-table-current-column)))
9822 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
9823 (cond
9824 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
9825 (setq n1 (- (match-end 1) (match-beginning 1)))
9826 (if (match-beginning 3)
9827 (setq n2 (- (match-end 2) (match-beginning 3))))
9828 (setq n (if n2 (max n1 n2) n1))
9829 (setq n1 (if n2 (min n1 n2)))
9830 (setq nn n)
9831 (while (and (> nn 0)
9832 (re-search-backward org-table-hline-regexp tbeg t))
9833 (push (org-current-line) hline-list)
9834 (setq nn (1- nn)))
9835 (setq hline-list (nreverse hline-list))
9836 (goto-line (nth (1- n) hline-list))
9837 (when (re-search-forward org-table-dataline-regexp)
9838 (org-table-goto-column col)
9839 (setq beg (point)))
9840 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
9841 (when (re-search-backward org-table-dataline-regexp)
9842 (org-table-goto-column col)
9843 (setq end (point)))
9844 (setq l (apply 'append (org-table-copy-region beg end)))
9845 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
9846 (if (equal x "") "0" x))
9847 l ",") "]"))
9848 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
9849 (setq n1 (string-to-number (match-string 1 desc))
9850 n2 (string-to-number (match-string 2 desc)))
9851 (beginning-of-line 1)
9852 (save-excursion
9853 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
9854 (org-table-goto-column col)
9855 (setq beg (point))))
9856 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
9857 (org-table-goto-column col)
9858 (setq end (point)))
9859 (setq l (apply 'append (org-table-copy-region beg end)))
9860 (concat "[" (mapconcat
9861 (lambda (x) (setq x (org-trim x))
9862 (if (equal x "") "0" x))
9863 l ",") "]"))
9864 ((string-match "\\([0-9]+\\)" desc)
9865 (beginning-of-line 1)
9866 (when (re-search-backward org-table-dataline-regexp tbeg t
9867 (string-to-number (match-string 0 desc)))
9868 (org-table-goto-column col)
9869 (org-trim (org-table-get-field))))))))
9870
9871 (defvar org-table-formula-history nil)
9872
9873 (defvar org-table-column-names nil
9874 "Alist with column names, derived from the `!' line.")
9875 (defvar org-table-column-name-regexp nil
9876 "Regular expression matching the current column names.")
9877 (defvar org-table-local-parameters nil
9878 "Alist with parameter names, derived from the `$' line.")
9879 (defvar org-table-named-field-locations nil
9880 "Alist with locations of named fields.")
9881
9882 (defun org-table-get-formula (&optional equation named)
9883 "Read a formula from the minibuffer, offer stored formula as default."
9884 (let* ((name (car (rassoc (list (org-current-line)
9885 (org-table-current-column))
9886 org-table-named-field-locations)))
9887 (scol (if named
9888 (if name name
9889 (error "Not in a named field"))
9890 (int-to-string (org-table-current-column))))
9891 (dummy (and name (not named)
9892 (not (y-or-n-p "Replace named-field formula with column equation? " ))
9893 (error "Abort")))
9894 (org-table-may-need-update nil)
9895 (stored-list (org-table-get-stored-formulas))
9896 (stored (cdr (assoc scol stored-list)))
9897 (eq (cond
9898 ((and stored equation (string-match "^ *=? *$" equation))
9899 stored)
9900 ((stringp equation)
9901 equation)
9902 (t (read-string
9903 (format "%s formula $%s=" (if named "Field" "Column") scol)
9904 (or stored "") 'org-table-formula-history
9905 ;stored
9906 ))))
9907 mustsave)
9908 (when (not (string-match "\\S-" eq))
9909 ;; remove formula
9910 (setq stored-list (delq (assoc scol stored-list) stored-list))
9911 (org-table-store-formulas stored-list)
9912 (error "Formula removed"))
9913 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
9914 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
9915 (if (and name (not named))
9916 ;; We set the column equation, delete the named one.
9917 (setq stored-list (delq (assoc name stored-list) stored-list)
9918 mustsave t))
9919 (if stored
9920 (setcdr (assoc scol stored-list) eq)
9921 (setq stored-list (cons (cons scol eq) stored-list)))
9922 (if (or mustsave (not (equal stored eq)))
9923 (org-table-store-formulas stored-list))
9924 eq))
9925
9926 (defun org-table-store-formulas (alist)
9927 "Store the list of formulas below the current table."
9928 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
9929 (save-excursion
9930 (goto-char (org-table-end))
9931 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
9932 (delete-region (point) (match-end 0)))
9933 (insert "#+TBLFM: "
9934 (mapconcat (lambda (x)
9935 (concat "$" (car x) "=" (cdr x)))
9936 alist "::")
9937 "\n")))
9938
9939 (defun org-table-get-stored-formulas ()
9940 "Return an alist with the t=stored formulas directly after current table."
9941 (interactive)
9942 (let (scol eq eq-alist strings string seen)
9943 (save-excursion
9944 (goto-char (org-table-end))
9945 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
9946 (setq strings (org-split-string (match-string 2) " *:: *"))
9947 (while (setq string (pop strings))
9948 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
9949 (setq scol (match-string 1 string)
9950 eq (match-string 2 string)
9951 eq-alist (cons (cons scol eq) eq-alist))
9952 (if (member scol seen)
9953 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
9954 (push scol seen))))))
9955 (nreverse eq-alist)))
9956
9957 (defun org-table-modify-formulas (action &rest columns)
9958 "Modify the formulas stored below the current table.
9959 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
9960 expected, for the other actions only a single column number is needed."
9961 (let ((list (org-table-get-stored-formulas))
9962 (nmax (length (org-split-string
9963 (buffer-substring (point-at-bol) (point-at-eol))
9964 "|")))
9965 col col1 col2 scol si sc1 sc2)
9966 (cond
9967 ((null list)) ; No action needed if there are no stored formulas
9968 ((eq action 'remove)
9969 (setq col (car columns)
9970 scol (int-to-string col))
9971 (org-table-replace-in-formulas list scol "INVALID")
9972 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
9973 (loop for i from (1+ col) upto nmax by 1 do
9974 (setq si (int-to-string i))
9975 (org-table-replace-in-formulas list si (int-to-string (1- i)))
9976 (if (assoc si list) (setcar (assoc si list)
9977 (int-to-string (1- i))))))
9978 ((eq action 'insert)
9979 (setq col (car columns))
9980 (loop for i from nmax downto col by 1 do
9981 (setq si (int-to-string i))
9982 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
9983 (if (assoc si list) (setcar (assoc si list)
9984 (int-to-string (1+ i))))))
9985 ((eq action 'swap)
9986 (setq col1 (car columns) col2 (nth 1 columns)
9987 sc1 (int-to-string col1) sc2 (int-to-string col2))
9988 ;; Hopefully, ZqZtZ will never be a name in a table
9989 (org-table-replace-in-formulas list sc1 "ZqZtZ")
9990 (org-table-replace-in-formulas list sc2 sc1)
9991 (org-table-replace-in-formulas list "ZqZtZ" sc2)
9992 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
9993 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
9994 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
9995 (t (error "Invalid action in `org-table-modify-formulas'")))
9996 (if list (org-table-store-formulas list))))
9997
9998 (defun org-table-replace-in-formulas (list s1 s2)
9999 (let (elt re s)
10000 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
10001 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
10002 re (concat (regexp-quote s1) "\\>"))
10003 (while (setq elt (pop list))
10004 (setq s (cdr elt))
10005 (while (string-match re s)
10006 (setq s (replace-match s2 t t s)))
10007 (setcdr elt s))))
10008
10009 (defun org-table-get-specials ()
10010 "Get the column names and local parameters for this table."
10011 (save-excursion
10012 (let ((beg (org-table-begin)) (end (org-table-end))
10013 names name fields fields1 field cnt c v line col)
10014 (setq org-table-column-names nil
10015 org-table-local-parameters nil
10016 org-table-named-field-locations nil)
10017 (goto-char beg)
10018 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
10019 (setq names (org-split-string (match-string 1) " *| *")
10020 cnt 1)
10021 (while (setq name (pop names))
10022 (setq cnt (1+ cnt))
10023 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
10024 (push (cons name (int-to-string cnt)) org-table-column-names))))
10025 (setq org-table-column-names (nreverse org-table-column-names))
10026 (setq org-table-column-name-regexp
10027 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
10028 (goto-char beg)
10029 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
10030 (setq fields (org-split-string (match-string 1) " *| *"))
10031 (while (setq field (pop fields))
10032 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
10033 (push (cons (match-string 1 field) (match-string 2 field))
10034 org-table-local-parameters))))
10035 (goto-char beg)
10036 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
10037 (setq c (match-string 1)
10038 fields (org-split-string (match-string 2) " *| *"))
10039 (save-excursion
10040 (beginning-of-line (if (equal c "_") 2 0))
10041 (setq line (org-current-line) col 1)
10042 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
10043 (setq fields1 (org-split-string (match-string 1) " *| *"))))
10044 (while (and fields1 (setq field (pop fields)))
10045 (setq v (pop fields1) col (1+ col))
10046 (when (and (stringp field) (stringp v)
10047 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
10048 (push (cons field v) org-table-local-parameters)
10049 (push (list field line col) org-table-named-field-locations)))))))
10050
10051 (defun org-this-word ()
10052 ;; Get the current word
10053 (save-excursion
10054 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
10055 (end (progn (skip-chars-forward "^ \t\n") (point))))
10056 (buffer-substring-no-properties beg end))))
10057
10058 (defun org-table-maybe-eval-formula ()
10059 "Check if the current field starts with \"=\" or \":=\".
10060 If yes, store the formula and apply it."
10061 ;; We already know we are in a table. Get field will only return a formula
10062 ;; when appropriate. It might return a separator line, but no problem.
10063 (when org-table-formula-evaluate-inline
10064 (let* ((field (org-trim (or (org-table-get-field) "")))
10065 named eq)
10066 (when (string-match "^:?=\\(.*\\)" field)
10067 (setq named (equal (string-to-char field) ?:)
10068 eq (match-string 1 field))
10069 (if (fboundp 'calc-eval)
10070 (org-table-eval-formula (if named '(4) nil) eq))))))
10071
10072 (defvar org-recalc-commands nil
10073 "List of commands triggering the recalculation of a line.
10074 Will be filled automatically during use.")
10075
10076 (defvar org-recalc-marks
10077 '((" " . "Unmarked: no special line, no automatic recalculation")
10078 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
10079 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
10080 ("!" . "Column name definition line. Reference in formula as $name.")
10081 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
10082 ("_" . "Names for values in row below this one.")
10083 ("^" . "Names for values in row above this one.")))
10084
10085 (defun org-table-rotate-recalc-marks (&optional newchar)
10086 "Rotate the recalculation mark in the first column.
10087 If in any row, the first field is not consistent with a mark,
10088 insert a new column for the markers.
10089 When there is an active region, change all the lines in the region,
10090 after prompting for the marking character.
10091 After each change, a message will be displayed indicating the meaning
10092 of the new mark."
10093 (interactive)
10094 (unless (org-at-table-p) (error "Not at a table"))
10095 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
10096 (beg (org-table-begin))
10097 (end (org-table-end))
10098 (l (org-current-line))
10099 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
10100 (l2 (if (org-region-active-p) (org-current-line (region-end))))
10101 (have-col
10102 (save-excursion
10103 (goto-char beg)
10104 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
10105 (col (org-table-current-column))
10106 (forcenew (car (assoc newchar org-recalc-marks)))
10107 epos new)
10108 (when l1
10109 (message "Change region to what mark? Type # * ! $ or SPC: ")
10110 (setq newchar (char-to-string (read-char-exclusive))
10111 forcenew (car (assoc newchar org-recalc-marks))))
10112 (if (and newchar (not forcenew))
10113 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
10114 newchar))
10115 (if l1 (goto-line l1))
10116 (save-excursion
10117 (beginning-of-line 1)
10118 (unless (looking-at org-table-dataline-regexp)
10119 (error "Not at a table data line")))
10120 (unless have-col
10121 (org-table-goto-column 1)
10122 (org-table-insert-column)
10123 (org-table-goto-column (1+ col)))
10124 (setq epos (point-at-eol))
10125 (save-excursion
10126 (beginning-of-line 1)
10127 (org-table-get-field
10128 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
10129 (concat " "
10130 (setq new (or forcenew
10131 (cadr (member (match-string 1) marks))))
10132 " ")
10133 " # ")))
10134 (if (and l1 l2)
10135 (progn
10136 (goto-line l1)
10137 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
10138 (and (looking-at org-table-dataline-regexp)
10139 (org-table-get-field 1 (concat " " new " "))))
10140 (goto-line l1)))
10141 (if (not (= epos (point-at-eol))) (org-table-align))
10142 (goto-line l)
10143 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
10144
10145 (defun org-table-maybe-recalculate-line ()
10146 "Recompute the current line if marked for it, and if we haven't just done it."
10147 (interactive)
10148 (and org-table-allow-automatic-line-recalculation
10149 (not (and (memq last-command org-recalc-commands)
10150 (equal org-last-recalc-line (org-current-line))))
10151 (save-excursion (beginning-of-line 1)
10152 (looking-at org-table-auto-recalculate-regexp))
10153 (fboundp 'calc-eval)
10154 (org-table-recalculate) t))
10155
10156 (defvar org-table-formula-debug nil
10157 "Non-nil means, debug table formulas.
10158 When nil, simply write \"#ERROR\" in corrupted fields.")
10159
10160 (defvar modes)
10161 (defsubst org-set-calc-mode (var &optional value)
10162 (if (stringp var)
10163 (setq var (assoc var '(("D" calc-angle-mode deg)
10164 ("R" calc-angle-mode rad)
10165 ("F" calc-prefer-frac t)
10166 ("S" calc-symbolic-mode t)))
10167 value (nth 2 var) var (nth 1 var)))
10168 (if (memq var modes)
10169 (setcar (cdr (memq var modes)) value)
10170 (cons var (cons value modes)))
10171 modes)
10172
10173 (defun org-table-eval-formula (&optional arg equation
10174 suppress-align suppress-const
10175 suppress-store)
10176 "Replace the table field value at the cursor by the result of a calculation.
10177
10178 This function makes use of Dave Gillespie's Calc package, in my view the
10179 most exciting program ever written for GNU Emacs. So you need to have Calc
10180 installed in order to use this function.
10181
10182 In a table, this command replaces the value in the current field with the
10183 result of a formula. It also installs the formula as the \"current\" column
10184 formula, by storing it in a special line below the table. When called
10185 with a `C-u' prefix, the current field must ba a named field, and the
10186 formula is installed as valid in only this specific field.
10187
10188 When called, the command first prompts for a formula, which is read in
10189 the minibuffer. Previously entered formulas are available through the
10190 history list, and the last used formula is offered as a default.
10191 These stored formulas are adapted correctly when moving, inserting, or
10192 deleting columns with the corresponding commands.
10193
10194 The formula can be any algebraic expression understood by the Calc package.
10195 For details, see the Org-mode manual.
10196
10197 This function can also be called from Lisp programs and offers
10198 additional arguments: EQUATION can be the formula to apply. If this
10199 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
10200 used to speed-up recursive calls by by-passing unnecessary aligns.
10201 SUPPRESS-CONST suppresses the interpretation of constants in the
10202 formula, assuming that this has been done already outside the function.
10203 SUPPRESS-STORE means the formula should not be stored, either because
10204 it is already stored, or because it is a modified equation that should
10205 not overwrite the stored one."
10206 (interactive "P")
10207 (require 'calc)
10208 (org-table-check-inside-data-field)
10209 (org-table-get-specials)
10210 (let* (fields
10211 (ndown (if (integerp arg) arg 1))
10212 (org-table-automatic-realign nil)
10213 (case-fold-search nil)
10214 (down (> ndown 1))
10215 (formula (if (and equation suppress-store)
10216 equation
10217 (org-table-get-formula equation (equal arg '(4)))))
10218 (n0 (org-table-current-column))
10219 (modes (copy-sequence org-calc-default-modes))
10220 n form fmt x ev orig c)
10221 ;; Parse the format string. Since we have a lot of modes, this is
10222 ;; a lot of work. However, I think calc still uses most of the time.
10223 (if (string-match ";" formula)
10224 (let ((tmp (org-split-string formula ";")))
10225 (setq formula (car tmp)
10226 fmt (concat (cdr (assoc "%" org-table-local-parameters))
10227 (nth 1 tmp)))
10228 (while (string-match "[pnfse]\\(-?[0-9]+\\)" fmt)
10229 (setq c (string-to-char (match-string 1 fmt))
10230 n (string-to-number (or (match-string 1 fmt) "")))
10231 (if (= c ?p) (setq modes (org-set-calc-mode 'calc-internal-prec n))
10232 (setq modes (org-set-calc-mode
10233 'calc-float-format
10234 (list (cdr (assoc c '((?n . float) (?f . fix)
10235 (?s . sci) (?e . eng))))
10236 n))))
10237 (setq fmt (replace-match "" t t fmt)))
10238 (while (string-match "[DRFS]" fmt)
10239 (setq modes (org-set-calc-mode (match-string 0 fmt)))
10240 (setq fmt (replace-match "" t t fmt)))
10241 (unless (string-match "\\S-" fmt)
10242 (setq fmt nil))))
10243 (if (and (not suppress-const) org-table-formula-use-constants)
10244 (setq formula (org-table-formula-substitute-names formula)))
10245 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
10246 (while (> ndown 0)
10247 (setq fields (org-split-string
10248 (buffer-substring
10249 (point-at-bol) (point-at-eol)) " *| *"))
10250 (if org-table-formula-numbers-only
10251 (setq fields (mapcar
10252 (lambda (x) (number-to-string (string-to-number x)))
10253 fields)))
10254 (setq ndown (1- ndown))
10255 (setq form (copy-sequence formula))
10256 ;; Insert the references to fields in same row
10257 (while (string-match "\\$\\([0-9]+\\)?" form)
10258 (setq n (if (match-beginning 1)
10259 (string-to-number (match-string 1 form))
10260 n0)
10261 x (nth (1- n) fields))
10262 (unless x (error "Invalid field specifier \"%s\""
10263 (match-string 0 form)))
10264 (if (equal x "") (setq x "0"))
10265 (setq form (replace-match (concat "(" x ")") t t form)))
10266 ;; Insert ranges in current column
10267 (while (string-match "\\&[-I0-9]+" form)
10268 (setq form (replace-match
10269 (save-match-data
10270 (org-table-get-vertical-vector (match-string 0 form)
10271 nil n0))
10272 t t form)))
10273 (setq ev (calc-eval (cons form modes)
10274 (if org-table-formula-numbers-only 'num)))
10275
10276 (when org-table-formula-debug
10277 (with-output-to-temp-buffer "*Help*"
10278 (princ (format "Substitution history of formula
10279 Orig: %s
10280 $xyz-> %s
10281 $1-> %s\n" orig formula form))
10282 (if (listp ev)
10283 (princ (format " %s^\nError: %s"
10284 (make-string (car ev) ?\-) (nth 1 ev)))
10285 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
10286 ev (or fmt "NONE")
10287 (if fmt (format fmt (string-to-number ev)) ev)))))
10288 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
10289 (unless (and (interactive-p) (not ndown))
10290 (unless (let (inhibit-redisplay)
10291 (y-or-n-p "Debugging Formula. Continue to next? "))
10292 (org-table-align)
10293 (error "Abort"))
10294 (delete-window (get-buffer-window "*Help*"))
10295 (message "")))
10296 (if (listp ev) (setq fmt nil ev "#ERROR"))
10297 (org-table-justify-field-maybe
10298 (if fmt (format fmt (string-to-number ev)) ev))
10299 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
10300 (call-interactively 'org-return)
10301 (setq ndown 0)))
10302 (and down (org-table-maybe-recalculate-line))
10303 (or suppress-align (and org-table-may-need-update
10304 (org-table-align)))))
10305
10306 (defun org-table-recalculate (&optional all noalign)
10307 "Recalculate the current table line by applying all stored formulas.
10308 With prefix arg ALL, do this for all lines in the table."
10309 (interactive "P")
10310 (or (memq this-command org-recalc-commands)
10311 (setq org-recalc-commands (cons this-command org-recalc-commands)))
10312 (unless (org-at-table-p) (error "Not at a table"))
10313 (org-table-get-specials)
10314 (let* ((eqlist (sort (org-table-get-stored-formulas)
10315 (lambda (a b) (string< (car a) (car b)))))
10316 (inhibit-redisplay t)
10317 (line-re org-table-dataline-regexp)
10318 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10319 (thiscol (org-table-current-column))
10320 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
10321 ;; Insert constants in all formulas
10322 (setq eqlist
10323 (mapcar (lambda (x)
10324 (setcdr x (org-table-formula-substitute-names (cdr x)))
10325 x)
10326 eqlist))
10327 ;; Split the equation list
10328 (while (setq eq (pop eqlist))
10329 (if (<= (string-to-char (car eq)) ?9)
10330 (push eq eqlnum)
10331 (push eq eqlname)))
10332 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
10333 (if all
10334 (progn
10335 (setq end (move-marker (make-marker) (1+ (org-table-end))))
10336 (goto-char (setq beg (org-table-begin)))
10337 (if (re-search-forward org-table-calculate-mark-regexp end t)
10338 ;; This is a table with marked lines, only compute selected lines
10339 (setq line-re org-table-recalculate-regexp)
10340 ;; Move forward to the first non-header line
10341 (if (and (re-search-forward org-table-dataline-regexp end t)
10342 (re-search-forward org-table-hline-regexp end t)
10343 (re-search-forward org-table-dataline-regexp end t))
10344 (setq beg (match-beginning 0))
10345 nil))) ;; just leave beg where it is
10346 (setq beg (point-at-bol)
10347 end (move-marker (make-marker) (1+ (point-at-eol)))))
10348 (goto-char beg)
10349 (and all (message "Re-applying formulas to full table..."))
10350 (while (re-search-forward line-re end t)
10351 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
10352 ;; Unprotected line, recalculate
10353 (and all (message "Re-applying formulas to full table...(line %d)"
10354 (setq cnt (1+ cnt))))
10355 (setq org-last-recalc-line (org-current-line))
10356 (setq eql eqlnum)
10357 (while (setq entry (pop eql))
10358 (goto-line org-last-recalc-line)
10359 (org-table-goto-column (string-to-number (car entry)) nil 'force)
10360 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
10361 (goto-line thisline)
10362 (org-table-goto-column thiscol)
10363 (or noalign (and org-table-may-need-update (org-table-align))
10364 (and all (message "Re-applying formulas to %d lines...done" cnt)))
10365 ;; Now do the names fields
10366 (while (setq eq (pop eqlname))
10367 (setq name (car eq)
10368 a (assoc name org-table-named-field-locations))
10369 (when a
10370 (message "Re-applying formula to named field: %s" name)
10371 (goto-line (nth 1 a))
10372 (org-table-goto-column (nth 2 a))
10373 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
10374 ;; back to initial position
10375 (goto-line thisline)
10376 (org-table-goto-column thiscol)
10377 (or noalign (and org-table-may-need-update (org-table-align))
10378 (and all (message "Re-applying formulas...done")))))
10379
10380 (defun org-table-formula-substitute-names (f)
10381 "Replace $const with values in string F."
10382 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
10383 ;; First, check for column names
10384 (while (setq start (string-match org-table-column-name-regexp f start))
10385 (setq start (1+ start))
10386 (setq a (assoc (match-string 1 f) org-table-column-names))
10387 (setq f (replace-match (concat "$" (cdr a)) t t f)))
10388 ;; Expand ranges to vectors
10389 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
10390 (setq n1 (string-to-number (match-string 1 f))
10391 n2 (string-to-number (match-string 2 f))
10392 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
10393 s (concat "[($" (number-to-string (1- nn1)) ")"))
10394 (loop for i from nn1 upto nn2 do
10395 (setq s (concat s ",($" (int-to-string i) ")")))
10396 (setq s (concat s "]"))
10397 (if (< n2 n1) (setq s (concat "rev(" s ")")))
10398 (setq f (replace-match s t t f)))
10399 ;; Parameters and constants
10400 (setq start 0)
10401 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
10402 (setq start (1+ start))
10403 (if (setq a (save-match-data
10404 (org-table-get-constant (match-string 1 f))))
10405 (setq f (replace-match (concat "(" a ")") t t f))))
10406 (if org-table-formula-debug
10407 (put-text-property 0 (length f) :orig-formula f1 f))
10408 f))
10409
10410 (defun org-table-get-constant (const)
10411 "Find the value for a parameter or constant in a formula.
10412 Parameters get priority."
10413 (or (cdr (assoc const org-table-local-parameters))
10414 (cdr (assoc const org-table-formula-constants))
10415 (and (fboundp 'constants-get) (constants-get const))
10416 "#UNDEFINED_NAME"))
10417
10418 (defvar org-edit-formulas-map (make-sparse-keymap))
10419 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
10420 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
10421 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
10422
10423 (defvar org-pos)
10424
10425 (defun org-table-edit-formulas ()
10426 "Edit the formulas of the current table in a separate buffer."
10427 (interactive)
10428 (unless (org-at-table-p)
10429 (error "Not at a table"))
10430 (org-table-get-specials)
10431 (let ((eql (org-table-get-stored-formulas))
10432 (pos (move-marker (make-marker) (point)))
10433 (wc (current-window-configuration))
10434 entry loc s)
10435 (switch-to-buffer-other-window "*Edit Formulas*")
10436 (erase-buffer)
10437 (fundamental-mode)
10438 (set (make-local-variable 'org-pos) pos)
10439 (set (make-local-variable 'org-window-configuration) wc)
10440 (use-local-map org-edit-formulas-map)
10441 (setq s "# Edit formulas and finish with `C-c C-c'.
10442 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
10443 # Use `C-c ?' to get information about $name at point.
10444 # To cancel editing, press `C-c C-q'.\n")
10445 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10446 (insert s)
10447 (while (setq entry (pop eql))
10448 (when (setq loc (assoc (car entry) org-table-named-field-locations))
10449 (setq s (format "# Named formula, referring to column %d in line %d\n"
10450 (nth 2 loc) (nth 1 loc)))
10451 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
10452 (insert s))
10453 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
10454 (remove-text-properties 0 (length s) '(face nil) s)
10455 (insert s))
10456 (goto-char (point-min))
10457 (message "Edit formulas and finish with `C-c C-c'.")))
10458
10459 (defun org-show-variable ()
10460 "Show the location/value of the $ expression at point."
10461 (interactive)
10462 (let (var (pos org-pos) (win (selected-window)) e)
10463 (save-excursion
10464 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
10465 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
10466 (setq var (match-string 1))
10467 (error "No variable at point")))
10468 (cond
10469 ((setq e (assoc var org-table-named-field-locations))
10470 (switch-to-buffer-other-window (marker-buffer pos))
10471 (goto-line (nth 1 e))
10472 (org-table-goto-column (nth 2 e))
10473 (select-window win)
10474 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
10475 ((setq e (assoc var org-table-column-names))
10476 (switch-to-buffer-other-window (marker-buffer pos))
10477 (goto-char pos)
10478 (goto-char (org-table-begin))
10479 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
10480 (org-table-end) t)
10481 (progn
10482 (goto-char (match-beginning 1))
10483 (message "Named column (column %s)" (cdr e)))
10484 (error "Column name not found"))
10485 (select-window win))
10486 ((string-match "^[0-9]$" var)
10487 ;; column number
10488 (switch-to-buffer-other-window (marker-buffer pos))
10489 (goto-char pos)
10490 (goto-char (org-table-begin))
10491 (recenter 1)
10492 (if (re-search-forward org-table-dataline-regexp
10493 (org-table-end) t)
10494 (progn
10495 (goto-char (match-beginning 0))
10496 (org-table-goto-column (string-to-number var))
10497 (message "Column %s" var))
10498 (error "Column name not found"))
10499 (select-window win))
10500 ((setq e (assoc var org-table-local-parameters))
10501 (switch-to-buffer-other-window (marker-buffer pos))
10502 (goto-char pos)
10503 (goto-char (org-table-begin))
10504 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
10505 (progn
10506 (goto-char (match-beginning 1))
10507 (message "Local parameter."))
10508 (error "Parameter not found"))
10509 (select-window win))
10510 (t
10511 (cond
10512 ((setq e (assoc var org-table-formula-constants))
10513 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
10514 ((setq e (and (fboundp 'constants-get) (constants-get var)))
10515 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
10516 (t (error "Undefined name $%s" var)))))))
10517
10518 (defun org-finish-edit-formulas (&optional arg)
10519 "Parse the buffer for formula definitions and install them.
10520 With prefix ARG, apply the new formulas to the table."
10521 (interactive "P")
10522 (let ((pos org-pos) eql)
10523 (goto-char (point-min))
10524 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
10525 (push (cons (match-string 1) (match-string 2)) eql))
10526 (set-window-configuration org-window-configuration)
10527 (select-window (get-buffer-window (marker-buffer pos)))
10528 (goto-char pos)
10529 (unless (org-at-table-p)
10530 (error "Lost table position - cannot install formulae"))
10531 (org-table-store-formulas eql)
10532 (move-marker pos nil)
10533 (kill-buffer "*Edit Formulas*")
10534 (if arg
10535 (org-table-recalculate 'all)
10536 (message "New formulas installed - press C-u C-c C-c to apply."))))
10537
10538 (defun org-abort-edit-formulas ()
10539 "Abort editing formulas, without installing the changes."
10540 (interactive)
10541 (let ((pos org-pos))
10542 (set-window-configuration org-window-configuration)
10543 (select-window (get-buffer-window (marker-buffer pos)))
10544 (goto-char pos)
10545 (message "Formula editing aborted without installing changes")))
10546
10547 ;;; The orgtbl minor mode
10548
10549 ;; Define a minor mode which can be used in other modes in order to
10550 ;; integrate the org-mode table editor.
10551
10552 ;; This is really a hack, because the org-mode table editor uses several
10553 ;; keys which normally belong to the major mode, for example the TAB and
10554 ;; RET keys. Here is how it works: The minor mode defines all the keys
10555 ;; necessary to operate the table editor, but wraps the commands into a
10556 ;; function which tests if the cursor is currently inside a table. If that
10557 ;; is the case, the table editor command is executed. However, when any of
10558 ;; those keys is used outside a table, the function uses `key-binding' to
10559 ;; look up if the key has an associated command in another currently active
10560 ;; keymap (minor modes, major mode, global), and executes that command.
10561 ;; There might be problems if any of the keys used by the table editor is
10562 ;; otherwise used as a prefix key.
10563
10564 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
10565 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
10566 ;; addresses this by checking explicitly for both bindings.
10567
10568 ;; The optimized version (see variable `orgtbl-optimized') takes over
10569 ;; all keys which are bound to `self-insert-command' in the *global map*.
10570 ;; Some modes bind other commands to simple characters, for example
10571 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
10572 ;; active, this binding is ignored inside tables and replaced with a
10573 ;; modified self-insert.
10574
10575 (defvar orgtbl-mode nil
10576 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
10577 table editor in arbitrary modes.")
10578 (make-variable-buffer-local 'orgtbl-mode)
10579
10580 (defvar orgtbl-mode-map (make-keymap)
10581 "Keymap for `orgtbl-mode'.")
10582
10583 ;;;###autoload
10584 (defun turn-on-orgtbl ()
10585 "Unconditionally turn on `orgtbl-mode'."
10586 (orgtbl-mode 1))
10587
10588 ;;;###autoload
10589 (defun orgtbl-mode (&optional arg)
10590 "The `org-mode' table editor as a minor mode for use in other modes."
10591 (interactive)
10592 (if (eq major-mode 'org-mode)
10593 ;; Exit without error, in case some hook functions calls this
10594 ;; by accident in org-mode.
10595 (message "Orgtbl-mode is not useful in org-mode, command ignored")
10596 (setq orgtbl-mode
10597 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
10598 (if orgtbl-mode
10599 (progn
10600 (and (orgtbl-setup) (defun orgtbl-setup () nil))
10601 ;; Make sure we are first in minor-mode-map-alist
10602 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
10603 (and c (setq minor-mode-map-alist
10604 (cons c (delq c minor-mode-map-alist)))))
10605 (set (make-local-variable (quote org-table-may-need-update)) t)
10606 (org-add-hook 'before-change-functions 'org-before-change-function
10607 nil 'local)
10608 (set (make-local-variable 'org-old-auto-fill-inhibit-regexp)
10609 auto-fill-inhibit-regexp)
10610 (set (make-local-variable 'auto-fill-inhibit-regexp)
10611 (if auto-fill-inhibit-regexp
10612 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
10613 "[ \t]*|"))
10614 (org-add-to-invisibility-spec '(org-cwidth))
10615 (easy-menu-add orgtbl-mode-menu)
10616 (run-hooks 'orgtbl-mode-hook))
10617 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
10618 (org-cleanup-narrow-column-properties)
10619 (org-remove-from-invisibility-spec '(org-cwidth))
10620 (remove-hook 'before-change-functions 'org-before-change-function t)
10621 (easy-menu-remove orgtbl-mode-menu)
10622 (force-mode-line-update 'all))))
10623
10624 (defun org-cleanup-narrow-column-properties ()
10625 "Remove all properties related to narrow-column invisibility."
10626 (let ((s 1))
10627 (while (setq s (text-property-any s (point-max)
10628 'display org-narrow-column-arrow))
10629 (remove-text-properties s (1+ s) '(display t)))
10630 (setq s 1)
10631 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
10632 (remove-text-properties s (1+ s) '(org-cwidth t)))
10633 (setq s 1)
10634 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
10635 (remove-text-properties s (1+ s) '(invisible t)))))
10636
10637 ;; Install it as a minor mode.
10638 (put 'orgtbl-mode :included t)
10639 (put 'orgtbl-mode :menu-tag "Org Table Mode")
10640 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
10641
10642 (defun orgtbl-make-binding (fun n &rest keys)
10643 "Create a function for binding in the table minor mode.
10644 FUN is the command to call inside a table. N is used to create a unique
10645 command name. KEYS are keys that should be checked in for a command
10646 to execute outside of tables."
10647 (eval
10648 (list 'defun
10649 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
10650 '(arg)
10651 (concat "In tables, run `" (symbol-name fun) "'.\n"
10652 "Outside of tables, run the binding of `"
10653 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
10654 "'.")
10655 '(interactive "p")
10656 (list 'if
10657 '(org-at-table-p)
10658 (list 'call-interactively (list 'quote fun))
10659 (list 'let '(orgtbl-mode)
10660 (list 'call-interactively
10661 (append '(or)
10662 (mapcar (lambda (k)
10663 (list 'key-binding k))
10664 keys)
10665 '('orgtbl-error))))))))
10666
10667 (defun orgtbl-error ()
10668 "Error when there is no default binding for a table key."
10669 (interactive)
10670 (error "This key is has no function outside tables"))
10671
10672 (defun orgtbl-setup ()
10673 "Setup orgtbl keymaps."
10674 (let ((nfunc 0)
10675 (bindings
10676 (list
10677 '([(meta shift left)] org-table-delete-column)
10678 '([(meta left)] org-table-move-column-left)
10679 '([(meta right)] org-table-move-column-right)
10680 '([(meta shift right)] org-table-insert-column)
10681 '([(meta shift up)] org-table-kill-row)
10682 '([(meta shift down)] org-table-insert-row)
10683 '([(meta up)] org-table-move-row-up)
10684 '([(meta down)] org-table-move-row-down)
10685 '("\C-c\C-w" org-table-cut-region)
10686 '("\C-c\M-w" org-table-copy-region)
10687 '("\C-c\C-y" org-table-paste-rectangle)
10688 '("\C-c-" org-table-insert-hline)
10689 ; '([(shift tab)] org-table-previous-field)
10690 '("\C-m" org-table-next-row)
10691 (list (org-key 'S-return) 'org-table-copy-down)
10692 '([(meta return)] org-table-wrap-region)
10693 '("\C-c\C-q" org-table-wrap-region)
10694 '("\C-c?" org-table-current-column)
10695 '("\C-c " org-table-blank-field)
10696 '("\C-c+" org-table-sum)
10697 '("\C-c=" org-table-eval-formula)
10698 '("\C-c'" org-table-edit-formulas)
10699 '("\C-c`" org-table-edit-field)
10700 '("\C-c*" org-table-recalculate)
10701 '("\C-c|" org-table-create-or-convert-from-region)
10702 '("\C-c^" org-table-sort-lines)
10703 '([(control ?#)] org-table-rotate-recalc-marks)))
10704 elt key fun cmd)
10705 (while (setq elt (pop bindings))
10706 (setq nfunc (1+ nfunc))
10707 (setq key (car elt)
10708 fun (nth 1 elt)
10709 cmd (orgtbl-make-binding fun nfunc key))
10710 (define-key orgtbl-mode-map key cmd))
10711 ;; Special treatment needed for TAB and RET
10712 (define-key orgtbl-mode-map [(return)]
10713 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
10714 (define-key orgtbl-mode-map "\C-m"
10715 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
10716 (define-key orgtbl-mode-map [(tab)]
10717 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
10718 (define-key orgtbl-mode-map "\C-i"
10719 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
10720 (define-key orgtbl-mode-map "\C-i"
10721 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
10722 (define-key orgtbl-mode-map "\C-c\C-c"
10723 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
10724 (when orgtbl-optimized
10725 ;; If the user wants maximum table support, we need to hijack
10726 ;; some standard editing functions
10727 (org-remap orgtbl-mode-map
10728 'self-insert-command 'orgtbl-self-insert-command
10729 'delete-char 'org-delete-char
10730 'delete-backward-char 'org-delete-backward-char)
10731 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
10732 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
10733 '("OrgTbl"
10734 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
10735 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
10736 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
10737 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
10738 "--"
10739 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
10740 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
10741 ["Copy Field from Above"
10742 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
10743 "--"
10744 ("Column"
10745 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
10746 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
10747 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
10748 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
10749 "--"
10750 ["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])
10751 ("Row"
10752 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
10753 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
10754 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
10755 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
10756 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
10757 "--"
10758 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
10759 ("Rectangle"
10760 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
10761 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
10762 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
10763 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
10764 "--"
10765 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
10766 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
10767 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
10768 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
10769 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
10770 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
10771 ["Sum Column/Rectangle" org-table-sum
10772 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
10773 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
10774 ["Debug Formulas"
10775 (setq org-table-formula-debug (not org-table-formula-debug))
10776 :style toggle :selected org-table-formula-debug]
10777 ))
10778 t)
10779
10780 (defun orgtbl-tab (arg)
10781 "Justification and field motion for `orgtbl-mode'."
10782 (interactive "P")
10783 (if arg (org-table-edit-field t)
10784 (org-table-justify-field-maybe)
10785 (org-table-next-field)))
10786
10787 (defun orgtbl-ret ()
10788 "Justification and field motion for `orgtbl-mode'."
10789 (interactive)
10790 (org-table-justify-field-maybe)
10791 (org-table-next-row))
10792
10793 (defun orgtbl-self-insert-command (N)
10794 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
10795 If the cursor is in a table looking at whitespace, the whitespace is
10796 overwritten, and the table is not marked as requiring realignment."
10797 (interactive "p")
10798 (if (and (org-at-table-p)
10799 (or
10800 (and org-table-auto-blank-field
10801 (member last-command
10802 '(orgtbl-hijacker-command-100
10803 orgtbl-hijacker-command-101
10804 orgtbl-hijacker-command-102
10805 orgtbl-hijacker-command-103
10806 orgtbl-hijacker-command-104
10807 orgtbl-hijacker-command-105))
10808 (org-table-blank-field))
10809 t)
10810 (eq N 1)
10811 (looking-at "[^|\n]* +|"))
10812 (let (org-table-may-need-update)
10813 (goto-char (1- (match-end 0)))
10814 (delete-backward-char 1)
10815 (goto-char (match-beginning 0))
10816 (self-insert-command N))
10817 (setq org-table-may-need-update t)
10818 (let (orgtbl-mode)
10819 (call-interactively (key-binding (vector last-input-event))))))
10820
10821 (defun org-force-self-insert (N)
10822 "Needed to enforce self-insert under remapping."
10823 (interactive "p")
10824 (self-insert-command N))
10825
10826 ;;; Exporting
10827
10828 (defconst org-level-max 20)
10829
10830 (defun org-export-find-first-heading-line (list)
10831 "Remove all lines from LIST which are before the first headline."
10832 (let ((orig-list list)
10833 (re (concat "^" outline-regexp)))
10834 (while (and list
10835 (not (string-match re (car list))))
10836 (pop list))
10837 (or list orig-list)))
10838
10839 (defun org-skip-comments (lines)
10840 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
10841 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
10842 (re2 "^\\(\\*+\\)[ \t\n\r]")
10843 rtn line level)
10844 (while (setq line (pop lines))
10845 (cond
10846 ((and (string-match re1 line)
10847 (setq level (- (match-end 1) (match-beginning 1))))
10848 ;; Beginning of a COMMENT subtree. Skip it.
10849 (while (and (setq line (pop lines))
10850 (or (not (string-match re2 line))
10851 (> (- (match-end 1) (match-beginning 1)) level))))
10852 (setq lines (cons line lines)))
10853 ((string-match "^#" line)
10854 ;; an ordinary comment line
10855 )
10856 ((and org-export-table-remove-special-lines
10857 (string-match "^[ \t]*| *[!_^] *|" line))
10858 ;; a special table line that should be removed
10859 )
10860 (t (setq rtn (cons line rtn)))))
10861 (nreverse rtn)))
10862
10863 ;; ASCII
10864
10865 (defconst org-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
10866 "Characters for underlining headings in ASCII export.")
10867
10868 (defconst org-html-entities
10869 '(("nbsp")
10870 ("iexcl")
10871 ("cent")
10872 ("pound")
10873 ("curren")
10874 ("yen")
10875 ("brvbar")
10876 ("sect")
10877 ("uml")
10878 ("copy")
10879 ("ordf")
10880 ("laquo")
10881 ("not")
10882 ("shy")
10883 ("reg")
10884 ("macr")
10885 ("deg")
10886 ("plusmn")
10887 ("sup2")
10888 ("sup3")
10889 ("acute")
10890 ("micro")
10891 ("para")
10892 ("middot")
10893 ("odot"."o")
10894 ("star"."*")
10895 ("cedil")
10896 ("sup1")
10897 ("ordm")
10898 ("raquo")
10899 ("frac14")
10900 ("frac12")
10901 ("frac34")
10902 ("iquest")
10903 ("Agrave")
10904 ("Aacute")
10905 ("Acirc")
10906 ("Atilde")
10907 ("Auml")
10908 ("Aring") ("AA"."&Aring;")
10909 ("AElig")
10910 ("Ccedil")
10911 ("Egrave")
10912 ("Eacute")
10913 ("Ecirc")
10914 ("Euml")
10915 ("Igrave")
10916 ("Iacute")
10917 ("Icirc")
10918 ("Iuml")
10919 ("ETH")
10920 ("Ntilde")
10921 ("Ograve")
10922 ("Oacute")
10923 ("Ocirc")
10924 ("Otilde")
10925 ("Ouml")
10926 ("times")
10927 ("Oslash")
10928 ("Ugrave")
10929 ("Uacute")
10930 ("Ucirc")
10931 ("Uuml")
10932 ("Yacute")
10933 ("THORN")
10934 ("szlig")
10935 ("agrave")
10936 ("aacute")
10937 ("acirc")
10938 ("atilde")
10939 ("auml")
10940 ("aring")
10941 ("aelig")
10942 ("ccedil")
10943 ("egrave")
10944 ("eacute")
10945 ("ecirc")
10946 ("euml")
10947 ("igrave")
10948 ("iacute")
10949 ("icirc")
10950 ("iuml")
10951 ("eth")
10952 ("ntilde")
10953 ("ograve")
10954 ("oacute")
10955 ("ocirc")
10956 ("otilde")
10957 ("ouml")
10958 ("divide")
10959 ("oslash")
10960 ("ugrave")
10961 ("uacute")
10962 ("ucirc")
10963 ("uuml")
10964 ("yacute")
10965 ("thorn")
10966 ("yuml")
10967 ("fnof")
10968 ("Alpha")
10969 ("Beta")
10970 ("Gamma")
10971 ("Delta")
10972 ("Epsilon")
10973 ("Zeta")
10974 ("Eta")
10975 ("Theta")
10976 ("Iota")
10977 ("Kappa")
10978 ("Lambda")
10979 ("Mu")
10980 ("Nu")
10981 ("Xi")
10982 ("Omicron")
10983 ("Pi")
10984 ("Rho")
10985 ("Sigma")
10986 ("Tau")
10987 ("Upsilon")
10988 ("Phi")
10989 ("Chi")
10990 ("Psi")
10991 ("Omega")
10992 ("alpha")
10993 ("beta")
10994 ("gamma")
10995 ("delta")
10996 ("epsilon")
10997 ("varepsilon"."&epsilon;")
10998 ("zeta")
10999 ("eta")
11000 ("theta")
11001 ("iota")
11002 ("kappa")
11003 ("lambda")
11004 ("mu")
11005 ("nu")
11006 ("xi")
11007 ("omicron")
11008 ("pi")
11009 ("rho")
11010 ("sigmaf") ("varsigma"."&sigmaf;")
11011 ("sigma")
11012 ("tau")
11013 ("upsilon")
11014 ("phi")
11015 ("chi")
11016 ("psi")
11017 ("omega")
11018 ("thetasym") ("vartheta"."&thetasym;")
11019 ("upsih")
11020 ("piv")
11021 ("bull") ("bullet"."&bull;")
11022 ("hellip") ("dots"."&hellip;")
11023 ("prime")
11024 ("Prime")
11025 ("oline")
11026 ("frasl")
11027 ("weierp")
11028 ("image")
11029 ("real")
11030 ("trade")
11031 ("alefsym")
11032 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
11033 ("uarr") ("uparrow"."&uarr;")
11034 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
11035 ("darr")("downarrow"."&darr;")
11036 ("harr") ("leftrightarrow"."&harr;")
11037 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
11038 ("lArr") ("Leftarrow"."&lArr;")
11039 ("uArr") ("Uparrow"."&uArr;")
11040 ("rArr") ("Rightarrow"."&rArr;")
11041 ("dArr") ("Downarrow"."&dArr;")
11042 ("hArr") ("Leftrightarrow"."&hArr;")
11043 ("forall")
11044 ("part") ("partial"."&part;")
11045 ("exist") ("exists"."&exist;")
11046 ("empty") ("emptyset"."&empty;")
11047 ("nabla")
11048 ("isin") ("in"."&isin;")
11049 ("notin")
11050 ("ni")
11051 ("prod")
11052 ("sum")
11053 ("minus")
11054 ("lowast") ("ast"."&lowast;")
11055 ("radic")
11056 ("prop") ("proptp"."&prop;")
11057 ("infin") ("infty"."&infin;")
11058 ("ang") ("angle"."&ang;")
11059 ("and") ("vee"."&and;")
11060 ("or") ("wedge"."&or;")
11061 ("cap")
11062 ("cup")
11063 ("int")
11064 ("there4")
11065 ("sim")
11066 ("cong") ("simeq"."&cong;")
11067 ("asymp")("approx"."&asymp;")
11068 ("ne") ("neq"."&ne;")
11069 ("equiv")
11070 ("le")
11071 ("ge")
11072 ("sub") ("subset"."&sub;")
11073 ("sup") ("supset"."&sup;")
11074 ("nsub")
11075 ("sube")
11076 ("supe")
11077 ("oplus")
11078 ("otimes")
11079 ("perp")
11080 ("sdot") ("cdot"."&sdot;")
11081 ("lceil")
11082 ("rceil")
11083 ("lfloor")
11084 ("rfloor")
11085 ("lang")
11086 ("rang")
11087 ("loz") ("Diamond"."&loz;")
11088 ("spades") ("spadesuit"."&spades;")
11089 ("clubs") ("clubsuit"."&clubs;")
11090 ("hearts") ("diamondsuit"."&hearts;")
11091 ("diams") ("diamondsuit"."&diams;")
11092 ("quot")
11093 ("amp")
11094 ("lt")
11095 ("gt")
11096 ("OElig")
11097 ("oelig")
11098 ("Scaron")
11099 ("scaron")
11100 ("Yuml")
11101 ("circ")
11102 ("tilde")
11103 ("ensp")
11104 ("emsp")
11105 ("thinsp")
11106 ("zwnj")
11107 ("zwj")
11108 ("lrm")
11109 ("rlm")
11110 ("ndash")
11111 ("mdash")
11112 ("lsquo")
11113 ("rsquo")
11114 ("sbquo")
11115 ("ldquo")
11116 ("rdquo")
11117 ("bdquo")
11118 ("dagger")
11119 ("Dagger")
11120 ("permil")
11121 ("lsaquo")
11122 ("rsaquo")
11123 ("euro")
11124
11125 ("arccos"."arccos")
11126 ("arcsin"."arcsin")
11127 ("arctan"."arctan")
11128 ("arg"."arg")
11129 ("cos"."cos")
11130 ("cosh"."cosh")
11131 ("cot"."cot")
11132 ("coth"."coth")
11133 ("csc"."csc")
11134 ("deg"."deg")
11135 ("det"."det")
11136 ("dim"."dim")
11137 ("exp"."exp")
11138 ("gcd"."gcd")
11139 ("hom"."hom")
11140 ("inf"."inf")
11141 ("ker"."ker")
11142 ("lg"."lg")
11143 ("lim"."lim")
11144 ("liminf"."liminf")
11145 ("limsup"."limsup")
11146 ("ln"."ln")
11147 ("log"."log")
11148 ("max"."max")
11149 ("min"."min")
11150 ("Pr"."Pr")
11151 ("sec"."sec")
11152 ("sin"."sin")
11153 ("sinh"."sinh")
11154 ("sup"."sup")
11155 ("tan"."tan")
11156 ("tanh"."tanh")
11157 )
11158 "Entities for TeX->HTML translation.
11159 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
11160 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
11161 In that case, \"\\ent\" will be translated to \"&other;\".
11162 The list contains HTML entities for Latin-1, Greek and other symbols.
11163 It is supplemented by a number of commonly used TeX macros with appropriate
11164 translations. There is currently no way for users to extend this.")
11165
11166 (defun org-cleaned-string-for-export (string)
11167 "Cleanup a buffer substring so that links can be created safely."
11168 (interactive)
11169 (let* ((cb (current-buffer))
11170 (re-radio (and org-target-link-regexp
11171 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
11172 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
11173 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
11174 rtn)
11175 (save-excursion
11176 (set-buffer (get-buffer-create " org-mode-tmp"))
11177 (erase-buffer)
11178 (insert string)
11179 (org-mode)
11180 ;; Find targets in comments and move them out of comments,
11181 ;; but mark them as targets that should be invisible
11182 (goto-char (point-min))
11183 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
11184 (replace-match "\\1(INVISIBLE)"))
11185 ;; Find matches for radio targets and turn them into internal links
11186 (goto-char (point-min))
11187 (when re-radio
11188 (while (re-search-forward re-radio nil t)
11189 (replace-match "\\1[[\\2]]")))
11190 ;; Find all links that contain a newline and put them into a single line
11191 (goto-char (point-min))
11192 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
11193 (replace-match "\\1 \\3")
11194 (goto-char (match-beginning 0)))
11195 ;; Normalize links: Convert angle and plain links into bracket links
11196 (goto-char (point-min))
11197 (while (re-search-forward re-plain-link nil t)
11198 (replace-match
11199 (concat
11200 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11201 t t))
11202 (goto-char (point-min))
11203 (while (re-search-forward re-angle-link nil t)
11204 (replace-match
11205 (concat
11206 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
11207 t t))
11208
11209 ;; Remove comments
11210 (goto-char (point-min))
11211 (while (re-search-forward "^#.*\n?" nil t)
11212 (replace-match ""))
11213 (setq rtn (buffer-string)))
11214 (kill-buffer " org-mode-tmp")
11215 rtn))
11216
11217 (defun org-solidify-link-text (s &optional alist)
11218 "Take link text and make a safe target out of it."
11219 (save-match-data
11220 (let* ((rtn
11221 (mapconcat
11222 'identity
11223 (org-split-string s "[ \t\r\n]+") "--"))
11224 (a (assoc rtn alist)))
11225 (or (cdr a) rtn))))
11226
11227 (defun org-convert-to-odd-levels ()
11228 "Convert an org-mode file with all levels allowed to one with odd levels.
11229 This will leave level 1 alone, convert level 2 to level 3, level 3 to
11230 level 5 etc."
11231 (interactive)
11232 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
11233 (let ((org-odd-levels-only nil) n)
11234 (save-excursion
11235 (goto-char (point-min))
11236 (while (re-search-forward "^\\*\\*+" nil t)
11237 (setq n (1- (length (match-string 0))))
11238 (while (>= (setq n (1- n)) 0)
11239 (org-demote))
11240 (end-of-line 1))))))
11241
11242
11243 (defun org-convert-to-oddeven-levels ()
11244 "Convert an org-mode file with only odd levels to one with odd and even levels.
11245 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
11246 section with an even level, conversion would destroy the structure of the file. An error
11247 is signaled in this case."
11248 (interactive)
11249 (goto-char (point-min))
11250 ;; First check if there are no even levels
11251 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
11252 (org-show-hierarchy-above)
11253 (error "Not all levels are odd in this file. Conversion not possible."))
11254 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
11255 (let ((org-odd-levels-only nil) n)
11256 (save-excursion
11257 (goto-char (point-min))
11258 (while (re-search-forward "^\\*\\*+" nil t)
11259 (setq n (/ (length (match-string 0)) 2))
11260 (while (>= (setq n (1- n)) 0)
11261 (org-promote))
11262 (end-of-line 1))))))
11263
11264 (defun org-tr-level (n)
11265 "Make N odd if required."
11266 (if org-odd-levels-only (1+ (/ n 2)) n))
11267
11268 (defvar org-last-level nil) ; dynamically scoped variable
11269
11270 (defun org-export-as-ascii (arg)
11271 "Export the outline as a pretty ASCII file.
11272 If there is an active region, export only the region.
11273 The prefix ARG specifies how many levels of the outline should become
11274 underlined headlines. The default is 3."
11275 (interactive "P")
11276 (setq-default org-todo-line-regexp org-todo-line-regexp)
11277 (let* ((region
11278 (buffer-substring
11279 (if (org-region-active-p) (region-beginning) (point-min))
11280 (if (org-region-active-p) (region-end) (point-max))))
11281 (lines (org-export-find-first-heading-line
11282 (org-skip-comments
11283 (org-split-string
11284 (org-cleaned-string-for-export region)
11285 "[\r\n]"))))
11286 (org-startup-with-deadline-check nil)
11287 (level 0) line txt
11288 (umax nil)
11289 (case-fold-search nil)
11290 (filename (concat (file-name-sans-extension buffer-file-name)
11291 ".txt"))
11292 (buffer (find-file-noselect filename))
11293 (levels-open (make-vector org-level-max nil))
11294 (date (format-time-string "%Y/%m/%d" (current-time)))
11295 (time (format-time-string "%X" (org-current-time)))
11296 (author user-full-name)
11297 (title (buffer-name))
11298 (options nil)
11299 (email user-mail-address)
11300 (language org-export-default-language)
11301 (text nil)
11302 (todo nil)
11303 (lang-words nil))
11304
11305 (setq org-last-level 1)
11306 (org-init-section-numbers)
11307
11308 (find-file-noselect filename)
11309
11310 ;; Search for the export key lines
11311 (org-parse-key-lines)
11312
11313 (setq lang-words (or (assoc language org-export-language-setup)
11314 (assoc "en" org-export-language-setup)))
11315 (if org-export-ascii-show-new-buffer
11316 (switch-to-buffer-other-window buffer)
11317 (set-buffer buffer))
11318 (erase-buffer)
11319 (fundamental-mode)
11320 (if options (org-parse-export-options options))
11321 (setq umax (if arg (prefix-numeric-value arg)
11322 org-export-headline-levels))
11323
11324 ;; File header
11325 (if title (org-insert-centered title ?=))
11326 (insert "\n")
11327 (if (or author email)
11328 (insert (concat (nth 1 lang-words) ": " (or author "")
11329 (if email (concat " <" email ">") "")
11330 "\n")))
11331 (if (and date time)
11332 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
11333 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
11334
11335 (insert "\n\n")
11336
11337 (if org-export-with-toc
11338 (progn
11339 (insert (nth 3 lang-words) "\n"
11340 (make-string (length (nth 3 lang-words)) ?=) "\n")
11341 (mapcar '(lambda (line)
11342 (if (string-match org-todo-line-regexp
11343 line)
11344 ;; This is a headline
11345 (progn
11346 (setq level (- (match-end 1) (match-beginning 1))
11347 level (org-tr-level level)
11348 txt (match-string 3 line)
11349 todo
11350 (or (and (match-beginning 2)
11351 (not (equal (match-string 2 line)
11352 org-done-string)))
11353 ; TODO, not DONE
11354 (and org-export-mark-todo-in-toc
11355 (= level umax)
11356 (org-search-todo-below
11357 line lines level))))
11358 (setq txt (org-html-expand-for-ascii txt))
11359
11360 (if org-export-with-section-numbers
11361 (setq txt (concat (org-section-number level)
11362 " " txt)))
11363 (if (<= level umax)
11364 (progn
11365 (insert
11366 (make-string (* (1- level) 4) ?\ )
11367 (format (if todo "%s (*)\n" "%s\n") txt))
11368 (setq org-last-level level))
11369 ))))
11370 lines)))
11371
11372 (org-init-section-numbers)
11373 (while (setq line (pop lines))
11374 ;; Remove the quoted HTML tags.
11375 (setq line (org-html-expand-for-ascii line))
11376 ;; Remove targets
11377 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
11378 (setq line (replace-match "" t t line)))
11379 ;; Replace internal links
11380 (while (string-match org-bracket-link-regexp line)
11381 (setq line (replace-match
11382 (if (match-end 3) "[\\3]" "[\\1]")
11383 t nil line)))
11384 (cond
11385 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11386 ;; a Headline
11387 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11388 txt (match-string 2 line))
11389 (org-ascii-level-start level txt umax))
11390 (t (insert line "\n"))))
11391 (normal-mode)
11392 (save-buffer)
11393 (goto-char (point-min))))
11394
11395 (defun org-search-todo-below (line lines level)
11396 "Search the subtree below LINE for any TODO entries."
11397 (let ((rest (cdr (memq line lines)))
11398 (re org-todo-line-regexp)
11399 line lv todo)
11400 (catch 'exit
11401 (while (setq line (pop rest))
11402 (if (string-match re line)
11403 (progn
11404 (setq lv (- (match-end 1) (match-beginning 1))
11405 todo (and (match-beginning 2)
11406 (not (equal (match-string 2 line)
11407 org-done-string))))
11408 ; TODO, not DONE
11409 (if (<= lv level) (throw 'exit nil))
11410 (if todo (throw 'exit t))))))))
11411
11412 ;; FIXME: Try to handle <b> and <i> as faces via text properties.
11413 ;; We could also implement *bold*,/italic/ and _underline_ for ASCII export
11414 (defun org-html-expand-for-ascii (line)
11415 "Handle quoted HTML for ASCII export."
11416 (if org-export-html-expand
11417 (while (string-match "@<[^<>\n]*>" line)
11418 ;; We just remove the tags for now.
11419 (setq line (replace-match "" nil nil line))))
11420 line)
11421
11422 (defun org-insert-centered (s &optional underline)
11423 "Insert the string S centered and underline it with character UNDERLINE."
11424 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
11425 (insert (make-string ind ?\ ) s "\n")
11426 (if underline
11427 (insert (make-string ind ?\ )
11428 (make-string (string-width s) underline)
11429 "\n"))))
11430
11431 (defun org-ascii-level-start (level title umax)
11432 "Insert a new level in ASCII export."
11433 (let (char)
11434 (if (> level umax)
11435 (insert (make-string (* 2 (- level umax 1)) ?\ ) "* " title "\n")
11436 (if (or (not (equal (char-before) ?\n))
11437 (not (equal (char-before (1- (point))) ?\n)))
11438 (insert "\n"))
11439 (setq char (nth (- umax level) (reverse org-ascii-underline)))
11440 (if org-export-with-section-numbers
11441 (setq title (concat (org-section-number level) " " title)))
11442 (insert title "\n" (make-string (string-width title) char) "\n"))))
11443
11444 (defun org-export-copy-visible ()
11445 "Copy the visible part of the buffer to another buffer, for printing.
11446 Also removes the first line of the buffer if it specifies a mode,
11447 and all options lines."
11448 (interactive)
11449 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
11450 ".txt"))
11451 (buffer (find-file-noselect filename))
11452 (ore (concat
11453 (org-make-options-regexp
11454 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
11455 "STARTUP" "ARCHIVE"
11456 "TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE"))
11457 (if org-noutline-p "\\(\n\\|$\\)" "")))
11458 s e)
11459 (with-current-buffer buffer
11460 (erase-buffer)
11461 (text-mode))
11462 (save-excursion
11463 (setq s (goto-char (point-min)))
11464 (while (not (= (point) (point-max)))
11465 (goto-char (org-find-invisible))
11466 (append-to-buffer buffer s (point))
11467 (setq s (goto-char (org-find-visible)))))
11468 (switch-to-buffer-other-window buffer)
11469 (newline)
11470 (goto-char (point-min))
11471 (if (looking-at ".*-\\*- mode:.*\n")
11472 (replace-match ""))
11473 (while (re-search-forward ore nil t)
11474 (replace-match ""))
11475 (goto-char (point-min))))
11476
11477 (defun org-find-visible ()
11478 (if (featurep 'noutline)
11479 (let ((s (point)))
11480 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11481 (get-char-property s 'invisible)))
11482 s)
11483 (skip-chars-forward "^\n")
11484 (point)))
11485 (defun org-find-invisible ()
11486 (if (featurep 'noutline)
11487 (let ((s (point)))
11488 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
11489 (not (get-char-property s 'invisible))))
11490 s)
11491 (skip-chars-forward "^\r")
11492 (point)))
11493
11494 ;; HTML
11495
11496 (defun org-get-current-options ()
11497 "Return a string with current options as keyword options.
11498 Does include HTML export options as well as TODO and CATEGORY stuff."
11499 (format
11500 "#+TITLE: %s
11501 #+AUTHOR: %s
11502 #+EMAIL: %s
11503 #+LANGUAGE: %s
11504 #+TEXT: Some descriptive text to be emitted. Several lines OK.
11505 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s
11506 #+CATEGORY: %s
11507 #+SEQ_TODO: %s
11508 #+TYP_TODO: %s
11509 #+STARTUP: %s %s %s %s %s
11510 #+ARCHIVE: %s
11511 "
11512 (buffer-name) (user-full-name) user-mail-address org-export-default-language
11513 org-export-headline-levels
11514 org-export-with-section-numbers
11515 org-export-with-toc
11516 org-export-preserve-breaks
11517 org-export-html-expand
11518 org-export-with-fixed-width
11519 org-export-with-tables
11520 org-export-with-sub-superscripts
11521 org-export-with-emphasize
11522 org-export-with-TeX-macros
11523 (file-name-nondirectory buffer-file-name)
11524 (if (equal org-todo-interpretation 'sequence)
11525 (mapconcat 'identity org-todo-keywords " ")
11526 "TODO FEEDBACK VERIFY DONE")
11527 (if (equal org-todo-interpretation 'type)
11528 (mapconcat 'identity org-todo-keywords " ")
11529 "Me Jason Marie DONE")
11530 (cdr (assoc org-startup-folded
11531 '((nil . "showall") (t . "overview") (content . "content"))))
11532 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
11533 (if org-odd-levels-only "odd" "oddeven")
11534 (if org-hide-leading-stars "hidestars" "showstars")
11535 (if org-startup-align-all-tables "align" "noalign")
11536 org-archive-location
11537 ))
11538
11539 (defun org-insert-export-options-template ()
11540 "Insert into the buffer a template with information for exporting."
11541 (interactive)
11542 (if (not (bolp)) (newline))
11543 (let ((s (org-get-current-options)))
11544 (and (string-match "#\\+CATEGORY" s)
11545 (setq s (substring s 0 (match-beginning 0))))
11546 (insert s)))
11547
11548 (defun org-toggle-fixed-width-section (arg)
11549 "Toggle the fixed-width export.
11550 If there is no active region, the QUOTE keyword at the current headline is
11551 inserted or removed. When present, it causes the text between this headline
11552 and the next to be exported as fixed-width text, and unmodified.
11553 If there is an active region, this command adds or removes a colon as the
11554 first character of this line. If the first character of a line is a colon,
11555 this line is also exported in fixed-width font."
11556 (interactive "P")
11557 (let* ((cc 0)
11558 (regionp (org-region-active-p))
11559 (beg (if regionp (region-beginning) (point)))
11560 (end (if regionp (region-end)))
11561 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
11562 (re "[ \t]*\\(:\\)")
11563 off)
11564 (if regionp
11565 (save-excursion
11566 (goto-char beg)
11567 (setq cc (current-column))
11568 (beginning-of-line 1)
11569 (setq off (looking-at re))
11570 (while (> nlines 0)
11571 (setq nlines (1- nlines))
11572 (beginning-of-line 1)
11573 (cond
11574 (arg
11575 (move-to-column cc t)
11576 (insert ":\n")
11577 (forward-line -1))
11578 ((and off (looking-at re))
11579 (replace-match "" t t nil 1))
11580 ((not off) (move-to-column cc t) (insert ":")))
11581 (forward-line 1)))
11582 (save-excursion
11583 (org-back-to-heading)
11584 (if (looking-at (concat outline-regexp
11585 "\\( +\\<" org-quote-string "\\>\\)"))
11586 (replace-match "" t t nil 1)
11587 (if (looking-at outline-regexp)
11588 (progn
11589 (goto-char (match-end 0))
11590 (insert " " org-quote-string))))))))
11591
11592 (defun org-export-as-html-and-open (arg)
11593 "Export the outline as HTML and immediately open it with a browser.
11594 If there is an active region, export only the region.
11595 The prefix ARG specifies how many levels of the outline should become
11596 headlines. The default is 3. Lower levels will become bulleted lists."
11597 (interactive "P")
11598 (org-export-as-html arg 'hidden)
11599 (org-open-file buffer-file-name))
11600
11601 (defun org-export-as-html-batch ()
11602 "Call `org-export-as-html', may be used in batch processing as
11603 emacs --batch
11604 --load=$HOME/lib/emacs/org.el
11605 --eval \"(setq org-export-headline-levels 2)\"
11606 --visit=MyFile --funcall org-export-as-html-batch"
11607 (org-export-as-html org-export-headline-levels 'hidden))
11608
11609 (defun org-export-as-html (arg &optional hidden)
11610 "Export the outline as a pretty HTML file.
11611 If there is an active region, export only the region.
11612 The prefix ARG specifies how many levels of the outline should become
11613 headlines. The default is 3. Lower levels will become bulleted lists."
11614 (interactive "P")
11615 (setq-default org-todo-line-regexp org-todo-line-regexp)
11616 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
11617 (setq-default org-done-string org-done-string)
11618 (let* ((style org-export-html-style)
11619 (odd org-odd-levels-only)
11620 (region-p (org-region-active-p))
11621 (region
11622 (buffer-substring
11623 (if region-p (region-beginning) (point-min))
11624 (if region-p (region-end) (point-max))))
11625 (all_lines
11626 (org-skip-comments (org-split-string
11627 (org-cleaned-string-for-export region)
11628 "[\r\n]")))
11629 (lines (org-export-find-first-heading-line all_lines))
11630 (level 0) (line "") (origline "") txt todo
11631 (umax nil)
11632 (filename (concat (file-name-sans-extension buffer-file-name)
11633 ".html"))
11634 (buffer (find-file-noselect filename))
11635 (levels-open (make-vector org-level-max nil))
11636 (date (format-time-string "%Y/%m/%d" (current-time)))
11637 (time (format-time-string "%X" (org-current-time)))
11638 (author user-full-name)
11639 (title (buffer-name))
11640 (options nil)
11641 (quote-re (concat "^\\*+[ \t]*" org-quote-string "\\>"))
11642 (inquote nil)
11643 (infixed nil)
11644 (in-local-list nil)
11645 (local-list-num nil)
11646 (local-list-indent nil)
11647 (llt org-plain-list-ordered-item-terminator)
11648 (email user-mail-address)
11649 (language org-export-default-language)
11650 (text nil)
11651 (lang-words nil)
11652 (target-alist nil) tg
11653 (head-count 0) cnt
11654 (start 0)
11655 ;; FIXME: The following returns always nil under XEmacs
11656 (coding-system (and (fboundp 'coding-system-get)
11657 (boundp 'buffer-file-coding-system)
11658 buffer-file-coding-system))
11659 (coding-system-for-write (or coding-system coding-system-for-write))
11660 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
11661 (charset (and coding-system
11662 (coding-system-get coding-system 'mime-charset)))
11663 table-open type
11664 table-buffer table-orig-buffer
11665 ind start-is-num starter
11666 rpl path desc desc1 desc2 link
11667 )
11668 (message "Exporting...")
11669
11670 (setq org-last-level 1)
11671 (org-init-section-numbers)
11672
11673 ;; Search for the export key lines
11674 (org-parse-key-lines)
11675 (setq lang-words (or (assoc language org-export-language-setup)
11676 (assoc "en" org-export-language-setup)))
11677
11678 ;; Switch to the output buffer
11679 (if (or hidden (not org-export-html-show-new-buffer))
11680 (set-buffer buffer)
11681 (switch-to-buffer-other-window buffer))
11682 (erase-buffer)
11683 (fundamental-mode)
11684 (let ((case-fold-search nil)
11685 (org-odd-levels-only odd))
11686 (if options (org-parse-export-options options))
11687 (setq umax (if arg (prefix-numeric-value arg)
11688 org-export-headline-levels))
11689
11690 ;; File header
11691 (insert (format
11692 "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\"
11693 \"http://www.w3.org/TR/REC-html40/loose.dtd\">
11694 <html lang=\"%s\"><head>
11695 <title>%s</title>
11696 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\">
11697 <meta name=generator content=\"Org-mode\">
11698 <meta name=generated content=\"%s %s\">
11699 <meta name=author content=\"%s\">
11700 %s
11701 </head><body>
11702 "
11703 language (org-html-expand title) (or charset "iso-8859-1")
11704 date time author style))
11705 (if title (insert (concat "<H1 class=\"title\">"
11706 (org-html-expand title) "</H1>\n")))
11707 (if author (insert (concat (nth 1 lang-words) ": " author "\n")))
11708 (if email (insert (concat "<a href=\"mailto:" email "\">&lt;"
11709 email "&gt;</a>\n")))
11710 (if (or author email) (insert "<br>\n"))
11711 (if (and date time) (insert (concat (nth 2 lang-words) ": "
11712 date " " time "<br>\n")))
11713 (if text (insert (concat "<p>\n" (org-html-expand text))))
11714 (if org-export-with-toc
11715 (progn
11716 (insert (format "<H2>%s</H2>\n" (nth 3 lang-words)))
11717 (insert "<ul>\n")
11718 (setq lines
11719 (mapcar '(lambda (line)
11720 (if (string-match org-todo-line-regexp line)
11721 ;; This is a headline
11722 (progn
11723 (setq level (- (match-end 1) (match-beginning 1))
11724 level (org-tr-level level)
11725 txt (save-match-data
11726 (org-html-expand
11727 (match-string 3 line)))
11728 todo
11729 (or (and (match-beginning 2)
11730 (not (equal (match-string 2 line)
11731 org-done-string)))
11732 ; TODO, not DONE
11733 (and org-export-mark-todo-in-toc
11734 (= level umax)
11735 (org-search-todo-below
11736 line lines level))))
11737 (if org-export-with-section-numbers
11738 (setq txt (concat (org-section-number level)
11739 " " txt)))
11740 (if (<= level umax)
11741 (progn
11742 (setq head-count (+ head-count 1))
11743 (if (> level org-last-level)
11744 (progn
11745 (setq cnt (- level org-last-level))
11746 (while (>= (setq cnt (1- cnt)) 0)
11747 (insert "<ul>"))
11748 (insert "\n")))
11749 (if (< level org-last-level)
11750 (progn
11751 (setq cnt (- org-last-level level))
11752 (while (>= (setq cnt (1- cnt)) 0)
11753 (insert "</ul>"))
11754 (insert "\n")))
11755 ;; Check for targets
11756 (while (string-match org-target-regexp line)
11757 (setq tg (match-string 1 line)
11758 line (replace-match
11759 (concat "@<span class=\"target\">" tg "@</span> ")
11760 t t line))
11761 (push (cons (org-solidify-link-text tg)
11762 (format "sec-%d" head-count))
11763 target-alist))
11764 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
11765 (setq txt (replace-match "" t t txt)))
11766 (insert
11767 (format
11768 (if todo
11769 "<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>\n"
11770 "<li><a href=\"#sec-%d\">%s</a>\n")
11771 head-count txt))
11772
11773 (setq org-last-level level))
11774 )))
11775 line)
11776 lines))
11777 (while (> org-last-level 0)
11778 (setq org-last-level (1- org-last-level))
11779 (insert "</ul>\n"))
11780 ))
11781 (setq head-count 0)
11782 (org-init-section-numbers)
11783
11784 (while (setq line (pop lines) origline line)
11785 (catch 'nextline
11786
11787 ;; end of quote section?
11788 (when (and inquote (string-match "^\\*+" line))
11789 (insert "</pre>\n")
11790 (setq inquote nil))
11791 ;; inside a quote section?
11792 (when inquote
11793 (insert (org-html-protect line) "\n")
11794 (throw 'nextline nil))
11795
11796 ;; verbatim lines
11797 (when (and org-export-with-fixed-width
11798 (string-match "^[ \t]*:\\(.*\\)" line))
11799 (when (not infixed)
11800 (setq infixed t)
11801 (insert "<pre>\n"))
11802 (insert (org-html-protect (match-string 1 line)) "\n")
11803 (when (and lines
11804 (not (string-match "^[ \t]*\\(:.*\\)"
11805 (car lines))))
11806 (setq infixed nil)
11807 (insert "</pre>\n"))
11808 (throw 'nextline nil))
11809
11810
11811 ;; make targets to anchors
11812 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
11813 (cond
11814 ((match-end 2)
11815 (setq line (replace-match
11816 (concat "@<a name=\""
11817 (org-solidify-link-text (match-string 1 line))
11818 "\">\\nbsp@</a>")
11819 t t line)))
11820 ((and org-export-with-toc (equal (string-to-char line) ?*))
11821 (setq line (replace-match
11822 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
11823 ; (concat "@<i>" (match-string 1 line) "@</i> ")
11824 t t line)))
11825 (t
11826 (setq line (replace-match
11827 (concat "@<a name=\""
11828 (org-solidify-link-text (match-string 1 line))
11829 "\" class=\"target\">" (match-string 1 line) "@</a> ")
11830 t t line)))))
11831
11832 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
11833 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
11834 (setq line (org-html-expand line))
11835
11836 ;; Format the links
11837 (setq start 0)
11838 (while (string-match org-bracket-link-analytic-regexp line start)
11839 (setq start (match-beginning 0))
11840 (setq type (if (match-end 2) (match-string 2 line) "internal"))
11841 (setq path (match-string 3 line))
11842 (setq desc1 (if (match-end 5) (match-string 5 line))
11843 desc2 (if (match-end 2) (concat type ":" path) path)
11844 desc (or desc1 desc2))
11845 (cond
11846 ((equal type "internal")
11847 (setq rpl
11848 (concat
11849 "<a href=\"#"
11850 (org-solidify-link-text path target-alist)
11851 "\">" desc "</a>")))
11852 ((member type '("http" "https" "ftp" "mailto" "news"))
11853 ;; standard URL
11854 (setq link (concat type ":" path))
11855 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
11856 ((string= type "file")
11857 ;; FILE link
11858 (let* ((filename path)
11859 (abs-p (file-name-absolute-p filename))
11860 thefile file-is-image-p search)
11861 (save-match-data
11862 (if (string-match "::\\(.*\\)" filename)
11863 (setq search (match-string 1 filename)
11864 filename (replace-match "" nil nil filename)))
11865 (setq file-is-image-p
11866 (string-match (org-image-file-name-regexp) filename))
11867 (setq thefile (if abs-p (expand-file-name filename) filename))
11868 (when (and org-export-html-link-org-files-as-html
11869 (string-match "\\.org$" thefile))
11870 (setq thefile (concat (substring thefile 0
11871 (match-beginning 0))
11872 ".html"))
11873 (if (and search
11874 ;; make sure this is can be used as target search
11875 (not (string-match "^[0-9]*$" search))
11876 (not (string-match "^\\*" search))
11877 (not (string-match "^/.*/$" search)))
11878 (setq thefile (concat thefile "#"
11879 (org-solidify-link-text
11880 (org-link-unescape search)))))))
11881 (setq rpl (if (and org-export-html-inline-images
11882 file-is-image-p)
11883 (concat "<img src=\"" thefile "\"/>")
11884 (concat "<a href=\"" thefile "\">" desc "</a>")))))
11885 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell"))
11886 (setq rpl (concat "<i>&lt;" type ":"
11887 (save-match-data (org-link-unescape path))
11888 "&gt;</i>"))))
11889 (setq line (replace-match rpl t t line)
11890 start (+ start (length rpl))))
11891 ;; TODO items
11892 (if (and (string-match org-todo-line-regexp line)
11893 (match-beginning 2))
11894 (if (equal (match-string 2 line) org-done-string)
11895 (setq line (replace-match
11896 "<span class=\"done\">\\2</span>"
11897 nil nil line 2))
11898 (setq line (replace-match "<span class=\"todo\">\\2</span>"
11899 nil nil line 2))))
11900
11901 ;; DEADLINES
11902 (if (string-match org-deadline-line-regexp line)
11903 (progn
11904 (if (save-match-data
11905 (string-match "<a href"
11906 (substring line 0 (match-beginning 0))))
11907 nil ; Don't do the replacement - it is inside a link
11908 (setq line (replace-match "<span class=\"deadline\">\\&</span>"
11909 nil nil line 1)))))
11910 (cond
11911 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
11912 ;; This is a headline
11913 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
11914 txt (match-string 2 line))
11915 (if (<= level umax) (setq head-count (+ head-count 1)))
11916 (when in-local-list
11917 ;; Close any local lists before inserting a new header line
11918 (while local-list-num
11919 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11920 (pop local-list-num))
11921 (setq local-list-indent nil
11922 in-local-list nil))
11923 (org-html-level-start level txt umax
11924 (and org-export-with-toc (<= level umax))
11925 head-count)
11926 ;; QUOTES
11927 (when (string-match quote-re line)
11928 (insert "<pre>")
11929 (setq inquote t)))
11930
11931 ((and org-export-with-tables
11932 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
11933 (if (not table-open)
11934 ;; New table starts
11935 (setq table-open t table-buffer nil table-orig-buffer nil))
11936 ;; Accumulate lines
11937 (setq table-buffer (cons line table-buffer)
11938 table-orig-buffer (cons origline table-orig-buffer))
11939 (when (or (not lines)
11940 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
11941 (car lines))))
11942 (setq table-open nil
11943 table-buffer (nreverse table-buffer)
11944 table-orig-buffer (nreverse table-orig-buffer))
11945 (insert (org-format-table-html table-buffer table-orig-buffer))))
11946 (t
11947 ;; Normal lines
11948 (when (and (string-match
11949 (cond
11950 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+[.)]\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11951 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+\\.\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11952 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*]\\)\\|\\([0-9]+)\\)\\)?\\( +[^ \t\n\r]\\|[ \t]*$\\)")
11953 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
11954 line))
11955 (setq ind (org-get-string-indentation line)
11956 start-is-num (match-beginning 4)
11957 starter (if (match-beginning 2) (match-string 2 line))
11958 line (substring line (match-beginning 5)))
11959 (unless (string-match "[^ \t]" line)
11960 ;; empty line. Pretend indentation is large.
11961 (setq ind (1+ (or (car local-list-indent) 1))))
11962 (while (and in-local-list
11963 (or (and (= ind (car local-list-indent))
11964 (not starter))
11965 (< ind (car local-list-indent))))
11966 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
11967 (pop local-list-num) (pop local-list-indent)
11968 (setq in-local-list local-list-indent))
11969 (cond
11970 ((and starter
11971 (or (not in-local-list)
11972 (> ind (car local-list-indent))))
11973 ;; Start new (level of ) list
11974 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
11975 (push start-is-num local-list-num)
11976 (push ind local-list-indent)
11977 (setq in-local-list t))
11978 (starter
11979 ;; continue current list
11980 (insert "<li>\n"))))
11981 ;; Empty lines start a new paragraph. If hand-formatted lists
11982 ;; are not fully interpreted, lines starting with "-", "+", "*"
11983 ;; also start a new paragraph.
11984 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (insert "<p>"))
11985 (insert line (if org-export-preserve-breaks "<br>\n" "\n"))))
11986 ))
11987 (if org-export-html-with-timestamp
11988 (insert org-export-html-html-helper-timestamp))
11989 (insert "</body>\n</html>\n")
11990 (normal-mode)
11991 (save-buffer)
11992 (goto-char (point-min)))))
11993
11994 (defun org-format-table-html (lines olines)
11995 "Find out which HTML converter to use and return the HTML code."
11996 (if (string-match "^[ \t]*|" (car lines))
11997 ;; A normal org table
11998 (org-format-org-table-html lines)
11999 ;; Table made by table.el - test for spanning
12000 (let* ((hlines (delq nil (mapcar
12001 (lambda (x)
12002 (if (string-match "^[ \t]*\\+-" x) x
12003 nil))
12004 lines)))
12005 (first (car hlines))
12006 (ll (and (string-match "\\S-+" first)
12007 (match-string 0 first)))
12008 (re (concat "^[ \t]*" (regexp-quote ll)))
12009 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
12010 hlines))))
12011 (if (and (not spanning)
12012 (not org-export-prefer-native-exporter-for-tables))
12013 ;; We can use my own converter with HTML conversions
12014 (org-format-table-table-html lines)
12015 ;; Need to use the code generator in table.el, with the original text.
12016 (org-format-table-table-html-using-table-generate-source olines)))))
12017
12018 (defun org-format-org-table-html (lines)
12019 "Format a table into HTML."
12020 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
12021 (setq lines (nreverse lines))
12022 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
12023 (setq lines (nreverse lines))
12024 (when org-export-table-remove-special-lines
12025 ;; Check if the table has a marking column. If yes remove the
12026 ;; column and the special lines
12027 (let* ((special
12028 (not
12029 (memq nil
12030 (mapcar
12031 (lambda (x)
12032 (or (string-match "^[ \t]*|-" x)
12033 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
12034 lines)))))
12035 (if special
12036 (setq lines
12037 (delq nil
12038 (mapcar
12039 (lambda (x)
12040 (if (string-match "^[ \t]*| *[!_^] *|" x)
12041 nil ; ignore this line
12042 (and (or (string-match "^[ \t]*|-+\\+" x)
12043 (string-match "^[ \t]*|[^|]*|" x))
12044 (replace-match "|" t t x))))
12045 lines))))))
12046
12047 (let ((head (and org-export-highlight-first-table-line
12048 (delq nil (mapcar
12049 (lambda (x) (string-match "^[ \t]*|-" x))
12050 (cdr lines)))))
12051 line fields html)
12052 (setq html (concat org-export-html-table-tag "\n"))
12053 (while (setq line (pop lines))
12054 (catch 'next-line
12055 (if (string-match "^[ \t]*|-" line)
12056 (progn
12057 (setq head nil) ;; head ends here, first time around
12058 ;; ignore this line
12059 (throw 'next-line t)))
12060 ;; Break the line into fields
12061 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
12062 (setq html (concat
12063 html
12064 "<tr>"
12065 (mapconcat (lambda (x)
12066 (if head
12067 (concat "<th>" x "</th>")
12068 (concat "<td>" x "</td>")))
12069 fields "")
12070 "</tr>\n"))))
12071 (setq html (concat html "</table>\n"))
12072 html))
12073
12074 (defun org-fake-empty-table-line (line)
12075 "Replace everything except \"|\" with spaces."
12076 (let ((i (length line))
12077 (newstr (copy-sequence line)))
12078 (while (> i 0)
12079 (setq i (1- i))
12080 (if (not (eq (aref newstr i) ?|))
12081 (aset newstr i ?\ )))
12082 newstr))
12083
12084 (defun org-format-table-table-html (lines)
12085 "Format a table generated by table.el into HTML.
12086 This conversion does *not* use `table-generate-source' from table.el.
12087 This has the advantage that Org-mode's HTML conversions can be used.
12088 But it has the disadvantage, that no cell- or row-spanning is allowed."
12089 (let (line field-buffer
12090 (head org-export-highlight-first-table-line)
12091 fields html empty)
12092 (setq html (concat org-export-html-table-tag "\n"))
12093 (while (setq line (pop lines))
12094 (setq empty "&nbsp")
12095 (catch 'next-line
12096 (if (string-match "^[ \t]*\\+-" line)
12097 (progn
12098 (if field-buffer
12099 (progn
12100 (setq html (concat
12101 html
12102 "<tr>"
12103 (mapconcat
12104 (lambda (x)
12105 (if (equal x "") (setq x empty))
12106 (if head
12107 (concat "<th>" x "</th>\n")
12108 (concat "<td>" x "</td>\n")))
12109 field-buffer "\n")
12110 "</tr>\n"))
12111 (setq head nil)
12112 (setq field-buffer nil)))
12113 ;; Ignore this line
12114 (throw 'next-line t)))
12115 ;; Break the line into fields and store the fields
12116 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
12117 (if field-buffer
12118 (setq field-buffer (mapcar
12119 (lambda (x)
12120 (concat x "<br>" (pop fields)))
12121 field-buffer))
12122 (setq field-buffer fields))))
12123 (setq html (concat html "</table>\n"))
12124 html))
12125
12126 (defun org-format-table-table-html-using-table-generate-source (lines)
12127 "Format a table into html, using `table-generate-source' from table.el.
12128 This has the advantage that cell- or row-spanning is allowed.
12129 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
12130 (require 'table)
12131 (with-current-buffer (get-buffer-create " org-tmp1 ")
12132 (erase-buffer)
12133 (insert (mapconcat 'identity lines "\n"))
12134 (goto-char (point-min))
12135 (if (not (re-search-forward "|[^+]" nil t))
12136 (error "Error processing table"))
12137 (table-recognize-table)
12138 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
12139 (table-generate-source 'html " org-tmp2 ")
12140 (set-buffer " org-tmp2 ")
12141 (buffer-substring (point-min) (point-max))))
12142
12143 (defun org-html-protect (s)
12144 ;; convert & to &amp;, < to &lt; and > to &gt;
12145 (let ((start 0))
12146 (while (string-match "&" s start)
12147 (setq s (replace-match "&amp;" t t s)
12148 start (1+ (match-beginning 0))))
12149 (while (string-match "<" s)
12150 (setq s (replace-match "&lt;" t t s)))
12151 (while (string-match ">" s)
12152 (setq s (replace-match "&gt;" t t s))))
12153 s)
12154
12155 (defun org-html-expand (string)
12156 "Prepare STRING for HTML export. Applies all active conversions.
12157 If there are links in the string, don't modify these."
12158 (let* (m s l res)
12159 (while (setq m (string-match org-bracket-link-regexp string))
12160 (setq s (substring string 0 m)
12161 l (match-string 0 string)
12162 string (substring string (match-end 0)))
12163 (push (org-html-do-expand s) res)
12164 (push l res))
12165 (push (org-html-do-expand string) res)
12166 (apply 'concat (nreverse res))))
12167
12168 (defun org-html-do-expand (s)
12169 "Apply all active conversions to translate special ASCII to HTML."
12170 (setq s (org-html-protect s))
12171 (if org-export-html-expand
12172 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
12173 (setq s (replace-match "<\\1>" nil nil s))))
12174 (if org-export-with-emphasize
12175 (setq s (org-export-html-convert-emphasize s)))
12176 (if org-export-with-sub-superscripts
12177 (setq s (org-export-html-convert-sub-super s)))
12178 (if org-export-with-TeX-macros
12179 (let ((start 0) wd ass)
12180 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
12181 (setq wd (match-string 1 s))
12182 (if (setq ass (assoc wd org-html-entities))
12183 (setq s (replace-match (or (cdr ass)
12184 (concat "&" (car ass) ";"))
12185 t t s))
12186 (setq start (+ start (length wd)))))))
12187 s)
12188
12189 (defun org-create-multibrace-regexp (left right n)
12190 "Create a regular expression which will match a balanced sexp.
12191 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
12192 as single character strings.
12193 The regexp returned will match the entire expression including the
12194 delimiters. It will also define a single group which contains the
12195 match except for the outermost delimiters. The maximum depth of
12196 stacked delimiters is N. Escaping delimiters is not possible."
12197 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
12198 (or "\\|")
12199 (re nothing)
12200 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
12201 (while (> n 1)
12202 (setq n (1- n)
12203 re (concat re or next)
12204 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
12205 (concat left "\\(" re "\\)" right)))
12206
12207 (defvar org-match-substring-regexp
12208 (concat
12209 "\\([^\\]\\)\\([_^]\\)\\("
12210 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
12211 "\\|"
12212 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
12213 "\\|"
12214 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
12215 "The regular expression matching a sub- or superscript.")
12216
12217 (defun org-export-html-convert-sub-super (string)
12218 "Convert sub- and superscripts in STRING to HTML."
12219 (let (key c)
12220 (while (string-match org-match-substring-regexp string)
12221 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
12222 (setq c (or (match-string 8 string)
12223 (match-string 6 string)
12224 (match-string 5 string)))
12225 (setq string (replace-match
12226 (concat (match-string 1 string)
12227 "<" key ">" c "</" key ">")
12228 t t string)))
12229 (while (string-match "\\\\\\([_^]\\)" string)
12230 (setq string (replace-match (match-string 1 string) t t string))))
12231 string)
12232
12233 (defun org-export-html-convert-emphasize (string)
12234 (while (string-match org-italic-re string)
12235 (setq string (replace-match "\\1<i>\\3</i>\\4" t nil string)))
12236 (while (string-match org-bold-re string)
12237 (setq string (replace-match "\\1<b>\\3</b>\\4" t nil string)))
12238 (while (string-match org-underline-re string)
12239 (setq string (replace-match "\\1<u>\\3</u>\\4" t nil string)))
12240 string)
12241
12242 (defun org-parse-key-lines ()
12243 "Find the special key lines with the information for exporters."
12244 (save-excursion
12245 (goto-char 0)
12246 (let ((re (org-make-options-regexp
12247 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12248 key)
12249 (while (re-search-forward re nil t)
12250 (setq key (match-string 1))
12251 (cond ((string-equal key "TITLE")
12252 (setq title (match-string 2)))
12253 ((string-equal key "AUTHOR")
12254 (setq author (match-string 2)))
12255 ((string-equal key "EMAIL")
12256 (setq email (match-string 2)))
12257 ((string-equal key "LANGUAGE")
12258 (setq language (match-string 2)))
12259 ((string-equal key "TEXT")
12260 (setq text (concat text "\n" (match-string 2))))
12261 ((string-equal key "OPTIONS")
12262 (setq options (match-string 2))))))))
12263
12264 (defun org-parse-export-options (s)
12265 "Parse the export options line."
12266 (let ((op '(("H" . org-export-headline-levels)
12267 ("num" . org-export-with-section-numbers)
12268 ("toc" . org-export-with-toc)
12269 ("\\n" . org-export-preserve-breaks)
12270 ("@" . org-export-html-expand)
12271 (":" . org-export-with-fixed-width)
12272 ("|" . org-export-with-tables)
12273 ("^" . org-export-with-sub-superscripts)
12274 ("*" . org-export-with-emphasize)
12275 ("TeX" . org-export-with-TeX-macros)))
12276 o)
12277 (while (setq o (pop op))
12278 (if (string-match (concat (regexp-quote (car o)) ":\\([^ \t\n\r;,.]*\\)")
12279 s)
12280 (set (make-local-variable (cdr o))
12281 (car (read-from-string (match-string 1 s))))))))
12282
12283 (defun org-html-level-start (level title umax with-toc head-count)
12284 "Insert a new level in HTML export."
12285 (let ((l (1+ (max level umax))))
12286 (while (<= l org-level-max)
12287 (if (aref levels-open (1- l))
12288 (progn
12289 (org-html-level-close l)
12290 (aset levels-open (1- l) nil)))
12291 (setq l (1+ l)))
12292 (if (> level umax)
12293 (progn
12294 (if (aref levels-open (1- level))
12295 (insert "<li>" title "<p>\n")
12296 (aset levels-open (1- level) t)
12297 (insert "<ul><li>" title "<p>\n")))
12298 (if org-export-with-section-numbers
12299 (setq title (concat (org-section-number level) " " title)))
12300 (setq level (+ level 1))
12301 (if with-toc
12302 (insert (format "\n<H%d><a name=\"sec-%d\">%s</a></H%d>\n"
12303 level head-count title level))
12304 (insert (format "\n<H%d>%s</H%d>\n" level title level))))))
12305
12306 (defun org-html-level-close (&rest args)
12307 "Terminate one level in HTML export."
12308 (insert "</ul>"))
12309
12310 ;; Variable holding the vector with section numbers
12311 (defvar org-section-numbers (make-vector org-level-max 0))
12312
12313 (defun org-init-section-numbers ()
12314 "Initialize the vector for the section numbers."
12315 (let* ((level -1)
12316 (numbers (nreverse (org-split-string "" "\\.")))
12317 (depth (1- (length org-section-numbers)))
12318 (i depth) number-string)
12319 (while (>= i 0)
12320 (if (> i level)
12321 (aset org-section-numbers i 0)
12322 (setq number-string (or (car numbers) "0"))
12323 (if (string-match "\\`[A-Z]\\'" number-string)
12324 (aset org-section-numbers i
12325 (- (string-to-char number-string) ?A -1))
12326 (aset org-section-numbers i (string-to-number number-string)))
12327 (pop numbers))
12328 (setq i (1- i)))))
12329
12330 (defun org-section-number (&optional level)
12331 "Return a string with the current section number.
12332 When LEVEL is non-nil, increase section numbers on that level."
12333 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
12334 (when level
12335 (when (> level -1)
12336 (aset org-section-numbers
12337 level (1+ (aref org-section-numbers level))))
12338 (setq idx (1+ level))
12339 (while (<= idx depth)
12340 (if (not (= idx 1))
12341 (aset org-section-numbers idx 0))
12342 (setq idx (1+ idx))))
12343 (setq idx 0)
12344 (while (<= idx depth)
12345 (setq n (aref org-section-numbers idx))
12346 (setq string (concat string (if (not (string= string "")) "." "")
12347 (int-to-string n)))
12348 (setq idx (1+ idx)))
12349 (save-match-data
12350 (if (string-match "\\`\\([@0]\\.\\)+" string)
12351 (setq string (replace-match "" nil nil string)))
12352 (if (string-match "\\(\\.0\\)+\\'" string)
12353 (setq string (replace-match "" nil nil string))))
12354 string))
12355
12356
12357 (defun org-export-icalendar-this-file ()
12358 "Export current file as an iCalendar file.
12359 The iCalendar file will be located in the same directory as the Org-mode
12360 file, but with extension `.ics'."
12361 (interactive)
12362 (org-export-icalendar nil buffer-file-name))
12363
12364 (defun org-export-as-xml ()
12365 "Export current buffer as XOXO XML buffer."
12366 (interactive)
12367 (cond ((eq org-export-xml-type 'xoxo)
12368 (org-export-as-xoxo (current-buffer)))))
12369
12370 (defun org-export-as-xoxo-insert-into (buffer &rest output)
12371 (with-current-buffer buffer
12372 (apply 'insert output)))
12373
12374 (defun org-export-as-xoxo (&optional buffer)
12375 "Export the org buffer as XOXO.
12376 The XOXO buffer is named *xoxo-<source buffer name>*"
12377 (interactive (list (current-buffer)))
12378 ;; A quickie abstraction
12379
12380 ;; Output everything as XOXO
12381 (with-current-buffer (get-buffer buffer)
12382 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
12383 (let* ((filename (concat (file-name-sans-extension buffer-file-name)
12384 ".xml"))
12385 (out (find-file-noselect filename))
12386 (last-level 1)
12387 (hanging-li nil))
12388 ;; Check the output buffer is empty.
12389 (with-current-buffer out (erase-buffer))
12390 ;; Kick off the output
12391 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
12392 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
12393 (let* ((hd (match-string-no-properties 1))
12394 (level (length hd))
12395 (text (concat
12396 (match-string-no-properties 2)
12397 (save-excursion
12398 (goto-char (match-end 0))
12399 (let ((str ""))
12400 (catch 'loop
12401 (while 't
12402 (forward-line)
12403 (if (looking-at "^[ \t]\\(.*\\)")
12404 (setq str (concat str (match-string-no-properties 1)))
12405 (throw 'loop str)))))))))
12406
12407 ;; Handle level rendering
12408 (cond
12409 ((> level last-level)
12410 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
12411
12412 ((< level last-level)
12413 (dotimes (- (- last-level level) 1)
12414 (if hanging-li
12415 (org-export-as-xoxo-insert-into out "</li>\n"))
12416 (org-export-as-xoxo-insert-into out "</ol>\n"))
12417 (when hanging-li
12418 (org-export-as-xoxo-insert-into out "</li>\n")
12419 (setq hanging-li nil)))
12420
12421 ((equal level last-level)
12422 (if hanging-li
12423 (org-export-as-xoxo-insert-into out "</li>\n")))
12424 )
12425
12426 (setq last-level level)
12427
12428 ;; And output the new li
12429 (setq hanging-li 't)
12430 (if (equal ?+ (elt text 0))
12431 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
12432 (org-export-as-xoxo-insert-into out "<li>" text))))
12433
12434 ;; Finally finish off the ol
12435 (dotimes (- last-level 1)
12436 (if hanging-li
12437 (org-export-as-xoxo-insert-into out "</li>\n"))
12438 (org-export-as-xoxo-insert-into out "</ol>\n"))
12439
12440 ;; Finish the buffer off and clean it up.
12441 (switch-to-buffer-other-window out)
12442 (indent-region (point-min) (point-max) nil)
12443 (save-buffer)
12444 (goto-char (point-min))
12445 )))
12446
12447 ;;;###autoload
12448 (defun org-export-icalendar-all-agenda-files ()
12449 "Export all files in `org-agenda-files' to iCalendar .ics files.
12450 Each iCalendar file will be located in the same directory as the Org-mode
12451 file, but with extension `.ics'."
12452 (interactive)
12453 (apply 'org-export-icalendar nil (org-agenda-files t)))
12454
12455 ;;;###autoload
12456 (defun org-export-icalendar-combine-agenda-files ()
12457 "Export all files in `org-agenda-files' to a single combined iCalendar file.
12458 The file is stored under the name `org-combined-agenda-icalendar-file'."
12459 (interactive)
12460 (apply 'org-export-icalendar t (org-agenda-files t)))
12461
12462 (defun org-export-icalendar (combine &rest files)
12463 "Create iCalendar files for all elements of FILES.
12464 If COMBINE is non-nil, combine all calendar entries into a single large
12465 file and store it under the name `org-combined-agenda-icalendar-file'."
12466 (save-excursion
12467 (let* (file ical-file ical-buffer category started org-agenda-new-buffers)
12468 (when combine
12469 (setq ical-file org-combined-agenda-icalendar-file
12470 ical-buffer (org-get-agenda-file-buffer ical-file))
12471 (set-buffer ical-buffer) (erase-buffer))
12472 (while (setq file (pop files))
12473 (catch 'nextfile
12474 (org-check-agenda-file file)
12475 (unless combine
12476 (setq ical-file (concat (file-name-sans-extension file) ".ics"))
12477 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
12478 (set-buffer ical-buffer) (erase-buffer))
12479 (set-buffer (org-get-agenda-file-buffer file))
12480 (setq category (or org-category
12481 (file-name-sans-extension
12482 (file-name-nondirectory buffer-file-name))))
12483 (if (symbolp category) (setq category (symbol-name category)))
12484 (let ((standard-output ical-buffer))
12485 (if combine
12486 (and (not started) (setq started t)
12487 (org-start-icalendar-file org-icalendar-combined-name))
12488 (org-start-icalendar-file category))
12489 (org-print-icalendar-entries combine category)
12490 (when (or (and combine (not files)) (not combine))
12491 (org-finish-icalendar-file)
12492 (set-buffer ical-buffer)
12493 (save-buffer)
12494 (run-hooks 'org-after-save-iCalendar-file-hook)))))
12495 (org-release-buffers org-agenda-new-buffers))))
12496
12497 (defvar org-after-save-iCalendar-file-hook nil
12498 "Hook run after an iCalendar file has been saved.
12499 The iCalendar buffer is still current when this hook is run.
12500 A good way to use this is to tell a desktop calenndar application to re-read
12501 the iCalendar file.")
12502
12503 (defun org-print-icalendar-entries (&optional combine category)
12504 "Print iCalendar entries for the current Org-mode file to `standard-output'.
12505 When COMBINE is non nil, add the category to each line."
12506 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
12507 (dts (org-ical-ts-to-string
12508 (format-time-string (cdr org-time-stamp-formats) (current-time))
12509 "DTSTART"))
12510 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
12511 (save-excursion
12512 (goto-char (point-min))
12513 (while (re-search-forward org-ts-regexp nil t)
12514 (setq pos (match-beginning 0)
12515 ts (match-string 0)
12516 inc t
12517 hd (org-get-heading))
12518 (if (looking-at re2)
12519 (progn
12520 (goto-char (match-end 0))
12521 (setq ts2 (match-string 1) inc nil))
12522 (setq ts2 ts
12523 tmp (buffer-substring (max (point-min)
12524 (- pos org-ds-keyword-length))
12525 pos)
12526 deadlinep (string-match org-deadline-regexp tmp)
12527 scheduledp (string-match org-scheduled-regexp tmp)
12528 ;; donep (org-entry-is-done-p)
12529 ))
12530 (if (or (string-match org-tr-regexp hd)
12531 (string-match org-ts-regexp hd))
12532 (setq hd (replace-match "" t t hd)))
12533 (if combine
12534 (setq hd (concat hd " (category " category ")")))
12535 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
12536 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
12537 (princ (format "BEGIN:VEVENT
12538 %s
12539 %s
12540 SUMMARY:%s
12541 END:VEVENT\n"
12542 (org-ical-ts-to-string ts "DTSTART")
12543 (org-ical-ts-to-string ts2 "DTEND" inc)
12544 hd)))
12545 (when org-icalendar-include-todo
12546 (goto-char (point-min))
12547 (while (re-search-forward org-todo-line-regexp nil t)
12548 (setq state (match-string 1))
12549 (unless (equal state org-done-string)
12550 (setq hd (match-string 3))
12551 (if (string-match org-priority-regexp hd)
12552 (setq pri (string-to-char (match-string 2 hd))
12553 hd (concat (substring hd 0 (match-beginning 1))
12554 (substring hd (- (match-end 1)))))
12555 (setq pri org-default-priority))
12556 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
12557 (- org-lowest-priority ?A))))))
12558
12559 (princ (format "BEGIN:VTODO
12560 %s
12561 SUMMARY:%s
12562 SEQUENCE:1
12563 PRIORITY:%d
12564 END:VTODO\n"
12565 dts hd pri))))))))
12566
12567 (defun org-start-icalendar-file (name)
12568 "Start an iCalendar file by inserting the header."
12569 (let ((user user-full-name)
12570 (name (or name "unknown"))
12571 (timezone (cadr (current-time-zone))))
12572 (princ
12573 (format "BEGIN:VCALENDAR
12574 VERSION:2.0
12575 X-WR-CALNAME:%s
12576 PRODID:-//%s//Emacs with Org-mode//EN
12577 X-WR-TIMEZONE:%s
12578 CALSCALE:GREGORIAN\n" name user timezone))))
12579
12580 (defun org-finish-icalendar-file ()
12581 "Finish an iCalendar file by inserting the END statement."
12582 (princ "END:VCALENDAR\n"))
12583
12584 (defun org-ical-ts-to-string (s keyword &optional inc)
12585 "Take a time string S and convert it to iCalendar format.
12586 KEYWORD is added in front, to make a complete line like DTSTART....
12587 When INC is non-nil, increase the hour by two (if time string contains
12588 a time), or the day by one (if it does not contain a time)."
12589 (let ((t1 (org-parse-time-string s 'nodefault))
12590 t2 fmt have-time time)
12591 (if (and (car t1) (nth 1 t1) (nth 2 t1))
12592 (setq t2 t1 have-time t)
12593 (setq t2 (org-parse-time-string s)))
12594 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
12595 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
12596 (when inc
12597 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
12598 (setq time (encode-time s mi h d m y)))
12599 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
12600 (concat keyword (format-time-string fmt time))))
12601
12602
12603 ;;; Key bindings
12604
12605 ;; - Bindings in Org-mode map are currently
12606 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
12607 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
12608 ;; e (?) useful from outline-mode
12609 ;; i k @ expendable from outline-mode
12610 ;; 0123456789 % & ()_{} " ` free
12611
12612 ;; Make `C-c C-x' a prefix key
12613 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
12614
12615 ;; TAB key with modifiers
12616 (define-key org-mode-map "\C-i" 'org-cycle)
12617 (define-key org-mode-map [(tab)] 'org-cycle)
12618 (define-key org-mode-map [(meta tab)] 'org-complete)
12619 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
12620 ;; The following line is necessary under Suse GNU/Linux
12621 (unless (featurep 'xemacs)
12622 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
12623 (define-key org-mode-map [(shift tab)] 'org-shifttab)
12624
12625 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
12626 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
12627 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12628 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
12629 (define-key org-mode-map [(meta return)] 'org-meta-return)
12630 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
12631 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
12632
12633 ;; Cursor keys with modifiers
12634 (define-key org-mode-map [(meta left)] 'org-metaleft)
12635 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
12636 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
12637 (define-key org-mode-map [(meta right)] 'org-metaright)
12638 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
12639 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
12640 (define-key org-mode-map [(meta up)] 'org-metaup)
12641 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
12642 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
12643 (define-key org-mode-map [(meta down)] 'org-metadown)
12644 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
12645 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
12646
12647 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12648 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
12649 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
12650 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
12651 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
12652 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
12653 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
12654 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
12655 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
12656 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
12657 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
12658 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
12659 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
12660 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
12661 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
12662 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
12663
12664 ;; All the other keys
12665
12666 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12667 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
12668 (define-key org-mode-map "\C-c\C-j" 'org-goto)
12669 (define-key org-mode-map "\C-c\C-t" 'org-todo)
12670 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
12671 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
12672 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
12673 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12674 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
12675 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
12676 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12677 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
12678 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
12679 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
12680 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
12681 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
12682 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
12683 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
12684 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12685 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12686 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12687 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12688 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
12689 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
12690 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12691 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
12692 (define-key org-mode-map "\C-c]" 'org-remove-file)
12693 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
12694 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
12695 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
12696 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12697 (define-key org-mode-map "\C-m" 'org-return)
12698 (define-key org-mode-map "\C-c?" 'org-table-current-column)
12699 (define-key org-mode-map "\C-c " 'org-table-blank-field)
12700 (define-key org-mode-map "\C-c+" 'org-table-sum)
12701 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
12702 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
12703 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
12704 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12705 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
12706 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12707 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
12708 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12709 (define-key org-mode-map "\C-c\C-xa" 'org-export-as-ascii)
12710 (define-key org-mode-map "\C-c\C-x\C-a" 'org-export-as-ascii)
12711 (define-key org-mode-map "\C-c\C-xv" 'org-export-copy-visible)
12712 (define-key org-mode-map "\C-c\C-x\C-v" 'org-export-copy-visible)
12713 ;; OPML support is only an option for the future
12714 ;(define-key org-mode-map "\C-c\C-xo" 'org-export-as-opml)
12715 ;(define-key org-mode-map "\C-c\C-x\C-o" 'org-export-as-opml)
12716 (define-key org-mode-map "\C-c\C-xi" 'org-export-icalendar-this-file)
12717 (define-key org-mode-map "\C-c\C-x\C-i" 'org-export-icalendar-all-agenda-files)
12718 (define-key org-mode-map "\C-c\C-xc" 'org-export-icalendar-combine-agenda-files)
12719 (define-key org-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
12720 (define-key org-mode-map "\C-c\C-xt" 'org-insert-export-options-template)
12721 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12722 (define-key org-mode-map "\C-c\C-xh" 'org-export-as-html)
12723 (define-key org-mode-map "\C-c\C-xx" 'org-export-as-xml)
12724 (define-key org-mode-map "\C-c\C-x\C-x" 'org-export-as-xml)
12725 (define-key org-mode-map "\C-c\C-xb" 'org-export-as-html-and-open)
12726 (define-key org-mode-map "\C-c\C-x\C-b" 'org-export-as-html-and-open)
12727
12728 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
12729 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12730 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12731 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12732
12733 (defsubst org-table-p () (org-at-table-p))
12734
12735 (defun org-self-insert-command (N)
12736 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12737 If the cursor is in a table looking at whitespace, the whitespace is
12738 overwritten, and the table is not marked as requiring realignment."
12739 (interactive "p")
12740 (if (and (org-table-p)
12741 (progn
12742 ;; check if we blank the field, and if that triggers align
12743 (and org-table-auto-blank-field
12744 (member last-command
12745 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12746 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12747 ;; got extra space, this field does not determine column width
12748 (let (org-table-may-need-update) (org-table-blank-field))
12749 ;; no extra space, this field may determine column width
12750 (org-table-blank-field)))
12751 t)
12752 (eq N 1)
12753 (looking-at "[^|\n]* |"))
12754 (let (org-table-may-need-update)
12755 (goto-char (1- (match-end 0)))
12756 (delete-backward-char 1)
12757 (goto-char (match-beginning 0))
12758 (self-insert-command N))
12759 (setq org-table-may-need-update t)
12760 (self-insert-command N)))
12761
12762 (defun org-delete-backward-char (N)
12763 "Like `delete-backward-char', insert whitespace at field end in tables.
12764 When deleting backwards, in tables this function will insert whitespace in
12765 front of the next \"|\" separator, to keep the table aligned. The table will
12766 still be marked for re-alignment if the field did fill the entire column,
12767 because, in this case the deletion might narrow the column."
12768 (interactive "p")
12769 (if (and (org-table-p)
12770 (eq N 1)
12771 (string-match "|" (buffer-substring (point-at-bol) (point)))
12772 (looking-at ".*?|"))
12773 (let ((pos (point))
12774 (noalign (looking-at "[^|\n\r]* |"))
12775 (c org-table-may-need-update))
12776 (backward-delete-char N)
12777 (skip-chars-forward "^|")
12778 (insert " ")
12779 (goto-char (1- pos))
12780 ;; noalign: if there were two spaces at the end, this field
12781 ;; does not determine the width of the column.
12782 (if noalign (setq org-table-may-need-update c)))
12783 (backward-delete-char N)))
12784
12785 (defun org-delete-char (N)
12786 "Like `delete-char', but insert whitespace at field end in tables.
12787 When deleting characters, in tables this function will insert whitespace in
12788 front of the next \"|\" separator, to keep the table aligned. The table will
12789 still be marked for re-alignment if the field did fill the entire column,
12790 because, in this case the deletion might narrow the column."
12791 (interactive "p")
12792 (if (and (org-table-p)
12793 (not (bolp))
12794 (not (= (char-after) ?|))
12795 (eq N 1))
12796 (if (looking-at ".*?|")
12797 (let ((pos (point))
12798 (noalign (looking-at "[^|\n\r]* |"))
12799 (c org-table-may-need-update))
12800 (replace-match (concat
12801 (substring (match-string 0) 1 -1)
12802 " |"))
12803 (goto-char pos)
12804 ;; noalign: if there were two spaces at the end, this field
12805 ;; does not determine the width of the column.
12806 (if noalign (setq org-table-may-need-update c))))
12807 (delete-char N)))
12808
12809 ;; How to do this: Measure non-white length of current string
12810 ;; If equal to column width, we should realign.
12811
12812 (defun org-remap (map &rest commands)
12813 "In MAP, remap the functions given in COMMANDS.
12814 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12815 (let (new old)
12816 (while commands
12817 (setq old (pop commands) new (pop commands))
12818 (if (fboundp 'command-remapping)
12819 (define-key map (vector 'remap old) new)
12820 (substitute-key-definition old new map global-map)))))
12821
12822 (when (eq org-enable-table-editor 'optimized)
12823 ;; If the user wants maximum table support, we need to hijack
12824 ;; some standard editing functions
12825 (org-remap org-mode-map
12826 'self-insert-command 'org-self-insert-command
12827 'delete-char 'org-delete-char
12828 'delete-backward-char 'org-delete-backward-char)
12829 (define-key org-mode-map "|" 'org-force-self-insert))
12830
12831 (defun org-shiftcursor-error ()
12832 "Throw an error because Shift-Cursor command was applied in wrong context."
12833 (error "This command is active in special context like tables, headlines or timestamps"))
12834
12835 (defun org-shifttab ()
12836 "Global visibility cycling or move to previous table field.
12837 Calls `(org-cycle t)' or `org-table-previous-field', depending on context.
12838 See the individual commands for more information."
12839 (interactive)
12840 (cond
12841 ((org-at-table-p) (org-table-previous-field))
12842 (t (org-cycle '(4)))))
12843
12844 (defun org-shiftmetaleft ()
12845 "Promote subtree or delete table column.
12846 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
12847 See the individual commands for more information."
12848 (interactive)
12849 (cond
12850 ((org-at-table-p) (org-table-delete-column))
12851 ((org-on-heading-p) (org-promote-subtree))
12852 ((org-at-item-p) (call-interactively 'org-outdent-item))
12853 (t (org-shiftcursor-error))))
12854
12855 (defun org-shiftmetaright ()
12856 "Demote subtree or insert table column.
12857 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
12858 See the individual commands for more information."
12859 (interactive)
12860 (cond
12861 ((org-at-table-p) (org-table-insert-column))
12862 ((org-on-heading-p) (org-demote-subtree))
12863 ((org-at-item-p) (call-interactively 'org-indent-item))
12864 (t (org-shiftcursor-error))))
12865
12866 (defun org-shiftmetaup (&optional arg)
12867 "Move subtree up or kill table row.
12868 Calls `org-move-subtree-up' or `org-table-kill-row' or
12869 `org-move-item-up' depending on context. See the individual commands
12870 for more information."
12871 (interactive "P")
12872 (cond
12873 ((org-at-table-p) (org-table-kill-row))
12874 ((org-on-heading-p) (org-move-subtree-up arg))
12875 ((org-at-item-p) (org-move-item-up arg))
12876 (t (org-shiftcursor-error))))
12877 (defun org-shiftmetadown (&optional arg)
12878 "Move subtree down or insert table row.
12879 Calls `org-move-subtree-down' or `org-table-insert-row' or
12880 `org-move-item-down', depending on context. See the individual
12881 commands for more information."
12882 (interactive "P")
12883 (cond
12884 ((org-at-table-p) (org-table-insert-row arg))
12885 ((org-on-heading-p) (org-move-subtree-down arg))
12886 ((org-at-item-p) (org-move-item-down arg))
12887 (t (org-shiftcursor-error))))
12888
12889 (defun org-metaleft (&optional arg)
12890 "Promote heading or move table column to left.
12891 Calls `org-do-promote' or `org-table-move-column', depending on context.
12892 With no specific context, calls the Emacs default `backward-word'.
12893 See the individual commands for more information."
12894 (interactive "P")
12895 (cond
12896 ((org-at-table-p) (org-table-move-column 'left))
12897 ((or (org-on-heading-p) (org-region-active-p)) (org-do-promote))
12898 (t (backward-word (prefix-numeric-value arg)))))
12899
12900 (defun org-metaright (&optional arg)
12901 "Demote subtree or move table column to right.
12902 Calls `org-do-demote' or `org-table-move-column', depending on context.
12903 With no specific context, calls the Emacs default `forward-word'.
12904 See the individual commands for more information."
12905 (interactive "P")
12906 (cond
12907 ((org-at-table-p) (org-table-move-column nil))
12908 ((or (org-on-heading-p) (org-region-active-p)) (org-do-demote))
12909 (t (forward-word (prefix-numeric-value arg)))))
12910
12911 (defun org-metaup (&optional arg)
12912 "Move subtree up or move table row up.
12913 Calls `org-move-subtree-up' or `org-table-move-row' or
12914 `org-move-item-up', depending on context. See the individual commands
12915 for more information."
12916 (interactive "P")
12917 (cond
12918 ((org-at-table-p) (org-table-move-row 'up))
12919 ((org-on-heading-p) (org-move-subtree-up arg))
12920 ((org-at-item-p) (org-move-item-up arg))
12921 (t (org-shiftcursor-error))))
12922
12923 (defun org-metadown (&optional arg)
12924 "Move subtree down or move table row down.
12925 Calls `org-move-subtree-down' or `org-table-move-row' or
12926 `org-move-item-down', depending on context. See the individual
12927 commands for more information."
12928 (interactive "P")
12929 (cond
12930 ((org-at-table-p) (org-table-move-row nil))
12931 ((org-on-heading-p) (org-move-subtree-down arg))
12932 ((org-at-item-p) (org-move-item-down arg))
12933 (t (org-shiftcursor-error))))
12934
12935 (defun org-shiftup (&optional arg)
12936 "Increase item in timestamp or increase priority of current item.
12937 Calls `org-timestamp-up' or `org-priority-up', depending on context.
12938 See the individual commands for more information."
12939 (interactive "P")
12940 (cond
12941 ((org-at-timestamp-p) (org-timestamp-up arg))
12942 (t (org-priority-up))))
12943
12944 (defun org-shiftdown (&optional arg)
12945 "Decrease item in timestamp or decrease priority of current item.
12946 Calls `org-timestamp-down' or `org-priority-down', depending on context.
12947 See the individual commands for more information."
12948 (interactive "P")
12949 (cond
12950 ((org-at-timestamp-p) (org-timestamp-down arg))
12951 (t (org-priority-down))))
12952
12953 (defun org-shiftright ()
12954 "Next TODO keyword or timestamp one day later, depending on context."
12955 (interactive)
12956 (cond
12957 ((org-at-timestamp-p) (org-timestamp-up-day))
12958 ((org-on-heading-p) (org-todo 'right))
12959 (t (org-shiftcursor-error))))
12960
12961 (defun org-shiftleft ()
12962 "Previous TODO keyword or timestamp one day earlier, depending on context."
12963 (interactive)
12964 (cond
12965 ((org-at-timestamp-p) (org-timestamp-down-day))
12966 ((org-on-heading-p) (org-todo 'left))
12967 (t (org-shiftcursor-error))))
12968
12969 (defun org-copy-special ()
12970 "Copy region in table or copy current subtree.
12971 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12972 See the individual commands for more information."
12973 (interactive)
12974 (call-interactively
12975 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12976
12977 (defun org-cut-special ()
12978 "Cut region in table or cut current subtree.
12979 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12980 See the individual commands for more information."
12981 (interactive)
12982 (call-interactively
12983 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12984
12985 (defun org-paste-special (arg)
12986 "Paste rectangular region into table, or past subtree relative to level.
12987 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12988 See the individual commands for more information."
12989 (interactive "P")
12990 (if (org-at-table-p)
12991 (org-table-paste-rectangle)
12992 (org-paste-subtree arg)))
12993
12994 (defun org-ctrl-c-ctrl-c (&optional arg)
12995 "Set tags in headline, or update according to changed information at point.
12996
12997 This command does many different things, depending on context:
12998
12999 - If the cursor is in a headline, prompt for tags and insert them
13000 into the current line, aligned to `org-tags-column'. When called
13001 with prefix arg, realign all tags in the current buffer.
13002
13003 - If the cursor is in one of the special #+KEYWORD lines, this
13004 triggers scanning the buffer for these lines and updating the
13005 information.
13006
13007 - If the cursor is inside a table, realign the table. This command
13008 works even if the automatic table editor has been turned off.
13009
13010 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13011 the entire table.
13012
13013 - If the cursor is inside a table created by the table.el package,
13014 activate that table.
13015
13016 - If the current buffer is a remember buffer, close note and file it.
13017 with a prefix argument, file it without further interaction to the default
13018 location.
13019
13020 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13021 links in this buffer.
13022
13023 - If the cursor is on a numbered item in a plain list, renumber the
13024 ordered list."
13025 (interactive "P")
13026 (let ((org-enable-table-editor t))
13027 (cond
13028 ((and (local-variable-p 'org-finish-function (current-buffer))
13029 (fboundp org-finish-function))
13030 (funcall org-finish-function))
13031 ((org-on-target-p) (org-update-radio-target-regexp))
13032 ((org-on-heading-p) (org-set-tags arg))
13033 ((org-at-table.el-p)
13034 (require 'table)
13035 (beginning-of-line 1)
13036 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13037 (table-recognize-table))
13038 ((org-at-table-p)
13039 (org-table-maybe-eval-formula)
13040 (if arg
13041 (org-table-recalculate t)
13042 (org-table-maybe-recalculate-line))
13043 (org-table-align))
13044 ((org-at-item-p)
13045 (org-renumber-ordered-list (prefix-numeric-value arg)))
13046 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13047 (cond
13048 ((equal (match-string 1) "TBLFM")
13049 ;; Recalculate the table before this line
13050 (save-excursion
13051 (beginning-of-line 1)
13052 (skip-chars-backward " \r\n\t")
13053 (if (org-at-table-p) (org-table-recalculate t))))
13054 (t
13055 (org-mode-restart))))
13056 (t (error "C-c C-c can do nothing useful at this location.")))))
13057
13058 (defun org-mode-restart ()
13059 "Restart Org-mode, to scan again for special lines.
13060 Also updates the keyword regular expressions."
13061 (interactive)
13062 (let ((org-inhibit-startup t)) (org-mode))
13063 (message "Org-mode restarted to refresh keyword and special line setup"))
13064
13065 (defun org-return ()
13066 "Goto next table row or insert a newline.
13067 Calls `org-table-next-row' or `newline', depending on context.
13068 See the individual commands for more information."
13069 (interactive)
13070 (cond
13071 ((org-at-table-p)
13072 (org-table-justify-field-maybe)
13073 (org-table-next-row))
13074 (t (newline))))
13075
13076 (defun org-meta-return (&optional arg)
13077 "Insert a new heading or wrap a region in a table.
13078 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13079 See the individual commands for more information."
13080 (interactive "P")
13081 (cond
13082 ((org-at-table-p)
13083 (org-table-wrap-region arg))
13084 (t (org-insert-heading arg))))
13085
13086 ;;; Menu entries
13087
13088 ;; Define the Org-mode menus
13089 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13090 '("Tbl"
13091 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
13092 ["Next Field" org-cycle (org-at-table-p)]
13093 ["Previous Field" org-shifttab (org-at-table-p)]
13094 ["Next Row" org-return (org-at-table-p)]
13095 "--"
13096 ["Blank Field" org-table-blank-field (org-at-table-p)]
13097 ["Edit Field" org-table-edit-field (org-at-table-p)]
13098 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13099 "--"
13100 ("Column"
13101 ["Move Column Left" org-metaleft (org-at-table-p)]
13102 ["Move Column Right" org-metaright (org-at-table-p)]
13103 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13104 ["Insert Column" org-shiftmetaright (org-at-table-p)]
13105 "--"
13106 ["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])
13107 ("Row"
13108 ["Move Row Up" org-metaup (org-at-table-p)]
13109 ["Move Row Down" org-metadown (org-at-table-p)]
13110 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13111 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13112 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13113 "--"
13114 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
13115 ("Rectangle"
13116 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13117 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13118 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13119 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13120 "--"
13121 ("Calculate"
13122 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13123 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13124 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
13125 "--"
13126 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13127 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13128 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13129 "--"
13130 ["Sum Column/Rectangle" org-table-sum
13131 (or (org-at-table-p) (org-region-active-p))]
13132 ["Which Column?" org-table-current-column (org-at-table-p)])
13133 ["Debug Formulas"
13134 (setq org-table-formula-debug (not org-table-formula-debug))
13135 :style toggle :selected org-table-formula-debug]
13136 "--"
13137 ["Create" org-table-create (and (not (org-at-table-p))
13138 org-enable-table-editor)]
13139 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13140 ["Import from File" org-table-import (not (org-at-table-p))]
13141 ["Export to File" org-table-export (org-at-table-p)]
13142 "--"
13143 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13144
13145 (easy-menu-define org-org-menu org-mode-map "Org menu"
13146 '("Org"
13147 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
13148 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
13149 ["Sparse Tree" org-occur t]
13150 ["Show All" show-all t]
13151 "--"
13152 ["New Heading" org-insert-heading t]
13153 ("Navigate Headings"
13154 ["Up" outline-up-heading t]
13155 ["Next" outline-next-visible-heading t]
13156 ["Previous" outline-previous-visible-heading t]
13157 ["Next Same Level" outline-forward-same-level t]
13158 ["Previous Same Level" outline-backward-same-level t]
13159 "--"
13160 ["Jump" org-goto t])
13161 ("Edit Structure"
13162 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13163 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13164 "--"
13165 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13166 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13167 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13168 "--"
13169 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13170 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13171 ["Demote Heading" org-metaright (not (org-at-table-p))]
13172 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13173 "--"
13174 ["Archive Subtree" org-archive-subtree t]
13175 "--"
13176 ["Convert to odd levels" org-convert-to-odd-levels t]
13177 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13178 "--"
13179 ("TODO Lists"
13180 ["TODO/DONE/-" org-todo t]
13181 ["Show TODO Tree" org-show-todo-tree t]
13182 ["Global TODO list" org-todo-list t]
13183 "--"
13184 ["Set Priority" org-priority t]
13185 ["Priority Up" org-shiftup t]
13186 ["Priority Down" org-shiftdown t])
13187 ("Dates and Scheduling"
13188 ["Timestamp" org-time-stamp t]
13189 ["Timestamp (inactive)" org-time-stamp-inactive t]
13190 ("Change Date"
13191 ["1 Day Later" org-timestamp-up-day t]
13192 ["1 Day Earlier" org-timestamp-down-day t]
13193 ["1 ... Later" org-shiftup t]
13194 ["1 ... Earlier" org-shiftdown t])
13195 ["Compute Time Range" org-evaluate-time-range t]
13196 ["Schedule Item" org-schedule t]
13197 ["Deadline" org-deadline t]
13198 "--"
13199 ["Goto Calendar" org-goto-calendar t]
13200 ["Date from Calendar" org-date-from-calendar t])
13201 "--"
13202 ["Agenda Command" org-agenda t]
13203 ("File List for Agenda")
13204 ("Special views current file"
13205 ["TODO Tree" org-show-todo-tree t]
13206 ["Check Deadlines" org-check-deadlines t]
13207 ["Timeline" org-timeline t]
13208 ["Tags Tree" org-tags-sparse-tree t])
13209 "--"
13210 ("Hyperlinks"
13211 ["Store Link (Global)" org-store-link t]
13212 ["Insert Link" org-insert-link t]
13213 ["Follow Link" org-open-at-point t]
13214 "--"
13215 ["Descriptive Links"
13216 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13217 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
13218 ["Literal Links"
13219 (progn
13220 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13221 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
13222 "--"
13223 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
13224 (save-excursion (goto-char (point-min))
13225 (re-search-forward "<[a-z]+:" nil t))])
13226 "--"
13227 ("Export"
13228 ["ASCII" org-export-as-ascii t]
13229 ["Extract Visible Text" org-export-copy-visible t]
13230 ["HTML" org-export-as-html t]
13231 ["HTML and Open" org-export-as-html-and-open t]
13232 ["XML (XOXO)" org-export-as-xml t]
13233 "--"
13234 ["iCalendar this file" org-export-icalendar-this-file t]
13235 ["iCalendar all agenda files" org-export-icalendar-all-agenda-files
13236 :active t :keys "C-c C-x C-i"]
13237 ["iCalendar combined" org-export-icalendar-combine-agenda-files t]
13238 "--"
13239 ["Option Template" org-insert-export-options-template t]
13240 ["Toggle Fixed Width" org-toggle-fixed-width-section t])
13241 "--"
13242 ("Documentation"
13243 ["Show Version" org-version t]
13244 ["Info Documentation" org-info t])
13245 ("Customize"
13246 ["Browse Org Group" org-customize t]
13247 "--"
13248 ["Expand This Menu" org-create-customize-menu
13249 (fboundp 'customize-menu-create)])
13250 "--"
13251 ["Refresh setup" org-mode-restart t]
13252 ))
13253
13254 (defun org-info (&optional node)
13255 "Read documentation for Org-mode in the info system.
13256 With optional NODE, go directly to that node."
13257 (interactive)
13258 (require 'info)
13259 (Info-goto-node (format "(org)%s" (or node ""))))
13260
13261 (defun org-install-agenda-files-menu ()
13262 (let ((bl (buffer-list)))
13263 (save-excursion
13264 (while bl
13265 (set-buffer (pop bl))
13266 (if (eq major-mode 'org-mode) (setq bl nil)))
13267 (when (eq major-mode 'org-mode)
13268 (easy-menu-change
13269 '("Org") "File List for Agenda"
13270 (append
13271 (list
13272 ["Edit File List" (org-edit-agenda-file-list) t]
13273 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13274 ["Remove Current File from List" org-remove-file t]
13275 ["Cycle through agenda files" org-cycle-agenda-files t]
13276 "--")
13277 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13278
13279 ;;; Documentation
13280
13281 (defun org-customize ()
13282 "Call the customize function with org as argument."
13283 (interactive)
13284 (customize-browse 'org))
13285
13286 (defun org-create-customize-menu ()
13287 "Create a full customization menu for Org-mode, insert it into the menu."
13288 (interactive)
13289 (if (fboundp 'customize-menu-create)
13290 (progn
13291 (easy-menu-change
13292 '("Org") "Customize"
13293 `(["Browse Org group" org-customize t]
13294 "--"
13295 ,(customize-menu-create 'org)
13296 ["Set" Custom-set t]
13297 ["Save" Custom-save t]
13298 ["Reset to Current" Custom-reset-current t]
13299 ["Reset to Saved" Custom-reset-saved t]
13300 ["Reset to Standard Settings" Custom-reset-standard t]))
13301 (message "\"Org\"-menu now contains full customization menu"))
13302 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13303
13304 ;;; Miscellaneous stuff
13305
13306 (defun org-move-line-down (arg)
13307 "Move the current line down. With prefix argument, move it past ARG lines."
13308 (interactive "p")
13309 (let ((col (current-column))
13310 beg end pos)
13311 (beginning-of-line 1) (setq beg (point))
13312 (beginning-of-line 2) (setq end (point))
13313 (beginning-of-line (+ 1 arg))
13314 (setq pos (move-marker (make-marker) (point)))
13315 (insert (delete-and-extract-region beg end))
13316 (goto-char pos)
13317 (move-to-column col)))
13318
13319 (defun org-move-line-up (arg)
13320 "Move the current line up. With prefix argument, move it past ARG lines."
13321 (interactive "p")
13322 (let ((col (current-column))
13323 beg end pos)
13324 (beginning-of-line 1) (setq beg (point))
13325 (beginning-of-line 2) (setq end (point))
13326 (beginning-of-line (- arg))
13327 (setq pos (move-marker (make-marker) (point)))
13328 (insert (delete-and-extract-region beg end))
13329 (goto-char pos)
13330 (move-to-column col)))
13331
13332 ;; Paragraph filling stuff.
13333 ;; We want this to be just right, so use the full arsenal.
13334 ;; FIXME: This very likely does not work correctly for XEmacs, because the
13335 ;; filladapt package works slightly differently.
13336
13337 (defun org-set-autofill-regexps ()
13338 (interactive)
13339 ;; In the paragraph separator we include headlines, because filling
13340 ;; text in a line directly attached to a headline would otherwise
13341 ;; fill the headline as well.
13342 (set (make-local-variable 'paragraph-separate) "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
13343 ;; The paragraph starter includes hand-formatted lists.
13344 (set (make-local-variable 'paragraph-start)
13345 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*]\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13346 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13347 ;; But only if the user has not turned off tables or fixed-width regions
13348 (set (make-local-variable 'auto-fill-inhibit-regexp)
13349 (concat "\\*\\|#"
13350 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13351 (concat
13352 "\\|[ \t]*["
13353 (if org-enable-table-editor "|" "")
13354 (if org-enable-fixed-width-editor ":" "")
13355 "]"))))
13356 ;; We use our own fill-paragraph function, to make sure that tables
13357 ;; and fixed-width regions are not wrapped. That function will pass
13358 ;; through to `fill-paragraph' when appropriate.
13359 (set (make-local-variable 'fill-paragraph-function) 'org-fill-paragraph)
13360 ;; Adaptive filling: To get full control, first make sure that
13361 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13362 (set (make-local-variable 'adaptive-fill-regexp) "\000")
13363 (set (make-local-variable 'adaptive-fill-function)
13364 'org-adaptive-fill-function))
13365
13366 (defun org-fill-paragraph (&optional justify)
13367 "Re-align a table, pass through to fill-paragraph if no table."
13368 (let ((table-p (org-at-table-p))
13369 (table.el-p (org-at-table.el-p)))
13370 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
13371 (table.el-p t) ; skip table.el tables
13372 (table-p (org-table-align) t) ; align org-mode tables
13373 (t nil)))) ; call paragraph-fill
13374
13375 ;; For reference, this is the default value of adaptive-fill-regexp
13376 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13377
13378 (defun org-adaptive-fill-function ()
13379 "Return a fill prefix for org-mode files.
13380 In particular, this makes sure hanging paragraphs for hand-formatted lists
13381 work correctly."
13382 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
13383 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
13384
13385 ;; Functions needed for Emacs/XEmacs region compatibility
13386
13387 (defun org-add-hook (hook function &optional append local)
13388 "Add-hook, compatible with both Emacsen."
13389 (if (and local (featurep 'xemacs))
13390 (add-local-hook hook function append)
13391 (add-hook hook function append local)))
13392
13393 (defun org-region-active-p ()
13394 "Is `transient-mark-mode' on and the region active?
13395 Works on both Emacs and XEmacs."
13396 (if org-ignore-region
13397 nil
13398 (if (featurep 'xemacs)
13399 (and zmacs-regions (region-active-p))
13400 (and transient-mark-mode mark-active))))
13401
13402 (defun org-add-to-invisibility-spec (arg)
13403 "Add elements to `buffer-invisibility-spec'.
13404 See documentation for `buffer-invisibility-spec' for the kind of elements
13405 that can be added."
13406 (cond
13407 ((fboundp 'add-to-invisibility-spec)
13408 (add-to-invisibility-spec arg))
13409 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
13410 (setq buffer-invisibility-spec (list arg)))
13411 (t
13412 (setq buffer-invisibility-spec
13413 (cons arg buffer-invisibility-spec)))))
13414
13415 (defun org-remove-from-invisibility-spec (arg)
13416 "Remove elements from `buffer-invisibility-spec'."
13417 (if (fboundp 'remove-from-invisibility-spec)
13418 (remove-from-invisibility-spec arg)
13419 (if (consp buffer-invisibility-spec)
13420 (setq buffer-invisibility-spec
13421 (delete arg buffer-invisibility-spec)))))
13422
13423 (defun org-in-invisibility-spec-p (arg)
13424 "Is ARG a member of `buffer-invisibility-spec'?"
13425 (if (consp buffer-invisibility-spec)
13426 (member arg buffer-invisibility-spec)
13427 nil))
13428
13429 (defun org-image-file-name-regexp ()
13430 "Return regexp matching the file names of images."
13431 (if (fboundp 'image-file-name-regexp)
13432 (image-file-name-regexp)
13433 (let ((image-file-name-extensions
13434 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13435 "xbm" "xpm" "pbm" "pgm" "ppm")))
13436 (concat "\\."
13437 (regexp-opt (nconc (mapcar 'upcase
13438 image-file-name-extensions)
13439 image-file-name-extensions)
13440 t)
13441 "\\'"))))
13442
13443 ;; Functions needed for compatibility with old outline.el.
13444
13445 ;; Programming for the old outline.el (that uses selective display
13446 ;; instead of `invisible' text properties) is a nightmare, mostly
13447 ;; because regular expressions can no longer be anchored at
13448 ;; beginning/end of line. Therefore a number of function need special
13449 ;; treatment when the old outline.el is being used.
13450
13451 ;; The following functions capture almost the entire compatibility code
13452 ;; between the different versions of outline-mode. The only other
13453 ;; places where this is important are the font-lock-keywords, and in
13454 ;; `org-export-copy-visible'. Search for `org-noutline-p' to find them.
13455
13456 ;; C-a should go to the beginning of a *visible* line, also in the
13457 ;; new outline.el. I guess this should be patched into Emacs?
13458 (defun org-beginning-of-line ()
13459 "Go to the beginning of the current line. If that is invisible, continue
13460 to a visible line beginning. This makes the function of C-a more intuitive."
13461 (interactive)
13462 (beginning-of-line 1)
13463 (if (bobp)
13464 nil
13465 (backward-char 1)
13466 (if (org-invisible-p)
13467 (while (and (not (bobp)) (org-invisible-p))
13468 (backward-char 1)
13469 (beginning-of-line 1))
13470 (forward-char 1))))
13471
13472 (when org-noutline-p
13473 (define-key org-mode-map "\C-a" 'org-beginning-of-line))
13474 ;; FIXME: should I use substitute-key-definition to reach other bindings
13475 ;; of beginning-of-line?
13476
13477 (defun org-invisible-p ()
13478 "Check if point is at a character currently not visible."
13479 (if org-noutline-p
13480 ;; Early versions of noutline don't have `outline-invisible-p'.
13481 (if (fboundp 'outline-invisible-p)
13482 (outline-invisible-p)
13483 (get-char-property (point) 'invisible))
13484 (save-excursion
13485 (skip-chars-backward "^\r\n")
13486 (equal (char-before) ?\r))))
13487
13488 (defun org-invisible-p2 ()
13489 "Check if point is at a character currently not visible."
13490 (save-excursion
13491 (if org-noutline-p
13492 (progn
13493 (if (and (eolp) (not (bobp))) (backward-char 1))
13494 ;; Early versions of noutline don't have `outline-invisible-p'.
13495 (if (fboundp 'outline-invisible-p)
13496 (outline-invisible-p)
13497 (get-char-property (point) 'invisible)))
13498 (skip-chars-backward "^\r\n")
13499 (equal (char-before) ?\r))))
13500
13501 (defun org-back-to-heading (&optional invisible-ok)
13502 "Move to previous heading line, or beg of this line if it's a heading.
13503 Only visible heading lines are considered, unless INVISIBLE-OK is non-nil."
13504 (if org-noutline-p
13505 (outline-back-to-heading invisible-ok)
13506 (if (and (memq (char-before) '(?\n ?\r))
13507 (looking-at outline-regexp))
13508 t
13509 (if (re-search-backward (concat (if invisible-ok "\\([\r\n]\\|^\\)" "^")
13510 outline-regexp)
13511 nil t)
13512 (if invisible-ok
13513 (progn (goto-char (match-end 1))
13514 (looking-at outline-regexp)))
13515 (error "Before first heading")))))
13516
13517 (defun org-on-heading-p (&optional invisible-ok)
13518 "Return t if point is on a (visible) heading line.
13519 If INVISIBLE-OK is non-nil, an invisible heading line is ok too."
13520 (if org-noutline-p
13521 (outline-on-heading-p 'invisible-ok)
13522 (save-excursion
13523 (skip-chars-backward "^\n\r")
13524 (and (looking-at outline-regexp)
13525 (or invisible-ok
13526 (bobp)
13527 (equal (char-before) ?\n))))))
13528
13529 (defun org-on-target-p ()
13530 (let ((pos (point)))
13531 (save-excursion
13532 (skip-chars-forward "<")
13533 (and (re-search-backward "<<" nil t)
13534 (or (looking-at org-radio-target-regexp)
13535 (looking-at org-target-regexp))
13536 (<= (match-beginning 0) pos)
13537 (>= (1+ (match-end 0)) pos)))))
13538
13539 (defun org-up-heading-all (arg)
13540 "Move to the heading line of which the present line is a subheading.
13541 This function considers both visible and invisible heading lines.
13542 With argument, move up ARG levels."
13543 (if org-noutline-p
13544 (if (fboundp 'outline-up-heading-all)
13545 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13546 (outline-up-heading arg t)) ; emacs 22 version of outline.el
13547 (org-back-to-heading t)
13548 (looking-at outline-regexp)
13549 (if (<= (- (match-end 0) (match-beginning 0)) arg)
13550 (error "Cannot move up %d levels" arg)
13551 (re-search-backward
13552 (concat "[\n\r]" (regexp-quote
13553 (make-string (- (match-end 0) (match-beginning 0) arg)
13554 ?*))
13555 "[^*]"))
13556 (forward-char 1))))
13557
13558 (defun org-show-hidden-entry ()
13559 "Show an entry where even the heading is hidden."
13560 (save-excursion
13561 (if (not org-noutline-p)
13562 (progn
13563 (org-back-to-heading t)
13564 (org-flag-heading nil)))
13565 (org-show-entry)))
13566
13567 (defun org-check-occur-regexp (regexp)
13568 "If REGEXP starts with \"^\", modify it to check for \\r as well.
13569 Of course, only for the old outline mode."
13570 (if org-noutline-p
13571 regexp
13572 (if (string-match "^\\^" regexp)
13573 (concat "[\n\r]" (substring regexp 1))
13574 regexp)))
13575
13576 (defun org-flag-heading (flag &optional entry)
13577 "Flag the current heading. FLAG non-nil means make invisible.
13578 When ENTRY is non-nil, show the entire entry."
13579 (save-excursion
13580 (org-back-to-heading t)
13581 (if (not org-noutline-p)
13582 ;; Make the current headline visible
13583 (outline-flag-region (max 1 (1- (point))) (point) (if flag ?\r ?\n)))
13584 ;; Check if we should show the entire entry
13585 (if entry
13586 (progn
13587 (org-show-entry)
13588 (save-excursion ;; FIXME: Is this the fix for points in the -|
13589 ;; middle of text? |
13590 (and (outline-next-heading) ;; |
13591 (org-flag-heading nil)))) ; show the next heading _|
13592 (outline-flag-region (max 1 (1- (point)))
13593 (save-excursion (outline-end-of-heading) (point))
13594 (if org-noutline-p
13595 flag
13596 (if flag ?\r ?\n))))))
13597
13598 (defun org-end-of-subtree (&optional invisible-OK)
13599 ;; This is an exact copy of the original function, but it uses
13600 ;; `org-back-to-heading', to make it work also in invisible
13601 ;; trees. And is uses an invisible-OK argument.
13602 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13603 (org-back-to-heading invisible-OK)
13604 (let ((first t)
13605 (level (funcall outline-level)))
13606 (while (and (not (eobp))
13607 (or first (> (funcall outline-level) level)))
13608 (setq first nil)
13609 (outline-next-heading))
13610 (if (memq (preceding-char) '(?\n ?\^M))
13611 (progn
13612 ;; Go to end of line before heading
13613 (forward-char -1)
13614 (if (memq (preceding-char) '(?\n ?\^M))
13615 ;; leave blank line before heading
13616 (forward-char -1))))))
13617
13618 (defun org-show-subtree ()
13619 "Show everything after this heading at deeper levels."
13620 (outline-flag-region
13621 (point)
13622 (save-excursion
13623 (outline-end-of-subtree) (outline-next-heading) (point))
13624 (if org-noutline-p nil ?\n)))
13625
13626 (defun org-show-entry ()
13627 "Show the body directly following this heading.
13628 Show the heading too, if it is currently invisible."
13629 (interactive)
13630 (save-excursion
13631 (org-back-to-heading t)
13632 (outline-flag-region
13633 (1- (point))
13634 (save-excursion
13635 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13636 (or (match-beginning 1) (point-max)))
13637 (if org-noutline-p nil ?\n))))
13638
13639 (defun org-make-options-regexp (kwds)
13640 "Make a regular expression for keyword lines."
13641 (concat
13642 (if org-noutline-p "^" "[\n\r]")
13643 "#?[ \t]*\\+\\("
13644 (mapconcat 'regexp-quote kwds "\\|")
13645 "\\):[ \t]*"
13646 (if org-noutline-p "\\(.+\\)" "\\([^\n\r]+\\)")))
13647
13648 ;; Make `bookmark-jump' show the jump location if it was hidden.
13649 (eval-after-load "bookmark"
13650 '(if (boundp 'bookmark-after-jump-hook)
13651 ;; We can use the hook
13652 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13653 ;; Hook not available, use advice
13654 (defadvice bookmark-jump (after org-make-visible activate)
13655 "Make the position visible."
13656 (org-bookmark-jump-unhide))))
13657
13658 (defun org-bookmark-jump-unhide ()
13659 "Unhide the current position, to show the bookmark location."
13660 (and (eq major-mode 'org-mode)
13661 (or (org-invisible-p)
13662 (save-excursion (goto-char (max (point-min) (1- (point))))
13663 (org-invisible-p)))
13664 (org-show-hierarchy-above)))
13665
13666 ;;; Finish up
13667
13668 (provide 'org)
13669
13670 (run-hooks 'org-load-hook)
13671
13672 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13673 ;;; org.el ends here
13674