]> code.delx.au - gnu-emacs/blob - lisp/textmodes/org.el
5e15855a69dda21c430f8013042346d6c3f478a4
[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.44
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 NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
47 ;;
48 ;;
49 ;; Installation
50 ;; ------------
51 ;; If Org-mode is part of the Emacs distribution or an XEmacs package, you
52 ;; only need to copy the following lines to your .emacs file. The last two
53 ;; lines define *global* keys for the commands `org-store-link' and
54 ;; `org-agenda' - please choose suitable keys yourself.
55 ;;
56 ;; (add-to-list 'auto-mode-alist '("\\.org$" . org-mode))
57 ;; (define-key global-map "\C-cl" 'org-store-link)
58 ;; (define-key global-map "\C-ca" 'org-agenda)
59 ;;
60 ;; Furthermore you need to activate font-lock-mode in org-mode buffers.
61 ;; either of the following two lins will do the trick:
62 ;;
63 ;; (global-font-lock-mode 1) ; for all buffers
64 ;; (add-hook 'org-mode-hook 'turn-on-font-lock) ; org-mode buffers only
65 ;;
66 ;; If you have downloaded Org-mode from the Web, you have to take additional
67 ;; action: Byte-compile org.el and org-publish.el and put them together with
68 ;; org-install.el on your load path. Then also add to your .emacs file:
69 ;;
70 ;; (require 'org-install)
71 ;;
72 ;;
73 ;; Activation
74 ;; ----------
75 ;; The setup above will put all files with extension ".org" into Org-mode.
76 ;; As an alternative, make the first line of a file look like this:
77 ;;
78 ;; MY PROJECTS -*- mode: org; -*-
79 ;;
80 ;; which will select Org-mode for this buffer no matter what the file's
81 ;; name is.
82 ;;
83 ;; Documentation
84 ;; -------------
85 ;; The documentation of Org-mode can be found in the TeXInfo file. The
86 ;; distribution also contains a PDF version of it. At the homepage of
87 ;; Org-mode, you can read the same text online as HTML. There is also an
88 ;; excellent reference card made by Philip Rooke. This card can be found
89 ;; in the etc/ directory of Emacs 22.
90 ;;
91 ;; Recent changes
92 ;; --------------
93 ;; Version 4.44
94 ;; - Clock table can be done for a limited time interval.
95 ;; - Obsolete support for the old outline mode has been removed.
96 ;; - Bug fixes and code cleaning.
97 ;;
98 ;; Version 4.43
99 ;; - Bug fixes
100 ;; - `s' key in the agenda saves all org-mode buffers.
101 ;;
102 ;; Version 4.41
103 ;; - Shift-curser keys can modify inactive time stamps (inactive time
104 ;; stamps are the ones in [...] brackets.
105 ;; - Toggle all checkboxes in a region/below a headline.
106 ;; - Bug fixes.
107 ;;
108 ;; Version 4.40
109 ;; - Bug fixes.
110 ;;
111 ;; Version 4.39
112 ;; - Special tag ARCHIVE keeps a subtree closed and away from agenda lists.
113 ;; - LaTeX code in Org-mode files can be converted to images for HTML.
114 ;; - Bug fixes.
115 ;; - CDLaTeX-mode features can be used in Org-mode to help inserting
116 ;; LaTeX environment and math.
117 ;;
118 ;; Version 4.38
119 ;; - noutline.el is now required (important for XEmacs users only).
120 ;; - Dynamic blocks.
121 ;; - Archiving of all level 1 trees without open TODO items.
122 ;; - Clock reports can be inserted into the file in a special section.
123 ;; - FAQ removed from the manual, now only on the web.
124 ;; - Bug fixes.
125 ;;
126 ;; Version 4.37
127 ;; - Clock-feature for measuring time spent on specific items.
128 ;; - Improved emphasizing allows configuration and stacking.
129 ;;
130 ;; Version 4.36
131 ;; - Improved indentation of ASCII export, when headlines become items.
132 ;; - Handling of 12am and 12pm fixed. Times beyond 24:00 can be used
133 ;; and will not lead to conflicts.
134 ;; - Support for mutually exclusive TAGS with the fast tags interface.
135 ;; - Bug fixes.
136 ;;
137 ;; Version 4.35
138 ;; - HTML export is now valid XHTML.
139 ;; - Timeline can also show dates without entries. See new option
140 ;; `org-timeline-show-empty-dates'.
141 ;; - The bullets created by the ASCII exporter can now be configured.
142 ;; See the new option `org-export-ascii-bullets'.
143 ;; - New face `org-upcoming-deadline' (was `org-scheduled-previously').
144 ;; - New function `org-context' to allow testing for local context.
145 ;;
146 ;; Version 4.34
147 ;; - Bug fixes.
148 ;;
149 ;; Version 4.33
150 ;; - New commands to move through plain lists: S-up and S-down.
151 ;; - Bug fixes and documentation update.
152 ;;
153 ;; Version 4.32
154 ;; - Fast (single-key-per-tag) interface for setting TAGS.
155 ;; - The list of legal tags can be configured globally and locally.
156 ;; - Elisp and Info links (thanks to Todd Neal).
157 ;; - `org-export-publishing-directory' can be an alist, with different
158 ;; directories for different export types.
159 ;; - All context-sensitive commands use `call-interactively' to dispatch.
160 ;; - `org-confirm-shell-links' renamed to `org-confirm-shell-link-function'.
161 ;; - Bug fixes.
162 ;;
163 ;; Version 4.31
164 ;; - Bug fixes.
165 ;;
166 ;; Version 4.30
167 ;; - Modified installation: Autoloads have been collected in org-install.el.
168 ;; - Logging (org-log-done) is now a #+STARTUP option.
169 ;; - Checkboxes in plain list items, following up on Frank Ruell's idea.
170 ;; - File links inserted with C-c C-l will use relative paths if the linked
171 ;; file is in the current directory or a subdirectory of it.
172 ;; - New variable `org-link-file-path-type' to specify preference for
173 ;; relative and absolute paths.
174 ;; - New CSS classes for tags, timestamps, timestamp keywords.
175 ;; - Bug and typo fixes.
176 ;;
177 ;; Version 4.29
178 ;; - Inlining images in HTML export now depends on wheather the link
179 ;; contains a description or not.
180 ;; - TODO items can be scheduled from the global TODO list using C-c C-s.
181 ;; - TODO items already scheduled can be made to disappear from the global
182 ;; todo list, see `org-agenda-todo-ignore-scheduled'.
183 ;; - In Tables, formulas may also be Lisp forms.
184 ;; - Exporting the visible part of an outline with `C-c C-x v' works now
185 ;; for all available exporters.
186 ;; - Bug fixes, lots of them :-(
187 ;;
188 ;; Version 4.28
189 ;; - Bug fixes.
190 ;;
191 ;; Version 4.27
192 ;; - HTML exporter generalized to receive external options.
193 ;; As part of the process, author, email and date have been moved to the
194 ;; end of the HTML file.
195 ;; - Support for customizable file search in file links.
196 ;; - BibTeX database links as first application of the above.
197 ;; - New option `org-agenda-todo-list-sublevels' to turn off listing TODO
198 ;; entries that are sublevels of another TODO entry.
199 ;;
200 ;;
201 ;;; Code:
202
203 (eval-when-compile
204 (require 'cl)
205 (require 'calendar))
206 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
207 ;; the file noutline.el being loaded.
208 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
209 ;; We require noutline, which might be provided in outline.el
210 (require 'outline) (require 'noutline)
211 ;; Other stuff we need.
212 (require 'time-date)
213 (require 'easymenu)
214
215 ;;; Customization variables
216
217 (defvar org-version "4.44"
218 "The version number of the file org.el.")
219 (defun org-version ()
220 (interactive)
221 (message "Org-mode version %s" org-version))
222
223 ;; Compatibility constants
224 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
225 (defconst org-format-transports-properties-p
226 (let ((x "a"))
227 (add-text-properties 0 1 '(test t) x)
228 (get-text-property 0 'test (format "%s" x)))
229 "Does format transport text properties?")
230
231 (defgroup org nil
232 "Outline-based notes management and organizer."
233 :tag "Org"
234 :group 'outlines
235 :group 'hypermedia
236 :group 'calendar)
237
238 (defgroup org-startup nil
239 "Options concerning startup of Org-mode."
240 :tag "Org Startup"
241 :group 'org)
242
243 (defcustom org-startup-folded t
244 "Non-nil means, entering Org-mode will switch to OVERVIEW.
245 This can also be configured on a per-file basis by adding one of
246 the following lines anywhere in the buffer:
247
248 #+STARTUP: fold
249 #+STARTUP: nofold
250 #+STARTUP: content"
251 :group 'org-startup
252 :type '(choice
253 (const :tag "nofold: show all" nil)
254 (const :tag "fold: overview" t)
255 (const :tag "content: all headlines" content)))
256
257 (defcustom org-startup-truncated t
258 "Non-nil means, entering Org-mode will set `truncate-lines'.
259 This is useful since some lines containing links can be very long and
260 uninteresting. Also tables look terrible when wrapped."
261 :group 'org-startup
262 :type 'boolean)
263
264 (defcustom org-startup-align-all-tables nil
265 "Non-nil means, align all tables when visiting a file.
266 This is useful when the column width in tables is forced with <N> cookies
267 in table fields. Such tables will look correct only after the first re-align.
268 This can also be configured on a per-file basis by adding one of
269 the following lines anywhere in the buffer:
270 #+STARTUP: align
271 #+STARTUP: noalign"
272 :group 'org-startup
273 :type 'boolean)
274
275 (defcustom org-startup-with-deadline-check nil
276 "Non-nil means, entering Org-mode will run the deadline check.
277 This means, if you start editing an org file, you will get an
278 immediate reminder of any due deadlines.
279 This can also be configured on a per-file basis by adding one of
280 the following lines anywhere in the buffer:
281 #+STARTUP: dlcheck
282 #+STARTUP: nodlcheck"
283 :group 'org-startup
284 :type 'boolean)
285
286 (defcustom org-insert-mode-line-in-empty-file nil
287 "Non-nil means insert the first line setting Org-mode in empty files.
288 When the function `org-mode' is called interactively in an empty file, this
289 normally means that the file name does not automatically trigger Org-mode.
290 To ensure that the file will always be in Org-mode in the future, a
291 line enforcing Org-mode will be inserted into the buffer, if this option
292 has been set."
293 :group 'org-startup
294 :type 'boolean)
295
296 (defcustom org-CUA-compatible nil
297 "Non-nil means use alternative key bindings for S-<cursor movement>.
298 Org-mode used S-<cursor movement> for changing timestamps and priorities.
299 S-<cursor movement> is also used for example by `CUA-mode' to select text.
300 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
301 alternative bindings. Setting this variable to t will replace the following
302 keys both in Org-mode and in the Org-agenda buffer.
303
304 S-RET -> C-S-RET
305 S-up -> M-p
306 S-down -> M-n
307 S-left -> M--
308 S-right -> M-+
309
310 If you do not like the alternative keys, take a look at the variable
311 `org-disputed-keys'.
312
313 This option is only relevant at load-time of Org-mode. Changing it requires
314 a restart of Emacs to become effective."
315 :group 'org-startup
316 :type 'boolean)
317
318 (defvar org-disputed-keys
319 '((S-up [(shift up)] [(meta ?p)])
320 (S-down [(shift down)] [(meta ?n)])
321 (S-left [(shift left)] [(meta ?-)])
322 (S-right [(shift right)] [(meta ?+)])
323 (S-return [(shift return)] [(control shift return)]))
324 "Keys for which Org-mode and other modes compete.
325 This is an alist, cars are symbols for lookup, 1st element is the default key,
326 second element will be used when `org-CUA-compatible' is t.")
327
328 (defun org-key (key)
329 "Select a key according to `org-CUA-compatible'."
330 (nth (if org-CUA-compatible 2 1)
331 (or (assq key org-disputed-keys)
332 (error "Invalid Key %s in `org-key'" key))))
333
334 (defcustom org-ellipsis nil
335 "The ellipsis to use in the Org-mode outline.
336 When nil, just use the standard three dots. When a string, use that instead,
337 and just in Org-mode (which will then use its own display table).
338 Changing this requires executing `M-x org-mode' in a buffer to become
339 effective."
340 :group 'org-startup
341 :type '(choice (const :tag "Default" nil)
342 (string :tag "String" :value "...#")))
343
344 (defvar org-display-table nil
345 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
346
347 (defgroup org-keywords nil
348 "Keywords in Org-mode."
349 :tag "Org Keywords"
350 :group 'org)
351
352 (defcustom org-deadline-string "DEADLINE:"
353 "String to mark deadline entries.
354 A deadline is this string, followed by a time stamp. Should be a word,
355 terminated by a colon. You can insert a schedule keyword and
356 a timestamp with \\[org-deadline].
357 Changes become only effective after restarting Emacs."
358 :group 'org-keywords
359 :type 'string)
360
361 (defcustom org-scheduled-string "SCHEDULED:"
362 "String to mark scheduled TODO entries.
363 A schedule is this string, followed by a time stamp. Should be a word,
364 terminated by a colon. You can insert a schedule keyword and
365 a timestamp with \\[org-schedule].
366 Changes become only effective after restarting Emacs."
367 :group 'org-keywords
368 :type 'string)
369
370 (defcustom org-closed-string "CLOSED:"
371 "String used as the prefix for timestamps logging closing a TODO entry."
372 :group 'org-keywords
373 :type 'string)
374
375 (defcustom org-clock-string "CLOCK:"
376 "String used as prefix for timestamps clocking work hours on an item."
377 :group 'org-keywords
378 :type 'string)
379
380 (defcustom org-comment-string "COMMENT"
381 "Entries starting with this keyword will never be exported.
382 An entry can be toggled between COMMENT and normal with
383 \\[org-toggle-comment].
384 Changes become only effective after restarting Emacs."
385 :group 'org-keywords
386 :type 'string)
387
388 (defcustom org-quote-string "QUOTE"
389 "Entries starting with this keyword will be exported in fixed-width font.
390 Quoting applies only to the text in the entry following the headline, and does
391 not extend beyond the next headline, even if that is lower level.
392 An entry can be toggled between QUOTE and normal with
393 \\[org-toggle-fixed-width-section]."
394 :group 'org-keywords
395 :type 'string)
396
397 (defgroup org-structure nil
398 "Options concerning the general structure of Org-mode files."
399 :tag "Org Structure"
400 :group 'org)
401
402 (defgroup org-cycle nil
403 "Options concerning visibility cycling in Org-mode."
404 :tag "Org Cycle"
405 :group 'org-structure)
406
407 (defcustom org-cycle-global-at-bob t
408 "Cycle globally if cursor is at beginning of buffer and not at a headline.
409 This makes it possible to do global cycling without having to use S-TAB or
410 C-u TAB. For this special case to work, the first line of the buffer
411 must not be a headline - it may be empty ot some other text. When used in
412 this way, `org-cycle-hook' is disables temporarily, to make sure the
413 cursor stays at the beginning of the buffer.
414 When this option is nil, don't do anything special at the beginning
415 of the buffer."
416 :group 'org-cycle
417 :type 'boolean)
418
419 (defcustom org-cycle-emulate-tab t
420 "Where should `org-cycle' emulate TAB.
421 nil Never
422 white Only in completely white lines
423 whitestart Only at the beginning of lines, before the first non-white char.
424 t Everywhere except in headlines
425 If TAB is used in a place where it does not emulate TAB, the current subtree
426 visibility is cycled."
427 :group 'org-cycle
428 :type '(choice (const :tag "Never" nil)
429 (const :tag "Only in completely white lines" white)
430 (const :tag "Before first char in a line" whitestart)
431 (const :tag "Everywhere except in headlines" t)
432 ))
433
434 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
435 org-optimize-window-after-visibility-change)
436 "Hook that is run after `org-cycle' has changed the buffer visibility.
437 The function(s) in this hook must accept a single argument which indicates
438 the new state that was set by the most recent `org-cycle' command. The
439 argument is a symbol. After a global state change, it can have the values
440 `overview', `content', or `all'. After a local state change, it can have
441 the values `folded', `children', or `subtree'."
442 :group 'org-cycle
443 :type 'hook)
444
445 (defgroup org-edit-structure nil
446 "Options concerning structure editing in Org-mode."
447 :tag "Org Edit Structure"
448 :group 'org-structure)
449
450 (defcustom org-odd-levels-only nil
451 "Non-nil means, skip even levels and only use odd levels for the outline.
452 This has the effect that two stars are being added/taken away in
453 promotion/demotion commands. It also influences how levels are
454 handled by the exporters.
455 Changing it requires restart of `font-lock-mode' to become effective
456 for fontification also in regions already fontified.
457 You may also set this on a per-file basis by adding one of the following
458 lines to the buffer:
459
460 #+STARTUP: odd
461 #+STARTUP: oddeven"
462 :group 'org-edit-structure
463 :group 'org-font-lock
464 :type 'boolean)
465
466 (defcustom org-adapt-indentation t
467 "Non-nil means, adapt indentation when promoting and demoting.
468 When this is set and the *entire* text in an entry is indented, the
469 indentation is increased by one space in a demotion command, and
470 decreased by one in a promotion command. If any line in the entry
471 body starts at column 0, indentation is not changed at all."
472 :group 'org-edit-structure
473 :type 'boolean)
474
475 (defcustom org-insert-heading-hook nil
476 "Hook being run after inserting a new heading."
477 :group 'org-edit-structure
478 :type 'boolean)
479
480 (defcustom org-enable-fixed-width-editor t
481 "Non-nil means, lines starting with \":\" are treated as fixed-width.
482 This currently only means, they are never auto-wrapped.
483 When nil, such lines will be treated like ordinary lines.
484 See also the QUOTE keyword."
485 :group 'org-edit-structure
486 :type 'boolean)
487
488 (defgroup org-sparse-trees nil
489 "Options concerning sparse trees in Org-mode."
490 :tag "Org Sparse Trees"
491 :group 'org-structure)
492
493 (defcustom org-highlight-sparse-tree-matches t
494 "Non-nil means, highlight all matches that define a sparse tree.
495 The highlights will automatically disappear the next time the buffer is
496 changed by an edit command."
497 :group 'org-sparse-trees
498 :type 'boolean)
499
500 (defcustom org-show-hierarchy-above t
501 "Non-nil means, show full hierarchy when showing a spot in the tree.
502 Turning this off makes sparse trees more compact, but also less clear."
503 :group 'org-sparse-trees
504 :type 'boolean)
505
506 (defcustom org-show-following-heading t
507 "Non-nil means, show heading following match in `org-occur'.
508 When doing an `org-occur' it is useful to show the headline which
509 follows the match, even if they do not match the regexp. This makes it
510 easier to edit directly inside the sparse tree. However, if you use
511 `org-occur' mainly as an overview, the following headlines are
512 unnecessary clutter."
513 :group 'org-sparse-trees
514 :type 'boolean)
515
516 (defcustom org-occur-hook '(org-first-headline-recenter)
517 "Hook that is run after `org-occur' has constructed a sparse tree.
518 This can be used to recenter the window to show as much of the structure
519 as possible."
520 :group 'org-sparse-trees
521 :type 'hook)
522
523 (defgroup org-plain-lists nil
524 "Options concerning plain lists in Org-mode."
525 :tag "Org Plain lists"
526 :group 'org-structure)
527
528 (defcustom org-cycle-include-plain-lists nil
529 "Non-nil means, include plain lists into visibility cycling.
530 This means that during cycling, plain list items will *temporarily* be
531 interpreted as outline headlines with a level given by 1000+i where i is the
532 indentation of the bullet. In all other operations, plain list items are
533 not seen as headlines. For example, you cannot assign a TODO keyword to
534 such an item."
535 :group 'org-plain-lists
536 :type 'boolean)
537
538
539 (defcustom org-plain-list-ordered-item-terminator t
540 "The character that makes a line with leading number an ordered list item.
541 Valid values are ?. and ?\). To get both terminators, use t. While
542 ?. may look nicer, it creates the danger that a line with leading
543 number may be incorrectly interpreted as an item. ?\) therefore is
544 the safe choice."
545 :group 'org-plain-lists
546 :type '(choice (const :tag "dot like in \"2.\"" ?.)
547 (const :tag "paren like in \"2)\"" ?\))
548 (const :tab "both" t)))
549
550 (defcustom org-auto-renumber-ordered-lists t
551 "Non-nil means, automatically renumber ordered plain lists.
552 Renumbering happens when the sequence have been changed with
553 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
554 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
555 :group 'org-plain-lists
556 :type 'boolean)
557
558 (defgroup org-archive nil
559 "Options concerning archiving in Org-mode."
560 :tag "Org Archive"
561 :group 'org-structure)
562
563 (defcustom org-archive-tag "ARCHIVE"
564 "The tag that marks a subtree as archived.
565 An archived subtree does not open during visibility cycling, and does
566 not contribute to the agenda listings."
567 :group 'org-archive
568 :group 'org-keywords
569 :type 'string)
570
571 (defcustom org-agenda-skip-archived-trees t
572 "Non-nil means, the agenda will skip any items located in archived trees.
573 An archived tree is a tree marked with the tag ARCHIVE."
574 :group 'org-archive
575 :group 'org-agenda-display
576 :type 'boolean)
577
578 (defcustom org-cycle-open-archived-trees nil
579 "Non-nil means, `org-cycle' will open archived trees.
580 An archived tree is a tree marked with the tag ARCHIVE.
581 When nil, archived trees will stay folded. You can still open them with
582 normal outline commands like `show-all', but not with the cycling commands."
583 :group 'org-archive
584 :group 'org-cycle
585 :type 'boolean)
586
587 (defcustom org-sparse-tree-open-archived-trees nil
588 "Non-nil means sparse tree construction shows matches in archived trees.
589 When nil, matches in these trees are highlighted, but the trees are kept in
590 collapsed state."
591 :group 'org-archive
592 :group 'org-sparse-trees
593 :type 'boolean)
594
595 (defcustom org-archive-location "%s_archive::"
596 "The location where subtrees should be archived.
597 This string consists of two parts, separated by a double-colon.
598
599 The first part is a file name - when omitted, archiving happens in the same
600 file. %s will be replaced by the current file name (without directory part).
601 Archiving to a different file is useful to keep archived entries from
602 contributing to the Org-mode Agenda.
603
604 The part after the double colon is a headline. The archived entries will be
605 filed under that headline. When omitted, the subtrees are simply filed away
606 at the end of the file, as top-level entries.
607
608 Here are a few examples:
609 \"%s_archive::\"
610 If the current file is Projects.org, archive in file
611 Projects.org_archive, as top-level trees. This is the default.
612
613 \"::* Archived Tasks\"
614 Archive in the current file, under the top-level headline
615 \"* Archived Tasks\".
616
617 \"~/org/archive.org::\"
618 Archive in file ~/org/archive.org (absolute path), as top-level trees.
619
620 \"basement::** Finished Tasks\"
621 Archive in file ./basement (relative path), as level 3 trees
622 below the level 2 heading \"** Finished Tasks\".
623
624 You may set this option on a per-file basis by adding to the buffer a
625 line like
626
627 #+ARCHIVE: basement::** Finished Tasks"
628 :group 'org-archive
629 :type 'string)
630
631 (defcustom org-archive-mark-done t
632 "Non-nil means, mark entries as DONE when they are moved to the archive file."
633 :group 'org-archive
634 :type 'boolean)
635
636 (defcustom org-archive-stamp-time t
637 "Non-nil means, add a time stamp to entries moved to an archive file.
638 The time stamp will be added directly after the TODO state keyword in the
639 first line, so it is probably best to use this in combinations with
640 `org-archive-mark-done'."
641 :group 'org-archive
642 :type 'boolean)
643
644 (defgroup org-table nil
645 "Options concerning tables in Org-mode."
646 :tag "Org Table"
647 :group 'org)
648
649 (defcustom org-enable-table-editor 'optimized
650 "Non-nil means, lines starting with \"|\" are handled by the table editor.
651 When nil, such lines will be treated like ordinary lines.
652
653 When equal to the symbol `optimized', the table editor will be optimized to
654 do the following:
655 - Use automatic overwrite mode in front of whitespace in table fields.
656 This make the structure of the table stay in tact as long as the edited
657 field does not exceed the column width.
658 - Minimize the number of realigns. Normally, the table is aligned each time
659 TAB or RET are pressed to move to another field. With optimization this
660 happens only if changes to a field might have changed the column width.
661 Optimization requires replacing the functions `self-insert-command',
662 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
663 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
664 very good at guessing when a re-align will be necessary, but you can always
665 force one with \\[org-ctrl-c-ctrl-c].
666
667 If you would like to use the optimized version in Org-mode, but the
668 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
669
670 This variable can be used to turn on and off the table editor during a session,
671 but in order to toggle optimization, a restart is required.
672
673 See also the variable `org-table-auto-blank-field'."
674 :group 'org-table
675 :type '(choice
676 (const :tag "off" nil)
677 (const :tag "on" t)
678 (const :tag "on, optimized" optimized)))
679
680 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
681 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
682 In the optimized version, the table editor takes over all simple keys that
683 normally just insert a character. In tables, the characters are inserted
684 in a way to minimize disturbing the table structure (i.e. in overwrite mode
685 for empty fields). Outside tables, the correct binding of the keys is
686 restored.
687
688 The default for this option is t if the optimized version is also used in
689 Org-mode. See the variable `org-enable-table-editor' for details. Changing
690 this variable requires a restart of Emacs to become effective."
691 :group 'org-table
692 :type 'boolean)
693
694 (defgroup org-table-settings nil
695 "Settings for tables in Org-mode."
696 :tag "Org Table Settings"
697 :group 'org-table)
698
699 (defcustom org-table-default-size "5x2"
700 "The default size for newly created tables, Columns x Rows."
701 :group 'org-table-settings
702 :type 'string)
703
704 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
705 "Regular expression for recognizing numbers in table columns.
706 If a table column contains mostly numbers, it will be aligned to the
707 right. If not, it will be aligned to the left.
708
709 The default value of this option is a regular expression which allows
710 anything which looks remotely like a number as used in scientific
711 context. For example, all of the following will be considered a
712 number:
713 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
714
715 Other options offered by the customize interface are more restrictive."
716 :group 'org-table-settings
717 :type '(choice
718 (const :tag "Positive Integers"
719 "^[0-9]+$")
720 (const :tag "Integers"
721 "^[-+]?[0-9]+$")
722 (const :tag "Floating Point Numbers"
723 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
724 (const :tag "Floating Point Number or Integer"
725 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
726 (const :tag "Exponential, Floating point, Integer"
727 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
728 (const :tag "Very General Number-Like"
729 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
730 (string :tag "Regexp:")))
731
732 (defcustom org-table-number-fraction 0.5
733 "Fraction of numbers in a column required to make the column align right.
734 In a column all non-white fields are considered. If at least this
735 fraction of fields is matched by `org-table-number-fraction',
736 alignment to the right border applies."
737 :group 'org-table-settings
738 :type 'number)
739
740 (defgroup org-table-editing nil
741 "Bahavior of tables during editing in Org-mode."
742 :tag "Org Table Editing"
743 :group 'org-table)
744
745 (defcustom org-table-automatic-realign t
746 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
747 When nil, aligning is only done with \\[org-table-align], or after column
748 removal/insertion."
749 :group 'org-table-editing
750 :type 'boolean)
751
752 (defcustom org-table-limit-column-width t ;kw
753 "Non-nil means, allow to limit the width of table columns with <N> fields."
754 :group 'org-table-editing
755 :type 'boolean)
756
757 (defcustom org-table-auto-blank-field t
758 "Non-nil means, automatically blank table field when starting to type into it.
759 This only happens when typing immediately after a field motion
760 command (TAB, S-TAB or RET).
761 Only relevant when `org-enable-table-editor' is equal to `optimized'."
762 :group 'org-table-editing
763 :type 'boolean)
764
765 (defcustom org-table-tab-jumps-over-hlines t
766 "Non-nil means, tab in the last column of a table with jump over a hline.
767 If a horizontal separator line is following the current line,
768 `org-table-next-field' can either create a new row before that line, or jump
769 over the line. When this option is nil, a new line will be created before
770 this line."
771 :group 'org-table-editing
772 :type 'boolean)
773
774 (defcustom org-table-tab-recognizes-table.el t
775 "Non-nil means, TAB will automatically notice a table.el table.
776 When it sees such a table, it moves point into it and - if necessary -
777 calls `table-recognize-table'."
778 :group 'org-table-editing
779 :type 'boolean)
780
781 (defgroup org-table-calculation nil
782 "Options concerning tables in Org-mode."
783 :tag "Org Table Calculation"
784 :group 'org-table)
785
786 (defcustom org-table-copy-increment t
787 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
788 :group 'org-table-calculation
789 :type 'boolean)
790
791 (defcustom org-calc-default-modes
792 '(calc-internal-prec 12
793 calc-float-format (float 5)
794 calc-angle-mode deg
795 calc-prefer-frac nil
796 calc-symbolic-mode nil
797 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
798 calc-display-working-message t
799 )
800 "List with Calc mode settings for use in calc-eval for table formulas.
801 The list must contain alternating symbols (Calc modes variables and values).
802 Don't remove any of the default settings, just change the values. Org-mode
803 relies on the variables to be present in the list."
804 :group 'org-table-calculation
805 :type 'plist)
806
807 (defcustom org-table-formula-evaluate-inline t
808 "Non-nil means, TAB and RET evaluate a formula in current table field.
809 If the current field starts with an equal sign, it is assumed to be a formula
810 which should be evaluated as described in the manual and in the documentation
811 string of the command `org-table-eval-formula'. This feature requires the
812 Emacs calc package.
813 When this variable is nil, formula calculation is only available through
814 the command \\[org-table-eval-formula]."
815 :group 'org-table-calculation
816 :type 'boolean)
817
818
819 (defcustom org-table-formula-use-constants t
820 "Non-nil means, interpret constants in formulas in tables.
821 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
822 by the value given in `org-table-formula-constants', or by a value obtained
823 from the `constants.el' package."
824 :group 'org-table-calculation
825 :type 'boolean)
826
827 (defcustom org-table-formula-constants nil
828 "Alist with constant names and values, for use in table formulas.
829 The car of each element is a name of a constant, without the `$' before it.
830 The cdr is the value as a string. For example, if you'd like to use the
831 speed of light in a formula, you would configure
832
833 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
834
835 and then use it in an equation like `$1*$c'."
836 :group 'org-table-calculation
837 :type '(repeat
838 (cons (string :tag "name")
839 (string :tag "value"))))
840
841 (defcustom org-table-formula-numbers-only nil
842 "Non-nil means, calculate only with numbers in table formulas.
843 Then all input fields will be converted to a number, and the result
844 must also be a number. When nil, calc's full potential is available
845 in table calculations, including symbolics etc."
846 :group 'org-table-calculation
847 :type 'boolean)
848
849 (defcustom org-table-allow-automatic-line-recalculation t
850 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
851 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
852 :group 'org-table-calculation
853 :type 'boolean)
854
855 (defgroup org-link nil
856 "Options concerning links in Org-mode."
857 :tag "Org Link"
858 :group 'org)
859
860 (defcustom org-descriptive-links t
861 "Non-nil means, hide link part and only show description of bracket links.
862 Bracket links are like [[link][descritpion]]. This variable sets the initial
863 state in new org-mode buffers. The setting can then be toggled on a
864 per-buffer basis from the Org->Hyperlinks menu."
865 :group 'org-link
866 :type 'boolean)
867
868 (defcustom org-link-style 'bracket
869 "The style of links to be inserted with \\[org-insert-link].
870 Possible values are:
871 bracket [[link][description]]. This is recommended
872 plain Description \\n link. The old way, no longer recommended."
873 :group 'org-link
874 :type '(choice
875 (const :tag "Bracket (recommended)" bracket)
876 (const :tag "Plain (no longer recommended)" plain)))
877
878 (defcustom org-link-format "%s"
879 "Default format for external, URL-like linkes in the buffer.
880 This is a format string for printf, %s will be replaced by the link text.
881 The recommended value is just \"%s\", since links will be protected by
882 enclosing them in double brackets. If you prefer plain links (see variable
883 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
884 additional URL: prefix, so the format would be \"<URL:%s>\"."
885 :group 'org-link
886 :type '(choice
887 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
888 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
889 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
890 (string :tag "Other" :value "<%s>")))
891
892 (defcustom org-link-file-path-type 'adaptive
893 "How the path name in file links should be stored.
894 Valid values are:
895
896 relative relative to the current directory, i.e. the directory of the file
897 into which the link is being inserted.
898 absolute absolute path, if possible with ~ for home directory.
899 noabbrev absolute path, no abbreviation of home directory.
900 adaptive Use relative path for files in the current directory and sub-
901 directories of it. For other files, use an absolute path."
902 :group 'org-link
903 :type '(choice
904 (const relative)
905 (const absolute)
906 (const noabbrev)
907 (const adaptive)))
908
909 (defcustom org-activate-links '(bracket angle plain radio tag date)
910 "Types of links that should be activated in Org-mode files.
911 This is a list of symbols, each leading to the activation of a certain link
912 type. In principle, it does not hurt to turn on most link types - there may
913 be a small gain when turning off unused link types. The types are:
914
915 bracket The recommended [[link][description]] or [[link]] links with hiding.
916 angular Links in angular brackes that may contain whitespace like
917 <bbdb:Carsten Dominik>.
918 plain Plain links in normal text, no whitespace, like http://google.com.
919 radio Text that is matched by a radio target, see manual for details.
920 tag Tag settings in a headline (link to tag search).
921 date Time stamps (link to calendar).
922 camel CamelCase words defining text searches.
923
924 Changing this variable requires a restart of Emacs to become effective."
925 :group 'org-link
926 :type '(set (const :tag "Double bracket links (new style)" bracket)
927 (const :tag "Angular bracket links (old style)" angular)
928 (const :tag "plain text links" plain)
929 (const :tag "Radio target matches" radio)
930 (const :tag "Tags" tag)
931 (const :tag "Timestamps" date)
932 (const :tag "CamelCase words" camel)))
933
934 (defgroup org-link-store nil
935 "Options concerning storing links in Org-mode"
936 :tag "Org Store Link"
937 :group 'org-link)
938
939 (defcustom org-context-in-file-links t
940 "Non-nil means, file links from `org-store-link' contain context.
941 A search string will be added to the file name with :: as separator and
942 used to find the context when the link is activated by the command
943 `org-open-at-point'.
944 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
945 negates this setting for the duration of the command."
946 :group 'org-link-store
947 :type 'boolean)
948
949 (defcustom org-file-link-context-use-camel-case nil
950 "Non-nil means, use CamelCase to store a search context in a file link.
951 When nil, the search string simply consists of the words of the string.
952 CamelCase is deprecated, and support for it may be dropped in the future."
953 :group 'org-link-store
954 :type 'boolean)
955
956 (defcustom org-keep-stored-link-after-insertion nil
957 "Non-nil means, keep link in list for entire session.
958
959 The command `org-store-link' adds a link pointing to the current
960 location to an internal list. These links accumulate during a session.
961 The command `org-insert-link' can be used to insert links into any
962 Org-mode file (offering completion for all stored links). When this
963 option is nil, every link which has been inserted once using \\[org-insert-link]
964 will be removed from the list, to make completing the unused links
965 more efficient."
966 :group 'org-link-store
967 :type 'boolean)
968
969 (defcustom org-usenet-links-prefer-google nil
970 "Non-nil means, `org-store-link' will create web links to Google groups.
971 When nil, Gnus will be used for such links.
972 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
973 negates this setting for the duration of the command."
974 :group 'org-link-store
975 :type 'boolean)
976
977 (defgroup org-link-follow nil
978 "Options concerning following links in Org-mode"
979 :tag "Org Follow Link"
980 :group 'org-link)
981
982 (defcustom org-tab-follows-link nil
983 "Non-nil means, on links TAB will follow the link.
984 Needs to be set before org.el is loaded."
985 :group 'org-link-follow
986 :type 'boolean)
987
988 (defcustom org-return-follows-link nil
989 "Non-nil means, on links RET will follow the link.
990 Needs to be set before org.el is loaded."
991 :group 'org-link-follow
992 :type 'boolean)
993
994 (defcustom org-mouse-1-follows-link t
995 "Non-nil means, mouse-1 on a link will follow the link.
996 A longer mouse click will still set point. Does not wortk on XEmacs.
997 Needs to be set before org.el is loaded."
998 :group 'org-link-follow
999 :type 'boolean)
1000
1001 (defcustom org-mark-ring-length 4
1002 "Number of different positions to be recorded in the ring
1003 Changing this requires a restart of Emacs to work correctly."
1004 :group 'org-link-follow
1005 :type 'interger)
1006
1007 (defcustom org-link-frame-setup
1008 '((vm . vm-visit-folder-other-frame)
1009 (gnus . gnus-other-frame)
1010 (file . find-file-other-window))
1011 "Setup the frame configuration for following links.
1012 When following a link with Emacs, it may often be useful to display
1013 this link in another window or frame. This variable can be used to
1014 set this up for the different types of links.
1015 For VM, use any of
1016 `vm-visit-folder'
1017 `vm-visit-folder-other-frame'
1018 For Gnus, use any of
1019 `gnus'
1020 `gnus-other-frame'
1021 For FILE, use any of
1022 `find-file'
1023 `find-file-other-window'
1024 `find-file-other-frame'
1025 For the calendar, use the variable `calendar-setup'.
1026 For BBDB, it is currently only possible to display the matches in
1027 another window."
1028 :group 'org-link-follow
1029 :type '(list
1030 (cons (const vm)
1031 (choice
1032 (const vm-visit-folder)
1033 (const vm-visit-folder-other-window)
1034 (const vm-visit-folder-other-frame)))
1035 (cons (const gnus)
1036 (choice
1037 (const gnus)
1038 (const gnus-other-frame)))
1039 (cons (const file)
1040 (choice
1041 (const find-file)
1042 (const find-file-other-window)
1043 (const find-file-other-frame)))))
1044
1045 (defcustom org-open-non-existing-files nil
1046 "Non-nil means, `org-open-file' will open non-existing file.
1047 When nil, an error will be generated."
1048 :group 'org-link-follow
1049 :type 'boolean)
1050
1051 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1052 "Non-nil means, ask for confirmation before executing shell links.
1053 Shell links can be dangerous, just thing about a link
1054
1055 [[shell:rm -rf ~/*][Google Search]]
1056
1057 This link would show up in your Org-mode document as \"Google Search\"
1058 but really it would remove your entire home directory.
1059 Therefore I *definitely* advise against setting this variable to nil.
1060 Just change it to `y-or-n-p' of you want to confirm with a single key press
1061 rather than having to type \"yes\"."
1062 :group 'org-link-follow
1063 :type '(choice
1064 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1065 (const :tag "with y-or-n (faster)" y-or-n-p)
1066 (const :tag "no confirmation (dangerous)" nil)))
1067
1068 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1069 "Non-nil means, ask for confirmation before executing elisp links.
1070 Elisp links can be dangerous, just thing about a link
1071
1072 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1073
1074 This link would show up in your Org-mode document as \"Google Search\"
1075 but really it would remove your entire home directory.
1076 Therefore I *definitely* advise against setting this variable to nil.
1077 Just change it to `y-or-n-p' of you want to confirm with a single key press
1078 rather than having to type \"yes\"."
1079 :group 'org-link-follow
1080 :type '(choice
1081 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1082 (const :tag "with y-or-n (faster)" y-or-n-p)
1083 (const :tag "no confirmation (dangerous)" nil)))
1084
1085 (defconst org-file-apps-defaults-gnu
1086 '((remote . emacs)
1087 (t . mailcap))
1088 "Default file applications on a UNIX or GNU/Linux system.
1089 See `org-file-apps'.")
1090
1091 (defconst org-file-apps-defaults-macosx
1092 '((remote . emacs)
1093 (t . "open %s")
1094 ("ps" . "gv %s")
1095 ("ps.gz" . "gv %s")
1096 ("eps" . "gv %s")
1097 ("eps.gz" . "gv %s")
1098 ("dvi" . "xdvi %s")
1099 ("fig" . "xfig %s"))
1100 "Default file applications on a MacOS X system.
1101 The system \"open\" is known as a default, but we use X11 applications
1102 for some files for which the OS does not have a good default.
1103 See `org-file-apps'.")
1104
1105 (defconst org-file-apps-defaults-windowsnt
1106 (list
1107 '(remote . emacs)
1108 (cons t
1109 (list (if (featurep 'xemacs)
1110 'mswindows-shell-execute
1111 'w32-shell-execute)
1112 "open" 'file)))
1113 "Default file applications on a Windows NT system.
1114 The system \"open\" is used for most files.
1115 See `org-file-apps'.")
1116
1117 (defcustom org-file-apps
1118 '(
1119 ("txt" . emacs)
1120 ("tex" . emacs)
1121 ("ltx" . emacs)
1122 ("org" . emacs)
1123 ("el" . emacs)
1124 ("bib" . emacs)
1125 )
1126 "External applications for opening `file:path' items in a document.
1127 Org-mode uses system defaults for different file types, but
1128 you can use this variable to set the application for a given file
1129 extension. The entries in this list are cons cells where the car identifies
1130 files and the cdr the corresponding command. Possible values for the
1131 file identifier are
1132 \"ext\" A string identifying an extension
1133 `directory' Matches a directory
1134 `remote' Matches a remote file, accessible through tramp or efs.
1135 Remote files most likely should be visited through Emacs
1136 because external applications cannot handle such paths.
1137 t Default for all remaining files
1138
1139 Possible values for the command are:
1140 `emacs' The file will be visited by the current Emacs process.
1141 `default' Use the default application for this file type.
1142 string A command to be executed by a shell; %s will be replaced
1143 by the path to the file.
1144 sexp A Lisp form which will be evaluated. The file path will
1145 be available in the Lisp variable `file'.
1146 For more examples, see the system specific constants
1147 `org-file-apps-defaults-macosx'
1148 `org-file-apps-defaults-windowsnt'
1149 `org-file-apps-defaults-gnu'."
1150 :group 'org-link-follow
1151 :type '(repeat
1152 (cons (choice :value ""
1153 (string :tag "Extension")
1154 (const :tag "Default for unrecognized files" t)
1155 (const :tag "Remote file" remote)
1156 (const :tag "Links to a directory" directory))
1157 (choice :value ""
1158 (const :tag "Visit with Emacs" emacs)
1159 (const :tag "Use system default" default)
1160 (string :tag "Command")
1161 (sexp :tag "Lisp form")))))
1162
1163 (defcustom org-mhe-search-all-folders nil
1164 "Non-nil means, that the search for the mh-message will be extended to
1165 all folders if the message cannot be found in the folder given in the link.
1166 Searching all folders is very effective with one of the search engines
1167 supported by MH-E, but will be slow with pick."
1168 :group 'org-link-follow
1169 :type 'boolean)
1170
1171 (defgroup org-remember nil
1172 "Options concerning interaction with remember.el."
1173 :tag "Org Remember"
1174 :group 'org)
1175
1176 (defcustom org-directory "~/org"
1177 "Directory with org files.
1178 This directory will be used as default to prompt for org files.
1179 Used by the hooks for remember.el."
1180 :group 'org-remember
1181 :type 'directory)
1182
1183 (defcustom org-default-notes-file "~/.notes"
1184 "Default target for storing notes.
1185 Used by the hooks for remember.el. This can be a string, or nil to mean
1186 the value of `remember-data-file'."
1187 :group 'org-remember
1188 :type '(choice
1189 (const :tag "Default from remember-data-file" nil)
1190 file))
1191
1192 (defcustom org-remember-templates nil
1193 "Templates for the creation of remember buffers.
1194 When nil, just let remember make the buffer.
1195 When not nil, this is a list of 3-element lists. In each entry, the first
1196 element is a character, a unique key to select this template.
1197 The second element is the template. The third element is optional and can
1198 specify a destination file for remember items created with this template.
1199 The default file is given by `org-default-notes-file'.
1200
1201 The template specifies the structure of the remember buffer. It should have
1202 a first line starting with a star, to act as the org-mode headline.
1203 Furthermore, the following %-escapes will be replaced with content:
1204 %t time stamp, date only
1205 %T time stamp with date and time
1206 %u inactive time stamp, date only
1207 %U inactive time stamp with date and time
1208 %n user name
1209 %a annotation, normally the link created with org-store-link
1210 %i initial content, the region when remember is called with C-u.
1211 If %i is indented, the entire inserted text will be indented as well.
1212 %? This will be removed, and the cursor placed at this position."
1213 :group 'org-remember
1214 :type '(repeat :tag "enabled"
1215 (list :value (?a "\n" nil)
1216 (character :tag "Selection Key")
1217 (string :tag "Template")
1218 (file :tag "Destination file (optional)"))))
1219
1220 (defcustom org-reverse-note-order nil
1221 "Non-nil means, store new notes at the beginning of a file or entry.
1222 When nil, new notes will be filed to the end of a file or entry."
1223 :group 'org-remember
1224 :type '(choice
1225 (const :tag "Reverse always" t)
1226 (const :tag "Reverse never" nil)
1227 (repeat :tag "By file name regexp"
1228 (cons regexp boolean))))
1229
1230 (defgroup org-todo nil
1231 "Options concerning TODO items in Org-mode."
1232 :tag "Org TODO"
1233 :group 'org)
1234
1235 (defcustom org-todo-keywords '("TODO" "DONE")
1236 "List of TODO entry keywords.
1237 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1238 considered to mean that the entry is \"done\". All the other mean that
1239 action is required, and will make the entry show up in todo lists, diaries
1240 etc.
1241 The command \\[org-todo] cycles an entry through these states, and an
1242 additional state where no keyword is present. For details about this
1243 cycling, see also the variable `org-todo-interpretation'
1244 Changes become only effective after restarting Emacs."
1245 :group 'org-todo
1246 :group 'org-keywords
1247 :type '(repeat (string :tag "Keyword")))
1248
1249 (defcustom org-todo-interpretation 'sequence
1250 "Controls how TODO keywords are interpreted.
1251 This variable is only relevant if `org-todo-keywords' contains more than two
1252 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1253
1254 When `sequence', \\[org-todo] will always switch to the next state in the
1255 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1256 to state when executed several times in direct succession. Otherwise, it
1257 switches directly to DONE from any state.
1258 See the manual for more information."
1259 :group 'org-todo
1260 :group 'org-keywords
1261 :type '(choice (const sequence)
1262 (const type)))
1263
1264 (defcustom org-after-todo-state-change-hook nil
1265 "Hook which is run after the state of a TODO item was changed.
1266 The new state (a string with a TODO keyword, or nil) is available in the
1267 Lisp variable `state'."
1268 :group 'org-todo
1269 :type 'hook)
1270
1271 (defcustom org-log-done nil
1272 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1273 When the state of an entry is changed from nothing to TODO, remove a previous
1274 closing date.
1275 This can also be configured on a per-file basis by adding one of
1276 the following lines anywhere in the buffer:
1277
1278 #+STARTUP: logging
1279 #+STARTUP: nologging"
1280 :group 'org-todo
1281 :type 'boolean)
1282
1283 (defgroup org-priorities nil
1284 "Priorities in Org-mode."
1285 :tag "Org Priorities"
1286 :group 'org-todo)
1287
1288 (defcustom org-default-priority ?B
1289 "The default priority of TODO items.
1290 This is the priority an item get if no explicit priority is given."
1291 :group 'org-priorities
1292 :type 'character)
1293
1294 (defcustom org-lowest-priority ?C
1295 "The lowest priority of TODO items. A character like ?A, ?B etc."
1296 :group 'org-priorities
1297 :type 'character)
1298
1299 (defgroup org-time nil
1300 "Options concerning time stamps and deadlines in Org-mode."
1301 :tag "Org Time"
1302 :group 'org)
1303
1304 (defcustom org-insert-labeled-timestamps-at-point nil
1305 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1306 When nil, these labeled time stamps are forces into the second line of an
1307 entry, just after the headline. When scheduling from the global TODO list,
1308 the time stamp will always be forced into the second line."
1309 :group 'org-time
1310 :type 'boolean)
1311
1312 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1313 "Formats for `format-time-string' which are used for time stamps.
1314 It is not recommended to change this constant.")
1315
1316 (defcustom org-time-stamp-rounding-minutes 0
1317 "Number of minutes to round time stamps to upon insertion.
1318 When zero, insert the time unmodified. Useful rounding numbers
1319 should be factors of 60, so for example 5, 10, 15.
1320 When this is not zero, you can still force an exact time-stamp by using
1321 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1322 :group 'org-time
1323 :type 'integer)
1324
1325 (defcustom org-deadline-warning-days 30
1326 "No. of days before expiration during which a deadline becomes active.
1327 This variable governs the display in the org file."
1328 :group 'org-time
1329 :type 'number)
1330
1331 (defcustom org-popup-calendar-for-date-prompt t
1332 "Non-nil means, pop up a calendar when prompting for a date.
1333 In the calendar, the date can be selected with mouse-1. However, the
1334 minibuffer will also be active, and you can simply enter the date as well.
1335 When nil, only the minibuffer will be available."
1336 :group 'org-time
1337 :type 'boolean)
1338
1339 (defcustom org-calendar-follow-timestamp-change t
1340 "Non-nil means, make the calendar window follow timestamp changes.
1341 When a timestamp is modified and the calendar window is visible, it will be
1342 moved to the new date."
1343 :group 'org-time
1344 :type 'boolean)
1345
1346 (defgroup org-tags nil
1347 "Options concerning tags in Org-mode."
1348 :tag "Org Tags"
1349 :group 'org)
1350
1351 (defcustom org-tag-alist nil
1352 "List of tags allowed in Org-mode files.
1353 When this list is nil, Org-mode will base TAG input on what is already in the
1354 buffer.
1355 The value of this variable is an alist, the car may be (and should) be a
1356 character that is used to select that tag through the fast-tag-selection
1357 interface. See the manual for details."
1358 :group 'org-tags
1359 :type '(repeat
1360 (choice
1361 (cons (string :tag "Tag name")
1362 (character :tag "Access char"))
1363 (const :tag "Start radio group" (:startgroup))
1364 (const :tag "End radio group" (:endgroup)))))
1365
1366 (defcustom org-use-fast-tag-selection 'auto
1367 "Non-nil means, use fast tag selection scheme.
1368 This is a special interface to select and deselect tags with single keys.
1369 When nil, fast selection is never used.
1370 When the symbol `auto', fast selection is used if and only if selection
1371 characters for tags have been configured, either through the variable
1372 `org-tag-alist' or through a #+TAGS line in the buffer.
1373 When t, fast selection is always used and selection keys are assigned
1374 automatically if necessary."
1375 :group 'org-tags
1376 :type '(choice
1377 (const :tag "Always" t)
1378 (const :tag "Never" nil)
1379 (const :tag "When selection characters are configured" 'auto)))
1380
1381 (defcustom org-tags-column 48
1382 "The column to which tags should be indented in a headline.
1383 If this number is positive, it specifies the column. If it is negative,
1384 it means that the tags should be flushright to that column. For example,
1385 -79 works well for a normal 80 character screen."
1386 :group 'org-tags
1387 :type 'integer)
1388
1389 (defcustom org-auto-align-tags t
1390 "Non-nil means, realign tags after pro/demotion of TODO state change.
1391 These operations change the length of a headline and therefore shift
1392 the tags around. With this options turned on, after each such operation
1393 the tags are again aligned to `org-tags-column'."
1394 :group 'org-tags
1395 :type 'boolean)
1396
1397 (defcustom org-use-tag-inheritance t
1398 "Non-nil means, tags in levels apply also for sublevels.
1399 When nil, only the tags directly given in a specific line apply there.
1400 If you turn off this option, you very likely want to turn on the
1401 companion option `org-tags-match-list-sublevels'."
1402 :group 'org-tags
1403 :type 'boolean)
1404
1405 (defcustom org-tags-match-list-sublevels nil
1406 "Non-nil means list also sublevels of headlines matching tag search.
1407 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1408 the sublevels of a headline matching a tag search often also match
1409 the same search. Listing all of them can create very long lists.
1410 Setting this variable to nil causes subtrees of a match to be skipped.
1411 This option is off by default, because inheritance in on. If you turn
1412 inheritance off, you very likely want to turn this option on.
1413
1414 As a special case, if the tag search is restricted to TODO items, the
1415 value of this variable is ignored and sublevels are always checked, to
1416 make sure all corresponding TODO items find their way into the list."
1417 :group 'org-tags
1418 :type 'boolean)
1419
1420 (defvar org-tags-history nil
1421 "History of minibuffer reads for tags.")
1422 (defvar org-last-tags-completion-table nil
1423 "The last used completion table for tags.")
1424
1425 (defgroup org-agenda nil
1426 "Options concerning agenda display Org-mode."
1427 :tag "Org Agenda"
1428 :group 'org)
1429
1430 (defvar org-category nil
1431 "Variable used by org files to set a category for agenda display.
1432 Such files should use a file variable to set it, for example
1433
1434 -*- mode: org; org-category: \"ELisp\"
1435
1436 or contain a special line
1437
1438 #+CATEGORY: ELisp
1439
1440 If the file does not specify a category, then file's base name
1441 is used instead.")
1442 (make-variable-buffer-local 'org-category)
1443
1444 (defcustom org-agenda-files nil
1445 "The files to be used for agenda display.
1446 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1447 \\[org-remove-file]. You can also use customize to edit the list.
1448
1449 If the value of the variable is not a list but a single file name, then
1450 the list of agenda files is actually stored and maintained in that file, one
1451 agenda file per line."
1452 :group 'org-agenda
1453 :type '(choice
1454 (repeat :tag "List of files" file)
1455 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1456
1457 (defcustom org-agenda-custom-commands '(("w" todo "WAITING"))
1458 "Custom commands for the agenda.
1459 These commands will be offered on the splash screen displayed by the
1460 agenda dispatcher \\[org-agenda]. Each entry is a list of 3 items:
1461
1462 key The key (a single char as a string) to be associated with the command.
1463 type The command type, any of the following symbols:
1464 todo Entries with a specific TODO keyword, in all agenda files.
1465 tags Tags match in all agenda files.
1466 tags-todo Tags match in all agenda files, TODO entries only.
1467 todo-tree Sparse tree of specific TODO keyword in *current* file.
1468 tags-tree Sparse tree with all tags matches in *current* file.
1469 occur-tree Occur sparse tree for current file.
1470 match What to search for:
1471 - a single keyword for TODO keyword searches
1472 - a tags match expression for tags searches
1473 - a regular expression for occur searches"
1474 :group 'org-agenda
1475 :type '(repeat
1476 (list (string :tag "Key")
1477 (choice :tag "Type"
1478 (const :tag "Tags search in all agenda files" tags)
1479 (const :tag "Tags search of TODO entries, all agenda files" tags-todo)
1480 (const :tag "TODO keyword search in all agenda files" todo)
1481 (const :tag "Tags sparse tree in current buffer" tags-tree)
1482 (const :tag "TODO keyword tree in current buffer" todo-tree)
1483 (const :tag "Occur tree in current buffer" occur-tree))
1484 (string :tag "Match"))))
1485
1486 (defcustom org-agenda-todo-list-sublevels t
1487 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1488 When nil, the sublevels of a TODO entry are not checked, resulting in
1489 potentially much shorter TODO lists."
1490 :group 'org-agenda
1491 :group 'org-todo
1492 :type 'boolean)
1493
1494 (defcustom org-agenda-todo-ignore-scheduled nil
1495 "Non-nil means, don't show scheduled entries in the global todo list.
1496 The idea behind this is that by scheduling it, you have already taken care
1497 of this item."
1498 :group 'org-agenda
1499 :group 'org-todo
1500 :type 'boolean)
1501
1502 (defcustom org-agenda-include-all-todo nil
1503 "Non-nil means, the agenda will always contain all TODO entries.
1504 When nil, date-less entries will only be shown if `org-agenda' is called
1505 with a prefix argument.
1506 When non-nil, the TODO entries will be listed at the top of the agenda, before
1507 the entries for specific days."
1508 :group 'org-agenda
1509 :type 'boolean)
1510
1511 (defcustom org-agenda-include-diary nil
1512 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1513 :group 'org-agenda
1514 :type 'boolean)
1515
1516 (defcustom org-calendar-to-agenda-key [?c]
1517 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1518 The command `org-calendar-goto-agenda' will be bound to this key. The
1519 default is the character `c' because then `c' can be used to switch back and
1520 forth between agenda and calendar."
1521 :group 'org-agenda
1522 :type 'sexp)
1523
1524 (defgroup org-agenda-setup nil
1525 "Options concerning setting up the Agenda window in Org Mode."
1526 :tag "Org Agenda Window Setup"
1527 :group 'org-agenda)
1528
1529 (defcustom org-agenda-mouse-1-follows-link nil
1530 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1531 A longer mouse click will still set point. Does not wortk on XEmacs.
1532 Needs to be set before org.el is loaded."
1533 :group 'org-agenda-setup
1534 :type 'boolean)
1535
1536 (defcustom org-agenda-start-with-follow-mode nil
1537 "The initial value of follwo-mode in a newly created agenda window."
1538 :group 'org-agenda-setup
1539 :type 'boolean)
1540
1541 (defcustom org-select-agenda-window t
1542 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1543 When nil, cursor will remain in the current window."
1544 :group 'org-agenda-setup
1545 :type 'boolean)
1546
1547 (defcustom org-fit-agenda-window t
1548 "Non-nil means, change window size of agenda to fit content."
1549 :group 'org-agenda-setup
1550 :type 'boolean)
1551
1552 (defgroup org-agenda-display nil
1553 "Options concerning what to display initially in Agenda."
1554 :tag "Org Agenda Display"
1555 :group 'org-agenda)
1556
1557 (defcustom org-agenda-show-all-dates t
1558 "Non-nil means, `org-agenda' shows every day in the selected range.
1559 When nil, only the days which actually have entries are shown."
1560 :group 'org-agenda-display
1561 :type 'boolean)
1562
1563 (defcustom org-agenda-start-on-weekday 1
1564 "Non-nil means, start the overview always on the specified weekday.
1565 0 denotes Sunday, 1 denotes Monday etc.
1566 When nil, always start on the current day."
1567 :group 'org-agenda-display
1568 :type '(choice (const :tag "Today" nil)
1569 (number :tag "Weekday No.")))
1570
1571 (defcustom org-agenda-ndays 7
1572 "Number of days to include in overview display.
1573 Should be 1 or 7."
1574 :group 'org-agenda-display
1575 :type 'number)
1576
1577 (defcustom org-agenda-use-time-grid t
1578 "Non-nil means, show a time grid in the agenda schedule.
1579 A time grid is a set of lines for specific times (like every two hours between
1580 8:00 and 20:00). The items scheduled for a day at specific times are
1581 sorted in between these lines.
1582 For details about when the grid will be shown, and what it will look like, see
1583 the variable `org-agenda-time-grid'."
1584 :group 'org-agenda-display
1585 :type 'boolean)
1586
1587 (defcustom org-agenda-time-grid
1588 '((daily today require-timed)
1589 "----------------"
1590 (800 1000 1200 1400 1600 1800 2000))
1591
1592 "The settings for time grid for agenda display.
1593 This is a list of three items. The first item is again a list. It contains
1594 symbols specifying conditions when the grid should be displayed:
1595
1596 daily if the agenda shows a single day
1597 weekly if the agenda shows an entire week
1598 today show grid on current date, independent of daily/weekly display
1599 require-timed show grid only if at least on item has a time specification
1600
1601 The second item is a string which will be places behing the grid time.
1602
1603 The third item is a list of integers, indicating the times that should have
1604 a grid line."
1605 :group 'org-agenda-display
1606 :type
1607 '(list
1608 (set :greedy t :tag "Grid Display Options"
1609 (const :tag "Show grid in single day agenda display" daily)
1610 (const :tag "Show grid in weekly agenda display" weekly)
1611 (const :tag "Always show grid for today" today)
1612 (const :tag "Show grid only if any timed entries are present"
1613 require-timed)
1614 (const :tag "Skip grid times already present in an entry"
1615 remove-match))
1616 (string :tag "Grid String")
1617 (repeat :tag "Grid Times" (integer :tag "Time"))))
1618
1619 (defcustom org-agenda-sorting-strategy '(time-up category-keep priority-down)
1620 "Sorting structure for the agenda items of a single day.
1621 This is a list of symbols which will be used in sequence to determine
1622 if an entry should be listed before another entry. The following
1623 symbols are recognized:
1624
1625 time-up Put entries with time-of-day indications first, early first
1626 time-down Put entries with time-of-day indications first, late first
1627 category-keep Keep the default order of categories, corresponding to the
1628 sequence in `org-agenda-files'.
1629 category-up Sort alphabetically by category, A-Z.
1630 category-down Sort alphabetically by category, Z-A.
1631 priority-up Sort numerically by priority, high priority last.
1632 priority-down Sort numerically by priority, high priority first.
1633
1634 The different possibilities will be tried in sequence, and testing stops
1635 if one comparison returns a \"not-equal\". For example, the default
1636 '(time-up category-keep priority-down)
1637 means: Pull out all entries having a specified time of day and sort them,
1638 in order to make a time schedule for the current day the first thing in the
1639 agenda listing for the day. Of the entries without a time indication, keep
1640 the grouped in categories, don't sort the categories, but keep them in
1641 the sequence given in `org-agenda-files'. Within each category sort by
1642 priority.
1643
1644 Leaving out `category-keep' would mean that items will be sorted across
1645 categories by priority."
1646 :group 'org-agenda-display
1647 :type '(repeat
1648 (choice
1649 (const time-up)
1650 (const time-down)
1651 (const category-keep)
1652 (const category-up)
1653 (const category-down)
1654 (const priority-up)
1655 (const priority-down))))
1656
1657 (defcustom org-sort-agenda-notime-is-late t
1658 "Non-nil means, items without time are considered late.
1659 This is only relevant for sorting. When t, items which have no explicit
1660 time like 15:30 will be considered as 99:01, i.e. later than any items which
1661 do have a time. When nil, the default time is before 0:00. You can use this
1662 option to decide if the schedule for today should come before or after timeless
1663 agenda entries."
1664 :group 'org-agenda-display
1665 :type 'boolean)
1666
1667
1668 (defgroup org-agenda-prefix nil
1669 "Options concerning the entry prefix in the Org-mode agenda display."
1670 :tag "Org Agenda Prefix"
1671 :group 'org-agenda)
1672
1673 (defcustom org-agenda-prefix-format " %-12:c%?-12t% s"
1674 "Format specification for the prefix of items in the agenda buffer.
1675 This format works similar to a printf format, with the following meaning:
1676
1677 %c the category of the item, \"Diary\" for entries from the diary, or
1678 as given by the CATEGORY keyword or derived from the file name.
1679 %T the first tag of the item.
1680 %t the time-of-day specification if one applies to the entry, in the
1681 format HH:MM
1682 %s Scheduling/Deadline information, a short string
1683
1684 All specifiers work basically like the standard `%s' of printf, but may
1685 contain two additional characters: A question mark just after the `%' and
1686 a whitespace/punctuation character just before the final letter.
1687
1688 If the first character after `%' is a question mark, the entire field
1689 will only be included if the corresponding value applies to the
1690 current entry. This is useful for fields which should have fixed
1691 width when present, but zero width when absent. For example,
1692 \"%?-12t\" will result in a 12 character time field if a time of the
1693 day is specified, but will completely disappear in entries which do
1694 not contain a time.
1695
1696 If there is punctuation or whitespace character just before the final
1697 format letter, this character will be appended to the field value if
1698 the value is not empty. For example, the format \"%-12:c\" leads to
1699 \"Diary: \" if the category is \"Diary\". If the category were be
1700 empty, no additional colon would be interted.
1701
1702 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1703 - Indent the line with two space characters
1704 - Give the category in a 12 chars wide field, padded with whitespace on
1705 the right (because of `-'). Append a colon if there is a category
1706 (because of `:').
1707 - If there is a time-of-day, put it into a 12 chars wide field. If no
1708 time, don't put in an empty field, just skip it (because of '?').
1709 - Finally, put the scheduling information and append a whitespace.
1710
1711 As another example, if you don't want the time-of-day of entries in
1712 the prefix, you could use:
1713
1714 (setq org-agenda-prefix-format \" %-11:c% s\")
1715
1716 See also the variables `org-agenda-remove-times-when-in-prefix' and
1717 `org-agenda-remove-tags-when-in-prefix'."
1718 :type 'string
1719 :group 'org-agenda-prefix)
1720
1721 (defvar org-prefix-format-compiled nil
1722 "The compiled version of the most recently used prefix format.
1723 Depending on which command was used last, this may be the compiled version
1724 of `org-agenda-prefix-format' or `org-timeline-prefix-format'.")
1725
1726 (defcustom org-agenda-remove-times-when-in-prefix t
1727 "Non-nil means, remove duplicate time specifications in agenda items.
1728 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1729 time-of-day specification in a headline or diary entry is extracted and
1730 placed into the prefix. If this option is non-nil, the original specification
1731 \(a timestamp or -range, or just a plain time(range) specification like
1732 11:30-4pm) will be removed for agenda display. This makes the agenda less
1733 cluttered.
1734 The option can be t or nil. It may also be the symbol `beg', indicating
1735 that the time should only be removed what it is located at the beginning of
1736 the headline/diary entry."
1737 :group 'org-agenda-prefix
1738 :type '(choice
1739 (const :tag "Always" t)
1740 (const :tag "Never" nil)
1741 (const :tag "When at beginning of entry" beg)))
1742
1743 (defcustom org-agenda-remove-tags-when-in-prefix nil
1744 "Non-nil means, remove the tags from the headline copy in the agenda.
1745 When this is the symbol `prefix', only remove tags when
1746 `org-agenda-prefix-format' contains a `%T' specifier."
1747 :group 'org-agenda-prefix
1748 :type '(choice
1749 (const :tag "Always" t)
1750 (const :tag "Never" nil)
1751 (const :tag "When prefix format contains %T" prefix)))
1752
1753 (defgroup org-agenda-timeline nil
1754 "Options concerning the timeline buffer in Org Mode."
1755 :tag "Org Agenda Timeline"
1756 :group 'org-agenda)
1757
1758 (defcustom org-timeline-prefix-format " % s"
1759 "Like `org-agenda-prefix-format', but for the timeline of a single file."
1760 :type 'string
1761 :group 'org-agenda-timeline)
1762
1763 (defcustom org-select-timeline-window t
1764 "Non-nil means, after creating a timeline, move cursor into Timeline window.
1765 When nil, cursor will remain in the current window."
1766 :group 'org-agenda-timeline
1767 :type 'boolean)
1768
1769 (defcustom org-timeline-show-empty-dates 3
1770 "Non-nil means, `org-timeline' also shows dates without an entry.
1771 When nil, only the days which actually have entries are shown.
1772 When t, all days between the first and the last date are shown.
1773 When an integer, show also empty dates, but if there is a gap of more than
1774 N days, just insert a special line indicating the size of the gap."
1775 :group 'org-agenda-timeline
1776 :type '(choice
1777 (const :tag "None" nil)
1778 (const :tag "All" t)
1779 (number :tag "at most")))
1780
1781 (defgroup org-latex nil
1782 "Options for embedding LaTeX code into Org-mode"
1783 :tag "Org LaTeX"
1784 :group 'org)
1785
1786 (defcustom org-format-latex-options
1787 '(:foreground "Black" :background "Transparent" :scale 1.0
1788 :matchers ("begin" "$" "$$" "\\(" "\\["))
1789 "Options for creating images from LaTeX fragments.
1790 This is a property list with the following properties:
1791 :foreground the foreground color, for example \"Black\".
1792 :background the background color, or \"Transparent\".
1793 :scale a scaling factor for the size of the images
1794 :matchers a list indicating which matchers should be used to
1795 find LaTeX fragments. Valid members of this list are:
1796 \"begin\" find environments
1797 \"$\" find math expressions surrounded by $...$
1798 \"$$\" find math expressions surrounded by $$....$$
1799 \"\\(\" find math expressions surrounded by \\(...\\)
1800 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1801 :group 'org-latex
1802 :type 'plist)
1803
1804 (defgroup org-export nil
1805 "Options for exporting org-listings."
1806 :tag "Org Export"
1807 :group 'org)
1808
1809 (defgroup org-export-general nil
1810 "General options for exporting Org-mode files."
1811 :tag "Org Export General"
1812 :group 'org-export)
1813
1814 (defcustom org-export-publishing-directory "."
1815 "Path to the location where exported files should be located.
1816 This path may be relative to the directory where the Org-mode file lives.
1817 The default is to put them into the same directory as the Org-mode file.
1818 The variable may also be an alist with export types `:html', `:ascii',
1819 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
1820 is relative, it is interpreted relative to the directory where the exported
1821 Org-mode files lives."
1822 :group 'org-export-general
1823 :type '(choice
1824 (directory)
1825 (repeat
1826 (cons
1827 (choice :tag "Type"
1828 (const :html) (const :ascii) (const :ical) (const :xoxo))
1829 (directory)))))
1830
1831 (defcustom org-export-language-setup
1832 '(("en" "Author" "Date" "Table of Contents")
1833 ("cs" "Autor" "Datum" "Obsah")
1834 ("da" "Ophavsmand" "Dato" "Indhold")
1835 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1836 ("es" "Autor" "Fecha" "\xccndice")
1837 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1838 ("it" "Autore" "Data" "Indice")
1839 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1840 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1841 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1842 "Terms used in export text, translated to different languages.
1843 Use the variable `org-export-default-language' to set the language,
1844 or use the +OPTION lines for a per-file setting."
1845 :group 'org-export-general
1846 :type '(repeat
1847 (list
1848 (string :tag "HTML language tag")
1849 (string :tag "Author")
1850 (string :tag "Date")
1851 (string :tag "Table of Contents"))))
1852
1853 (defcustom org-export-default-language "en"
1854 "The default language of HTML export, as a string.
1855 This should have an association in `org-export-language-setup'."
1856 :group 'org-export-general
1857 :type 'string)
1858
1859 (defcustom org-export-headline-levels 3
1860 "The last level which is still exported as a headline.
1861 Inferior levels will produce itemize lists when exported.
1862 Note that a numeric prefix argument to an exporter function overrides
1863 this setting.
1864
1865 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1866 :group 'org-export-general
1867 :type 'number)
1868
1869 (defcustom org-export-with-section-numbers t
1870 "Non-nil means, add section numbers to headlines when exporting.
1871
1872 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1873 :group 'org-export-general
1874 :type 'boolean)
1875
1876 (defcustom org-export-with-toc t
1877 "Non-nil means, create a table of contents in exported files.
1878 The TOC contains headlines with levels up to`org-export-headline-levels'.
1879
1880 Headlines which contain any TODO items will be marked with \"(*)\" in
1881 ASCII export, and with red color in HTML output.
1882
1883 In HTML output, the TOC will be clickable.
1884
1885 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1886 :group 'org-export-general
1887 :type 'boolean)
1888
1889 (defcustom org-export-mark-todo-in-toc nil
1890 "Non-nil means, mark TOC lines that contain any open TODO items."
1891 :group 'org-export-general
1892 :type 'boolean)
1893
1894 (defcustom org-export-preserve-breaks nil
1895 "Non-nil means, preserve all line breaks when exporting.
1896 Normally, in HTML output paragraphs will be reformatted. In ASCII
1897 export, line breaks will always be preserved, regardless of this variable.
1898
1899 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1900 :group 'org-export-general
1901 :type 'boolean)
1902
1903 (defcustom org-export-with-archived-trees 'headline
1904 "Whether subtrees with the ARCHIVE tag should be exported.
1905 This can have three different values
1906 nil Do not export, pretend this tree is not present
1907 t Do export the entire tree
1908 headline Only export the headline, but skip the tree below it."
1909 :group 'org-export-general
1910 :group 'org-archive
1911 :type '(choice
1912 (const :tag "not at all" nil)
1913 (const :tag "headline only" 'headline)
1914 (const :tag "entirely" t)))
1915
1916 (defcustom org-export-with-timestamps t
1917 "Nil means, do not export time stamps and associated keywords."
1918 :group 'org-export
1919 :type 'boolean)
1920
1921 (defcustom org-export-remove-timestamps-from-toc t
1922 "Nil means, remove timestamps from the table of contents entries."
1923 :group 'org-export
1924 :type 'boolean)
1925
1926 (defcustom org-export-with-tags t
1927 "Nil means, do not export tags, just remove them from headlines."
1928 :group 'org-export-general
1929 :type 'boolean)
1930
1931 (defcustom org-export-with-timestamps t
1932 "Nil means, do not export timestamps and associated keywords."
1933 :group 'org-export-general
1934 :type 'boolean)
1935
1936 (defgroup org-export-translation nil
1937 "Options for translating special ascii sequences for the export backends."
1938 :tag "Org Export Translation"
1939 :group 'org-export)
1940
1941 (defcustom org-export-with-emphasize t
1942 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1943 If the export target supports emphasizing text, the word will be
1944 typeset in bold, italic, or underlined, respectively. Works only for
1945 single words, but you can say: I *really* *mean* *this*.
1946 Not all export backends support this.
1947
1948 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1949 :group 'org-export-translation
1950 :type 'boolean)
1951
1952 (defcustom org-export-with-sub-superscripts t
1953 "Non-nil means, interpret \"_\" and \"^\" for export.
1954 When this option is turned on, you can use TeX-like syntax for sub- and
1955 superscripts. Several characters after \"_\" or \"^\" will be
1956 considered as a single item - so grouping with {} is normally not
1957 needed. For example, the following things will be parsed as single
1958 sub- or superscripts.
1959
1960 10^24 or 10^tau several digits will be considered 1 item.
1961 10^-12 or 10^-tau a leading sign with digits or a word
1962 x^2-y^3 will be read as x^2 - y^3, because items are
1963 terminated by almost any nonword/nondigit char.
1964 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1965
1966 Still, ambiguity is possible - so when in doubt use {} to enclose the
1967 sub/superscript.
1968 Not all export backends support this, but HTML does.
1969
1970 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1971 :group 'org-export-translation
1972 :type 'boolean)
1973
1974 (defcustom org-export-with-TeX-macros t
1975 "Non-nil means, interpret simple TeX-like macros when exporting.
1976 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1977 No only real TeX macros will work here, but the standard HTML entities
1978 for math can be used as macro names as well. For a list of supported
1979 names in HTML export, see the constant `org-html-entities'.
1980 Not all export backends support this.
1981
1982 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1983 :group 'org-export-translation
1984 :group 'org-latex
1985 :type 'boolean)
1986
1987 (defcustom org-export-with-LaTeX-fragments nil
1988 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
1989 When set, the exporter will find LaTeX environments if the \\begin line is
1990 the first non-white thing on a line. It will also find the math delimiters
1991 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
1992 display math.
1993
1994 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
1995 :group 'org-export-translation
1996 :group 'org-latex
1997 :type 'boolean)
1998
1999 (defcustom org-export-with-fixed-width t
2000 "Non-nil means, lines starting with \":\" will be in fixed width font.
2001 This can be used to have pre-formatted text, fragments of code etc. For
2002 example:
2003 : ;; Some Lisp examples
2004 : (while (defc cnt)
2005 : (ding))
2006 will be looking just like this in also HTML. See also the QUOTE keyword.
2007 Not all export backends support this.
2008
2009 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
2010 :group 'org-export-translation
2011 :type 'boolean)
2012
2013 (defcustom org-match-sexp-depth 3
2014 "Number of stacked braces for sub/superscript matching.
2015 This has to be set before loading org.el to be effective."
2016 :group 'org-export-translation
2017 :type 'integer)
2018
2019 (defgroup org-export-tables nil
2020 "Options for exporting tables in Org-mode."
2021 :tag "Org Export Tables"
2022 :group 'org-export)
2023
2024 (defcustom org-export-with-tables t
2025 "If non-nil, lines starting with \"|\" define a table.
2026 For example:
2027
2028 | Name | Address | Birthday |
2029 |-------------+----------+-----------|
2030 | Arthur Dent | England | 29.2.2100 |
2031
2032 Not all export backends support this.
2033
2034 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2035 :group 'org-export-tables
2036 :type 'boolean)
2037
2038 (defcustom org-export-highlight-first-table-line t
2039 "Non-nil means, highlight the first table line.
2040 In HTML export, this means use <th> instead of <td>.
2041 In tables created with table.el, this applies to the first table line.
2042 In Org-mode tables, all lines before the first horizontal separator
2043 line will be formatted with <th> tags."
2044 :group 'org-export-tables
2045 :type 'boolean)
2046
2047 (defcustom org-export-table-remove-special-lines t
2048 "Remove special lines and marking characters in calculating tables.
2049 This removes the special marking character column from tables that are set
2050 up for spreadsheet calculations. It also removes the entire lines
2051 marked with `!', `_', or `^'. The lines with `$' are kept, because
2052 the values of constants may be useful to have."
2053 :group 'org-export-tables
2054 :type 'boolean)
2055
2056 (defcustom org-export-prefer-native-exporter-for-tables nil
2057 "Non-nil means, always export tables created with table.el natively.
2058 Natively means, use the HTML code generator in table.el.
2059 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2060 the table does not use row- or column-spanning). This has the
2061 advantage, that the automatic HTML conversions for math symbols and
2062 sub/superscripts can be applied. Org-mode's HTML generator is also
2063 much faster."
2064 :group 'org-export-tables
2065 :type 'boolean)
2066
2067 (defgroup org-export-ascii nil
2068 "Options specific for ASCII export of Org-mode files."
2069 :tag "Org Export ASCII"
2070 :group 'org-export)
2071
2072 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2073 "Characters for underlining headings in ASCII export.
2074 In the given sequence, these characters will be used for level 1, 2, ..."
2075 :group 'org-export-ascii
2076 :type '(repeat character))
2077
2078 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2079 "Bullet characters for headlines converted to lists in ASCII export.
2080 The first character is is used for the first lest level generated in this
2081 way, and so on. If there are more levels than characters given here,
2082 the list will be repeated.
2083 Note that plain lists will keep the same bullets as the have in the
2084 Org-mode file."
2085 :group 'org-export-ascii
2086 :type '(repeat character))
2087
2088 (defcustom org-export-ascii-show-new-buffer t
2089 "Non-nil means, popup buffer containing the exported ASCII text.
2090 Otherwise the buffer will just be saved to a file and stay hidden."
2091 :group 'org-export-ascii
2092 :type 'boolean)
2093
2094 (defgroup org-export-xml nil
2095 "Options specific for XML export of Org-mode files."
2096 :tag "Org Export XML"
2097 :group 'org-export)
2098
2099 (defgroup org-export-html nil
2100 "Options specific for HTML export of Org-mode files."
2101 :tag "Org Export HTML"
2102 :group 'org-export)
2103
2104 (defcustom org-export-html-style
2105 "<style type=\"text/css\">
2106 html {
2107 font-family: Times, serif;
2108 font-size: 12pt;
2109 }
2110 .title { text-align: center; }
2111 .todo { color: red; }
2112 .done { color: green; }
2113 .timestamp { color: grey }
2114 .timestamp-kwd { color: CadetBlue }
2115 .tag { background-color:lightblue; font-weight:normal }
2116 .target { background-color: lavender; }
2117 pre {
2118 border: 1pt solid #AEBDCC;
2119 background-color: #F3F5F7;
2120 padding: 5pt;
2121 font-family: courier, monospace;
2122 }
2123 table { border-collapse: collapse; }
2124 td, th {
2125 vertical-align: top;
2126 border: 1pt solid #ADB9CC;
2127 }
2128 </style>"
2129 "The default style specification for exported HTML files.
2130 Since there are different ways of setting style information, this variable
2131 needs to contain the full HTML structure to provide a style, including the
2132 surrounding HTML tags. The style specifications should include definitions
2133 for new classes todo, done, title, and deadline. For example, legal values
2134 would be:
2135
2136 <style type=\"text/css\">
2137 p { font-weight: normal; color: gray; }
2138 h1 { color: black; }
2139 .title { text-align: center; }
2140 .todo, .deadline { color: red; }
2141 .done { color: green; }
2142 </style>
2143
2144 or, if you want to keep the style in a file,
2145
2146 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2147
2148 As the value of this option simply gets inserted into the HTML <head> header,
2149 you can \"misuse\" it to add arbitrary text to the header."
2150 :group 'org-export-html
2151 :type 'string)
2152
2153 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2154 "Format for typesetting the document title in HTML export."
2155 :group 'org-export-html
2156 :type 'string)
2157
2158 (defcustom org-export-html-toplevel-hlevel 2
2159 "The <H> level for level 1 headings in HTML export."
2160 :group 'org-export-html
2161 :type 'string)
2162
2163 (defcustom org-export-html-link-org-files-as-html t
2164 "Non-nil means, make file links to `file.org' point to `file.html'.
2165 When org-mode is exporting an org-mode file to HTML, links to
2166 non-html files are directly put into a href tag in HTML.
2167 However, links to other Org-mode files (recognized by the
2168 extension `.org.) should become links to the corresponding html
2169 file, assuming that the linked org-mode file will also be
2170 converted to HTML.
2171 When nil, the links still point to the plain `.org' file."
2172 :group 'org-export-html
2173 :type 'boolean)
2174
2175 (defcustom org-export-html-inline-images 'maybe
2176 "Non-nil means, inline images into exported HTML pages.
2177 This is done using an <img> tag. When nil, an anchor with href is used to
2178 link to the image. If this option is `maybe', then images in links with
2179 an empty description will be inlined, while images with a description will
2180 be linked only."
2181 :group 'org-export-html
2182 :type '(choice (const :tag "Never" nil)
2183 (const :tag "Always" t)
2184 (const :tag "When there is no description" maybe)))
2185
2186 (defcustom org-export-html-expand t
2187 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2188 When nil, these tags will be exported as plain text and therefore
2189 not be interpreted by a browser.
2190
2191 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2192 :group 'org-export-html
2193 :type 'boolean)
2194
2195 (defcustom org-export-html-table-tag
2196 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2197 "The HTML tag used to start a table.
2198 This must be a <table> tag, but you may change the options like
2199 borders and spacing."
2200 :group 'org-export-html
2201 :type 'string)
2202
2203 (defcustom org-export-html-with-timestamp nil
2204 "If non-nil, write `org-export-html-html-helper-timestamp'
2205 into the exported HTML text. Otherwise, the buffer will just be saved
2206 to a file."
2207 :group 'org-export-html
2208 :type 'boolean)
2209
2210 (defcustom org-export-html-html-helper-timestamp
2211 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2212 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2213 :group 'org-export-html
2214 :type 'string)
2215
2216 (defcustom org-export-html-show-new-buffer nil
2217 "Non-nil means, popup buffer containing the exported html text.
2218 Otherwise, the buffer will just be saved to a file and stay hidden."
2219 :group 'org-export-html
2220 :type 'boolean)
2221
2222 (defgroup org-export-icalendar nil
2223 "Options specific for iCalendar export of Org-mode files."
2224 :tag "Org Export iCalendar"
2225 :group 'org-export)
2226
2227 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2228 "The file name for the iCalendar file covering all agenda files.
2229 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2230 The file name should be absolute."
2231 :group 'org-export-icalendar
2232 :type 'file)
2233
2234 (defcustom org-icalendar-include-todo nil
2235 "Non-nil means, export to iCalendar files should also cover TODO items."
2236 :group 'org-export-icalendar
2237 :type 'boolean)
2238
2239 (defcustom org-icalendar-combined-name "OrgMode"
2240 "Calendar name for the combined iCalendar representing all agenda files."
2241 :group 'org-export-icalendar
2242 :type 'string)
2243
2244 (defgroup org-font-lock nil
2245 "Font-lock settings for highlighting in Org-mode."
2246 :tag "Org Font Lock"
2247 :group 'org)
2248
2249 (defcustom org-level-color-stars-only nil
2250 "Non-nil means fontify only the stars in each headline.
2251 When nil, the entire headline is fontified.
2252 Changing it requires restart of `font-lock-mode' to become effective
2253 also in regions already fontified."
2254 :group 'org-font-lock
2255 :type 'boolean)
2256
2257 (defcustom org-hide-leading-stars nil
2258 "Non-nil means, hide the first N-1 stars in a headline.
2259 This works by using the face `org-hide' for these stars. This
2260 face is white for a light background, and black for a dark
2261 background. You may have to customize the face `org-hide' to
2262 make this work.
2263 Changing it requires restart of `font-lock-mode' to become effective
2264 also in regions already fontified.
2265 You may also set this on a per-file basis by adding one of the following
2266 lines to the buffer:
2267
2268 #+STARTUP: hidestars
2269 #+STARTUP: showstars"
2270 :group 'org-font-lock
2271 :type 'boolean)
2272
2273 (defcustom org-fontify-done-headline nil
2274 "Non-nil means, change the face of a headline if it is marked DONE.
2275 Normally, only the TODO/DONE keyword indicates the state of a headline.
2276 When this is non-nil, the headline after the keyword is set to the
2277 `org-headline-done' as an additional indication."
2278 :group 'org-font-lock
2279 :type 'boolean)
2280
2281 (defcustom org-fontify-emphasized-text t
2282 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2283 Changing this variable requires a restart of Emacs to take effect."
2284 :group 'org-font-lock
2285 :type 'boolean)
2286
2287 (defvar org-emph-re nil
2288 "Regular expression for matching emphasis.")
2289 (defvar org-emphasis-regexp-components) ; defined just below
2290 (defvar org-emphasis-alist) ; defined just below
2291 (defun org-set-emph-re (var val)
2292 "Set variable and compute the emphasis regular expression."
2293 (set var val)
2294 (when (and (boundp 'org-emphasis-alist)
2295 (boundp 'org-emphasis-regexp-components)
2296 org-emphasis-alist org-emphasis-regexp-components)
2297 (let* ((e org-emphasis-regexp-components)
2298 (pre (car e))
2299 (post (nth 1 e))
2300 (border (nth 2 e))
2301 (body (nth 3 e))
2302 (nl (nth 4 e))
2303 (stacked (nth 5 e))
2304 (body1 (concat body "*?"))
2305 (markers (mapconcat 'car org-emphasis-alist "")))
2306 ;; make sure special characters appear at the right position in the class
2307 (if (string-match "\\^" markers)
2308 (setq markers (concat (replace-match "" t t markers) "^")))
2309 (if (string-match "-" markers)
2310 (setq markers (concat (replace-match "" t t markers) "-")))
2311 (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2312 ;; Make the regexp
2313 (setq org-emph-re
2314 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2315 "\\("
2316 "\\([" markers "]\\)"
2317 "\\("
2318 "[^" border markers "]"
2319 body1
2320 "[^" border markers "]"
2321 "\\)"
2322 "\\3\\)"
2323 "\\([" post (if stacked markers) "]\\|$\\)")))))
2324
2325 (defcustom org-emphasis-regexp-components
2326 '(" \t(" " \t.,?;:'\")" " \t\r\n,." "." 1 nil)
2327 "Components used to build the reqular expression for emphasis.
2328 This is a list with 6 entries. Terminology: In an emphasis string
2329 like \" *strong word* \", we call the initial space PREMATCH, the final
2330 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2331 and \"trong wor\" is the body. The different components in this variable
2332 specify what is allowed/forbidden in each part:
2333
2334 pre Chars allowed as prematch. Beginning of line will be allowed too.
2335 post Chars allowed as postmatch. End of line will be allowed too.
2336 border The chars *forbidden* as border characters. In addition to the
2337 characters given here, all marker characters are forbidden too.
2338 body-regexp A regexp like \".\" to match a body character. Don't use
2339 non-shy groups here, and don't allow newline here.
2340 newline The maximum number of newlines allowed in an emphasis exp.
2341 stacked Non-nil means, allow stacked styles. This works only in HTML
2342 export. When this is set, all marker characters (as given in
2343 `org-emphasis-alist') will be allowed as pre/post, aiding
2344 inside-out matching.
2345 Use customize to modify this, or restart Emacs after changing it."
2346 :group 'org-font-lock
2347 :set 'org-set-emph-re
2348 :type '(list
2349 (sexp :tag "Allowed chars in pre ")
2350 (sexp :tag "Allowed chars in post ")
2351 (sexp :tag "Forbidden chars in border ")
2352 (sexp :tag "Regexp for body ")
2353 (integer :tag "number of newlines allowed")
2354 (boolean :tag "Stacking allowed ")))
2355
2356 (defcustom org-emphasis-alist
2357 '(("*" bold "<b>" "</b>")
2358 ("/" italic "<i>" "</i>")
2359 ("_" underline "<u>" "</u>")
2360 ("=" shadow "<code>" "</code>")
2361 ("+" (:strike-through t) "<del>" "</del>")
2362 )
2363 "Special syntax for emphasized text.
2364 Text starting and ending with a special character will be emphasized, for
2365 example *bold*, _underlined_ and /italic/. This variable sets the marker
2366 characters, the face to bbe used by font-lock for highlighting in Org-mode
2367 Emacs buffers, and the HTML tags to be used for this.
2368 Use customize to modify this, or restart Emacs after changing it."
2369 :group 'org-font-lock
2370 :set 'org-set-emph-re
2371 :type '(repeat
2372 (list
2373 (string :tag "Marker character")
2374 (choice
2375 (face :tag "Font-lock-face")
2376 (plist :tag "Face property list"))
2377 (string :tag "HTML start tag")
2378 (string :tag "HTML end tag"))))
2379
2380 (defgroup org-faces nil
2381 "Faces in Org-mode."
2382 :tag "Org Faces"
2383 :group 'org-font-lock)
2384
2385 (defun org-compatible-face (specs)
2386 "Make a compatible face specification.
2387 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2388 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2389 to the top of the list. The `min-colors' attribute will be removed from
2390 any other entries, and any resulting duplicates will be removed entirely."
2391 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2392 (let (r e a)
2393 (while (setq e (pop specs))
2394 (cond
2395 ((memq (car e) '(t default)) (push e r))
2396 ((setq a (member '(min-colors 8) (car e)))
2397 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2398 (cdr e)))))
2399 ((setq a (assq 'min-colors (car e)))
2400 (setq e (cons (delq a (car e)) (cdr e)))
2401 (or (assoc (car e) r) (push e r)))
2402 (t (or (assoc (car e) r) (push e r)))))
2403 (nreverse r))
2404 specs))
2405
2406 (defface org-hide
2407 '((((background light)) (:foreground "white"))
2408 (((background dark)) (:foreground "black")))
2409 "Face used to hide leading stars in headlines.
2410 The forground color of this face should be equal to the background
2411 color of the frame."
2412 :group 'org-faces)
2413
2414 (defface org-level-1 ;; font-lock-function-name-face
2415 (org-compatible-face
2416 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2417 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2418 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2419 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2420 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2421 (t (:bold t))))
2422 "Face used for level 1 headlines."
2423 :group 'org-faces)
2424
2425 (defface org-level-2 ;; font-lock-variable-name-face
2426 (org-compatible-face
2427 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2428 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2429 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2430 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2431 (t (:bold t))))
2432 "Face used for level 2 headlines."
2433 :group 'org-faces)
2434
2435 (defface org-level-3 ;; font-lock-keyword-face
2436 (org-compatible-face
2437 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2438 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2439 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2440 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2441 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2442 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2443 (t (:bold t))))
2444 "Face used for level 3 headlines."
2445 :group 'org-faces)
2446
2447 (defface org-level-4 ;; font-lock-comment-face
2448 (org-compatible-face
2449 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2450 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2451 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2452 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2453 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2454 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2455 (t (:bold t))))
2456 "Face used for level 4 headlines."
2457 :group 'org-faces)
2458
2459 (defface org-level-5 ;; font-lock-type-face
2460 (org-compatible-face
2461 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2462 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2463 (((class color) (min-colors 8)) (:foreground "green"))))
2464 "Face used for level 5 headlines."
2465 :group 'org-faces)
2466
2467 (defface org-level-6 ;; font-lock-constant-face
2468 (org-compatible-face
2469 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2470 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2471 (((class color) (min-colors 8)) (:foreground "magenta"))))
2472 "Face used for level 6 headlines."
2473 :group 'org-faces)
2474
2475 (defface org-level-7 ;; font-lock-builtin-face
2476 (org-compatible-face
2477 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2478 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2479 (((class color) (min-colors 8)) (:foreground "blue"))))
2480 "Face used for level 7 headlines."
2481 :group 'org-faces)
2482
2483 (defface org-level-8 ;; font-lock-string-face
2484 (org-compatible-face
2485 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2486 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2487 (((class color) (min-colors 8)) (:foreground "green"))))
2488 "Face used for level 8 headlines."
2489 :group 'org-faces)
2490
2491 (defface org-special-keyword ;; font-lock-string-face
2492 (org-compatible-face
2493 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2494 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2495 (t (:italic t))))
2496 "Face used for special keywords."
2497 :group 'org-faces)
2498
2499 (defface org-warning ;; font-lock-warning-face
2500 (org-compatible-face
2501 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2502 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2503 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2504 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2505 (t (:bold t))))
2506 "Face for deadlines and TODO keywords."
2507 :group 'org-faces)
2508
2509 (defface org-headline-done ;; font-lock-string-face
2510 (org-compatible-face
2511 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2512 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2513 (((class color) (min-colors 8) (background light)) (:bold nil))))
2514 "Face used to indicate that a headline is DONE.
2515 This face is only used if `org-fontify-done-headline' is set."
2516 :group 'org-faces)
2517
2518 (defface org-archived ; similar to shadow
2519 (org-compatible-face
2520 '((((class color grayscale) (min-colors 88) (background light))
2521 (:foreground "grey50"))
2522 (((class color grayscale) (min-colors 88) (background dark))
2523 (:foreground "grey70"))
2524 (((class color) (min-colors 8) (background light))
2525 (:foreground "green"))
2526 (((class color) (min-colors 8) (background dark))
2527 (:foreground "yellow"))))
2528 "Face for headline with the ARCHIVE tag."
2529 :group 'org-faces)
2530
2531 (defface org-link
2532 '((((class color) (background light)) (:foreground "Purple" :underline t))
2533 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2534 (t (:underline t)))
2535 "Face for links."
2536 :group 'org-faces)
2537
2538 (defface org-date
2539 '((((class color) (background light)) (:foreground "Purple" :underline t))
2540 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2541 (t (:underline t)))
2542 "Face for links."
2543 :group 'org-faces)
2544
2545 (defface org-tag
2546 '((t (:bold t)))
2547 "Face for tags."
2548 :group 'org-faces)
2549
2550 (defface org-todo ;; font-lock-warning-face
2551 (org-compatible-face
2552 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2553 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2554 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2555 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2556 (t (:inverse-video t :bold t))))
2557 "Face for TODO keywords."
2558 :group 'org-faces)
2559
2560 (defface org-done ;; font-lock-type-face
2561 (org-compatible-face
2562 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2563 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2564 (((class color) (min-colors 8)) (:foreground "green"))
2565 (t (:bold t))))
2566 "Face used for DONE."
2567 :group 'org-faces)
2568
2569 (defface org-table ;; font-lock-function-name-face
2570 (org-compatible-face
2571 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2572 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2573 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2574 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2575 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2576 (((class color) (min-colors 8) (background dark)))))
2577 "Face used for tables."
2578 :group 'org-faces)
2579
2580 (defface org-formula
2581 (org-compatible-face
2582 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2583 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2584 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2585 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2586 (t (:bold t :italic t))))
2587 "Face for formulas."
2588 :group 'org-faces)
2589
2590 (defface org-scheduled-today
2591 (org-compatible-face
2592 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2593 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2594 (((class color) (min-colors 8)) (:foreground "green"))
2595 (t (:bold t :italic t))))
2596 "Face for items scheduled for a certain day."
2597 :group 'org-faces)
2598
2599 (defface org-scheduled-previously
2600 (org-compatible-face
2601 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2602 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2603 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2604 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2605 (t (:bold t))))
2606 "Face for items scheduled previously, and not yet done."
2607 :group 'org-faces)
2608
2609 (defface org-upcoming-deadline
2610 (org-compatible-face
2611 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2612 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2613 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2614 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2615 (t (:bold t))))
2616 "Face for items scheduled previously, and not yet done."
2617 :group 'org-faces)
2618
2619 (defface org-time-grid ;; font-lock-variable-name-face
2620 (org-compatible-face
2621 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2622 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2623 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2624 "Face used for time grids."
2625 :group 'org-faces)
2626
2627 (defconst org-level-faces
2628 '(org-level-1 org-level-2 org-level-3 org-level-4
2629 org-level-5 org-level-6 org-level-7 org-level-8
2630 ))
2631 (defconst org-n-levels (length org-level-faces))
2632
2633
2634 ;; Variables for pre-computed regular expressions, all buffer local
2635 (defvar org-done-string nil
2636 "The last string in `org-todo-keywords', indicating an item is DONE.")
2637 (make-variable-buffer-local 'org-done-string)
2638 (defvar org-todo-regexp nil
2639 "Matches any of the TODO state keywords.")
2640 (make-variable-buffer-local 'org-todo-regexp)
2641 (defvar org-not-done-regexp nil
2642 "Matches any of the TODO state keywords except the last one.")
2643 (make-variable-buffer-local 'org-not-done-regexp)
2644 (defvar org-todo-line-regexp nil
2645 "Matches a headline and puts TODO state into group 2 if present.")
2646 (make-variable-buffer-local 'org-todo-line-regexp)
2647 (defvar org-todo-line-tags-regexp nil
2648 "Matches a headline and puts TODO state into group 2 if present.
2649 Also put tags into group 4 if tags are present.")
2650 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2651 (defvar org-nl-done-regexp nil
2652 "Matches newline followed by a headline with the DONE keyword.")
2653 (make-variable-buffer-local 'org-nl-done-regexp)
2654 (defvar org-looking-at-done-regexp nil
2655 "Matches the DONE keyword a point.")
2656 (make-variable-buffer-local 'org-looking-at-done-regexp)
2657 (defvar org-todo-kwd-priority-p nil
2658 "Do TODO items have priorities?")
2659 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2660 (defvar org-todo-kwd-max-priority nil
2661 "Maximum priority of TODO items.")
2662 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2663 (defvar org-ds-keyword-length 12
2664 "Maximum length of the Deadline and SCHEDULED keywords.")
2665 (make-variable-buffer-local 'org-ds-keyword-length)
2666 (defvar org-deadline-regexp nil
2667 "Matches the DEADLINE keyword.")
2668 (make-variable-buffer-local 'org-deadline-regexp)
2669 (defvar org-deadline-time-regexp nil
2670 "Matches the DEADLINE keyword together with a time stamp.")
2671 (make-variable-buffer-local 'org-deadline-time-regexp)
2672 (defvar org-deadline-line-regexp nil
2673 "Matches the DEADLINE keyword and the rest of the line.")
2674 (make-variable-buffer-local 'org-deadline-line-regexp)
2675 (defvar org-scheduled-regexp nil
2676 "Matches the SCHEDULED keyword.")
2677 (make-variable-buffer-local 'org-scheduled-regexp)
2678 (defvar org-scheduled-time-regexp nil
2679 "Matches the SCHEDULED keyword together with a time stamp.")
2680 (make-variable-buffer-local 'org-scheduled-time-regexp)
2681 (defvar org-closed-time-regexp nil
2682 "Matches the CLOSED keyword together with a time stamp.")
2683 (make-variable-buffer-local 'org-closed-time-regexp)
2684
2685 (defvar org-keyword-time-regexp nil
2686 "Matches any of the 3 keywords, together with the time stamp.")
2687 (make-variable-buffer-local 'org-keyword-time-regexp)
2688 (defvar org-maybe-keyword-time-regexp nil
2689 "Matches a timestamp, possibly preceeded by a keyword.")
2690 (make-variable-buffer-local 'org-keyword-time-regexp)
2691
2692 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2693 rear-nonsticky t mouse-map t)
2694 "Properties to remove when a string without properties is wanted.")
2695
2696 (defsubst org-match-string-no-properties (num &optional string)
2697 (if (featurep 'xemacs)
2698 (let ((s (match-string num string)))
2699 (remove-text-properties 0 (length s) org-rm-props s)
2700 s)
2701 (match-string-no-properties num string)))
2702
2703 (defsubst org-no-properties (s)
2704 (remove-text-properties 0 (length s) org-rm-props s)
2705 s)
2706
2707 (defsubst org-set-local (var value)
2708 "Make VAR local in current buffer and set it to VALUE."
2709 (set (make-variable-buffer-local var) value))
2710
2711 (defsubst org-mode-p ()
2712 "Check if the current buffer is in Org-mode."
2713 (eq major-mode 'org-mode))
2714
2715 (defun org-set-regexps-and-options ()
2716 "Precompute regular expressions for current buffer."
2717 (when (org-mode-p)
2718 (let ((re (org-make-options-regexp
2719 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2720 "STARTUP" "ARCHIVE" "TAGS" "CALC")))
2721 (splitre "[ \t]+")
2722 kwds int key value cat arch tags)
2723 (save-excursion
2724 (save-restriction
2725 (widen)
2726 (goto-char (point-min))
2727 (while (re-search-forward re nil t)
2728 (setq key (match-string 1) value (org-match-string-no-properties 2))
2729 (cond
2730 ((equal key "CATEGORY")
2731 (if (string-match "[ \t]+$" value)
2732 (setq value (replace-match "" t t value)))
2733 (setq cat (intern value)))
2734 ((equal key "SEQ_TODO")
2735 (setq int 'sequence
2736 kwds (append kwds (org-split-string value splitre))))
2737 ((equal key "PRI_TODO")
2738 (setq int 'priority
2739 kwds (append kwds (org-split-string value splitre))))
2740 ((equal key "TYP_TODO")
2741 (setq int 'type
2742 kwds (append kwds (org-split-string value splitre))))
2743 ((equal key "TAGS")
2744 (setq tags (append tags (org-split-string value splitre))))
2745 ((equal key "STARTUP")
2746 (let ((opts (org-split-string value splitre))
2747 (set '(("fold" org-startup-folded t)
2748 ("overview" org-startup-folded t)
2749 ("nofold" org-startup-folded nil)
2750 ("showall" org-startup-folded nil)
2751 ("content" org-startup-folded content)
2752 ("hidestars" org-hide-leading-stars t)
2753 ("showstars" org-hide-leading-stars nil)
2754 ("odd" org-odd-levels-only t)
2755 ("oddeven" org-odd-levels-only nil)
2756 ("align" org-startup-align-all-tables t)
2757 ("noalign" org-startup-align-all-tables nil)
2758 ("logging" org-log-done t)
2759 ("nologging" org-log-done nil)
2760 ("dlcheck" org-startup-with-deadline-check t)
2761 ("nodlcheck" org-startup-with-deadline-check nil)))
2762 l var val)
2763 (while (setq l (assoc (pop opts) set))
2764 (setq var (nth 1 l) val (nth 2 l))
2765 (set (make-local-variable var) val))))
2766 ((equal key "ARCHIVE")
2767 (string-match " *$" value)
2768 (setq arch (replace-match "" t t value))
2769 (remove-text-properties 0 (length arch)
2770 '(face t fontified t) arch)))
2771 )))
2772 (and cat (org-set-local 'org-category cat))
2773 (and kwds (org-set-local 'org-todo-keywords kwds))
2774 (and arch (org-set-local 'org-archive-location arch))
2775 (and int (org-set-local 'org-todo-interpretation int))
2776 (when tags
2777 (let (e tgs)
2778 (while (setq e (pop tags))
2779 (cond
2780 ((equal e "{") (push '(:startgroup) tgs))
2781 ((equal e "}") (push '(:endgroup) tgs))
2782 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
2783 (push (cons (match-string 1 e)
2784 (string-to-char (match-string 2 e)))
2785 tgs))
2786 (t (push (list e) tgs))))
2787 (org-set-local 'org-tag-alist nil)
2788 (while (setq e (pop tgs))
2789 (or (and (stringp (car e))
2790 (assoc (car e) org-tag-alist))
2791 (push e org-tag-alist))))))
2792
2793 ;; Compute the regular expressions and other local variables
2794 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2795 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2796 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2797 (length org-scheduled-string)))
2798 org-done-string
2799 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2800 org-todo-regexp
2801 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2802 "\\|") "\\)\\>")
2803 org-not-done-regexp
2804 (concat "\\<\\("
2805 (mapconcat 'regexp-quote
2806 (nreverse (cdr (reverse org-todo-keywords)))
2807 "\\|")
2808 "\\)\\>")
2809 org-todo-line-regexp
2810 (concat "^\\(\\*+\\)[ \t]*\\("
2811 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2812 "\\)? *\\(.*\\)")
2813 org-nl-done-regexp
2814 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2815 org-todo-line-tags-regexp
2816 (concat "^\\(\\*+\\)[ \t]*\\("
2817 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2818 "\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
2819 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2820 org-deadline-regexp (concat "\\<" org-deadline-string)
2821 org-deadline-time-regexp
2822 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2823 org-deadline-line-regexp
2824 (concat "\\<\\(" org-deadline-string "\\).*")
2825 org-scheduled-regexp
2826 (concat "\\<" org-scheduled-string)
2827 org-scheduled-time-regexp
2828 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2829 org-closed-time-regexp
2830 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2831 org-keyword-time-regexp
2832 (concat "\\<\\(" org-scheduled-string
2833 "\\|" org-deadline-string
2834 "\\|" org-closed-string
2835 "\\|" org-clock-string "\\)"
2836 " *[[<]\\([^]>]+\\)[]>]")
2837 org-maybe-keyword-time-regexp
2838 (concat "\\(\\<\\(" org-scheduled-string
2839 "\\|" org-deadline-string
2840 "\\|" org-closed-string
2841 "\\|" org-clock-string "\\)\\)?"
2842 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
2843
2844 (org-set-font-lock-defaults)))
2845
2846 ;; Tell the compiler about dynamically scoped variables,
2847 ;; and variables from other packages
2848 (defvar calc-embedded-close-formula) ; defined by the calc package
2849 (defvar calc-embedded-open-formula) ; defined by the calc package
2850 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
2851 (defvar zmacs-regions) ; XEmacs regions
2852 (defvar original-date) ; dynamically scoped in calendar
2853 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2854 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2855 (defvar org-html-entities) ; defined later in this file
2856 (defvar org-goto-start-pos) ; dynamically scoped parameter
2857 (defvar org-time-was-given) ; dynamically scoped parameter
2858 (defvar org-ts-what) ; dynamically scoped parameter
2859 (defvar org-current-export-file) ; dynamically scoped parameter
2860 (defvar org-current-export-dir) ; dynamically scoped parameter
2861 (defvar mark-active) ; Emacs only, not available in XEmacs.
2862 (defvar timecnt) ; dynamically scoped parameter
2863 (defvar levels-open) ; dynamically scoped parameter
2864 (defvar entry) ; dynamically scoped parameter
2865 (defvar state) ; dynamically scoped into `org-after-todo-state-change-hook'
2866 (defvar date) ; dynamically scoped parameter
2867 (defvar description) ; dynamically scoped parameter
2868 (defvar ans1) ; dynamically scoped parameter
2869 (defvar ans2) ; dynamically scoped parameter
2870 (defvar starting-day) ; local variable
2871 (defvar include-all-loc) ; local variable
2872 (defvar vm-message-pointer) ; from vm
2873 (defvar vm-folder-directory) ; from vm
2874 (defvar wl-summary-buffer-elmo-folder) ; from wanderlust
2875 (defvar wl-summary-buffer-folder-name) ; from wanderlust
2876 (defvar gnus-group-name) ; from gnus
2877 (defvar gnus-article-current) ; from gnus
2878 (defvar w3m-current-url) ; from w3m
2879 (defvar w3m-current-title) ; from w3m
2880 (defvar mh-progs) ; from MH-E
2881 (defvar mh-current-folder) ; from MH-E
2882 (defvar mh-show-folder-buffer) ; from MH-E
2883 (defvar mh-index-folder) ; from MH-E
2884 (defvar mh-searcher) ; from MH-E
2885 (defvar org-selected-point) ; dynamically scoped parameter
2886 (defvar calendar-mode-map) ; from calendar.el
2887 (defvar last-arg) ; local variable
2888 (defvar remember-save-after-remembering) ; from remember.el
2889 (defvar remember-data-file) ; from remember.el
2890 (defvar annotation) ; from remember.el, dynamically scoped in `remember-mode'
2891 (defvar initial) ; from remember.el, dynamically scoped in `remember-mode'
2892 (defvar orgtbl-mode) ; defined later in this file
2893 (defvar Info-current-file) ; from info.el
2894 (defvar Info-current-node) ; from info.el
2895 (defvar texmathp-why) ; from texmathp.el
2896 (defvar org-latex-regexps)
2897
2898 ;;; Define the mode
2899
2900 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2901 (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."))
2902
2903 (defvar org-struct-menu) ; defined later in this file
2904 (defvar org-org-menu) ; defined later in this file
2905 (defvar org-tbl-menu) ; defined later in this file
2906
2907 ;; We use a before-change function to check if a table might need
2908 ;; an update.
2909 (defvar org-table-may-need-update t
2910 "Indicates that a table might need an update.
2911 This variable is set by `org-before-change-function'.
2912 `org-table-align' sets it back to nil.")
2913 (defvar org-mode-map)
2914 (defvar org-mode-hook nil)
2915 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2916 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2917
2918
2919 ;;;###autoload
2920 (define-derived-mode org-mode outline-mode "Org"
2921 "Outline-based notes management and organizer, alias
2922 \"Carsten's outline-mode for keeping track of everything.\"
2923
2924 Org-mode develops organizational tasks around a NOTES file which
2925 contains information about projects as plain text. Org-mode is
2926 implemented on top of outline-mode, which is ideal to keep the content
2927 of large files well structured. It supports ToDo items, deadlines and
2928 time stamps, which magically appear in the diary listing of the Emacs
2929 calendar. Tables are easily created with a built-in table editor.
2930 Plain text URL-like links connect to websites, emails (VM), Usenet
2931 messages (Gnus), BBDB entries, and any files related to the project.
2932 For printing and sharing of notes, an Org-mode file (or a part of it)
2933 can be exported as a structured ASCII or HTML file.
2934
2935 The following commands are available:
2936
2937 \\{org-mode-map}"
2938
2939 ;; Get rid of Outline menus, they are not needed
2940 ;; Need to do this here because define-derived-mode sets up
2941 ;; the keymap so late.
2942 (if (featurep 'xemacs)
2943 (progn
2944 ;; Assume this is Greg's port, it used easymenu
2945 (easy-menu-remove outline-mode-menu-heading)
2946 (easy-menu-remove outline-mode-menu-show)
2947 (easy-menu-remove outline-mode-menu-hide))
2948 (define-key org-mode-map [menu-bar headings] 'undefined)
2949 (define-key org-mode-map [menu-bar hide] 'undefined)
2950 (define-key org-mode-map [menu-bar show] 'undefined))
2951
2952 (easy-menu-add org-org-menu)
2953 (easy-menu-add org-tbl-menu)
2954 (org-install-agenda-files-menu)
2955 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2956 (org-add-to-invisibility-spec '(org-cwidth))
2957 (when (featurep 'xemacs)
2958 (org-set-local 'line-move-ignore-invisible t))
2959 (setq outline-regexp "\\*+")
2960 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2961 (setq outline-level 'org-outline-level)
2962 (when (and org-ellipsis (stringp org-ellipsis))
2963 (unless org-display-table
2964 (setq org-display-table (make-display-table)))
2965 (set-display-table-slot org-display-table
2966 4 (string-to-vector org-ellipsis))
2967 (setq buffer-display-table org-display-table))
2968 (org-set-regexps-and-options)
2969 ;; Calc embedded
2970 (org-set-local 'calc-embedded-open-mode "# ")
2971 (modify-syntax-entry ?# "<")
2972 (if org-startup-truncated (setq truncate-lines t))
2973 (org-set-local 'font-lock-unfontify-region-function
2974 'org-unfontify-region)
2975 ;; Activate before-change-function
2976 (org-set-local 'org-table-may-need-update t)
2977 (org-add-hook 'before-change-functions 'org-before-change-function nil
2978 'local)
2979 ;; Check for running clock before killing a buffer
2980 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
2981 ;; Paragraphs and auto-filling
2982 (org-set-autofill-regexps)
2983 (org-update-radio-target-regexp)
2984
2985 (if (and org-insert-mode-line-in-empty-file
2986 (interactive-p)
2987 (= (point-min) (point-max)))
2988 (insert " -*- mode: org -*-\n\n"))
2989
2990 (unless org-inhibit-startup
2991 (when org-startup-align-all-tables
2992 (let ((bmp (buffer-modified-p)))
2993 (org-table-map-tables 'org-table-align)
2994 (set-buffer-modified-p bmp)))
2995 (if org-startup-with-deadline-check
2996 (call-interactively 'org-check-deadlines)
2997 (cond
2998 ((eq org-startup-folded t)
2999 (org-cycle '(4)))
3000 ((eq org-startup-folded 'content)
3001 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3002 (org-cycle '(4)) (org-cycle '(4))))))))
3003
3004 (defsubst org-call-with-arg (command arg)
3005 "Call COMMAND interactively, but pretend prefix are was ARG."
3006 (let ((current-prefix-arg arg)) (call-interactively command)))
3007
3008 (defsubst org-current-line (&optional pos)
3009 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
3010
3011 (defun org-current-time ()
3012 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3013 (if (> org-time-stamp-rounding-minutes 0)
3014 (let ((r org-time-stamp-rounding-minutes)
3015 (time (decode-time)))
3016 (apply 'encode-time
3017 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3018 (nthcdr 2 time))))
3019 (current-time)))
3020
3021 (defun org-add-props (string plist &rest props)
3022 "Add text properties to entire string, from beginning to end.
3023 PLIST may be a list of properties, PROPS are individual properties and values
3024 that will be added to PLIST. Returns the string that was modified."
3025 (add-text-properties
3026 0 (length string) (if props (append plist props) plist) string)
3027 string)
3028 (put 'org-add-props 'lisp-indent-function 2)
3029
3030
3031 ;;; Font-Lock stuff
3032
3033 (defvar org-mouse-map (make-sparse-keymap))
3034 (define-key org-mouse-map
3035 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3036 (define-key org-mouse-map
3037 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3038 (when org-mouse-1-follows-link
3039 (define-key org-mouse-map [follow-link] 'mouse-face))
3040 (when org-tab-follows-link
3041 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3042 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3043 (when org-return-follows-link
3044 (define-key org-mouse-map [(return)] 'org-open-at-point)
3045 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3046
3047 (require 'font-lock)
3048
3049 (defconst org-non-link-chars "]\t\n\r<>")
3050 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3051 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3052 (defconst org-link-re-with-space
3053 (concat
3054 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3055 "\\([^" org-non-link-chars " ]"
3056 "[^" org-non-link-chars "]*"
3057 "[^" org-non-link-chars " ]\\)>?")
3058 "Matches a link with spaces, optional angular brackets around it.")
3059
3060 (defconst org-link-re-with-space2
3061 (concat
3062 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3063 "\\([^" org-non-link-chars " ]"
3064 "[^]\t\n\r]*"
3065 "[^" org-non-link-chars " ]\\)>?")
3066 "Matches a link with spaces, optional angular brackets around it.")
3067
3068 (defconst org-angle-link-re
3069 (concat
3070 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3071 "\\([^" org-non-link-chars " ]"
3072 "[^" org-non-link-chars "]*"
3073 "\\)>")
3074 "Matches link with angular brackets, spaces are allowed.")
3075 (defconst org-plain-link-re
3076 (concat
3077 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3078 "\\([^]\t\n\r<>,;() ]+\\)")
3079 "Matches plain link, without spaces.")
3080
3081 (defconst org-bracket-link-regexp
3082 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3083 "Matches a link in double brackets.")
3084
3085 (defconst org-bracket-link-analytic-regexp
3086 (concat
3087 "\\[\\["
3088 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3089 "\\([^]]+\\)"
3090 "\\]"
3091 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3092 "\\]"))
3093 ; 1: http:
3094 ; 2: http
3095 ; 3: path
3096 ; 4: [desc]
3097 ; 5: desc
3098
3099
3100 (defconst org-ts-lengths
3101 (cons (length (format-time-string (car org-time-stamp-formats)))
3102 (length (format-time-string (cdr org-time-stamp-formats))))
3103 "This holds the lengths of the two different time formats.")
3104 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3105 "Regular expression for fast time stamp matching.")
3106 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3107 "Regular expression for fast time stamp matching.")
3108 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3109 "Regular expression matching time strings for analysis.")
3110 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3111 "Regular expression matching time stamps, with groups.")
3112 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3113 "Regular expression matching time stamps (also [..]), with groups.")
3114 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3115 "Regular expression matching a time stamp range.")
3116 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3117 org-ts-regexp "\\)?")
3118 "Regular expression matching a time stamp or time stamp range.")
3119
3120 (defvar org-\81§emph-face nil)
3121
3122 (defun org-do-emphasis-faces (limit)
3123 "Run through the buffer and add overlays to links."
3124 (if (re-search-forward org-emph-re limit t)
3125 (progn
3126 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3127 'face
3128 (nth 1 (assoc (match-string 3)
3129 org-emphasis-alist)))
3130 (add-text-properties (match-beginning 2) (match-end 2)
3131 '(font-lock-multiline t))
3132 (backward-char 1)
3133 t)))
3134
3135 (defun org-activate-plain-links (limit)
3136 "Run through the buffer and add overlays to links."
3137 (if (re-search-forward org-plain-link-re limit t)
3138 (progn
3139 (add-text-properties (match-beginning 0) (match-end 0)
3140 (list 'mouse-face 'highlight
3141 'rear-nonsticky t
3142 'keymap org-mouse-map
3143 ))
3144 t)))
3145
3146 (defun org-activate-angle-links (limit)
3147 "Run through the buffer and add overlays to links."
3148 (if (re-search-forward org-angle-link-re limit t)
3149 (progn
3150 (add-text-properties (match-beginning 0) (match-end 0)
3151 (list 'mouse-face 'highlight
3152 'rear-nonsticky t
3153 'keymap org-mouse-map
3154 ))
3155 t)))
3156
3157 (defun org-activate-bracket-links (limit)
3158 "Run through the buffer and add overlays to bracketed links."
3159 (if (re-search-forward org-bracket-link-regexp limit t)
3160 (let* ((help (concat "LINK: "
3161 (org-match-string-no-properties 1)))
3162 ;; FIXME: above we should remove the escapes.
3163 ;; but that requires another match, protecting match data,
3164 ;; a lot of overhead for font-lock.
3165 (ip (list 'invisible 'org-link 'intangible t 'rear-nonsticky t
3166 'keymap org-mouse-map 'mouse-face 'highlight
3167 'help-echo help))
3168 (vp (list 'rear-nonsticky t
3169 'keymap org-mouse-map 'mouse-face 'highlight
3170 'help-echo help)))
3171 ;; We need to remove the invisible property here. Table narrowing
3172 ;; may have made some of this invisible.
3173 (remove-text-properties (match-beginning 0) (match-end 0)
3174 '(invisible nil))
3175 (if (match-end 3)
3176 (progn
3177 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3178 (add-text-properties (match-beginning 3) (match-end 3) vp)
3179 (add-text-properties (match-end 3) (match-end 0) ip))
3180 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3181 (add-text-properties (match-beginning 1) (match-end 1) vp)
3182 (add-text-properties (match-end 1) (match-end 0) ip))
3183 t)))
3184
3185 (defun org-activate-dates (limit)
3186 "Run through the buffer and add overlays to dates."
3187 (if (re-search-forward org-tsr-regexp limit t)
3188 (progn
3189 (add-text-properties (match-beginning 0) (match-end 0)
3190 (list 'mouse-face 'highlight
3191 'rear-nonsticky t
3192 'keymap org-mouse-map))
3193 t)))
3194
3195 (defvar org-target-link-regexp nil
3196 "Regular expression matching radio targets in plain text.")
3197 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3198 "Regular expression matching a link target.")
3199 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3200 "Regular expression matching a link target.")
3201
3202 (defun org-activate-target-links (limit)
3203 "Run through the buffer and add overlays to target matches."
3204 (when org-target-link-regexp
3205 (let ((case-fold-search t))
3206 (if (re-search-forward org-target-link-regexp limit t)
3207 (progn
3208 (add-text-properties (match-beginning 0) (match-end 0)
3209 (list 'mouse-face 'highlight
3210 'rear-nonsticky t
3211 'keymap org-mouse-map
3212 'help-echo "Radio target link"
3213 'org-linked-text t))
3214 t)))))
3215
3216 (defun org-update-radio-target-regexp ()
3217 "Find all radio targets in this file and update the regular expression."
3218 (interactive)
3219 (when (memq 'radio org-activate-links)
3220 (setq org-target-link-regexp
3221 (org-make-target-link-regexp (org-all-targets 'radio)))
3222 (org-restart-font-lock)))
3223
3224 (defun org-hide-wide-columns (limit)
3225 (let (s e)
3226 (setq s (text-property-any (point) (or limit (point-max))
3227 'org-cwidth t))
3228 (when s
3229 (setq e (next-single-property-change s 'org-cwidth))
3230 (add-text-properties s e '(invisible org-cwidth intangible t))
3231 (goto-char e)
3232 t)))
3233
3234 (defun org-restart-font-lock ()
3235 "Restart font-lock-mode, to force refontification."
3236 (when (and (boundp 'font-lock-mode) font-lock-mode)
3237 (font-lock-mode -1)
3238 (font-lock-mode 1)))
3239
3240 (defun org-all-targets (&optional radio)
3241 "Return a list of all targets in this file.
3242 With optional argument RADIO, only find radio targets."
3243 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3244 rtn)
3245 (save-excursion
3246 (goto-char (point-min))
3247 (while (re-search-forward re nil t)
3248 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3249 rtn)))
3250
3251 (defun org-make-target-link-regexp (targets)
3252 "Make regular expression matching all strings in TARGETS.
3253 The regular expression finds the targets also if there is a line break
3254 between words."
3255 (and targets
3256 (concat
3257 "\\<\\("
3258 (mapconcat
3259 (lambda (x)
3260 (while (string-match " +" x)
3261 (setq x (replace-match "\\s-+" t t x)))
3262 x)
3263 targets
3264 "\\|")
3265 "\\)\\>")))
3266
3267 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3268 "Matches CamelCase words, possibly with a star before it.")
3269
3270 (defun org-activate-camels (limit)
3271 "Run through the buffer and add overlays to dates."
3272 (if (re-search-forward org-camel-regexp limit t)
3273 (progn
3274 (add-text-properties (match-beginning 0) (match-end 0)
3275 (list 'mouse-face 'highlight
3276 'rear-nonsticky t
3277 'keymap org-mouse-map))
3278 t)))
3279
3280 (defun org-activate-tags (limit)
3281 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3282 (progn
3283 (add-text-properties (match-beginning 1) (match-end 1)
3284 (list 'mouse-face 'highlight
3285 'rear-nonsticky t
3286 'keymap org-mouse-map))
3287 t)))
3288
3289 (defun org-font-lock-level ()
3290 (save-excursion
3291 (org-back-to-heading t)
3292 (- (match-end 0) (match-beginning 0))))
3293
3294 (defun org-outline-level ()
3295 (save-excursion
3296 (looking-at outline-regexp)
3297 (if (match-beginning 1)
3298 (+ (org-get-string-indentation (match-string 1)) 1000)
3299 (- (match-end 0) (match-beginning 0)))))
3300
3301 (defvar org-font-lock-keywords nil)
3302
3303 (defun org-set-font-lock-defaults ()
3304 (let* ((em org-fontify-emphasized-text)
3305 (lk org-activate-links)
3306 (org-font-lock-extra-keywords
3307 ;; Headlines
3308 (list
3309 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3310 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3311 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3312 (1 'org-table))
3313 ;; Links
3314 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3315 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3316 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3317 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3318 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3319 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3320 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3321 (if org-table-limit-column-width
3322 '(org-hide-wide-columns (0 nil append)))
3323 ;; TODO lines
3324 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3325 '(1 'org-todo t))
3326 ;; Priorities
3327 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3328 ;; Special keywords
3329 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3330 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3331 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3332 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3333 ;; Emphasis
3334 (if em '(org-do-emphasis-faces))
3335 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3336 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3337 2 'bold prepend)
3338 ;; COMMENT
3339 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3340 "\\|" org-quote-string "\\)\\>")
3341 '(1 'org-special-keyword t))
3342 '("^#.*" (0 'font-lock-comment-face t))
3343 ;; DONE
3344 (if org-fontify-done-headline
3345 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3346 '(1 'org-done t) '(2 'org-headline-done t))
3347 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3348 '(1 'org-done t)))
3349 ;; Table stuff
3350 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3351 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3352 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3353 (if org-format-transports-properties-p
3354 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3355 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3356 )))
3357 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3358 ;; Now set the full font-lock-keywords
3359 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3360 (org-set-local 'font-lock-defaults
3361 '(org-font-lock-keywords t nil nil backward-paragraph))
3362 (kill-local-variable 'font-lock-keywords) nil))
3363
3364 (defvar org-m nil)
3365 (defvar org-l nil)
3366 (defvar org-f nil)
3367 (defun org-get-level-face (n)
3368 "Get the right face for match N in font-lock matching of healdines."
3369 (setq org-l (- (match-end 2) (match-beginning 1)))
3370 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3371 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3372 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3373 (cond
3374 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3375 ((eq n 2) org-f)
3376 (t (if org-level-color-stars-only nil org-f))))
3377
3378 (defun org-unfontify-region (beg end &optional maybe_loudly)
3379 "Remove fontification and activation overlays from links."
3380 (font-lock-default-unfontify-region beg end)
3381 (let* ((buffer-undo-list t)
3382 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3383 (inhibit-modification-hooks t)
3384 deactivate-mark buffer-file-name buffer-file-truename)
3385 (remove-text-properties beg end
3386 '(mouse-face nil keymap nil org-linked-text nil
3387 rear-nonsticky nil
3388 invisible nil intangible nil))))
3389 ;;; Visibility cycling
3390
3391 (defvar org-cycle-global-status nil)
3392 (make-variable-buffer-local 'org-cycle-global-status)
3393 (defvar org-cycle-subtree-status nil)
3394 (make-variable-buffer-local 'org-cycle-subtree-status)
3395
3396 ;;;###autoload
3397 (defun org-cycle (&optional arg)
3398 "Visibility cycling for Org-mode.
3399
3400 - When this function is called with a prefix argument, rotate the entire
3401 buffer through 3 states (global cycling)
3402 1. OVERVIEW: Show only top-level headlines.
3403 2. CONTENTS: Show all headlines of all levels, but no body text.
3404 3. SHOW ALL: Show everything.
3405
3406 - When point is at the beginning of a headline, rotate the subtree started
3407 by this line through 3 different states (local cycling)
3408 1. FOLDED: Only the main headline is shown.
3409 2. CHILDREN: The main headline and the direct children are shown.
3410 From this state, you can move to one of the children
3411 and zoom in further.
3412 3. SUBTREE: Show the entire subtree, including body text.
3413
3414 - When there is a numeric prefix, go up to a heading with level ARG, do
3415 a `show-subtree' and return to the previous cursor position. If ARG
3416 is negative, go up that many levels.
3417
3418 - When point is not at the beginning of a headline, execute
3419 `indent-relative', like TAB normally does. See the option
3420 `org-cycle-emulate-tab' for details.
3421
3422 - Special case: if point is the the beginning of the buffer and there is
3423 no headline in line 1, this function will act as if called with prefix arg."
3424 (interactive "P")
3425
3426 (let* ((outline-regexp
3427 (if org-cycle-include-plain-lists
3428 "\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) "
3429 outline-regexp))
3430 (bob-special (and org-cycle-global-at-bob (bobp)
3431 (not (looking-at outline-regexp))))
3432 (org-cycle-hook
3433 (if bob-special
3434 (delq 'org-optimize-window-after-visibility-change
3435 (copy-sequence org-cycle-hook))
3436 org-cycle-hook))
3437 (pos (point)))
3438
3439 (if (or bob-special (equal arg '(4)))
3440 ;; special case: use global cycling
3441 (setq arg t))
3442
3443 (cond
3444
3445 ((org-at-table-p 'any)
3446 ;; Enter the table or move to the next field in the table
3447 (or (org-table-recognize-table.el)
3448 (progn
3449 (if arg (org-table-edit-field t)
3450 (org-table-justify-field-maybe)
3451 (call-interactively 'org-table-next-field)))))
3452
3453 ((eq arg t) ;; Global cycling
3454
3455 (cond
3456 ((and (eq last-command this-command)
3457 (eq org-cycle-global-status 'overview))
3458 ;; We just created the overview - now do table of contents
3459 ;; This can be slow in very large buffers, so indicate action
3460 (message "CONTENTS...")
3461 (org-content)
3462 (message "CONTENTS...done")
3463 (setq org-cycle-global-status 'contents)
3464 (run-hook-with-args 'org-cycle-hook 'contents))
3465
3466 ((and (eq last-command this-command)
3467 (eq org-cycle-global-status 'contents))
3468 ;; We just showed the table of contents - now show everything
3469 (show-all)
3470 (message "SHOW ALL")
3471 (setq org-cycle-global-status 'all)
3472 (run-hook-with-args 'org-cycle-hook 'all))
3473
3474 (t
3475 ;; Default action: go to overview
3476 (org-overview)
3477 (message "OVERVIEW")
3478 (setq org-cycle-global-status 'overview)
3479 (run-hook-with-args 'org-cycle-hook 'overview))))
3480
3481 ((integerp arg)
3482 ;; Show-subtree, ARG levels up from here.
3483 (save-excursion
3484 (org-back-to-heading)
3485 (outline-up-heading (if (< arg 0) (- arg)
3486 (- (funcall outline-level) arg)))
3487 (org-show-subtree)))
3488
3489 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3490 ;; At a heading: rotate between three different views
3491 (org-back-to-heading)
3492 (let ((goal-column 0) eoh eol eos)
3493 ;; First, some boundaries
3494 (save-excursion
3495 (org-back-to-heading)
3496 (save-excursion
3497 (beginning-of-line 2)
3498 (while (and (not (eobp)) ;; this is like `next-line'
3499 (get-char-property (1- (point)) 'invisible))
3500 (beginning-of-line 2)) (setq eol (point)))
3501 (outline-end-of-heading) (setq eoh (point))
3502 (org-end-of-subtree t) (setq eos (point))
3503 (outline-next-heading))
3504 ;; Find out what to do next and set `this-command'
3505 (cond
3506 ((and (= eos eoh)
3507 ;; Nothing is hidden behind this heading
3508 (message "EMPTY ENTRY")
3509 (setq org-cycle-subtree-status nil)))
3510 ((>= eol eos)
3511 ;; Entire subtree is hidden in one line: open it
3512 (org-show-entry)
3513 (show-children)
3514 (message "CHILDREN")
3515 (setq org-cycle-subtree-status 'children)
3516 (run-hook-with-args 'org-cycle-hook 'children))
3517 ((and (eq last-command this-command)
3518 (eq org-cycle-subtree-status 'children))
3519 ;; We just showed the children, now show everything.
3520 (org-show-subtree)
3521 (message "SUBTREE")
3522 (setq org-cycle-subtree-status 'subtree)
3523 (run-hook-with-args 'org-cycle-hook 'subtree))
3524 (t
3525 ;; Default action: hide the subtree.
3526 (hide-subtree)
3527 (message "FOLDED")
3528 (setq org-cycle-subtree-status 'folded)
3529 (run-hook-with-args 'org-cycle-hook 'folded)))))
3530
3531 ;; TAB emulation
3532 (buffer-read-only (org-back-to-heading))
3533
3534 ((org-try-cdlatex-tab))
3535
3536 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3537 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3538 (or (and (eq org-cycle-emulate-tab 'white)
3539 (= (match-end 0) (point-at-eol)))
3540 (and (eq org-cycle-emulate-tab 'whitestart)
3541 (>= (match-end 0) pos))))
3542 t
3543 (eq org-cycle-emulate-tab t))
3544 (if (and (looking-at "[ \n\r\t]")
3545 (string-match "^[ \t]*$" (buffer-substring
3546 (point-at-bol) (point))))
3547 (progn
3548 (beginning-of-line 1)
3549 (and (looking-at "[ \t]+") (replace-match ""))))
3550 (indent-relative))
3551
3552 (t (save-excursion
3553 (org-back-to-heading)
3554 (org-cycle))))))
3555
3556 ;;;###autoload
3557 (defun org-global-cycle (&optional arg)
3558 "Cycle the global visibility. For details see `org-cycle'."
3559 (interactive "P")
3560 (if (integerp arg)
3561 (progn
3562 (show-all)
3563 (hide-sublevels arg)
3564 (setq org-cycle-global-status 'contents))
3565 (org-cycle '(4))))
3566
3567 (defun org-overview ()
3568 "Switch to overview mode, shoing only top-level headlines.
3569 Really, this shows all headlines with level equal or greater than the level
3570 of the first headline in the buffer. This is important, because if the
3571 first headline is not level one, then (hide-sublevels 1) gives confusing
3572 results."
3573 (interactive)
3574 (hide-sublevels (save-excursion
3575 (goto-char (point-min))
3576 (if (re-search-forward (concat "^" outline-regexp) nil t)
3577 (progn
3578 (goto-char (match-beginning 0))
3579 (funcall outline-level))
3580 1))))
3581
3582 ;; FIXME: allow an argument to give a limiting level for this.
3583 (defun org-content ()
3584 "Show all headlines in the buffer, like a table of contents"
3585 (interactive)
3586 (save-excursion
3587 ;; Visit all headings and show their offspring
3588 (goto-char (point-max))
3589 (catch 'exit
3590 (while (and (progn (condition-case nil
3591 (outline-previous-visible-heading 1)
3592 (error (goto-char (point-min))))
3593 t)
3594 (looking-at outline-regexp))
3595 (show-branches)
3596 (if (bobp) (throw 'exit nil))))))
3597
3598
3599 (defun org-optimize-window-after-visibility-change (state)
3600 "Adjust the window after a change in outline visibility.
3601 This function is the default value of the hook `org-cycle-hook'."
3602 (when (get-buffer-window (current-buffer))
3603 (cond
3604 ((eq state 'overview) (org-first-headline-recenter 1))
3605 ((eq state 'content) nil)
3606 ((eq state 'all) nil)
3607 ((eq state 'folded) nil)
3608 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3609 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3610
3611 (defun org-subtree-end-visible-p ()
3612 "Is the end of the current subtree visible?"
3613 (pos-visible-in-window-p
3614 (save-excursion (org-end-of-subtree t) (point))))
3615
3616 (defun org-first-headline-recenter (&optional N)
3617 "Move cursor to the first headline and recenter the headline.
3618 Optional argument N means, put the headline into the Nth line of the window."
3619 (goto-char (point-min))
3620 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
3621 (beginning-of-line)
3622 (recenter (prefix-numeric-value N))))
3623
3624 (defvar org-goto-window-configuration nil)
3625 (defvar org-goto-marker nil)
3626 (defvar org-goto-map (make-sparse-keymap))
3627 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3628 (while (setq cmd (pop cmds))
3629 (substitute-key-definition cmd cmd org-goto-map global-map)))
3630 (define-key org-goto-map "\C-m" 'org-goto-ret)
3631 (define-key org-goto-map [(left)] 'org-goto-left)
3632 (define-key org-goto-map [(right)] 'org-goto-right)
3633 (define-key org-goto-map [(?q)] 'org-goto-quit)
3634 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3635 (define-key org-goto-map "\C-i" 'org-cycle)
3636 (define-key org-goto-map [(tab)] 'org-cycle)
3637 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3638 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3639 (define-key org-goto-map "n" 'outline-next-visible-heading)
3640 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3641 (define-key org-goto-map "f" 'outline-forward-same-level)
3642 (define-key org-goto-map "b" 'outline-backward-same-level)
3643 (define-key org-goto-map "u" 'outline-up-heading)
3644 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3645 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3646 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3647 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3648 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3649 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3650 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3651
3652 (defconst org-goto-help
3653 "Select a location to jump to, press RET
3654 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3655
3656 (defun org-goto ()
3657 "Go to a different location of the document, keeping current visibility.
3658
3659 When you want to go to a different location in a document, the fastest way
3660 is often to fold the entire buffer and then dive into the tree. This
3661 method has the disadvantage, that the previous location will be folded,
3662 which may not be what you want.
3663
3664 This command works around this by showing a copy of the current buffer in
3665 overview mode. You can dive into the tree in that copy, to find the
3666 location you want to reach. When pressing RET, the command returns to the
3667 original buffer in which the visibility is still unchanged. It then jumps
3668 to the new location, making it and the headline hierarchy above it visible."
3669 (interactive)
3670 (let* ((org-goto-start-pos (point))
3671 (selected-point
3672 (org-get-location (current-buffer) org-goto-help)))
3673 (if selected-point
3674 (progn
3675 (org-mark-ring-push org-goto-start-pos)
3676 (goto-char selected-point)
3677 (if (or (org-invisible-p) (org-invisible-p2))
3678 (org-show-hierarchy-above)))
3679 (error "Quit"))))
3680
3681 (defun org-get-location (buf help)
3682 "Let the user select a location in the Org-mode buffer BUF.
3683 This function uses a recursive edit. It returns the selected position
3684 or nil."
3685 (let (org-selected-point)
3686 (save-excursion
3687 (save-window-excursion
3688 (delete-other-windows)
3689 (switch-to-buffer (get-buffer-create "*org-goto*"))
3690 (with-output-to-temp-buffer "*Help*"
3691 (princ help))
3692 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3693 (setq buffer-read-only nil)
3694 (erase-buffer)
3695 (insert-buffer-substring buf)
3696 (let ((org-startup-truncated t)
3697 (org-startup-folded t)
3698 (org-startup-align-all-tables nil)
3699 (org-startup-with-deadline-check nil))
3700 (org-mode))
3701 (setq buffer-read-only t)
3702 (if (boundp 'org-goto-start-pos)
3703 (goto-char org-goto-start-pos)
3704 (goto-char (point-min)))
3705 (org-beginning-of-line)
3706 (message "Select location and press RET")
3707 ;; now we make sure that during selection, ony very few keys work
3708 ;; and that it is impossible to switch to another window.
3709 (let ((gm (current-global-map))
3710 (overriding-local-map org-goto-map))
3711 (unwind-protect
3712 (progn
3713 (use-global-map org-goto-map)
3714 (recursive-edit))
3715 (use-global-map gm)))))
3716 (kill-buffer "*org-goto*")
3717 org-selected-point))
3718
3719 (defun org-goto-ret (&optional arg)
3720 "Finish `org-goto' by going to the new location."
3721 (interactive "P")
3722 (setq org-selected-point (point)
3723 current-prefix-arg arg)
3724 (throw 'exit nil))
3725
3726 (defun org-goto-left ()
3727 "Finish `org-goto' by going to the new location."
3728 (interactive)
3729 (if (org-on-heading-p)
3730 (progn
3731 (beginning-of-line 1)
3732 (setq org-selected-point (point)
3733 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3734 (throw 'exit nil))
3735 (error "Not on a heading")))
3736
3737 (defun org-goto-right ()
3738 "Finish `org-goto' by going to the new location."
3739 (interactive)
3740 (if (org-on-heading-p)
3741 (progn
3742 (outline-end-of-subtree)
3743 (or (eobp) (forward-char 1))
3744 (setq org-selected-point (point)
3745 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3746 (throw 'exit nil))
3747 (error "Not on a heading")))
3748
3749 (defun org-goto-quit ()
3750 "Finish `org-goto' without cursor motion."
3751 (interactive)
3752 (setq org-selected-point nil)
3753 (throw 'exit nil))
3754
3755 ;;; Promotion, Demotion, Inserting new headlines
3756
3757 (defvar org-ignore-region nil
3758 "To temporarily disable the active region.")
3759
3760 (defun org-insert-heading (&optional force-heading)
3761 "Insert a new heading or item with same depth at point.
3762 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
3763 If point is at the beginning of a headline, insert a sibling before the
3764 current headline. If point is in the middle of a headline, split the headline
3765 at that position and make the rest of the headline part of the sibling below
3766 the current headline."
3767 (interactive "P")
3768 (if (= (buffer-size) 0)
3769 (insert "\n* ")
3770 (when (or force-heading (not (org-insert-item)))
3771 (let* ((head (save-excursion
3772 (condition-case nil
3773 (progn
3774 (org-back-to-heading)
3775 (match-string 0))
3776 (error "*"))))
3777 pos)
3778 (cond
3779 ((and (org-on-heading-p) (bolp)
3780 (save-excursion (backward-char 1) (not (org-invisible-p))))
3781 (open-line 1))
3782 ((and (bolp) (save-excursion
3783 (backward-char 1) (not (org-invisible-p))))
3784 nil)
3785 (t (newline)))
3786 (insert head) (just-one-space)
3787 (setq pos (point))
3788 (end-of-line 1)
3789 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
3790 (run-hooks 'org-insert-heading-hook)))))
3791
3792 (defun org-insert-item (&optional checkbox)
3793 "Insert a new item at the current level.
3794 Return t when things worked, nil when we are not in an item."
3795 (when (save-excursion
3796 (condition-case nil
3797 (progn
3798 (org-beginning-of-item)
3799 (org-at-item-p)
3800 t)
3801 (error nil)))
3802 (let* ((bul (match-string 0))
3803 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3804 (match-end 0)))
3805 pos)
3806 (cond
3807 ((and (org-at-item-p) (<= (point) eow))
3808 ;; before the bullet
3809 (beginning-of-line 1)
3810 (open-line 1))
3811 ((<= (point) eow)
3812 (beginning-of-line 1))
3813 (t (newline)))
3814 (insert bul (if checkbox "[ ]" ""))
3815 (just-one-space)
3816 (setq pos (point))
3817 (end-of-line 1)
3818 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
3819 (org-maybe-renumber-ordered-list)
3820 t))
3821
3822 (defun org-insert-todo-heading (arg)
3823 "Insert a new heading with the same level and TODO state as current heading.
3824 If the heading has no TODO state, or if the state is DONE, use the first
3825 state (TODO by default). Also with prefix arg, force first state."
3826 (interactive "P")
3827 (when (not (org-insert-item 'checkbox))
3828 (org-insert-heading)
3829 (save-excursion
3830 (org-back-to-heading)
3831 (outline-previous-heading)
3832 (looking-at org-todo-line-regexp))
3833 (if (or arg
3834 (not (match-beginning 2))
3835 (equal (match-string 2) org-done-string))
3836 (insert (car org-todo-keywords) " ")
3837 (insert (match-string 2) " "))))
3838
3839 (defun org-promote-subtree ()
3840 "Promote the entire subtree.
3841 See also `org-promote'."
3842 (interactive)
3843 (save-excursion
3844 (org-map-tree 'org-promote)))
3845
3846 (defun org-demote-subtree ()
3847 "Demote the entire subtree. See `org-demote'.
3848 See also `org-promote'."
3849 (interactive)
3850 (save-excursion
3851 (org-map-tree 'org-demote)))
3852
3853 (defun org-do-promote ()
3854 "Promote the current heading higher up the tree.
3855 If the region is active in `transient-mark-mode', promote all headings
3856 in the region."
3857 (interactive)
3858 (save-excursion
3859 (if (org-region-active-p)
3860 (org-map-region 'org-promote (region-beginning) (region-end))
3861 (org-promote)))
3862 (org-fix-position-after-promote))
3863
3864 (defun org-do-demote ()
3865 "Demote the current heading lower down the tree.
3866 If the region is active in `transient-mark-mode', demote all headings
3867 in the region."
3868 (interactive)
3869 (save-excursion
3870 (if (org-region-active-p)
3871 (org-map-region 'org-demote (region-beginning) (region-end))
3872 (org-demote)))
3873 (org-fix-position-after-promote))
3874
3875 (defun org-fix-position-after-promote ()
3876 "Make sure that after pro/demotion cursor position is right."
3877 (and (equal (char-after) ?\ )
3878 (equal (char-before) ?*)
3879 (forward-char 1)))
3880
3881 (defun org-get-legal-level (level change)
3882 "Rectify a level change under the influence of `org-odd-levels-only'
3883 LEVEL is a current level, CHANGE is by how much the level should be
3884 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3885 even level numbers will become the next higher odd number."
3886 (if org-odd-levels-only
3887 (cond ((not change) (1+ (* 2 (/ level 2))))
3888 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3889 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3890 (max 1 (+ level change))))
3891
3892 (defun org-promote ()
3893 "Promote the current heading higher up the tree.
3894 If the region is active in `transient-mark-mode', promote all headings
3895 in the region."
3896 (org-back-to-heading t)
3897 (let* ((level (save-match-data (funcall outline-level)))
3898 (up-head (make-string (org-get-legal-level level -1) ?*))
3899 (diff (abs (- level (length up-head)))))
3900 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3901 (replace-match up-head nil t)
3902 ;; Fixup tag positioning
3903 (and org-auto-align-tags (org-set-tags nil t))
3904 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
3905
3906 (defun org-demote ()
3907 "Demote the current heading lower down the tree.
3908 If the region is active in `transient-mark-mode', demote all headings
3909 in the region."
3910 (org-back-to-heading t)
3911 (let* ((level (save-match-data (funcall outline-level)))
3912 (down-head (make-string (org-get-legal-level level 1) ?*))
3913 (diff (abs (- level (length down-head)))))
3914 (replace-match down-head nil t)
3915 ;; Fixup tag positioning
3916 (and org-auto-align-tags (org-set-tags nil t))
3917 (if org-adapt-indentation (org-fixup-indentation diff))))
3918
3919 (defun org-map-tree (fun)
3920 "Call FUN for every heading underneath the current one."
3921 (org-back-to-heading)
3922 (let ((level (funcall outline-level)))
3923 (save-excursion
3924 (funcall fun)
3925 (while (and (progn
3926 (outline-next-heading)
3927 (> (funcall outline-level) level))
3928 (not (eobp)))
3929 (funcall fun)))))
3930
3931 (defun org-map-region (fun beg end)
3932 "Call FUN for every heading between BEG and END."
3933 (let ((org-ignore-region t))
3934 (save-excursion
3935 (setq end (copy-marker end))
3936 (goto-char beg)
3937 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3938 (< (point) end))
3939 (funcall fun))
3940 (while (and (progn
3941 (outline-next-heading)
3942 (< (point) end))
3943 (not (eobp)))
3944 (funcall fun)))))
3945
3946 (defun org-fixup-indentation (diff)
3947 "Change the indentation in the current entry by DIFF
3948 However, if any line in the current entry has no indentation, or if it
3949 would end up with no indentation after the change, nothing at all is done."
3950 (save-excursion
3951 (let ((end (save-excursion (outline-next-heading)
3952 (point-marker)))
3953 (prohibit (if (> diff 0)
3954 "^\\S-"
3955 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
3956 col)
3957 (unless (save-excursion (re-search-forward prohibit end t))
3958 (while (re-search-forward "^[ \t]+" end t)
3959 (goto-char (match-end 0))
3960 (setq col (current-column))
3961 (if (< diff 0) (replace-match ""))
3962 (indent-to (+ diff col))))
3963 (move-marker end nil))))
3964
3965 ;;; Vertical tree motion, cutting and pasting of subtrees
3966
3967 (defun org-move-subtree-up (&optional arg)
3968 "Move the current subtree up past ARG headlines of the same level."
3969 (interactive "p")
3970 (org-move-subtree-down (- (prefix-numeric-value arg))))
3971
3972 (defun org-move-subtree-down (&optional arg)
3973 "Move the current subtree down past ARG headlines of the same level."
3974 (interactive "p")
3975 (setq arg (prefix-numeric-value arg))
3976 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3977 'outline-get-last-sibling))
3978 (ins-point (make-marker))
3979 (cnt (abs arg))
3980 beg end txt folded)
3981 ;; Select the tree
3982 (org-back-to-heading)
3983 (setq beg (point))
3984 (save-match-data
3985 (save-excursion (outline-end-of-heading)
3986 (setq folded (org-invisible-p)))
3987 (outline-end-of-subtree))
3988 (outline-next-heading)
3989 (setq end (point))
3990 ;; Find insertion point, with error handling
3991 (goto-char beg)
3992 (while (> cnt 0)
3993 (or (and (funcall movfunc) (looking-at outline-regexp))
3994 (progn (goto-char beg)
3995 (error "Cannot move past superior level or buffer limit")))
3996 (setq cnt (1- cnt)))
3997 (if (> arg 0)
3998 ;; Moving forward - still need to move over subtree
3999 (progn (outline-end-of-subtree)
4000 (outline-next-heading)
4001 (if (not (or (looking-at (concat "^" outline-regexp))
4002 (bolp)))
4003 (newline))))
4004 (move-marker ins-point (point))
4005 (setq txt (buffer-substring beg end))
4006 (delete-region beg end)
4007 (insert txt)
4008 (goto-char ins-point)
4009 (if folded (hide-subtree))
4010 (move-marker ins-point nil)))
4011
4012 (defvar org-subtree-clip ""
4013 "Clipboard for cut and paste of subtrees.
4014 This is actually only a copy of the kill, because we use the normal kill
4015 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4016
4017 (defvar org-subtree-clip-folded nil
4018 "Was the last copied subtree folded?
4019 This is used to fold the tree back after pasting.")
4020
4021 (defun org-cut-subtree ()
4022 "Cut the current subtree into the clipboard.
4023 This is a short-hand for marking the subtree and then cutting it."
4024 (interactive)
4025 (org-copy-subtree 'cut))
4026
4027 (defun org-copy-subtree (&optional cut)
4028 "Cut the current subtree into the clipboard.
4029 This is a short-hand for marking the subtree and then copying it.
4030 If CUT is non-nil, actually cut the subtree."
4031 (interactive)
4032 (let (beg end folded)
4033 (org-back-to-heading)
4034 (setq beg (point))
4035 (save-match-data
4036 (save-excursion (outline-end-of-heading)
4037 (setq folded (org-invisible-p)))
4038 (outline-end-of-subtree))
4039 (if (equal (char-after) ?\n) (forward-char 1))
4040 (setq end (point))
4041 (goto-char beg)
4042 (when (> end beg)
4043 (setq org-subtree-clip-folded folded)
4044 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4045 (setq org-subtree-clip (current-kill 0))
4046 (message "%s: Subtree with %d characters"
4047 (if cut "Cut" "Copied")
4048 (length org-subtree-clip)))))
4049
4050 (defun org-paste-subtree (&optional level tree)
4051 "Paste the clipboard as a subtree, with modification of headline level.
4052 The entire subtree is promoted or demoted in order to match a new headline
4053 level. By default, the new level is derived from the visible headings
4054 before and after the insertion point, and taken to be the inferior headline
4055 level of the two. So if the previous visible heading is level 3 and the
4056 next is level 4 (or vice versa), level 4 will be used for insertion.
4057 This makes sure that the subtree remains an independent subtree and does
4058 not swallow low level entries.
4059
4060 You can also force a different level, either by using a numeric prefix
4061 argument, or by inserting the heading marker by hand. For example, if the
4062 cursor is after \"*****\", then the tree will be shifted to level 5.
4063
4064 If you want to insert the tree as is, just use \\[yank].
4065
4066 If optional TREE is given, use this text instead of the kill ring."
4067 (interactive "P")
4068 (unless (org-kill-is-subtree-p tree)
4069 (error
4070 (substitute-command-keys
4071 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4072 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4073 (^re (concat "^\\(" outline-regexp "\\)"))
4074 (re (concat "\\(" outline-regexp "\\)"))
4075 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4076
4077 (old-level (if (string-match ^re txt)
4078 (- (match-end 0) (match-beginning 0))
4079 -1))
4080 (force-level (cond (level (prefix-numeric-value level))
4081 ((string-match
4082 ^re_ (buffer-substring (point-at-bol) (point)))
4083 (- (match-end 0) (match-beginning 0)))
4084 (t nil)))
4085 (previous-level (save-excursion
4086 (condition-case nil
4087 (progn
4088 (outline-previous-visible-heading 1)
4089 (if (looking-at re)
4090 (- (match-end 0) (match-beginning 0))
4091 1))
4092 (error 1))))
4093 (next-level (save-excursion
4094 (condition-case nil
4095 (progn
4096 (outline-next-visible-heading 1)
4097 (if (looking-at re)
4098 (- (match-end 0) (match-beginning 0))
4099 1))
4100 (error 1))))
4101 (new-level (or force-level (max previous-level next-level)))
4102 (shift (if (or (= old-level -1)
4103 (= new-level -1)
4104 (= old-level new-level))
4105 0
4106 (- new-level old-level)))
4107 (shift1 shift)
4108 (delta (if (> shift 0) -1 1))
4109 (func (if (> shift 0) 'org-demote 'org-promote))
4110 (org-odd-levels-only nil)
4111 beg end)
4112 ;; Remove the forces level indicator
4113 (if force-level
4114 (delete-region (point-at-bol) (point)))
4115 ;; Make sure we start at the beginning of an empty line
4116 (if (not (bolp)) (insert "\n"))
4117 (if (not (looking-at "[ \t]*$"))
4118 (progn (insert "\n") (backward-char 1)))
4119 ;; Paste
4120 (setq beg (point))
4121 (if (string-match "[ \t\r\n]+\\'" txt)
4122 (setq txt (replace-match "\n" t t txt)))
4123 (insert txt)
4124 (setq end (point))
4125 (if (looking-at "[ \t\r\n]+")
4126 (replace-match "\n"))
4127 (goto-char beg)
4128 ;; Shift if necessary
4129 (if (= shift 0)
4130 (message "Pasted at level %d, without shift" new-level)
4131 (save-restriction
4132 (narrow-to-region beg end)
4133 (while (not (= shift 0))
4134 (org-map-region func (point-min) (point-max))
4135 (setq shift (+ delta shift)))
4136 (goto-char (point-min))
4137 (message "Pasted at level %d, with shift by %d levels"
4138 new-level shift1)))
4139 (if (and kill-ring
4140 (eq org-subtree-clip (current-kill 0))
4141 org-subtree-clip-folded)
4142 ;; The tree was folded before it was killed/copied
4143 (hide-subtree))))
4144
4145 (defun org-kill-is-subtree-p (&optional txt)
4146 "Check if the current kill is an outline subtree, or a set of trees.
4147 Returns nil if kill does not start with a headline, or if the first
4148 headline level is not the largest headline level in the tree.
4149 So this will actually accept several entries of equal levels as well,
4150 which is OK for `org-paste-subtree'.
4151 If optional TXT is given, check this string instead of the current kill."
4152 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4153 (start-level (and kill
4154 (string-match (concat "\\`" outline-regexp) kill)
4155 (- (match-end 0) (match-beginning 0))))
4156 (re (concat "^" outline-regexp))
4157 (start 1))
4158 (if (not start-level)
4159 nil ;; does not even start with a heading
4160 (catch 'exit
4161 (while (setq start (string-match re kill (1+ start)))
4162 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4163 (throw 'exit nil)))
4164 t))))
4165
4166 (defun org-narrow-to-subtree ()
4167 "Narrow buffer to the current subtree."
4168 (interactive)
4169 (save-excursion
4170 (narrow-to-region
4171 (progn (org-back-to-heading) (point))
4172 (progn (org-end-of-subtree t) (point)))))
4173
4174 ;;; Plain list items
4175
4176 (defun org-at-item-p ()
4177 "Is point in a line starting a hand-formatted item?"
4178 (let ((llt org-plain-list-ordered-item-terminator))
4179 (save-excursion
4180 (goto-char (point-at-bol))
4181 (looking-at
4182 (cond
4183 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4184 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4185 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4186 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4187
4188 (defun org-at-item-checkbox-p ()
4189 "Is point at a line starting a plain-list item with a checklet?"
4190 (and (org-at-item-p)
4191 (save-excursion
4192 (goto-char (match-end 0))
4193 (skip-chars-forward " \t")
4194 (looking-at "\\[[ X]\\]"))))
4195
4196 (defun org-toggle-checkbox (&optional arg)
4197 "Toggle the checkbox in the current line."
4198 (interactive "P")
4199 (catch 'exit
4200 (let (beg end status (firstnew 'unknown))
4201 (cond
4202 ((org-region-active-p)
4203 (setq beg (region-beginning) end (region-end)))
4204 ((org-on-heading-p)
4205 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
4206 ((org-at-item-checkbox-p)
4207 (save-excursion
4208 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
4209 (throw 'exit t))
4210 (t (error "Not at a checkbox or heading, and no active region")))
4211 (save-excursion
4212 (goto-char beg)
4213 (while (< (point) end)
4214 (when (org-at-item-checkbox-p)
4215 (setq status (equal (match-string 0) "[X]"))
4216 (when (eq firstnew 'unknown)
4217 (setq firstnew (not status)))
4218 (replace-match
4219 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
4220 (beginning-of-line 2))))))
4221
4222 (defun org-get-indentation (&optional line)
4223 "Get the indentation of the current line, interpreting tabs.
4224 When LINE is given, assume it represents a line and compute its indentation."
4225 (if line
4226 (if (string-match "^ *" (org-remove-tabs line))
4227 (match-end 0))
4228 (save-excursion
4229 (beginning-of-line 1)
4230 (skip-chars-forward " \t")
4231 (current-column))))
4232
4233 (defun org-remove-tabs (s &optional width)
4234 "Replace tabulators in S with spaces.
4235 Assumes that s is a single line, starting in column 0."
4236 (setq width (or width tab-width))
4237 (while (string-match "\t" s)
4238 (setq s (replace-match
4239 (make-string
4240 (- (* width (/ (+ (match-beginning 0) width) width))
4241 (match-beginning 0)) ?\ )
4242 t t s)))
4243 s)
4244
4245 ;; FIXME: document properly.
4246 (defun org-fix-indentation (line ind)
4247 "If the current indenation is smaller than ind1, leave it alone.
4248 If it is larger than ind, reduce it by ind."
4249 (let* ((l (org-remove-tabs line))
4250 (i (org-get-indentation l))
4251 (i1 (car ind)) (i2 (cdr ind)))
4252 (if (>= i i2) (setq l (substring line i2)))
4253 (if (> i1 0)
4254 (concat (make-string i1 ?\ ) l)
4255 l)))
4256
4257 (defun org-beginning-of-item ()
4258 "Go to the beginning of the current hand-formatted item.
4259 If the cursor is not in an item, throw an error."
4260 (interactive)
4261 (let ((pos (point))
4262 (limit (save-excursion (org-back-to-heading)
4263 (beginning-of-line 2) (point)))
4264 ind ind1)
4265 (if (org-at-item-p)
4266 (beginning-of-line 1)
4267 (beginning-of-line 1)
4268 (skip-chars-forward " \t")
4269 (setq ind (current-column))
4270 (if (catch 'exit
4271 (while t
4272 (beginning-of-line 0)
4273 (if (< (point) limit) (throw 'exit nil))
4274 (unless (looking-at "[ \t]*$")
4275 (skip-chars-forward " \t")
4276 (setq ind1 (current-column))
4277 (if (< ind1 ind)
4278 (throw 'exit (org-at-item-p))))))
4279 nil
4280 (goto-char pos)
4281 (error "Not in an item")))))
4282
4283 (defun org-end-of-item ()
4284 "Go to the end of the current hand-formatted item.
4285 If the cursor is not in an item, throw an error."
4286 (interactive)
4287 (let ((pos (point))
4288 (limit (save-excursion (outline-next-heading) (point)))
4289 (ind (save-excursion
4290 (org-beginning-of-item)
4291 (skip-chars-forward " \t")
4292 (current-column)))
4293 ind1)
4294 (if (catch 'exit
4295 (while t
4296 (beginning-of-line 2)
4297 (if (>= (point) limit) (throw 'exit t))
4298 (unless (looking-at "[ \t]*$")
4299 (skip-chars-forward " \t")
4300 (setq ind1 (current-column))
4301 (if (<= ind1 ind) (throw 'exit t)))))
4302 (beginning-of-line 1)
4303 (goto-char pos)
4304 (error "Not in an item"))))
4305
4306 (defun org-next-item ()
4307 "Move to the beginning of the next item in the current plain list.
4308 Error if not at a plain list, or if this is the last item in the list."
4309 (interactive)
4310 (let (ind ind1 (pos (point)))
4311 (org-beginning-of-item)
4312 (setq ind (org-get-indentation))
4313 (org-end-of-item)
4314 (setq ind1 (org-get-indentation))
4315 (unless (and (org-at-item-p) (= ind ind1))
4316 (goto-char pos)
4317 (error "On last item"))))
4318
4319 (defun org-previous-item ()
4320 "Move to the beginning of the previous item in the current plain list.
4321 Error if not at a plain list, or if this is the last item in the list."
4322 (interactive)
4323 (let (beg ind (pos (point)))
4324 (org-beginning-of-item)
4325 (setq beg (point))
4326 (setq ind (org-get-indentation))
4327 (goto-char beg)
4328 (catch 'exit
4329 (while t
4330 (beginning-of-line 0)
4331 (if (looking-at "[ \t]*$")
4332 nil
4333 (if (<= (org-get-indentation) ind)
4334 (throw 'exit t)))))
4335 (condition-case nil
4336 (org-beginning-of-item)
4337 (error (goto-char pos)
4338 (error "On first item")))))
4339
4340 (defun org-move-item-down ()
4341 "Move the plain list item at point down, i.e. swap with following item.
4342 Subitems (items with larger indentation) are considered part of the item,
4343 so this really moves item trees."
4344 (interactive)
4345 (let (beg end ind ind1 (pos (point)) txt)
4346 (org-beginning-of-item)
4347 (setq beg (point))
4348 (setq ind (org-get-indentation))
4349 (org-end-of-item)
4350 (setq end (point))
4351 (setq ind1 (org-get-indentation))
4352 (if (and (org-at-item-p) (= ind ind1))
4353 (progn
4354 (org-end-of-item)
4355 (setq txt (buffer-substring beg end))
4356 (save-excursion
4357 (delete-region beg end))
4358 (setq pos (point))
4359 (insert txt)
4360 (goto-char pos)
4361 (org-maybe-renumber-ordered-list))
4362 (goto-char pos)
4363 (error "Cannot move this item further down"))))
4364
4365 (defun org-move-item-up (arg)
4366 "Move the plain list item at point up, i.e. swap with previous item.
4367 Subitems (items with larger indentation) are considered part of the item,
4368 so this really moves item trees."
4369 (interactive "p")
4370 (let (beg end ind ind1 (pos (point)) txt)
4371 (org-beginning-of-item)
4372 (setq beg (point))
4373 (setq ind (org-get-indentation))
4374 (org-end-of-item)
4375 (setq end (point))
4376 (goto-char beg)
4377 (catch 'exit
4378 (while t
4379 (beginning-of-line 0)
4380 (if (looking-at "[ \t]*$")
4381 nil
4382 (if (<= (setq ind1 (org-get-indentation)) ind)
4383 (throw 'exit t)))))
4384 (condition-case nil
4385 (org-beginning-of-item)
4386 (error (goto-char beg)
4387 (error "Cannot move this item further up")))
4388 (setq ind1 (org-get-indentation))
4389 (if (and (org-at-item-p) (= ind ind1))
4390 (progn
4391 (setq txt (buffer-substring beg end))
4392 (save-excursion
4393 (delete-region beg end))
4394 (setq pos (point))
4395 (insert txt)
4396 (goto-char pos)
4397 (org-maybe-renumber-ordered-list))
4398 (goto-char pos)
4399 (error "Cannot move this item further up"))))
4400
4401 (defun org-maybe-renumber-ordered-list ()
4402 "Renumber the ordered list at point if setup allows it.
4403 This tests the user option `org-auto-renumber-ordered-lists' before
4404 doing the renumbering."
4405 (and org-auto-renumber-ordered-lists
4406 (org-at-item-p)
4407 (match-beginning 3)
4408 (org-renumber-ordered-list 1)))
4409
4410 (defun org-get-string-indentation (s)
4411 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4412 (let ((n -1) (i 0) (w tab-width) c)
4413 (catch 'exit
4414 (while (< (setq n (1+ n)) (length s))
4415 (setq c (aref s n))
4416 (cond ((= c ?\ ) (setq i (1+ i)))
4417 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4418 (t (throw 'exit t)))))
4419 i))
4420
4421 (defun org-renumber-ordered-list (arg)
4422 "Renumber an ordered plain list.
4423 Cursor needs to be in the first line of an item, the line that starts
4424 with something like \"1.\" or \"2)\"."
4425 (interactive "p")
4426 (unless (and (org-at-item-p)
4427 (match-beginning 3))
4428 (error "This is not an ordered list"))
4429 (let ((line (org-current-line))
4430 (col (current-column))
4431 (ind (org-get-string-indentation
4432 (buffer-substring (point-at-bol) (match-beginning 3))))
4433 ;; (term (substring (match-string 3) -1))
4434 ind1 (n (1- arg)))
4435 ;; find where this list begins
4436 (catch 'exit
4437 (while t
4438 (catch 'next
4439 (beginning-of-line 0)
4440 (if (looking-at "[ \t]*$") (throw 'next t))
4441 (skip-chars-forward " \t") (setq ind1 (current-column))
4442 (if (or (< ind1 ind)
4443 (and (= ind1 ind)
4444 (not (org-at-item-p))))
4445 (throw 'exit t)))))
4446 ;; Walk forward and replace these numbers
4447 (catch 'exit
4448 (while t
4449 (catch 'next
4450 (beginning-of-line 2)
4451 (if (eobp) (throw 'exit nil))
4452 (if (looking-at "[ \t]*$") (throw 'next nil))
4453 (skip-chars-forward " \t") (setq ind1 (current-column))
4454 (if (> ind1 ind) (throw 'next t))
4455 (if (< ind1 ind) (throw 'exit t))
4456 (if (not (org-at-item-p)) (throw 'exit nil))
4457 (if (not (match-beginning 3))
4458 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4459 (delete-region (match-beginning 3) (1- (match-end 3)))
4460 (goto-char (match-beginning 3))
4461 (insert (format "%d" (setq n (1+ n)))))))
4462 (goto-line line)
4463 (move-to-column col)))
4464
4465 (defvar org-last-indent-begin-marker (make-marker))
4466 (defvar org-last-indent-end-marker (make-marker))
4467
4468 (defun org-outdent-item (arg)
4469 "Outdent a local list item."
4470 (interactive "p")
4471 (org-indent-item (- arg)))
4472
4473 (defun org-indent-item (arg)
4474 "Indent a local list item."
4475 (interactive "p")
4476 (unless (org-at-item-p)
4477 (error "Not on an item"))
4478 (save-excursion
4479 (let (beg end ind ind1)
4480 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4481 (setq beg org-last-indent-begin-marker
4482 end org-last-indent-end-marker)
4483 (org-beginning-of-item)
4484 (setq beg (move-marker org-last-indent-begin-marker (point)))
4485 (org-end-of-item)
4486 (setq end (move-marker org-last-indent-end-marker (point))))
4487 (goto-char beg)
4488 (skip-chars-forward " \t") (setq ind (current-column))
4489 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4490 (while (< (point) end)
4491 (beginning-of-line 1)
4492 (skip-chars-forward " \t") (setq ind1 (current-column))
4493 (delete-region (point-at-bol) (point))
4494 (indent-to-column (+ ind1 arg))
4495 (beginning-of-line 2)))))
4496
4497 ;;; Archiving
4498
4499 (defun org-archive-subtree (&optional find-done)
4500 "Move the current subtree to the archive.
4501 The archive can be a certain top-level heading in the current file, or in
4502 a different file. The tree will be moved to that location, the subtree
4503 heading be marked DONE, and the current time will be added.
4504
4505 When called with prefix argument FIND-DONE, find whole trees without any
4506 open TODO items and archive them (after getting confirmation from the user).
4507 If the cursor is not at a headline when this comand is called, try all level
4508 1 trees. If the cursor is on a headline, only try the direct children of
4509 this heading. "
4510 (interactive "P")
4511 (if find-done
4512 (org-archive-all-done)
4513 ;; Save all relevant TODO keyword-relatex variables
4514
4515 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4516 (tr-org-todo-keywords org-todo-keywords)
4517 (tr-org-todo-interpretation org-todo-interpretation)
4518 (tr-org-done-string org-done-string)
4519 (tr-org-todo-regexp org-todo-regexp)
4520 (tr-org-todo-line-regexp org-todo-line-regexp)
4521 (this-buffer (current-buffer))
4522 file heading buffer level newfile-p)
4523 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4524 (progn
4525 (setq file (format (match-string 1 org-archive-location)
4526 (file-name-nondirectory buffer-file-name))
4527 heading (match-string 2 org-archive-location)))
4528 (error "Invalid `org-archive-location'"))
4529 (if (> (length file) 0)
4530 (setq newfile-p (not (file-exists-p file))
4531 buffer (find-file-noselect file))
4532 (setq buffer (current-buffer)))
4533 (unless buffer
4534 (error "Cannot access file \"%s\"" file))
4535 (if (and (> (length heading) 0)
4536 (string-match "^\\*+" heading))
4537 (setq level (match-end 0))
4538 (setq heading nil level 0))
4539 (save-excursion
4540 ;; We first only copy, in case something goes wrong
4541 ;; we need to protect this-command, to avoid kill-region sets it,
4542 ;; which would lead to duplication of subtrees
4543 (let (this-command) (org-copy-subtree))
4544 (set-buffer buffer)
4545 ;; Enforce org-mode for the archive buffer
4546 (if (not (org-mode-p))
4547 ;; Force the mode for future visits.
4548 (let ((org-insert-mode-line-in-empty-file t))
4549 (call-interactively 'org-mode)))
4550 (when newfile-p
4551 (goto-char (point-max))
4552 (insert (format "\nArchived entries from file %s\n\n"
4553 (buffer-file-name this-buffer))))
4554 ;; Force the TODO keywords of the original buffer
4555 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4556 (org-todo-keywords tr-org-todo-keywords)
4557 (org-todo-interpretation tr-org-todo-interpretation)
4558 (org-done-string tr-org-done-string)
4559 (org-todo-regexp tr-org-todo-regexp)
4560 (org-todo-line-regexp tr-org-todo-line-regexp))
4561 (goto-char (point-min))
4562 (if heading
4563 (progn
4564 (if (re-search-forward
4565 (concat "\\(^\\|\r\\)"
4566 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4567 nil t)
4568 (goto-char (match-end 0))
4569 ;; Heading not found, just insert it at the end
4570 (goto-char (point-max))
4571 (or (bolp) (insert "\n"))
4572 (insert "\n" heading "\n")
4573 (end-of-line 0))
4574 ;; Make the subtree visible
4575 (show-subtree)
4576 (org-end-of-subtree t)
4577 (skip-chars-backward " \t\r\n")
4578 (and (looking-at "[ \t\r\n]*")
4579 (replace-match "\n\n")))
4580 ;; No specific heading, just go to end of file.
4581 (goto-char (point-max)) (insert "\n"))
4582 ;; Paste
4583 (org-paste-subtree (1+ level))
4584 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4585 (if org-archive-mark-done
4586 (org-todo (length org-todo-keywords)))
4587 ;; Move cursor to right after the TODO keyword
4588 (when org-archive-stamp-time
4589 (beginning-of-line 1)
4590 (looking-at org-todo-line-regexp)
4591 (goto-char (or (match-end 2) (match-beginning 3)))
4592 (insert "(" (format-time-string (cdr org-time-stamp-formats)
4593 (org-current-time))
4594 ")"))
4595 ;; Save the buffer, if it is not the same buffer.
4596 (if (not (eq this-buffer buffer)) (save-buffer))))
4597 ;; Here we are back in the original buffer. Everything seems to have
4598 ;; worked. So now cut the tree and finish up.
4599 (let (this-command) (org-cut-subtree))
4600 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4601 (message "Subtree archived %s"
4602 (if (eq this-buffer buffer)
4603 (concat "under heading: " heading)
4604 (concat "in file: " (abbreviate-file-name file)))))))
4605
4606 (defun org-archive-all-done (&optional tag)
4607 "Archive sublevels of the current tree without open TODO items.
4608 If the cursor is not on a headline, try all level 1 trees. If
4609 it is on a headline, try all direct children.
4610 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
4611 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
4612 (rea (concat ".*:" org-archive-tag ":"))
4613 (begm (make-marker))
4614 (endm (make-marker))
4615 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
4616 "Move subtree to archive (no open TODO items)? "))
4617 beg end (cntarch 0))
4618 (if (org-on-heading-p)
4619 (progn
4620 (setq re1 (concat "^" (regexp-quote
4621 (make-string
4622 (1+ (- (match-end 0) (match-beginning 0)))
4623 ?*))
4624 " "))
4625 (move-marker begm (point))
4626 (move-marker endm (org-end-of-subtree)))
4627 (setq re1 "^* ")
4628 (move-marker begm (point-min))
4629 (move-marker endm (point-max)))
4630 (save-excursion
4631 (goto-char begm)
4632 (while (re-search-forward re1 endm t)
4633 (setq beg (match-beginning 0)
4634 end (save-excursion (org-end-of-subtree t) (point)))
4635 (goto-char beg)
4636 (if (re-search-forward re end t)
4637 (goto-char end)
4638 (goto-char beg)
4639 (if (and (or (not tag) (not (looking-at rea)))
4640 (y-or-n-p question))
4641 (progn
4642 (if tag
4643 (org-toggle-tag org-archive-tag 'on)
4644 (org-archive-subtree))
4645 (setq cntarch (1+ cntarch)))
4646 (goto-char end)))))
4647 (message "%d trees archived" cntarch)))
4648
4649 (defun org-cycle-hide-archived-subtrees (state)
4650 "Re-hide all archived subtrees after a visibility state change."
4651 (when (and (not org-cycle-open-archived-trees)
4652 (not (memq state '(overview folded))))
4653 (save-excursion
4654 (let* ((globalp (memq state '(contents all)))
4655 (beg (if globalp (point-min) (point)))
4656 (end (if globalp (point-max) (org-end-of-subtree))))
4657 (org-hide-archived-subtrees beg end)))))
4658
4659 (defun org-hide-archived-subtrees (beg end)
4660 "Re-hide all archived subtrees after a visibility state change."
4661 (save-excursion
4662 (let* ((re (concat ":" org-archive-tag ":")))
4663 (goto-char beg)
4664 (while (re-search-forward re end t)
4665 (and (org-on-heading-p) (hide-subtree))
4666 (org-end-of-subtree)))))
4667
4668 (defun org-toggle-tag (tag &optional onoff)
4669 "Toggle the tag TAG for the current line.
4670 If ONOFF is `on' or `off', don't toggle but set to this state."
4671 (unless (org-on-heading-p) (error "Not on headling"))
4672 (let (res current)
4673 (save-excursion
4674 (beginning-of-line)
4675 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
4676 (point-at-eol) t)
4677 (progn
4678 (setq current (match-string 1))
4679 (replace-match ""))
4680 (setq current ""))
4681 (setq current (nreverse (org-split-string current ":")))
4682 (cond
4683 ((eq onoff 'on)
4684 (setq res t)
4685 (or (member tag current) (push tag current)))
4686 ((eq onoff 'off)
4687 (or (not (member tag current)) (setq current (delete tag current))))
4688 (t (if (member tag current)
4689 (setq current (delete tag current))
4690 (setq res t)
4691 (push tag current))))
4692 (end-of-line 1)
4693 (when current
4694 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
4695 (org-set-tags nil t))
4696 res))
4697
4698 (defun org-toggle-archive-tag (&optional arg)
4699 "Toggle the archive tag for the current headline.
4700 With prefix ARG, check all children of current headline and offer tagging
4701 the children that do not contain any open TODO items."
4702 (interactive "P")
4703 (if arg
4704 (org-archive-all-done 'tag)
4705 (let (set)
4706 (save-excursion
4707 (org-back-to-heading t)
4708 (setq set (org-toggle-tag org-archive-tag))
4709 (when set (hide-subtree)))
4710 (and set (beginning-of-line 1))
4711 (message "Subtree %s" (if set "archived" "unarchived")))))
4712
4713 (defun org-prepare-agenda-buffers (files)
4714 "Create buffers for all agenda files, protect archived trees and comments."
4715 (interactive)
4716 (let ((pa '(:org-archived t))
4717 (pc '(:org-comment t))
4718 (pall '(:org-archived t :org-comment t))
4719 (rea (concat ":" org-archive-tag ":"))
4720 bmp file re)
4721 (save-excursion
4722 (while (setq file (pop files))
4723 (org-check-agenda-file file)
4724 (set-buffer (org-get-agenda-file-buffer file))
4725 (widen)
4726 (setq bmp (buffer-modified-p))
4727 (save-excursion
4728 (remove-text-properties (point-min) (point-max) pall)
4729 (when org-agenda-skip-archived-trees
4730 (goto-char (point-min))
4731 (while (re-search-forward rea nil t)
4732 (if (org-on-heading-p)
4733 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
4734 (goto-char (point-min))
4735 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
4736 (while (re-search-forward re nil t)
4737 (add-text-properties
4738 (match-beginning 0) (org-end-of-subtree t) pc)))
4739 (set-buffer-modified-p bmp)))))
4740
4741 (defun org-agenda-skip ()
4742 "Throw to `:skip' in places that should be skipped."
4743 (let ((p (point-at-bol)))
4744 (and org-agenda-skip-archived-trees
4745 (get-text-property p :org-archived)
4746 (org-end-of-subtree)
4747 (throw :skip t))
4748 (and (get-text-property p :org-comment)
4749 (org-end-of-subtree)
4750 (throw :skip t))
4751 (if (equal (char-after p) ?#) (throw :skip t))))
4752
4753 (defun org-agenda-toggle-archive-tag ()
4754 "Toggle the archive tag for the current entry."
4755 (interactive)
4756 (org-agenda-check-no-diary)
4757 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
4758 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
4759 (org-agenda-error)))
4760 (buffer (marker-buffer hdmarker))
4761 (pos (marker-position hdmarker))
4762 (buffer-read-only nil)
4763 newhead)
4764 (with-current-buffer buffer
4765 (widen)
4766 (goto-char pos)
4767 (org-show-hidden-entry)
4768 (save-excursion
4769 (and (outline-next-heading)
4770 (org-flag-heading nil))) ; show the next heading
4771 (call-interactively 'org-toggle-archive-tag)
4772 (end-of-line 1)
4773 (setq newhead (org-get-heading)))
4774 (org-agenda-change-all-lines newhead hdmarker)
4775 (beginning-of-line 1)))
4776
4777 ;;; Dynamic blocks
4778
4779 (defun org-find-dblock (name)
4780 "Find the first dynamic block with name NAME in the buffer.
4781 If not found, stay at current position and return nil."
4782 (let (pos)
4783 (save-excursion
4784 (goto-char (point-min))
4785 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
4786 nil t)
4787 (match-beginning 0))))
4788 (if pos (goto-char pos))
4789 pos))
4790
4791 (defconst org-dblock-start-re
4792 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
4793 "Matches the startline of a dynamic block, with parameters.")
4794
4795 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
4796 "Matches the end of a dyhamic block.")
4797
4798 (defun org-create-dblock (plist)
4799 "Create a dynamic block section, with parameters taken from PLIST.
4800 PLIST must containe a :name entry which is used as name of the block."
4801 (unless (bolp) (newline))
4802 (let ((name (plist-get plist :name)))
4803 (insert "#+BEGIN: " name)
4804 (while plist
4805 (if (eq (car plist) :name)
4806 (setq plist (cddr plist))
4807 (insert " " (prin1-to-string (pop plist)))))
4808 (insert "\n\n#+END:\n")
4809 (beginning-of-line -2)))
4810
4811 (defun org-prepare-dblock ()
4812 "Prepare dynamic block for refresh.
4813 This empties the block, puts the cursor at the insert position and returns
4814 the property list including an extra property :name with the block name."
4815 (unless (looking-at org-dblock-start-re)
4816 (error "Not at a dynamic block"))
4817 (let* ((begdel (1+ (match-end 0)))
4818 (name (match-string 1))
4819 (params (append (list :name name)
4820 (read (concat "(" (match-string 3) ")")))))
4821 (unless (re-search-forward org-dblock-end-re nil t)
4822 (error "Dynamic block not terminated"))
4823 (delete-region begdel (match-beginning 0))
4824 (goto-char begdel)
4825 (open-line 1)
4826 params))
4827
4828 (defun org-map-dblocks (&optional command)
4829 "Apply COMMAND to all dynamic blocks in the current buffer.
4830 If COMMAND is not given, use `org-update-dblock'."
4831 (let ((cmd (or command 'org-update-dblock))
4832 pos)
4833 (save-excursion
4834 (goto-char (point-min))
4835 (while (re-search-forward org-dblock-start-re nil t)
4836 (goto-char (setq pos (match-beginning 0)))
4837 (condition-case nil
4838 (funcall cmd)
4839 (error (message "Error during update of dynamic block")))
4840 (goto-char pos)
4841 (unless (re-search-forward org-dblock-end-re nil t)
4842 (error "Dynamic block not terminated"))))))
4843
4844 (defun org-dblock-update (&optional arg)
4845 "User command for updating dynamic blocks.
4846 Update the dynamic block at point. With prefix ARG, update all dynamic
4847 blocks in the buffer."
4848 (interactive "P")
4849 (if arg
4850 (org-update-all-dblocks)
4851 (or (looking-at org-dblock-start-re)
4852 (org-beginning-of-dblock))
4853 (org-update-dblock)))
4854
4855 (defun org-update-dblock ()
4856 "Update the dynamic block at point
4857 This means to empty the block, parse for parameters and then call
4858 the correct writing function."
4859 (let* ((pos (point))
4860 (params (org-prepare-dblock))
4861 (name (plist-get params :name))
4862 (cmd (intern (concat "org-dblock-write:" name))))
4863 (funcall cmd params)
4864 (goto-char pos)))
4865
4866 (defun org-beginning-of-dblock ()
4867 "Find the beginning of the dynamic block at point.
4868 Error if there is no scuh block at point."
4869 (let ((pos (point))
4870 beg)
4871 (end-of-line 1)
4872 (if (and (re-search-backward org-dblock-start-re nil t)
4873 (setq beg (match-beginning 0))
4874 (re-search-forward org-dblock-end-re nil t)
4875 (> (match-end 0) pos))
4876 (goto-char beg)
4877 (goto-char pos)
4878 (error "Not in a dynamic block"))))
4879
4880 (defun org-update-all-dblocks ()
4881 "Update all dynamic blocks in the buffer.
4882 This function can be used in a hook."
4883 (when (org-mode-p)
4884 (org-map-dblocks 'org-update-dblock)))
4885
4886
4887 ;;; Completion
4888
4889 (defun org-complete (&optional arg)
4890 "Perform completion on word at point.
4891 At the beginning of a headline, this completes TODO keywords as given in
4892 `org-todo-keywords'.
4893 If the current word is preceded by a backslash, completes the TeX symbols
4894 that are supported for HTML support.
4895 If the current word is preceded by \"#+\", completes special words for
4896 setting file options.
4897 At all other locations, this simply calls `ispell-complete-word'."
4898 (interactive "P")
4899 (catch 'exit
4900 (let* ((end (point))
4901 (beg1 (save-excursion
4902 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4903 (skip-chars-backward "a-zA-Z_@0-9")
4904 (point)))
4905 (beg (save-excursion
4906 (if (equal (char-before (point)) ?\ ) (backward-char 1))
4907 (skip-chars-backward "a-zA-Z0-9_:$")
4908 (point)))
4909 (confirm (lambda (x) (stringp (car x))))
4910 (camel (equal (char-before beg) ?*))
4911 (tag (equal (char-before beg1) ?:))
4912 (texp (equal (char-before beg) ?\\))
4913 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
4914 beg)
4915 "#+"))
4916 (completion-ignore-case opt)
4917 (type nil)
4918 (tbl nil)
4919 (table (cond
4920 (opt
4921 (setq type :opt)
4922 (mapcar (lambda (x)
4923 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
4924 (cons (match-string 2 x) (match-string 1 x)))
4925 (org-split-string (org-get-current-options) "\n")))
4926 (texp
4927 (setq type :tex)
4928 org-html-entities)
4929 ((string-match "\\`\\*+[ \t]*\\'"
4930 (buffer-substring (point-at-bol) beg))
4931 (setq type :todo)
4932 (mapcar 'list org-todo-keywords))
4933 (camel
4934 (setq type :camel)
4935 (save-excursion
4936 (goto-char (point-min))
4937 (while (re-search-forward org-todo-line-regexp nil t)
4938 (push (list
4939 (if org-file-link-context-use-camel-case
4940 (org-make-org-heading-camel (match-string 3) t)
4941 (org-make-org-heading-search-string
4942 (match-string 3) t)))
4943 tbl)))
4944 tbl)
4945 (tag (setq type :tag beg beg1)
4946 (or org-tag-alist (org-get-buffer-tags)))
4947 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
4948 (pattern (buffer-substring-no-properties beg end))
4949 (completion (try-completion pattern table confirm)))
4950 (cond ((eq completion t)
4951 (if (equal type :opt)
4952 (insert (substring (cdr (assoc (upcase pattern) table))
4953 (length pattern)))))
4954 ((null completion)
4955 (message "Can't find completion for \"%s\"" pattern)
4956 (ding))
4957 ((not (string= pattern completion))
4958 (delete-region beg end)
4959 (if (string-match " +$" completion)
4960 (setq completion (replace-match "" t t completion)))
4961 (insert completion)
4962 (if (get-buffer-window "*Completions*")
4963 (delete-window (get-buffer-window "*Completions*")))
4964 (if (assoc completion table)
4965 (if (eq type :todo) (insert " ")
4966 (if (eq type :tag) (insert ":"))))
4967 (if (and (equal type :opt) (assoc completion table))
4968 (message "%s" (substitute-command-keys
4969 "Press \\[org-complete] again to insert example settings"))))
4970 (t
4971 (message "Making completion list...")
4972 (let ((list (sort (all-completions pattern table confirm)
4973 'string<)))
4974 (with-output-to-temp-buffer "*Completions*"
4975 (condition-case nil
4976 ;; Protection needed for XEmacs and emacs 21
4977 (display-completion-list list pattern)
4978 (error (display-completion-list list)))))
4979 (message "Making completion list...%s" "done"))))))
4980
4981 ;;; Comments, TODO and DEADLINE
4982
4983 (defun org-toggle-comment ()
4984 "Change the COMMENT state of an entry."
4985 (interactive)
4986 (save-excursion
4987 (org-back-to-heading)
4988 (if (looking-at (concat outline-regexp
4989 "\\( +\\<" org-comment-string "\\>\\)"))
4990 (replace-match "" t t nil 1)
4991 (if (looking-at outline-regexp)
4992 (progn
4993 (goto-char (match-end 0))
4994 (insert " " org-comment-string))))))
4995
4996 (defvar org-last-todo-state-is-todo nil
4997 "This is non-nil when the last TODO state change led to a TODO state.
4998 If the last change removed the TODO tag or switched to DONE, then
4999 this is nil.")
5000
5001 (defun org-todo (&optional arg)
5002 "Change the TODO state of an item.
5003 The state of an item is given by a keyword at the start of the heading,
5004 like
5005 *** TODO Write paper
5006 *** DONE Call mom
5007
5008 The different keywords are specified in the variable `org-todo-keywords'.
5009 By default the available states are \"TODO\" and \"DONE\".
5010 So for this example: when the item starts with TODO, it is changed to DONE.
5011 When it starts with DONE, the DONE is removed. And when neither TODO nor
5012 DONE are present, add TODO at the beginning of the heading.
5013
5014 With prefix arg, use completion to determine the new state. With numeric
5015 prefix arg, switch to that state."
5016 (interactive "P")
5017 (save-excursion
5018 (org-back-to-heading)
5019 (if (looking-at outline-regexp) (goto-char (match-end 0)))
5020 (or (looking-at (concat " +" org-todo-regexp " *"))
5021 (looking-at " *"))
5022 (let* ((this (match-string 1))
5023 (completion-ignore-case t)
5024 (member (member this org-todo-keywords))
5025 (tail (cdr member))
5026 (state (cond
5027 ((equal arg '(4))
5028 ;; Read a state with completion
5029 (completing-read "State: " (mapcar (lambda(x) (list x))
5030 org-todo-keywords)
5031 nil t))
5032 ((eq arg 'right)
5033 (if this
5034 (if tail (car tail) nil)
5035 (car org-todo-keywords)))
5036 ((eq arg 'left)
5037 (if (equal member org-todo-keywords)
5038 nil
5039 (if this
5040 (nth (- (length org-todo-keywords) (length tail) 2)
5041 org-todo-keywords)
5042 org-done-string)))
5043 (arg
5044 ;; user requests a specific state
5045 (nth (1- (prefix-numeric-value arg))
5046 org-todo-keywords))
5047 ((null member) (car org-todo-keywords))
5048 ((null tail) nil) ;; -> first entry
5049 ((eq org-todo-interpretation 'sequence)
5050 (car tail))
5051 ((memq org-todo-interpretation '(type priority))
5052 (if (eq this-command last-command)
5053 (car tail)
5054 (if (> (length tail) 0) org-done-string nil)))
5055 (t nil)))
5056 (next (if state (concat " " state " ") " ")))
5057 (replace-match next t t)
5058 (setq org-last-todo-state-is-todo
5059 (not (equal state org-done-string)))
5060 (when org-log-done
5061 (if (equal state org-done-string)
5062 (org-add-planning-info 'closed (current-time) 'scheduled)
5063 (if (not this)
5064 (org-add-planning-info nil nil 'closed))))
5065 ;; Fixup tag positioning
5066 (and org-auto-align-tags (org-set-tags nil t))
5067 (run-hooks 'org-after-todo-state-change-hook)))
5068 ;; Fixup cursor location if close to the keyword
5069 (if (and (outline-on-heading-p)
5070 (not (bolp))
5071 (save-excursion (beginning-of-line 1)
5072 (looking-at org-todo-line-regexp))
5073 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
5074 (progn
5075 (goto-char (or (match-end 2) (match-end 1)))
5076 (just-one-space))))
5077
5078 (defun org-log-done (&optional undone)
5079 "Add a time stamp logging that a TODO entry has been closed.
5080 When UNDONE is non-nil, remove such a time stamp again."
5081 (interactive)
5082 (let (beg end col)
5083 (save-excursion
5084 (org-back-to-heading t)
5085 (setq beg (point))
5086 (looking-at (concat outline-regexp " *"))
5087 (goto-char (match-end 0))
5088 (setq col (current-column))
5089 (outline-next-heading)
5090 (setq end (point))
5091 (goto-char beg)
5092 (when (re-search-forward (concat
5093 "[\r\n]\\([ \t]*"
5094 (regexp-quote org-closed-string)
5095 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
5096 (delete-region (match-beginning 1) (match-end 1)))
5097 (unless undone
5098 (org-back-to-heading t)
5099 (skip-chars-forward "^\n\r")
5100 (goto-char (min (1+ (point)) (point-max)))
5101 (when (not (member (char-before) '(?\r ?\n)))
5102 (insert "\n"))
5103 (indent-to col)
5104 (insert org-closed-string " "
5105 (format-time-string
5106 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5107 (org-current-time))
5108 "\n")))))
5109
5110 (defun org-show-todo-tree (arg)
5111 "Make a compact tree which shows all headlines marked with TODO.
5112 The tree will show the lines where the regexp matches, and all higher
5113 headlines above the match.
5114 With \\[universal-argument] prefix, also show the DONE entries.
5115 With a numeric prefix N, construct a sparse tree for the Nth element
5116 of `org-todo-keywords'."
5117 (interactive "P")
5118 (let ((case-fold-search nil)
5119 (kwd-re
5120 (cond ((null arg) org-not-done-regexp)
5121 ((equal arg '(4)) org-todo-regexp)
5122 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
5123 (regexp-quote (nth (1- (prefix-numeric-value arg))
5124 org-todo-keywords)))
5125 (t (error "Invalid prefix argument: %s" arg)))))
5126 (message "%d TODO entries found"
5127 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
5128
5129 (defun org-deadline ()
5130 "Insert the DEADLINE: string to make a deadline.
5131 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5132 to modify it to the correct date."
5133 (interactive)
5134 (org-add-planning-info 'deadline nil 'closed))
5135
5136 (defun org-schedule ()
5137 "Insert the SCHEDULED: string to schedule a TODO item.
5138 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5139 to modify it to the correct date."
5140 (interactive)
5141 (org-add-planning-info 'scheduled nil 'closed))
5142
5143 (defun org-add-planning-info (what &optional time &rest remove)
5144 "Insert new timestamp with keyword in the line directly after the headline.
5145 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
5146 If non is given, the user is prompted for a date.
5147 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
5148 be removed."
5149 (interactive)
5150 (when what (setq time (or time (org-read-date nil 'to-time))))
5151 (when (and org-insert-labeled-timestamps-at-point
5152 (member what '(scheduled deadline)))
5153 (insert
5154 (if (eq what 'scheduled) org-scheduled-string org-deadline-string)
5155 " "
5156 (format-time-string (car org-time-stamp-formats) time))
5157 (setq what nil))
5158 (save-excursion
5159 (let (col list elt (buffer-invisibility-spec nil) ts)
5160 (org-back-to-heading t)
5161 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
5162 (goto-char (match-end 1))
5163 (setq col (current-column))
5164 (goto-char (1+ (match-end 0)))
5165 (if (and (not (looking-at outline-regexp))
5166 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
5167 "[^\r\n]*"))
5168 (not (equal (match-string 1) org-clock-string)))
5169 (narrow-to-region (match-beginning 0) (match-end 0))
5170 (insert "\n")
5171 (backward-char 1)
5172 (narrow-to-region (point) (point))
5173 (indent-to-column col))
5174 ;; Check if we have to remove something.
5175 (setq list (cons what remove))
5176 (while list
5177 (setq elt (pop list))
5178 (goto-char (point-min))
5179 (when (or (and (eq elt 'scheduled)
5180 (re-search-forward org-scheduled-time-regexp nil t))
5181 (and (eq elt 'deadline)
5182 (re-search-forward org-deadline-time-regexp nil t))
5183 (and (eq elt 'closed)
5184 (re-search-forward org-closed-time-regexp nil t)))
5185 (replace-match "")
5186 (if (looking-at " +") (replace-match ""))))
5187 (goto-char (point-max))
5188 (when what
5189 (insert
5190 (if (not (equal (char-before) ?\ )) " " "")
5191 (cond ((eq what 'scheduled) org-scheduled-string)
5192 ((eq what 'deadline) org-deadline-string)
5193 ((eq what 'closed) org-closed-string))
5194 " ")
5195 (insert
5196 (setq ts
5197 (format-time-string
5198 (if (eq what 'closed)
5199 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5200 (car org-time-stamp-formats))
5201 time))))
5202 (goto-char (point-min))
5203 (widen)
5204 (if (looking-at "[ \t]+\r?\n")
5205 (replace-match ""))
5206 ts)))
5207
5208 (defun org-occur (regexp &optional callback)
5209 "Make a compact tree which shows all matches of REGEXP.
5210 The tree will show the lines where the regexp matches, and all higher
5211 headlines above the match. It will also show the heading after the match,
5212 to make sure editing the matching entry is easy.
5213 If CALLBACK is non-nil, it is a function which is called to confirm
5214 that the match should indeed be shown."
5215 (interactive "sRegexp: ")
5216 (org-remove-occur-highlights nil nil t)
5217 (let ((cnt 0))
5218 (save-excursion
5219 (goto-char (point-min))
5220 (org-overview)
5221 (while (re-search-forward regexp nil t)
5222 (when (or (not callback)
5223 (save-match-data (funcall callback)))
5224 (setq cnt (1+ cnt))
5225 (org-highlight-new-match (match-beginning 0) (match-end 0))
5226 (org-show-hierarchy-above))))
5227 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
5228 nil 'local)
5229 (unless org-sparse-tree-open-archived-trees
5230 (org-hide-archived-subtrees (point-min) (point-max)))
5231 (run-hooks 'org-occur-hook)
5232 (if (interactive-p)
5233 (message "%d match(es) for regexp %s" cnt regexp))
5234 cnt))
5235
5236 (defun org-show-hierarchy-above ()
5237 "Make sure point and the headings hierarchy above is visible."
5238 (catch 'exit
5239 (if (org-on-heading-p t)
5240 (org-flag-heading nil) ; only show the heading
5241 (and (or (org-invisible-p) (org-invisible-p2))
5242 (org-show-hidden-entry))) ; show entire entry
5243 (save-excursion
5244 (and org-show-following-heading
5245 (outline-next-heading)
5246 (org-flag-heading nil))) ; show the next heading
5247 (when org-show-hierarchy-above
5248 (save-excursion ; show all higher headings
5249 (while (and (condition-case nil
5250 (progn (org-up-heading-all 1) t)
5251 (error nil))
5252 (not (bobp)))
5253 (org-flag-heading nil))))))
5254
5255 ;; Overlay compatibility functions
5256 (defun org-make-overlay (beg end &optional buffer)
5257 (if (featurep 'xemacs)
5258 (make-extent beg end buffer)
5259 (make-overlay beg end buffer)))
5260 (defun org-delete-overlay (ovl)
5261 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
5262 (defun org-detatch-overlay (ovl)
5263 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
5264 (defun org-move-overlay (ovl beg end &optional buffer)
5265 (if (featurep 'xemacs)
5266 (set-extent-endpoints ovl beg end buffer)
5267 (move-overlay ovl beg end buffer)))
5268 (defun org-overlay-put (ovl prop value)
5269 (if (featurep 'xemacs)
5270 (set-extent-property ovl prop value)
5271 (overlay-put ovl prop value)))
5272 (defun org-overlays-at (pos)
5273 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
5274 (defun org-overlay-start (o)
5275 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
5276 (defun org-overlay-end (o)
5277 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
5278
5279 (defvar org-occur-highlights nil)
5280 (make-variable-buffer-local 'org-occur-highlights)
5281 (defun org-highlight-new-match (beg end)
5282 "Highlight from BEG to END and mark the highlight is an occur headline."
5283 (let ((ov (org-make-overlay beg end)))
5284 (org-overlay-put ov 'face 'secondary-selection)
5285 (push ov org-occur-highlights)))
5286
5287 (defvar org-inhibit-highlight-removal nil)
5288 (defun org-remove-occur-highlights (&optional beg end noremove)
5289 "Remove the occur highlights from the buffer.
5290 BEG and END are ignored. If NOREMOVE is nil, remove this function
5291 from the `before-change-functions' in the current buffer."
5292 (interactive)
5293 (unless org-inhibit-highlight-removal
5294 (mapc 'org-delete-overlay org-occur-highlights)
5295 (setq org-occur-highlights nil)
5296 (unless noremove
5297 (remove-hook 'before-change-functions
5298 'org-remove-occur-highlights 'local))))
5299
5300 ;;; Priorities
5301
5302 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
5303 "Regular expression matching the priority indicator.")
5304
5305 (defvar org-remove-priority-next-time nil)
5306
5307 (defun org-priority-up ()
5308 "Increase the priority of the current item."
5309 (interactive)
5310 (org-priority 'up))
5311
5312 (defun org-priority-down ()
5313 "Decrease the priority of the current item."
5314 (interactive)
5315 (org-priority 'down))
5316
5317 (defun org-priority (&optional action)
5318 "Change the priority of an item by ARG.
5319 ACTION can be set, up, or down."
5320 (interactive)
5321 (setq action (or action 'set))
5322 (let (current new news have remove)
5323 (save-excursion
5324 (org-back-to-heading)
5325 (if (looking-at org-priority-regexp)
5326 (setq current (string-to-char (match-string 2))
5327 have t)
5328 (setq current org-default-priority))
5329 (cond
5330 ((eq action 'set)
5331 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
5332 (setq new (read-char-exclusive))
5333 (cond ((equal new ?\ ) (setq remove t))
5334 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
5335 (error "Priority must be between `%c' and `%c'"
5336 ?A org-lowest-priority))))
5337 ((eq action 'up)
5338 (setq new (1- current)))
5339 ((eq action 'down)
5340 (setq new (1+ current)))
5341 (t (error "Invalid action")))
5342 (setq new (min (max ?A (upcase new)) org-lowest-priority))
5343 (setq news (format "%c" new))
5344 (if have
5345 (if remove
5346 (replace-match "" t t nil 1)
5347 (replace-match news t t nil 2))
5348 (if remove
5349 (error "No priority cookie found in line")
5350 (looking-at org-todo-line-regexp)
5351 (if (match-end 2)
5352 (progn
5353 (goto-char (match-end 2))
5354 (insert " [#" news "]"))
5355 (goto-char (match-beginning 3))
5356 (insert "[#" news "] ")))))
5357 (if remove
5358 (message "Priority removed")
5359 (message "Priority of current item set to %s" news))))
5360
5361
5362 (defun org-get-priority (s)
5363 "Find priority cookie and return priority."
5364 (save-match-data
5365 (if (not (string-match org-priority-regexp s))
5366 (* 1000 (- org-lowest-priority org-default-priority))
5367 (* 1000 (- org-lowest-priority
5368 (string-to-char (match-string 2 s)))))))
5369
5370 ;;; Timestamps
5371
5372 (defvar org-last-changed-timestamp nil)
5373
5374 (defun org-time-stamp (arg)
5375 "Prompt for a date/time and insert a time stamp.
5376 If the user specifies a time like HH:MM, or if this command is called
5377 with a prefix argument, the time stamp will contain date and time.
5378 Otherwise, only the date will be included. All parts of a date not
5379 specified by the user will be filled in from the current date/time.
5380 So if you press just return without typing anything, the time stamp
5381 will represent the current date/time. If there is already a timestamp
5382 at the cursor, it will be modified."
5383 (interactive "P")
5384 (let ((fmt (if arg (cdr org-time-stamp-formats)
5385 (car org-time-stamp-formats)))
5386 (org-time-was-given nil)
5387 time)
5388 (cond
5389 ((and (org-at-timestamp-p)
5390 (eq last-command 'org-time-stamp)
5391 (eq this-command 'org-time-stamp))
5392 (insert "--")
5393 (setq time (let ((this-command this-command))
5394 (org-read-date arg 'totime)))
5395 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5396 (insert (format-time-string fmt time)))
5397 ((org-at-timestamp-p)
5398 (setq time (let ((this-command this-command))
5399 (org-read-date arg 'totime)))
5400 (and (org-at-timestamp-p) (replace-match
5401 (setq org-last-changed-timestamp
5402 (format-time-string fmt time))
5403 t t))
5404 (message "Timestamp updated"))
5405 (t
5406 (setq time (let ((this-command this-command))
5407 (org-read-date arg 'totime)))
5408 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5409 (insert (format-time-string fmt time))))))
5410
5411 (defun org-time-stamp-inactive (&optional arg)
5412 "Insert an inactive time stamp.
5413 An inactive time stamp is enclosed in square brackets instead of angle
5414 brackets. It is inactive in the sense that it does not trigger agenda entries,
5415 does not link to the calendar and cannot be changed with the S-cursor keys.
5416 So these are more for recording a certain time/date."
5417 (interactive "P")
5418 (let ((fmt (if arg (cdr org-time-stamp-formats)
5419 (car org-time-stamp-formats)))
5420 (org-time-was-given nil)
5421 time)
5422 (setq time (org-read-date arg 'totime))
5423 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5424 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
5425 (insert (format-time-string fmt time))))
5426
5427 (defvar org-date-ovl (org-make-overlay 1 1))
5428 (org-overlay-put org-date-ovl 'face 'org-warning)
5429 (org-detatch-overlay org-date-ovl)
5430
5431 (defun org-read-date (&optional with-time to-time)
5432 "Read a date and make things smooth for the user.
5433 The prompt will suggest to enter an ISO date, but you can also enter anything
5434 which will at least partially be understood by `parse-time-string'.
5435 Unrecognized parts of the date will default to the current day, month, year,
5436 hour and minute. For example,
5437 3-2-5 --> 2003-02-05
5438 feb 15 --> currentyear-02-15
5439 sep 12 9 --> 2009-09-12
5440 12:45 --> today 12:45
5441 22 sept 0:34 --> currentyear-09-22 0:34
5442 12 --> currentyear-currentmonth-12
5443 Fri --> nearest Friday (today or later)
5444 etc.
5445 The function understands only English month and weekday abbreviations,
5446 but this can be configured with the variables `parse-time-months' and
5447 `parse-time-weekdays'.
5448
5449 While prompting, a calendar is popped up - you can also select the
5450 date with the mouse (button 1). The calendar shows a period of three
5451 months. To scroll it to other months, use the keys `>' and `<'.
5452 If you don't like the calendar, turn it off with
5453 \(setq org-popup-calendar-for-date-prompt nil)
5454
5455 With optional argument TO-TIME, the date will immediately be converted
5456 to an internal time.
5457 With an optional argument WITH-TIME, the prompt will suggest to also
5458 insert a time. Note that when WITH-TIME is not set, you can still
5459 enter a time, and this function will inform the calling routine about
5460 this change. The calling routine may then choose to change the format
5461 used to insert the time stamp into the buffer to include the time."
5462 (require 'parse-time)
5463 (let* ((org-time-stamp-rounding-minutes
5464 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
5465 (ct (org-current-time))
5466 (default-time
5467 ;; Default time is either today, or, when entering a range,
5468 ;; the range start.
5469 (if (save-excursion
5470 (re-search-backward
5471 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
5472 (- (point) 20) t))
5473 (apply
5474 'encode-time
5475 (mapcar (lambda(x) (or x 0))
5476 (parse-time-string (match-string 1))))
5477 ct))
5478 (calendar-move-hook nil)
5479 (view-diary-entries-initially nil)
5480 (view-calendar-holidays-initially nil)
5481 (timestr (format-time-string
5482 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
5483 (prompt (format "YYYY-MM-DD [%s]: " timestr))
5484 ans ans1 ans2
5485 second minute hour day month year tl wday wday1)
5486
5487 (if org-popup-calendar-for-date-prompt
5488 (save-excursion
5489 (save-window-excursion
5490 (calendar)
5491 (calendar-forward-day (- (time-to-days default-time)
5492 (calendar-absolute-from-gregorian
5493 (calendar-current-date))))
5494 (org-eval-in-calendar nil)
5495 (let* ((old-map (current-local-map))
5496 (map (copy-keymap calendar-mode-map))
5497 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
5498 (define-key map (kbd "RET") 'org-calendar-select)
5499 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
5500 'org-calendar-select-mouse)
5501 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
5502 'org-calendar-select-mouse)
5503 (define-key minibuffer-local-map [(meta shift left)]
5504 (lambda () (interactive)
5505 (org-eval-in-calendar '(calendar-backward-month 1))))
5506 (define-key minibuffer-local-map [(meta shift right)]
5507 (lambda () (interactive)
5508 (org-eval-in-calendar '(calendar-forward-month 1))))
5509 (define-key minibuffer-local-map [(shift up)]
5510 (lambda () (interactive)
5511 (org-eval-in-calendar '(calendar-backward-week 1))))
5512 (define-key minibuffer-local-map [(shift down)]
5513 (lambda () (interactive)
5514 (org-eval-in-calendar '(calendar-forward-week 1))))
5515 (define-key minibuffer-local-map [(shift left)]
5516 (lambda () (interactive)
5517 (org-eval-in-calendar '(calendar-backward-day 1))))
5518 (define-key minibuffer-local-map [(shift right)]
5519 (lambda () (interactive)
5520 (org-eval-in-calendar '(calendar-forward-day 1))))
5521 (define-key minibuffer-local-map ">"
5522 (lambda () (interactive)
5523 (org-eval-in-calendar '(scroll-calendar-left 1))))
5524 (define-key minibuffer-local-map "<"
5525 (lambda () (interactive)
5526 (org-eval-in-calendar '(scroll-calendar-right 1))))
5527 (unwind-protect
5528 (progn
5529 (use-local-map map)
5530 (setq ans (read-string prompt "" nil nil))
5531 (if (not (string-match "\\S-" ans)) (setq ans nil))
5532 (setq ans (or ans1 ans ans2)))
5533 (use-local-map old-map)))))
5534 ;; Naked prompt only
5535 (setq ans (read-string prompt "" nil timestr)))
5536 (org-detatch-overlay org-date-ovl)
5537
5538 (if (string-match
5539 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
5540 (progn
5541 (setq year (if (match-end 2)
5542 (string-to-number (match-string 2 ans))
5543 (string-to-number (format-time-string "%Y")))
5544 month (string-to-number (match-string 3 ans))
5545 day (string-to-number (match-string 4 ans)))
5546 (if (< year 100) (setq year (+ 2000 year)))
5547 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
5548 t nil ans))))
5549 (setq tl (parse-time-string ans)
5550 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
5551 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
5552 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
5553 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
5554 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
5555 second (or (nth 0 tl) 0)
5556 wday (nth 6 tl))
5557 (when (and wday (not (nth 3 tl)))
5558 ;; Weekday was given, but no day, so pick that day in the week
5559 ;; on or after the derived date.
5560 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
5561 (unless (equal wday wday1)
5562 (setq day (+ day (% (- wday wday1 -7) 7)))))
5563 (if (and (boundp 'org-time-was-given)
5564 (nth 2 tl))
5565 (setq org-time-was-given t))
5566 (if (< year 100) (setq year (+ 2000 year)))
5567 (if to-time
5568 (encode-time second minute hour day month year)
5569 (if (or (nth 1 tl) (nth 2 tl))
5570 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
5571 (format "%04d-%02d-%02d" year month day)))))
5572
5573 (defun org-eval-in-calendar (form)
5574 "Eval FORM in the calendar window and return to current window.
5575 Also, store the cursor date in variable ans2."
5576 (let ((sw (selected-window)))
5577 (select-window (get-buffer-window "*Calendar*"))
5578 (eval form)
5579 (when (calendar-cursor-to-date)
5580 (let* ((date (calendar-cursor-to-date))
5581 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5582 (setq ans2 (format-time-string "%Y-%m-%d" time))))
5583 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
5584 (select-window sw)))
5585
5586 (defun org-calendar-select ()
5587 "Return to `org-read-date' with the date currently selected.
5588 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5589 (interactive)
5590 (when (calendar-cursor-to-date)
5591 (let* ((date (calendar-cursor-to-date))
5592 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5593 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5594 (if (active-minibuffer-window) (exit-minibuffer))))
5595
5596 (defun org-calendar-select-mouse (ev)
5597 "Return to `org-read-date' with the date currently selected.
5598 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5599 (interactive "e")
5600 (mouse-set-point ev)
5601 (when (calendar-cursor-to-date)
5602 (let* ((date (calendar-cursor-to-date))
5603 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5604 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5605 (if (active-minibuffer-window) (exit-minibuffer))))
5606
5607 (defun org-check-deadlines (ndays)
5608 "Check if there are any deadlines due or past due.
5609 A deadline is considered due if it happens within `org-deadline-warning-days'
5610 days from today's date. If the deadline appears in an entry marked DONE,
5611 it is not shown. The prefix arg NDAYS can be used to test that many
5612 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
5613 (interactive "P")
5614 (let* ((org-warn-days
5615 (cond
5616 ((equal ndays '(4)) 100000)
5617 (ndays (prefix-numeric-value ndays))
5618 (t org-deadline-warning-days)))
5619 (case-fold-search nil)
5620 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
5621 (callback
5622 (lambda ()
5623 (and (let ((d1 (time-to-days (current-time)))
5624 (d2 (time-to-days
5625 (org-time-string-to-time (match-string 1)))))
5626 (< (- d2 d1) org-warn-days))
5627 (not (org-entry-is-done-p))))))
5628 (message "%d deadlines past-due or due within %d days"
5629 (org-occur regexp callback)
5630 org-warn-days)))
5631
5632 (defun org-evaluate-time-range (&optional to-buffer)
5633 "Evaluate a time range by computing the difference between start and end.
5634 Normally the result is just printed in the echo area, but with prefix arg
5635 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
5636 If the time range is actually in a table, the result is inserted into the
5637 next column.
5638 For time difference computation, a year is assumed to be exactly 365
5639 days in order to avoid rounding problems."
5640 (interactive "P")
5641 (or
5642 (org-clock-update-time-maybe)
5643 (save-excursion
5644 (unless (org-at-date-range-p)
5645 (goto-char (point-at-bol))
5646 (re-search-forward org-tr-regexp (point-at-eol) t))
5647 (if (not (org-at-date-range-p))
5648 (error "Not at a time-stamp range, and none found in current line")))
5649 (let* ((ts1 (match-string 1))
5650 (ts2 (match-string 2))
5651 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
5652 (match-end (match-end 0))
5653 (time1 (org-time-string-to-time ts1))
5654 (time2 (org-time-string-to-time ts2))
5655 (t1 (time-to-seconds time1))
5656 (t2 (time-to-seconds time2))
5657 (diff (abs (- t2 t1)))
5658 (negative (< (- t2 t1) 0))
5659 ;; (ys (floor (* 365 24 60 60)))
5660 (ds (* 24 60 60))
5661 (hs (* 60 60))
5662 (fy "%dy %dd %02d:%02d")
5663 (fy1 "%dy %dd")
5664 (fd "%dd %02d:%02d")
5665 (fd1 "%dd")
5666 (fh "%02d:%02d")
5667 y d h m align)
5668 (if havetime
5669 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5670 y 0
5671 d (floor (/ diff ds)) diff (mod diff ds)
5672 h (floor (/ diff hs)) diff (mod diff hs)
5673 m (floor (/ diff 60)))
5674 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5675 y 0
5676 d (floor (+ (/ diff ds) 0.5))
5677 h 0 m 0))
5678 (if (not to-buffer)
5679 (message (org-make-tdiff-string y d h m))
5680 (when (org-at-table-p)
5681 (goto-char match-end)
5682 (setq align t)
5683 (and (looking-at " *|") (goto-char (match-end 0))))
5684 (if (looking-at
5685 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
5686 (replace-match ""))
5687 (if negative (insert " -"))
5688 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
5689 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
5690 (insert " " (format fh h m))))
5691 (if align (org-table-align))
5692 (message "Time difference inserted")))))
5693
5694 (defun org-make-tdiff-string (y d h m)
5695 (let ((fmt "")
5696 (l nil))
5697 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
5698 l (push y l)))
5699 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
5700 l (push d l)))
5701 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
5702 l (push h l)))
5703 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
5704 l (push m l)))
5705 (apply 'format fmt (nreverse l))))
5706
5707 (defun org-time-string-to-time (s)
5708 (apply 'encode-time (org-parse-time-string s)))
5709
5710 (defun org-parse-time-string (s &optional nodefault)
5711 "Parse the standard Org-mode time string.
5712 This should be a lot faster than the normal `parse-time-string'.
5713 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
5714 hour and minute fields will be nil if not given."
5715 (if (string-match org-ts-regexp1 s)
5716 (list 0
5717 (if (or (match-beginning 8) (not nodefault))
5718 (string-to-number (or (match-string 8 s) "0")))
5719 (if (or (match-beginning 7) (not nodefault))
5720 (string-to-number (or (match-string 7 s) "0")))
5721 (string-to-number (match-string 4 s))
5722 (string-to-number (match-string 3 s))
5723 (string-to-number (match-string 2 s))
5724 nil nil nil)
5725 (make-list 9 0)))
5726
5727 (defun org-timestamp-up (&optional arg)
5728 "Increase the date item at the cursor by one.
5729 If the cursor is on the year, change the year. If it is on the month or
5730 the day, change that.
5731 With prefix ARG, change by that many units."
5732 (interactive "p")
5733 (org-timestamp-change (prefix-numeric-value arg)))
5734
5735 (defun org-timestamp-down (&optional arg)
5736 "Decrease the date item at the cursor by one.
5737 If the cursor is on the year, change the year. If it is on the month or
5738 the day, change that.
5739 With prefix ARG, change by that many units."
5740 (interactive "p")
5741 (org-timestamp-change (- (prefix-numeric-value arg))))
5742
5743 (defun org-timestamp-up-day (&optional arg)
5744 "Increase the date in the time stamp by one day.
5745 With prefix ARG, change that many days."
5746 (interactive "p")
5747 (if (and (not (org-at-timestamp-p t))
5748 (org-on-heading-p))
5749 (org-todo 'up)
5750 (org-timestamp-change (prefix-numeric-value arg) 'day)))
5751
5752 (defun org-timestamp-down-day (&optional arg)
5753 "Decrease the date in the time stamp by one day.
5754 With prefix ARG, change that many days."
5755 (interactive "p")
5756 (if (and (not (org-at-timestamp-p t))
5757 (org-on-heading-p))
5758 (org-todo 'down)
5759 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
5760
5761 (defsubst org-pos-in-match-range (pos n)
5762 (and (match-beginning n)
5763 (<= (match-beginning n) pos)
5764 (>= (match-end n) pos)))
5765
5766 (defun org-at-timestamp-p (&optional also-inactive)
5767 "Determine if the cursor is in or at a timestamp."
5768 (interactive)
5769 (let* ((tsr (if also-inactive org-ts-regexp3 org-ts-regexp2))
5770 (pos (point))
5771 (ans (or (looking-at tsr)
5772 (save-excursion
5773 (skip-chars-backward "^[<\n\r\t")
5774 (if (> (point) 1) (backward-char 1))
5775 (and (looking-at tsr)
5776 (> (- (match-end 0) pos) -1))))))
5777 (and (boundp 'org-ts-what)
5778 (setq org-ts-what
5779 (cond
5780 ((org-pos-in-match-range pos 2) 'year)
5781 ((org-pos-in-match-range pos 3) 'month)
5782 ((org-pos-in-match-range pos 7) 'hour)
5783 ((org-pos-in-match-range pos 8) 'minute)
5784 ((or (org-pos-in-match-range pos 4)
5785 (org-pos-in-match-range pos 5)) 'day)
5786 (t 'day))))
5787 ans))
5788
5789 (defun org-timestamp-change (n &optional what)
5790 "Change the date in the time stamp at point.
5791 The date will be changed by N times WHAT. WHAT can be `day', `month',
5792 `year', `minute', `second'. If WHAT is not given, the cursor position
5793 in the timestamp determines what will be changed."
5794 (let ((fmt (car org-time-stamp-formats))
5795 org-ts-what
5796 (pos (point))
5797 ts time time0)
5798 (if (not (org-at-timestamp-p t))
5799 (error "Not at a timestamp"))
5800 (setq org-ts-what (or what org-ts-what))
5801 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
5802 (- (match-end 0) (match-beginning 0))))
5803 1)
5804 (cdr org-time-stamp-formats)
5805 (car org-time-stamp-formats)))
5806 (if (= (char-after (match-beginning 0)) ?\[)
5807 (setq fmt (concat "[" (substring fmt 1 -1) "]")))
5808 (setq ts (match-string 0))
5809 (replace-match "")
5810 (setq time0 (org-parse-time-string ts))
5811 (setq time
5812 (apply 'encode-time
5813 (append
5814 (list (or (car time0) 0))
5815 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
5816 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
5817 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
5818 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
5819 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
5820 (nthcdr 6 time0))))
5821 (if (eq what 'calendar)
5822 (let ((cal-date
5823 (save-excursion
5824 (save-match-data
5825 (set-buffer "*Calendar*")
5826 (calendar-cursor-to-date)))))
5827 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
5828 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
5829 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
5830 (setcar time0 (or (car time0) 0))
5831 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
5832 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
5833 (setq time (apply 'encode-time time0))))
5834 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
5835 (org-clock-update-time-maybe)
5836 (goto-char pos)
5837 ;; Try to recenter the calendar window, if any
5838 (if (and org-calendar-follow-timestamp-change
5839 (get-buffer-window "*Calendar*" t)
5840 (memq org-ts-what '(day month year)))
5841 (org-recenter-calendar (time-to-days time)))))
5842
5843 (defun org-recenter-calendar (date)
5844 "If the calendar is visible, recenter it to DATE."
5845 (let* ((win (selected-window))
5846 (cwin (get-buffer-window "*Calendar*" t))
5847 (calendar-move-hook nil))
5848 (when cwin
5849 (select-window cwin)
5850 (calendar-goto-date (if (listp date) date
5851 (calendar-gregorian-from-absolute date)))
5852 (select-window win))))
5853
5854 (defun org-goto-calendar (&optional arg)
5855 "Go to the Emacs calendar at the current date.
5856 If there is a time stamp in the current line, go to that date.
5857 A prefix ARG can be used to force the current date."
5858 (interactive "P")
5859 (let ((tsr org-ts-regexp) diff
5860 (calendar-move-hook nil)
5861 (view-calendar-holidays-initially nil)
5862 (view-diary-entries-initially nil))
5863 (if (or (org-at-timestamp-p)
5864 (save-excursion
5865 (beginning-of-line 1)
5866 (looking-at (concat ".*" tsr))))
5867 (let ((d1 (time-to-days (current-time)))
5868 (d2 (time-to-days
5869 (org-time-string-to-time (match-string 1)))))
5870 (setq diff (- d2 d1))))
5871 (calendar)
5872 (calendar-goto-today)
5873 (if (and diff (not arg)) (calendar-forward-day diff))))
5874
5875 (defun org-date-from-calendar ()
5876 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
5877 If there is already a time stamp at the cursor position, update it."
5878 (interactive)
5879 (org-timestamp-change 0 'calendar))
5880
5881 ;;; The clock for measuring work time.
5882
5883 (defvar org-clock-marker (make-marker)
5884 "Marker recording the last clock-in.")
5885
5886 (defun org-clock-in ()
5887 "Start the clock on the current item.
5888 If necessary, clock-out of the currently active clock."
5889 (interactive)
5890 (org-clock-out t)
5891 (let (ts)
5892 (save-excursion
5893 (org-back-to-heading t)
5894 (beginning-of-line 2)
5895 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5896 (not (equal (match-string 1) org-clock-string)))
5897 (beginning-of-line 1))
5898 (insert "\n") (backward-char 1)
5899 (indent-relative)
5900 (insert org-clock-string " "
5901 (setq ts (concat "[" (format-time-string
5902 (substring
5903 (cdr org-time-stamp-formats) 1 -1)
5904 (current-time))
5905 "]")))
5906 (move-marker org-clock-marker (point))
5907 (message "Clock started at %s" ts))))
5908
5909 (defun org-clock-out (&optional fail-quietly)
5910 "Stop the currently running clock.
5911 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
5912 (interactive)
5913 (catch 'exit
5914 (if (not (marker-buffer org-clock-marker))
5915 (if fail-quietly (throw 'exit t) (error "No active clock")))
5916 (let (ts te s h m)
5917 (save-excursion
5918 (set-buffer (marker-buffer org-clock-marker))
5919 (goto-char org-clock-marker)
5920 (beginning-of-line 1)
5921 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
5922 (equal (match-string 1) org-clock-string))
5923 (setq ts (match-string 2))
5924 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
5925 (goto-char org-clock-marker)
5926 (setq te (concat "[" (format-time-string
5927 (substring
5928 (cdr org-time-stamp-formats) 1 -1)
5929 (current-time))
5930 "]"))
5931 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
5932 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
5933 h (floor (/ s 3600))
5934 s (- s (* 3600 h))
5935 m (floor (/ s 60))
5936 s (- s (* 60 s)))
5937 (insert "--" te " => " (format "%2d:%02d" h m))
5938 (move-marker org-clock-marker nil)
5939 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
5940
5941 (defun org-clock-cancel ()
5942 "Cancel the running clock be removing the start timestamp."
5943 (interactive)
5944 (if (not (marker-buffer org-clock-marker))
5945 (error "No active clock"))
5946 (save-excursion
5947 (set-buffer (marker-buffer org-clock-marker))
5948 (goto-char org-clock-marker)
5949 (delete-region (1- (point-at-bol)) (point-at-eol)))
5950 (message "Clock canceled"))
5951
5952 (defvar org-clock-file-total-minutes nil
5953 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
5954 (make-variable-buffer-local 'org-clock-file-total-minutes)
5955
5956 (defun org-clock-sum (&optional tstart tend)
5957 "Sum the times for each subtree.
5958 Puts the resulting times in minutes as a text property on each headline."
5959 (interactive)
5960 (let* ((bmp (buffer-modified-p))
5961 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
5962 org-clock-string
5963 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
5964 (lmax 30)
5965 (ltimes (make-vector lmax 0))
5966 (t1 0)
5967 (level 0)
5968 ts te dt
5969 time)
5970 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
5971 (save-excursion
5972 (goto-char (point-max))
5973 (while (re-search-backward re nil t)
5974 (if (match-end 2)
5975 ;; A time
5976 (setq ts (match-string 2)
5977 te (match-string 3)
5978 ts (time-to-seconds
5979 (apply 'encode-time (org-parse-time-string ts)))
5980 te (time-to-seconds
5981 (apply 'encode-time (org-parse-time-string te)))
5982 ts (if tstart (max ts tstart) ts)
5983 te (if tend (min te tend) te)
5984 dt (- te ts)
5985 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
5986 ;; A headline
5987 (setq level (- (match-end 1) (match-beginning 1)))
5988 (when (or (> t1 0) (> (aref ltimes level) 0))
5989 (loop for l from 0 to level do
5990 (aset ltimes l (+ (aref ltimes l) t1)))
5991 (setq t1 0 time (aref ltimes level))
5992 (loop for l from level to (1- lmax) do
5993 (aset ltimes l 0))
5994 (goto-char (match-beginning 0))
5995 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
5996 (setq org-clock-file-total-minutes (aref ltimes 0)))
5997 (set-buffer-modified-p bmp)))
5998
5999 (defun org-clock-display (&optional total-only)
6000 "Show subtree times in the entire buffer.
6001 If TOTAL-ONLY is non-nil, only show the total time for the entire file
6002 in the echo area."
6003 (interactive)
6004 (org-remove-clock-overlays)
6005 (let (time h m p)
6006 (org-clock-sum)
6007 (unless total-only
6008 (save-excursion
6009 (goto-char (point-min))
6010 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6011 (goto-char p)
6012 (when (setq time (get-text-property p :org-clock-minutes))
6013 (org-put-clock-overlay time (funcall outline-level))))
6014 (setq h (/ org-clock-file-total-minutes 60)
6015 m (- org-clock-file-total-minutes (* 60 h)))
6016 ;; Arrange to remove the overlays upon next change.
6017 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
6018 nil 'local)))
6019 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
6020
6021 (defvar org-clock-overlays nil)
6022 (make-variable-buffer-local 'org-clock-overlays)
6023
6024 (defun org-put-clock-overlay (time &optional level)
6025 "Put an overlays on the current line, displaying TIME.
6026 If LEVEL is given, prefix time with a corresponding number of stars.
6027 This creates a new overlay and stores it in `org-clock-overlays', so that it
6028 will be easy to remove."
6029 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
6030 (l (if level (org-get-legal-level level 0) 0))
6031 (off 0)
6032 ov tx)
6033 (move-to-column c)
6034 (unless (eolp) (skip-chars-backward "^ \t"))
6035 (skip-chars-backward " \t")
6036 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
6037 tx (concat (buffer-substring (1- (point)) (point))
6038 (make-string (+ off (max 0 (- c (current-column)))) ?.)
6039 (org-add-props (format "%s %2d:%02d%s"
6040 (make-string l ?*) h m
6041 (make-string (- 10 l) ?\ ))
6042 '(face secondary-selection))
6043 ""))
6044 (org-overlay-put ov 'display tx)
6045 (push ov org-clock-overlays)))
6046
6047 (defun org-remove-clock-overlays (&optional beg end noremove)
6048 "Remove the occur highlights from the buffer.
6049 BEG and END are ignored. If NOREMOVE is nil, remove this function
6050 from the `before-change-functions' in the current buffer."
6051 (interactive)
6052 (unless org-inhibit-highlight-removal
6053 (mapc 'org-delete-overlay org-clock-overlays)
6054 (setq org-clock-overlays nil)
6055 (unless noremove
6056 (remove-hook 'before-change-functions
6057 'org-remove-clock-overlays 'local))))
6058
6059 (defun org-clock-out-if-current ()
6060 "Clock out if the current entry contains the running clock.
6061 This is used to stop the clock after a TODO entry is marked DONE."
6062 (when (and (equal state org-done-string)
6063 (equal (marker-buffer org-clock-marker) (current-buffer))
6064 (< (point) org-clock-marker)
6065 (> (save-excursion (outline-next-heading) (point))
6066 org-clock-marker))
6067 (org-clock-out)))
6068
6069 (add-hook 'org-after-todo-state-change-hook
6070 'org-clock-out-if-current)
6071
6072 (defun org-check-running-clock ()
6073 "Check if the current buffer contains the running clock.
6074 If yes, offer to stop it and to save the buffer with the changes."
6075 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
6076 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
6077 (buffer-name))))
6078 (org-clock-out)
6079 (when (y-or-n-p "Save changed buffer?")
6080 (save-buffer))))
6081
6082 (defun org-clock-report ()
6083 "Create a table containing a report about clocked time.
6084 If the buffer contains lines
6085 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
6086
6087 #+END: clocktable
6088 then the table will be inserted between these lines, replacing whatever
6089 is was there before. If these lines are not in the buffer, the table
6090 is inserted at point, surrounded by the special lines.
6091 The BEGIN line can contain parameters. Allowed are:
6092 :maxlevel The maximum level to be included in the table. Default is 3.
6093 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
6094 (interactive)
6095 (org-remove-clock-overlays)
6096 (unless (org-find-dblock "clocktable")
6097 (org-create-dblock (list :name "clocktable"
6098 :maxlevel 2 :emphasize nil)))
6099 (org-update-dblock))
6100
6101 (defun org-clock-update-time-maybe ()
6102 "If this is a CLOCK line, update it and return t.
6103 Otherwise, return nil."
6104 (interactive)
6105 (save-excursion
6106 (beginning-of-line 1)
6107 (skip-chars-forward " \t")
6108 (when (looking-at org-clock-string)
6109 (let ((re (concat "[ \t]*" org-clock-string
6110 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
6111 "\\([ \t]*=>.*\\)?"))
6112 ts te h m s)
6113 (if (not (looking-at re))
6114 nil
6115 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
6116 (end-of-line 1)
6117 (setq ts (match-string 1)
6118 te (match-string 2))
6119 (setq s (- (time-to-seconds
6120 (apply 'encode-time (org-parse-time-string te)))
6121 (time-to-seconds
6122 (apply 'encode-time (org-parse-time-string ts))))
6123 h (floor (/ s 3600))
6124 s (- s (* 3600 h))
6125 m (floor (/ s 60))
6126 s (- s (* 60 s)))
6127 (insert " => " (format "%2d:%02d" h m))
6128 t)))))
6129
6130 (defun org-clock-special-range (key &optional time as-strings)
6131 "Return two times bordering a special time range.
6132 Key is a symbol specifying the range and can be one of `today', `yesterday',
6133 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
6134 A week starts Monday 0:00 and ends Sunday 24:00.
6135 The range is determined relative to TIME. TIME defaults to the current time.
6136 The return value is a cons cell with two internal times like the ones
6137 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
6138 the returned times will be formatted strings."
6139 (let* ((tm (decode-time (or time (current-time))))
6140 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
6141 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
6142 (dow (nth 6 tm))
6143 s1 m1 h1 d1 month1 y1 diff ts te fm)
6144 (cond
6145 ((eq key 'today)
6146 (setq h 0 m 0 h1 24 m1 0))
6147 ((eq key 'yesterday)
6148 (setq d (1- d) h 0 m 0 h1 24 m1 0))
6149 ((eq key 'thisweek)
6150 (setq diff (if (= dow 0) 6 (1- dow))
6151 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6152 ((eq key 'lastweek)
6153 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
6154 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6155 ((eq key 'thismonth)
6156 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
6157 ((eq key 'lastmonth)
6158 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
6159 ((eq key 'thisyear)
6160 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
6161 ((eq key 'lastyear)
6162 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
6163 (t (error "No such time block %s" key)))
6164 (setq ts (encode-time s m h d month y)
6165 te (encode-time (or s1 s) (or m1 m) (or h1 h)
6166 (or d1 d) (or month1 month) (or y1 y)))
6167 (setq fm (cdr org-time-stamp-formats))
6168 (if as-strings
6169 (cons (format-time-string fm ts) (format-time-string fm te))
6170 (cons ts te))))
6171
6172 (defun org-dblock-write:clocktable (params)
6173 "Write the standard clocktable."
6174 (let ((hlchars '((1 . "*") (2 . ?/)))
6175 (emph nil)
6176 (ins (make-marker))
6177 ipos time h m p level hlc hdl maxlevel
6178 ts te cc block)
6179 (setq maxlevel (or (plist-get params :maxlevel) 3)
6180 emph (plist-get params :emphasize)
6181 ts (plist-get params :tstart)
6182 te (plist-get params :tend)
6183 block (plist-get params :block))
6184 (when block
6185 (setq cc (org-clock-special-range block nil t)
6186 ts (car cc) te (cdr cc)))
6187 (if ts (setq ts (time-to-seconds
6188 (apply 'encode-time (org-parse-time-string ts)))))
6189 (if te (setq te (time-to-seconds
6190 (apply 'encode-time (org-parse-time-string te)))))
6191 (move-marker ins (point))
6192 (setq ipos (point))
6193 (insert-before-markers "Clock summary at ["
6194 (substring
6195 (format-time-string (cdr org-time-stamp-formats))
6196 1 -1)
6197 "]."
6198 (if block
6199 (format " Considered range is /%s/." block)
6200 "")
6201 "\n\n|L|Headline|Time|\n")
6202 (org-clock-sum ts te)
6203 (setq h (/ org-clock-file-total-minutes 60)
6204 m (- org-clock-file-total-minutes (* 60 h)))
6205 (insert-before-markers "|-\n|0|" "*Total file time*| "
6206 (format "*%d:%02d*" h m)
6207 "|\n")
6208 (goto-char (point-min))
6209 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6210 (goto-char p)
6211 (when (setq time (get-text-property p :org-clock-minutes))
6212 (save-excursion
6213 (beginning-of-line 1)
6214 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
6215 (setq level (- (match-end 1) (match-beginning 1)))
6216 (<= level maxlevel))
6217 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
6218 hdl (match-string 2)
6219 h (/ time 60)
6220 m (- time (* 60 h)))
6221 (goto-char ins)
6222 (if (= level 1) (insert-before-markers "|-\n"))
6223 (insert-before-markers
6224 "| " (int-to-string level) "|" hlc hdl hlc " |"
6225 (make-string (1- level) ?|)
6226 hlc
6227 (format "%d:%02d" h m)
6228 hlc
6229 " |\n")))))
6230 (goto-char ins)
6231 (backward-delete-char 1)
6232 (goto-char ipos)
6233 (skip-chars-forward "^|")
6234 (org-table-align)))
6235
6236 (defun org-collect-clock-time-entries ()
6237 "Return an internal list with clocking information.
6238 This list has one entry for each CLOCK interval.
6239 FIXME: describe the elements."
6240 (interactive)
6241 (let ((re (concat "^[ \t]*" org-clock-string
6242 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
6243 rtn beg end next cont level title total closedp leafp
6244 clockpos titlepos h m donep)
6245 (save-excursion
6246 (org-clock-sum)
6247 (goto-char (point-min))
6248 (while (re-search-forward re nil t)
6249 (setq clockpos (match-beginning 0)
6250 beg (match-string 1) end (match-string 2)
6251 cont (match-end 0))
6252 (setq beg (apply 'encode-time (org-parse-time-string beg))
6253 end (apply 'encode-time (org-parse-time-string end)))
6254 (org-back-to-heading t)
6255 (setq donep (org-entry-is-done-p))
6256 (setq titlepos (point)
6257 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
6258 h (/ total 60) m (- total (* 60 h))
6259 total (cons h m))
6260 (looking-at "\\(\\*+\\) +\\(.*\\)")
6261 (setq level (- (match-end 1) (match-beginning 1))
6262 title (org-match-string-no-properties 2))
6263 (save-excursion (outline-next-heading) (setq next (point)))
6264 (setq closedp (re-search-forward org-closed-time-regexp next t))
6265 (goto-char next)
6266 (setq leafp (and (looking-at "^\\*+ ")
6267 (<= (- (match-end 0) (point)) level)))
6268 (push (list beg end clockpos closedp donep
6269 total title titlepos level leafp)
6270 rtn)
6271 (goto-char cont)))
6272 (nreverse rtn)))
6273
6274 ;;; Agenda, and Diary Integration
6275
6276 ;;; Define the mode
6277
6278 (defvar org-agenda-mode-map (make-sparse-keymap)
6279 "Keymap for `org-agenda-mode'.")
6280
6281 (defvar org-agenda-menu) ; defined later in this file.
6282 (defvar org-agenda-follow-mode nil)
6283 (defvar org-agenda-show-log nil)
6284 (defvar org-agenda-buffer-name "*Org Agenda*")
6285 (defvar org-agenda-redo-command nil)
6286 (defvar org-agenda-mode-hook nil)
6287 (defvar org-agenda-type nil)
6288 (defvar org-agenda-force-single-file nil)
6289
6290 (defun org-agenda-mode ()
6291 "Mode for time-sorted view on action items in Org-mode files.
6292
6293 The following commands are available:
6294
6295 \\{org-agenda-mode-map}"
6296 (interactive)
6297 (kill-all-local-variables)
6298 (setq major-mode 'org-agenda-mode)
6299 (setq mode-name "Org-Agenda")
6300 (use-local-map org-agenda-mode-map)
6301 (easy-menu-add org-agenda-menu)
6302 (if org-startup-truncated (setq truncate-lines t))
6303 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
6304 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
6305 (unless org-agenda-keep-modes
6306 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
6307 org-agenda-show-log nil))
6308 (easy-menu-change
6309 '("Agenda") "Agenda Files"
6310 (append
6311 (list
6312 (vector
6313 (if (get 'org-agenda-files 'org-restrict)
6314 "Restricted to single file"
6315 "Edit File List")
6316 '(org-edit-agenda-file-list)
6317 (not (get 'org-agenda-files 'org-restrict)))
6318 "--")
6319 (mapcar 'org-file-menu-entry (org-agenda-files))))
6320 (org-agenda-set-mode-name)
6321 (apply
6322 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
6323 (list 'org-agenda-mode-hook)))
6324
6325 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
6326 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
6327 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
6328 (define-key org-agenda-mode-map " " 'org-agenda-show)
6329 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
6330 (define-key org-agenda-mode-map "o" 'delete-other-windows)
6331 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
6332 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
6333 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
6334 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
6335 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
6336 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
6337 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
6338 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
6339 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
6340 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
6341 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
6342
6343 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
6344 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
6345 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
6346 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
6347 (while l (define-key org-agenda-mode-map
6348 (int-to-string (pop l)) 'digit-argument)))
6349
6350 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
6351 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
6352 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
6353 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
6354 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
6355 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
6356 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
6357 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
6358 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
6359 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
6360 (define-key org-agenda-mode-map "n" 'next-line)
6361 (define-key org-agenda-mode-map "p" 'previous-line)
6362 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
6363 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
6364 (define-key org-agenda-mode-map "," 'org-agenda-priority)
6365 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
6366 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
6367 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
6368 (eval-after-load "calendar"
6369 '(define-key calendar-mode-map org-calendar-to-agenda-key
6370 'org-calendar-goto-agenda))
6371 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
6372 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
6373 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
6374 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
6375 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
6376 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
6377 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
6378 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
6379 (define-key org-agenda-mode-map "O" 'org-clock-out)
6380 (define-key org-agenda-mode-map "X" 'org-clock-cancel)
6381 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
6382 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
6383 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
6384 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
6385 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
6386 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
6387 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
6388 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
6389 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
6390 "Local keymap for agenda entries from Org-mode.")
6391
6392 (define-key org-agenda-keymap
6393 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
6394 (define-key org-agenda-keymap
6395 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
6396 (when org-agenda-mouse-1-follows-link
6397 (define-key org-agenda-keymap [follow-link] 'mouse-face))
6398 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
6399 '("Agenda"
6400 ("Agenda Files")
6401 "--"
6402 ["Show" org-agenda-show t]
6403 ["Go To (other window)" org-agenda-goto t]
6404 ["Go To (one window)" org-agenda-switch-to t]
6405 ["Follow Mode" org-agenda-follow-mode
6406 :style toggle :selected org-agenda-follow-mode :active t]
6407 "--"
6408 ["Cycle TODO" org-agenda-todo t]
6409 ("Tags"
6410 ["Show all Tags" org-agenda-show-tags t]
6411 ["Set Tags" org-agenda-set-tags t])
6412 ("Schedule"
6413 ["Schedule" org-agenda-schedule t]
6414 ["Set Deadline" org-agenda-deadline t]
6415 "--"
6416 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
6417 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
6418 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
6419 ("Priority"
6420 ["Set Priority" org-agenda-priority t]
6421 ["Increase Priority" org-agenda-priority-up t]
6422 ["Decrease Priority" org-agenda-priority-down t]
6423 ["Show Priority" org-agenda-show-priority t])
6424 "--"
6425 ;; ["New agenda command" org-agenda t]
6426 ["Rebuild buffer" org-agenda-redo t]
6427 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
6428 "--"
6429 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
6430 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
6431 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
6432 "--"
6433 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
6434 :style radio :selected (equal org-agenda-ndays 1)]
6435 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
6436 :style radio :selected (equal org-agenda-ndays 7)]
6437 "--"
6438 ["Show Logbook entries" org-agenda-log-mode
6439 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
6440 ["Include Diary" org-agenda-toggle-diary
6441 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
6442 ["Use Time Grid" org-agenda-toggle-time-grid
6443 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
6444 "--"
6445 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
6446 ("Calendar Commands"
6447 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
6448 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
6449 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
6450 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
6451 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
6452 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
6453 "--"
6454 ["Quit" org-agenda-quit t]
6455 ["Exit and Release Buffers" org-agenda-exit t]
6456 ))
6457
6458 ;;;###autoload
6459 (defun org-agenda (arg)
6460 "Dispatch agenda commands to collect entries to the agenda buffer.
6461 Prompts for a character to select a command. Any prefix arg will be passed
6462 on to the selected command. The default selections are:
6463
6464 a Call `org-agenda' to display the agenda for the current day or week.
6465 t Call `org-todo-list' to display the global todo list.
6466 T Call `org-todo-list' to display the global todo list, select only
6467 entries with a specific TODO keyword (the user gets a prompt).
6468 m Call `org-tags-view' to display headlines with tags matching
6469 a condition (the user is prompted for the condition).
6470 M Like `m', but select only TODO entries, no ordinary headlines.
6471
6472 More commands can be added by configuring the variable
6473 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
6474 searches can be pre-defined in this way.
6475
6476 If the current buffer is in Org-mode and visiting a file, you can also
6477 first press `1' to indicate that the agenda should be temporarily (until the
6478 next use of \\[org-agenda]) restricted to the current file."
6479 (interactive "P")
6480 (catch 'exit
6481 (let ((restrict-ok (and buffer-file-name (org-mode-p)))
6482 (bfn buffer-file-name)
6483 (custom org-agenda-custom-commands)
6484 c entry key type string)
6485 (put 'org-agenda-files 'org-restrict nil)
6486 (save-window-excursion
6487 (delete-other-windows)
6488 (switch-to-buffer-other-window " *Agenda Commands*")
6489 (erase-buffer)
6490 (insert
6491 "Press key for an agenda command:
6492 --------------------------------
6493 a Agenda for current week or day
6494 t List of all TODO entries T Entries with special TODO kwd
6495 m Match a TAGS query M Like m, but only TODO entries
6496 C Configure your own agenda commands")
6497 (while (setq entry (pop custom))
6498 (setq key (car entry) type (nth 1 entry) string (nth 2 entry))
6499 (insert (format "\n%-4s%-14s: %s"
6500 key
6501 (cond
6502 ((eq type 'tags) "Tags query")
6503 ((eq type 'todo) "TODO keyword")
6504 ((eq type 'tags-tree) "Tags tree")
6505 ((eq type 'todo-tree) "TODO kwd tree")
6506 ((eq type 'occur-tree) "Occur tree")
6507 (t "???"))
6508 (org-add-props string nil 'face 'org-warning))))
6509 (goto-char (point-min))
6510 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
6511 (message "Press key for agenda command%s"
6512 (if restrict-ok ", or [1] to restrict to current file" ""))
6513 (setq c (read-char-exclusive))
6514 (message "")
6515 (when (equal c ?1)
6516 (if restrict-ok
6517 (put 'org-agenda-files 'org-restrict (list bfn))
6518 (error "Cannot restrict agenda to current buffer"))
6519 (message "Press key for agenda command%s"
6520 (if restrict-ok " (restricted to current file)" ""))
6521 (setq c (read-char-exclusive))
6522 (message "")))
6523 (require 'calendar) ; FIXME: can we avoid this for some commands?
6524 ;; For example the todo list should not need it (but does...)
6525 (cond
6526 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
6527 ((equal c ?a) (call-interactively 'org-agenda-list))
6528 ((equal c ?t) (call-interactively 'org-todo-list))
6529 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
6530 ((equal c ?m) (call-interactively 'org-tags-view))
6531 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
6532 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
6533 (setq type (nth 1 entry) string (nth 2 entry))
6534 (cond
6535 ((eq type 'tags)
6536 (org-tags-view current-prefix-arg string))
6537 ((eq type 'tags-todo)
6538 (org-tags-view '(4) string))
6539 ((eq type 'todo)
6540 (org-todo-list string))
6541 ((eq type 'tags-tree)
6542 (org-check-for-org-mode)
6543 (org-tags-sparse-tree current-prefix-arg string))
6544 ((eq type 'todo-tree)
6545 (org-check-for-org-mode)
6546 (org-occur (concat "^" outline-regexp "[ \t]*"
6547 (regexp-quote string) "\\>")))
6548 ((eq type 'occur-tree)
6549 (org-check-for-org-mode)
6550 (org-occur string))
6551 (t (error "Invalid custom agenda command type %s" type))))
6552 (t (error "Invalid key"))))))
6553
6554 (defun org-check-for-org-mode ()
6555 "Make sure current buffer is in org-mode. Error if not."
6556 (or (org-mode-p)
6557 (error "Cannot execute org-mode agenda command on buffer in %s."
6558 major-mode)))
6559
6560 (defun org-fit-agenda-window ()
6561 "Fit the window to the buffer size."
6562 (and org-fit-agenda-window
6563 (fboundp 'fit-window-to-buffer)
6564 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
6565 (/ (frame-height) 2))))
6566
6567 (defun org-agenda-files (&optional unrestricted)
6568 "Get the list of agenda files.
6569 Optional UNRESTRICTED means return the full list even if a restriction
6570 is currently in place."
6571 (cond
6572 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
6573 ((stringp org-agenda-files) (org-read-agenda-file-list))
6574 ((listp org-agenda-files) org-agenda-files)
6575 (t (error "Invalid value of `org-agenda-files'"))))
6576
6577 (defvar org-window-configuration)
6578
6579 (defun org-edit-agenda-file-list ()
6580 "Edit the list of agenda files.
6581 Depending on setup, this either uses customize to edit the variable
6582 `org-agenda-files', or it visits the file that is holding the list. In the
6583 latter case, the buffer is set up in a way that saving it automatically kills
6584 the buffer and restores the previous window configuration."
6585 (interactive)
6586 (if (stringp org-agenda-files)
6587 (let ((cw (current-window-configuration)))
6588 (find-file org-agenda-files)
6589 (org-set-local 'org-window-configuration cw)
6590 (org-add-hook 'after-save-hook
6591 (lambda ()
6592 (set-window-configuration
6593 (prog1 org-window-configuration
6594 (kill-buffer (current-buffer))))
6595 (org-install-agenda-files-menu)
6596 (message "New agenda file list installed"))
6597 nil 'local)
6598 (message (substitute-command-keys
6599 "Edit list and finish with \\[save-buffer]")))
6600 (customize-variable 'org-agenda-files)))
6601
6602 (defun org-store-new-agenda-file-list (list)
6603 "Set new value for the agenda file list and save it correcly."
6604 (if (stringp org-agenda-files)
6605 (let ((f org-agenda-files) b)
6606 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
6607 (with-temp-file f
6608 (insert (mapconcat 'identity list "\n") "\n")))
6609 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
6610 (setq org-agenda-files list)
6611 (customize-save-variable 'org-agenda-files org-agenda-files))))
6612
6613 (defun org-read-agenda-file-list ()
6614 "Read the list of agenda files from a file."
6615 (when (stringp org-agenda-files)
6616 (with-temp-buffer
6617 (insert-file-contents org-agenda-files)
6618 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
6619
6620 (defvar org-agenda-markers nil
6621 "List of all currently active markers created by `org-agenda'.")
6622 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
6623 "Creation time of the last agenda marker.")
6624
6625 (defun org-agenda-new-marker (&optional pos)
6626 "Return a new agenda marker.
6627 Org-mode keeps a list of these markers and resets them when they are
6628 no longer in use."
6629 (let ((m (copy-marker (or pos (point)))))
6630 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
6631 (push m org-agenda-markers)
6632 m))
6633
6634 (defun org-agenda-maybe-reset-markers (&optional force)
6635 "Reset markers created by `org-agenda'. But only if they are old enough."
6636 (if (or force
6637 (> (- (time-to-seconds (current-time))
6638 org-agenda-last-marker-time)
6639 5))
6640 (while org-agenda-markers
6641 (move-marker (pop org-agenda-markers) nil))))
6642
6643 (defvar org-agenda-new-buffers nil
6644 "Buffers created to visit agenda files.")
6645
6646 (defun org-get-agenda-file-buffer (file)
6647 "Get a buffer visiting FILE. If the buffer needs to be created, add
6648 it to the list of buffers which might be released later."
6649 (let ((buf (find-buffer-visiting file)))
6650 (if buf
6651 buf ; just return it
6652 ;; Make a new buffer and remember it
6653 (setq buf (find-file-noselect file))
6654 (if buf (push buf org-agenda-new-buffers))
6655 buf)))
6656
6657 (defun org-release-buffers (blist)
6658 "Release all buffers in list, asking the user for confirmation when needed.
6659 When a buffer is unmodified, it is just killed. When modified, it is saved
6660 \(if the user agrees) and then killed."
6661 (let (buf file)
6662 (while (setq buf (pop blist))
6663 (setq file (buffer-file-name buf))
6664 (when (and (buffer-modified-p buf)
6665 file
6666 (y-or-n-p (format "Save file %s? " file)))
6667 (with-current-buffer buf (save-buffer)))
6668 (kill-buffer buf))))
6669
6670 (defvar org-respect-restriction nil) ; Dynamically-scoped param.
6671
6672 (defun org-timeline (&optional include-all keep-modes)
6673 "Show a time-sorted view of the entries in the current org file.
6674 Only entries with a time stamp of today or later will be listed. With
6675 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
6676 under the current date.
6677 If the buffer contains an active region, only check the region for
6678 dates."
6679 (interactive "P")
6680 (require 'calendar)
6681 (org-agenda-maybe-reset-markers 'force)
6682 (org-compile-prefix-format org-timeline-prefix-format)
6683 (let* ((dopast t)
6684 (dotodo include-all)
6685 (doclosed org-agenda-show-log)
6686 (org-agenda-keep-modes keep-modes)
6687 (entry buffer-file-name)
6688 (org-agenda-files (list buffer-file-name))
6689 (date (calendar-current-date))
6690 (win (selected-window))
6691 (pos1 (point))
6692 (beg (if (org-region-active-p) (region-beginning) (point-min)))
6693 (end (if (org-region-active-p) (region-end) (point-max)))
6694 (day-numbers (org-get-all-dates beg end 'no-ranges
6695 t doclosed ; always include today
6696 org-timeline-show-empty-dates))
6697 (today (time-to-days (current-time)))
6698 (org-respect-restriction t)
6699 (past t)
6700 args
6701 s e rtn d emptyp)
6702 (org-prepare-agenda-buffers org-agenda-files)
6703 (setq org-agenda-redo-command
6704 (list 'progn
6705 (list 'switch-to-buffer-other-window (current-buffer))
6706 (list 'org-timeline (list 'quote include-all) t)))
6707 (if (not dopast)
6708 ;; Remove past dates from the list of dates.
6709 (setq day-numbers (delq nil (mapcar (lambda(x)
6710 (if (>= x today) x nil))
6711 day-numbers))))
6712 (switch-to-buffer-other-window
6713 (get-buffer-create org-agenda-buffer-name))
6714 (setq buffer-read-only nil)
6715 (erase-buffer)
6716 (org-agenda-mode) (setq buffer-read-only nil)
6717 (org-set-local 'org-agenda-type 'timeline)
6718 (if doclosed (push :closed args))
6719 (push :timestamp args)
6720 (if dotodo (push :todo args))
6721 (while (setq d (pop day-numbers))
6722 (if (and (listp d) (eq (car d) :omitted))
6723 (progn
6724 (setq s (point))
6725 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
6726 (put-text-property s (1- (point)) 'face 'org-level-3))
6727 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
6728 (if (and (>= d today)
6729 dopast
6730 past)
6731 (progn
6732 (setq past nil)
6733 (insert (make-string 79 ?-) "\n")))
6734 (setq date (calendar-gregorian-from-absolute d))
6735 (setq s (point))
6736 (setq rtn (and (not emptyp)
6737 (apply 'org-agenda-get-day-entries
6738 entry date args)))
6739 (if (or rtn (equal d today) org-timeline-show-empty-dates)
6740 (progn
6741 (insert (calendar-day-name date) " "
6742 (number-to-string (extract-calendar-day date)) " "
6743 (calendar-month-name (extract-calendar-month date)) " "
6744 (number-to-string (extract-calendar-year date)) "\n")
6745 (put-text-property s (1- (point)) 'face
6746 'org-level-3)
6747 (if (equal d today)
6748 (put-text-property s (1- (point)) 'org-today t))
6749 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
6750 (put-text-property s (1- (point)) 'day d)))))
6751 (goto-char (point-min))
6752 (setq buffer-read-only t)
6753 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6754 (point-min)))
6755 (when (not org-select-timeline-window)
6756 (select-window win)
6757 (goto-char pos1))))
6758
6759 ;;;###autoload
6760 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
6761 "Produce a weekly view from all files in variable `org-agenda-files'.
6762 The view will be for the current week, but from the overview buffer you
6763 will be able to go to other weeks.
6764 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
6765 also be shown, under the current date.
6766 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
6767 on the days are also shown. See the variable `org-log-done' for how
6768 to turn on logging.
6769 START-DAY defaults to TODAY, or to the most recent match for the weekday
6770 given in `org-agenda-start-on-weekday'.
6771 NDAYS defaults to `org-agenda-ndays'."
6772 (interactive "P")
6773 (org-agenda-maybe-reset-markers 'force)
6774 (org-compile-prefix-format org-agenda-prefix-format)
6775 (require 'calendar)
6776 (let* ((org-agenda-start-on-weekday
6777 (if (or (equal ndays 1)
6778 (and (null ndays) (equal 1 org-agenda-ndays)))
6779 nil org-agenda-start-on-weekday))
6780 (org-agenda-keep-modes keep-modes)
6781 (thefiles (org-agenda-files))
6782 (files thefiles)
6783 (win (selected-window))
6784 (today (time-to-days (current-time)))
6785 (sd (or start-day today))
6786 (start (if (or (null org-agenda-start-on-weekday)
6787 (< org-agenda-ndays 7))
6788 sd
6789 (let* ((nt (calendar-day-of-week
6790 (calendar-gregorian-from-absolute sd)))
6791 (n1 org-agenda-start-on-weekday)
6792 (d (- nt n1)))
6793 (- sd (+ (if (< d 0) 7 0) d)))))
6794 (day-numbers (list start))
6795 (inhibit-redisplay t)
6796 s e rtn rtnall file date d start-pos end-pos todayp nd)
6797 (org-prepare-agenda-buffers files)
6798 (setq org-agenda-redo-command
6799 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
6800 ;; Make the list of days
6801 (setq ndays (or ndays org-agenda-ndays)
6802 nd ndays)
6803 (while (> ndays 1)
6804 (push (1+ (car day-numbers)) day-numbers)
6805 (setq ndays (1- ndays)))
6806 (setq day-numbers (nreverse day-numbers))
6807 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6808 (progn
6809 (delete-other-windows)
6810 (switch-to-buffer-other-window
6811 (get-buffer-create org-agenda-buffer-name))))
6812 (setq buffer-read-only nil)
6813 (erase-buffer)
6814 (org-agenda-mode) (setq buffer-read-only nil)
6815 (org-set-local 'org-agenda-type 'agenda)
6816 (org-set-local 'starting-day (car day-numbers))
6817 (org-set-local 'include-all-loc include-all)
6818 (when (and (or include-all org-agenda-include-all-todo)
6819 (member today day-numbers))
6820 (setq files thefiles
6821 rtnall nil)
6822 (while (setq file (pop files))
6823 (catch 'nextfile
6824 (org-check-agenda-file file)
6825 (setq date (calendar-gregorian-from-absolute today)
6826 rtn (org-agenda-get-day-entries
6827 file date :todo))
6828 (setq rtnall (append rtnall rtn))))
6829 (when rtnall
6830 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
6831 (add-text-properties (point-min) (1- (point))
6832 (list 'face 'org-level-3))
6833 (insert (org-finalize-agenda-entries rtnall) "\n")))
6834 (while (setq d (pop day-numbers))
6835 (setq date (calendar-gregorian-from-absolute d)
6836 s (point))
6837 (if (or (setq todayp (= d today))
6838 (and (not start-pos) (= d sd)))
6839 (setq start-pos (point))
6840 (if (and start-pos (not end-pos))
6841 (setq end-pos (point))))
6842 (setq files thefiles
6843 rtnall nil)
6844 (while (setq file (pop files))
6845 (catch 'nextfile
6846 (org-check-agenda-file file)
6847 (if org-agenda-show-log
6848 (setq rtn (org-agenda-get-day-entries
6849 file date
6850 :deadline :scheduled :timestamp :closed))
6851 (setq rtn (org-agenda-get-day-entries
6852 file date
6853 :deadline :scheduled :timestamp)))
6854 (setq rtnall (append rtnall rtn))))
6855 (if org-agenda-include-diary
6856 (progn
6857 (require 'diary-lib)
6858 (setq rtn (org-get-entries-from-diary date))
6859 (setq rtnall (append rtnall rtn))))
6860 (if (or rtnall org-agenda-show-all-dates)
6861 (progn
6862 (insert (format "%-9s %2d %s %4d\n"
6863 (calendar-day-name date)
6864 (extract-calendar-day date)
6865 (calendar-month-name (extract-calendar-month date))
6866 (extract-calendar-year date)))
6867 (put-text-property s (1- (point)) 'face
6868 'org-level-3)
6869 (if rtnall (insert
6870 (org-finalize-agenda-entries
6871 (org-agenda-add-time-grid-maybe
6872 rtnall nd todayp))
6873 "\n"))
6874 (put-text-property s (1- (point)) 'day d))))
6875 (goto-char (point-min))
6876 (setq buffer-read-only t)
6877 (org-fit-agenda-window)
6878 (unless (and (pos-visible-in-window-p (point-min))
6879 (pos-visible-in-window-p (point-max)))
6880 (goto-char (1- (point-max)))
6881 (recenter -1)
6882 (if (not (pos-visible-in-window-p (or start-pos 1)))
6883 (progn
6884 (goto-char (or start-pos 1))
6885 (recenter 1))))
6886 (goto-char (or start-pos 1))
6887 (if (not org-select-agenda-window) (select-window win))
6888 (message "")))
6889
6890 (defvar org-select-this-todo-keyword nil)
6891
6892 ;;;###autoload
6893 (defun org-todo-list (arg &optional keep-modes)
6894 "Show all TODO entries from all agenda file in a single list.
6895 The prefix arg can be used to select a specific TODO keyword and limit
6896 the list to these. When using \\[universal-argument], you will be prompted
6897 for a keyword. A numeric prefix directly selects the Nth keyword in
6898 `org-todo-keywords'."
6899 (interactive "P")
6900 (org-agenda-maybe-reset-markers 'force)
6901 (org-compile-prefix-format org-agenda-prefix-format)
6902 (let* ((org-agenda-keep-modes keep-modes)
6903 (today (time-to-days (current-time)))
6904 (date (calendar-gregorian-from-absolute today))
6905 (win (selected-window))
6906 (kwds org-todo-keywords)
6907 (completion-ignore-case t)
6908 (org-select-this-todo-keyword
6909 (if (stringp arg) arg
6910 (and arg (integerp arg) (> arg 0)
6911 (nth (1- arg) org-todo-keywords))))
6912 rtn rtnall files file pos)
6913 (when (equal arg '(4))
6914 (setq org-select-this-todo-keyword
6915 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
6916 nil t)))
6917 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
6918 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
6919 (progn
6920 (delete-other-windows)
6921 (switch-to-buffer-other-window
6922 (get-buffer-create org-agenda-buffer-name))))
6923 (setq buffer-read-only nil)
6924 (erase-buffer)
6925 (org-agenda-mode) (setq buffer-read-only nil)
6926 (org-set-local 'org-agenda-type 'todo)
6927 (org-set-local 'last-arg arg)
6928 (org-set-local 'org-todo-keywords kwds)
6929 (org-set-local 'org-agenda-redo-command
6930 '(org-todo-list (or current-prefix-arg last-arg) t))
6931 (setq files (org-agenda-files)
6932 rtnall nil)
6933 (org-prepare-agenda-buffers files)
6934 (while (setq file (pop files))
6935 (catch 'nextfile
6936 (org-check-agenda-file file)
6937 (setq rtn (org-agenda-get-day-entries file date :todo))
6938 (setq rtnall (append rtnall rtn))))
6939 (insert "Global list of TODO items of type: ")
6940 (add-text-properties (point-min) (1- (point))
6941 (list 'face 'org-level-3))
6942 (setq pos (point))
6943 (insert (or org-select-this-todo-keyword "ALL") "\n")
6944 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
6945 (setq pos (point))
6946 (insert
6947 "Available with `N r': (0)ALL "
6948 (let ((n 0))
6949 (mapconcat (lambda (x)
6950 (format "(%d)%s" (setq n (1+ n)) x))
6951 org-todo-keywords " "))
6952 "\n")
6953 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
6954 (when rtnall
6955 (insert (org-finalize-agenda-entries rtnall) "\n"))
6956 (goto-char (point-min))
6957 (setq buffer-read-only t)
6958 (org-fit-agenda-window)
6959 (if (not org-select-agenda-window) (select-window win))))
6960
6961 (defun org-check-agenda-file (file)
6962 "Make sure FILE exists. If not, ask user what to do."
6963 (when (not (file-exists-p file))
6964 (message "non-existent file %s. [R]emove from list or [A]bort?"
6965 (abbreviate-file-name file))
6966 (let ((r (downcase (read-char-exclusive))))
6967 (cond
6968 ((equal r ?r)
6969 (org-remove-file file)
6970 (throw 'nextfile t))
6971 (t (error "Abort"))))))
6972
6973 (defun org-agenda-check-type (error &rest types)
6974 "Check if agenda buffer is of allowed type.
6975 If ERROR is non-nil, throw an error, otherwise just return nil."
6976 (if (memq org-agenda-type types)
6977 t
6978 (if error
6979 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
6980 nil)))
6981
6982 (defun org-agenda-quit ()
6983 "Exit agenda by removing the window or the buffer."
6984 (interactive)
6985 (let ((buf (current-buffer)))
6986 (if (not (one-window-p)) (delete-window))
6987 (kill-buffer buf)
6988 (org-agenda-maybe-reset-markers 'force)))
6989
6990 (defun org-agenda-exit ()
6991 "Exit agenda by removing the window or the buffer.
6992 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
6993 Org-mode buffers visited directly by the user will not be touched."
6994 (interactive)
6995 (org-release-buffers org-agenda-new-buffers)
6996 (setq org-agenda-new-buffers nil)
6997 (org-agenda-quit))
6998
6999 ;; FIXME: move this function.
7000 (defun org-save-all-org-buffers ()
7001 "Save all Org-mode buffers without user confirmation."
7002 (interactive)
7003 (message "Saving all Org-mode buffers...")
7004 (save-some-buffers t 'org-mode-p)
7005 (message "Saving all Org-mode buffers... done"))
7006
7007 (defun org-agenda-redo ()
7008 "Rebuild Agenda.
7009 When this is the global TODO list, a prefix argument will be interpreted."
7010 (interactive)
7011 (message "Rebuilding agenda buffer...")
7012 (eval org-agenda-redo-command)
7013 (message "Rebuilding agenda buffer...done"))
7014
7015 (defun org-agenda-goto-today ()
7016 "Go to today."
7017 (interactive)
7018 (org-agenda-check-type t 'timeline 'agenda)
7019 (if (boundp 'starting-day)
7020 (let ((cmd (car org-agenda-redo-command))
7021 (iall (nth 1 org-agenda-redo-command))
7022 (nday (nth 3 org-agenda-redo-command))
7023 (keep (nth 4 org-agenda-redo-command)))
7024 (eval (list cmd iall nil nday keep)))
7025 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
7026 (point-min)))))
7027
7028 (defun org-agenda-later (arg)
7029 "Go forward in time by `org-agenda-ndays' days.
7030 With prefix ARG, go forward that many times `org-agenda-ndays'."
7031 (interactive "p")
7032 (org-agenda-check-type t 'agenda)
7033 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
7034 (+ starting-day (* arg org-agenda-ndays)) nil t))
7035
7036 (defun org-agenda-earlier (arg)
7037 "Go back in time by `org-agenda-ndays' days.
7038 With prefix ARG, go back that many times `org-agenda-ndays'."
7039 (interactive "p")
7040 (org-agenda-check-type t 'agenda)
7041 (org-agenda-list (if (boundp 'include-all-loc) include-all-loc nil)
7042 (- starting-day (* arg org-agenda-ndays)) nil t))
7043
7044 (defun org-agenda-week-view ()
7045 "Switch to weekly view for agenda."
7046 (interactive)
7047 (org-agenda-check-type t 'agenda)
7048 (setq org-agenda-ndays 7)
7049 (org-agenda-list include-all-loc
7050 (or (get-text-property (point) 'day)
7051 starting-day)
7052 nil t)
7053 (org-agenda-set-mode-name)
7054 (message "Switched to week view"))
7055
7056 (defun org-agenda-day-view ()
7057 "Switch to daily view for agenda."
7058 (interactive)
7059 (org-agenda-check-type t 'agenda)
7060 (setq org-agenda-ndays 1)
7061 (org-agenda-list include-all-loc
7062 (or (get-text-property (point) 'day)
7063 starting-day)
7064 nil t)
7065 (org-agenda-set-mode-name)
7066 (message "Switched to day view"))
7067
7068 (defun org-agenda-next-date-line (&optional arg)
7069 "Jump to the next line indicating a date in agenda buffer."
7070 (interactive "p")
7071 (org-agenda-check-type t 'agenda 'timeline)
7072 (beginning-of-line 1)
7073 (if (looking-at "^\\S-") (forward-char 1))
7074 (if (not (re-search-forward "^\\S-" nil t arg))
7075 (progn
7076 (backward-char 1)
7077 (error "No next date after this line in this buffer")))
7078 (goto-char (match-beginning 0)))
7079
7080 (defun org-agenda-previous-date-line (&optional arg)
7081 "Jump to the previous line indicating a date in agenda buffer."
7082 (interactive "p")
7083 (org-agenda-check-type t 'agenda 'timeline)
7084 (beginning-of-line 1)
7085 (if (not (re-search-backward "^\\S-" nil t arg))
7086 (error "No previous date before this line in this buffer")))
7087
7088 ;; Initialize the highlight
7089 (defvar org-hl (org-make-overlay 1 1))
7090 (org-overlay-put org-hl 'face 'highlight)
7091
7092 (defun org-highlight (begin end &optional buffer)
7093 "Highlight a region with overlay."
7094 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
7095 org-hl begin end (or buffer (current-buffer))))
7096
7097 (defun org-unhighlight ()
7098 "Detach overlay INDEX."
7099 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
7100
7101
7102 (defun org-agenda-follow-mode ()
7103 "Toggle follow mode in an agenda buffer."
7104 (interactive)
7105 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
7106 (org-agenda-set-mode-name)
7107 (message "Follow mode is %s"
7108 (if org-agenda-follow-mode "on" "off")))
7109
7110 (defun org-agenda-log-mode ()
7111 "Toggle log mode in an agenda buffer."
7112 (interactive)
7113 (org-agenda-check-type t 'agenda 'timeline)
7114 (setq org-agenda-show-log (not org-agenda-show-log))
7115 (org-agenda-set-mode-name)
7116 (org-agenda-redo)
7117 (message "Log mode is %s"
7118 (if org-agenda-show-log "on" "off")))
7119
7120 (defun org-agenda-toggle-diary ()
7121 "Toggle diary inclusion in an agenda buffer."
7122 (interactive)
7123 (org-agenda-check-type t 'agenda)
7124 (setq org-agenda-include-diary (not org-agenda-include-diary))
7125 (org-agenda-redo)
7126 (org-agenda-set-mode-name)
7127 (message "Diary inclusion turned %s"
7128 (if org-agenda-include-diary "on" "off")))
7129
7130 (defun org-agenda-toggle-time-grid ()
7131 "Toggle time grid in an agenda buffer."
7132 (interactive)
7133 (org-agenda-check-type t 'agenda)
7134 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
7135 (org-agenda-redo)
7136 (org-agenda-set-mode-name)
7137 (message "Time-grid turned %s"
7138 (if org-agenda-use-time-grid "on" "off")))
7139
7140 (defun org-agenda-set-mode-name ()
7141 "Set the mode name to indicate all the small mode settings."
7142 (setq mode-name
7143 (concat "Org-Agenda"
7144 (if (equal org-agenda-ndays 1) " Day" "")
7145 (if (equal org-agenda-ndays 7) " Week" "")
7146 (if org-agenda-follow-mode " Follow" "")
7147 (if org-agenda-include-diary " Diary" "")
7148 (if org-agenda-use-time-grid " Grid" "")
7149 (if org-agenda-show-log " Log" "")))
7150 (force-mode-line-update))
7151
7152 (defun org-agenda-post-command-hook ()
7153 (and (eolp) (not (bolp)) (backward-char 1))
7154 (if (and org-agenda-follow-mode
7155 (get-text-property (point) 'org-marker))
7156 (org-agenda-show)))
7157
7158 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
7159
7160 (defun org-get-entries-from-diary (date)
7161 "Get the (Emacs Calendar) diary entries for DATE."
7162 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
7163 (diary-display-hook '(fancy-diary-display))
7164 (list-diary-entries-hook
7165 (cons 'org-diary-default-entry list-diary-entries-hook))
7166 (diary-file-name-prefix-function nil) ; turn this feature off
7167 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
7168 entries
7169 (org-disable-agenda-to-diary t))
7170 (save-excursion
7171 (save-window-excursion
7172 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
7173 (if (not (get-buffer fancy-diary-buffer))
7174 (setq entries nil)
7175 (with-current-buffer fancy-diary-buffer
7176 (setq buffer-read-only nil)
7177 (if (= (point-max) 1)
7178 ;; No entries
7179 (setq entries nil)
7180 ;; Omit the date and other unnecessary stuff
7181 (org-agenda-cleanup-fancy-diary)
7182 ;; Add prefix to each line and extend the text properties
7183 (if (= (point-max) 1)
7184 (setq entries nil)
7185 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
7186 (set-buffer-modified-p nil)
7187 (kill-buffer fancy-diary-buffer)))
7188 (when entries
7189 (setq entries (org-split-string entries "\n"))
7190 (setq entries
7191 (mapcar
7192 (lambda (x)
7193 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
7194 ;; Extend the text properties to the beginning of the line
7195 (org-add-props x (text-properties-at (1- (length x)) x)))
7196 entries)))))
7197
7198 (defun org-agenda-cleanup-fancy-diary ()
7199 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
7200 This gets rid of the date, the underline under the date, and
7201 the dummy entry installed by `org-mode' to ensure non-empty diary for each
7202 date. It also removes lines that contain only whitespace."
7203 (goto-char (point-min))
7204 (if (looking-at ".*?:[ \t]*")
7205 (progn
7206 (replace-match "")
7207 (re-search-forward "\n=+$" nil t)
7208 (replace-match "")
7209 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
7210 (re-search-forward "\n=+$" nil t)
7211 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
7212 (goto-char (point-min))
7213 (while (re-search-forward "^ +\n" nil t)
7214 (replace-match ""))
7215 (goto-char (point-min))
7216 (if (re-search-forward "^Org-mode dummy\n?" nil t)
7217 (replace-match "")))
7218
7219 ;; Make sure entries from the diary have the right text properties.
7220 (eval-after-load "diary-lib"
7221 '(if (boundp 'diary-modify-entry-list-string-function)
7222 ;; We can rely on the hook, nothing to do
7223 nil
7224 ;; Hook not avaiable, must use advice to make this work
7225 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
7226 "Make the position visible."
7227 (if (and org-disable-agenda-to-diary ;; called from org-agenda
7228 (stringp string)
7229 buffer-file-name)
7230 (setq string (org-modify-diary-entry-string string))))))
7231
7232 (defun org-modify-diary-entry-string (string)
7233 "Add text properties to string, allowing org-mode to act on it."
7234 (org-add-props string nil
7235 'mouse-face 'highlight
7236 'keymap org-agenda-keymap
7237 'help-echo (format "mouse-2 or RET jump to diary file %s"
7238 (abbreviate-file-name buffer-file-name))
7239 'org-agenda-diary-link t
7240 'org-marker (org-agenda-new-marker (point-at-bol))))
7241
7242 (defun org-diary-default-entry ()
7243 "Add a dummy entry to the diary.
7244 Needed to avoid empty dates which mess up holiday display."
7245 ;; Catch the error if dealing with the new add-to-diary-alist
7246 (when org-disable-agenda-to-diary
7247 (condition-case nil
7248 (add-to-diary-list original-date "Org-mode dummy" "")
7249 (error
7250 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
7251
7252 (defun org-cycle-agenda-files ()
7253 "Cycle through the files in `org-agenda-files'.
7254 If the current buffer visits an agenda file, find the next one in the list.
7255 If the current buffer does not, find the first agenda file."
7256 (interactive)
7257 (let* ((fs (org-agenda-files t))
7258 (files (append fs (list (car fs))))
7259 (tcf (if buffer-file-name (file-truename buffer-file-name)))
7260 file)
7261 (unless files (error "No agenda files"))
7262 (catch 'exit
7263 (while (setq file (pop files))
7264 (if (equal (file-truename file) tcf)
7265 (when (car files)
7266 (find-file (car files))
7267 (throw 'exit t))))
7268 (find-file (car fs)))))
7269
7270 (defun org-agenda-file-to-end ()
7271 "Move/add the current file to the end of the agenda file list.
7272 If the file is not present in the list, it is appended to the list. If it is
7273 present, it is moved there."
7274 (interactive)
7275 (org-agenda-file-to-front 'to-end))
7276
7277 (defun org-agenda-file-to-front (&optional to-end)
7278 "Move/add the current file to the top of the agenda file list.
7279 If the file is not present in the list, it is added to the front. If it is
7280 present, it is moved there. With optional argument TO-END, add/move to the
7281 end of the list."
7282 (interactive "P")
7283 (let ((file-alist (mapcar (lambda (x)
7284 (cons (file-truename x) x))
7285 (org-agenda-files t)))
7286 (ctf (file-truename buffer-file-name))
7287 x had)
7288 (setq x (assoc ctf file-alist) had x)
7289
7290 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
7291 (if to-end
7292 (setq file-alist (append (delq x file-alist) (list x)))
7293 (setq file-alist (cons x (delq x file-alist))))
7294 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
7295 (org-install-agenda-files-menu)
7296 (message "File %s to %s of agenda file list"
7297 (if had "moved" "added") (if to-end "end" "front"))))
7298
7299 (defun org-remove-file (&optional file)
7300 "Remove current file from the list of files in variable `org-agenda-files'.
7301 These are the files which are being checked for agenda entries.
7302 Optional argument FILE means, use this file instead of the current."
7303 (interactive)
7304 (let* ((file (or file buffer-file-name))
7305 (true-file (file-truename file))
7306 (afile (abbreviate-file-name file))
7307 (files (delq nil (mapcar
7308 (lambda (x)
7309 (if (equal true-file
7310 (file-truename x))
7311 nil x))
7312 (org-agenda-files t)))))
7313 (if (not (= (length files) (length (org-agenda-files t))))
7314 (progn
7315 (org-store-new-agenda-file-list files)
7316 (org-install-agenda-files-menu)
7317 (message "Removed file: %s" afile))
7318 (message "File was not in list: %s" afile))))
7319
7320 (defun org-file-menu-entry (file)
7321 (vector file (list 'find-file file) t))
7322
7323 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
7324 "Return a list of all relevant day numbers from BEG to END buffer positions.
7325 If NO-RANGES is non-nil, include only the start and end dates of a range,
7326 not every single day in the range. If FORCE-TODAY is non-nil, make
7327 sure that TODAY is included in the list. If INACTIVE is non-nil, also
7328 inactive time stamps (those in square brackets) are included.
7329 When EMPTY is non-nil, also include days without any entries."
7330 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
7331 dates dates1 date day day1 day2 ts1 ts2)
7332 (if force-today
7333 (setq dates (list (time-to-days (current-time)))))
7334 (save-excursion
7335 (goto-char beg)
7336 (while (re-search-forward re end t)
7337 (setq day (time-to-days (org-time-string-to-time
7338 (substring (match-string 1) 0 10))))
7339 (or (memq day dates) (push day dates)))
7340 (unless no-ranges
7341 (goto-char beg)
7342 (while (re-search-forward org-tr-regexp end t)
7343 (setq ts1 (substring (match-string 1) 0 10)
7344 ts2 (substring (match-string 2) 0 10)
7345 day1 (time-to-days (org-time-string-to-time ts1))
7346 day2 (time-to-days (org-time-string-to-time ts2)))
7347 (while (< (setq day1 (1+ day1)) day2)
7348 (or (memq day1 dates) (push day1 dates)))))
7349 (setq dates (sort dates '<))
7350 (when empty
7351 (while (setq day (pop dates))
7352 (setq day2 (car dates))
7353 (push day dates1)
7354 (when (and day2 empty)
7355 (if (or (eq empty t)
7356 (and (numberp empty) (<= (- day2 day) empty)))
7357 (while (< (setq day (1+ day)) day2)
7358 (push (list day) dates1))
7359 (push (cons :omitted (- day2 day)) dates1))))
7360 (setq dates (nreverse dates1)))
7361 dates)))
7362
7363 ;;;###autoload
7364 (defun org-diary (&rest args)
7365 "Return diary information from org-files.
7366 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
7367 It accesses org files and extracts information from those files to be
7368 listed in the diary. The function accepts arguments specifying what
7369 items should be listed. The following arguments are allowed:
7370
7371 :timestamp List the headlines of items containing a date stamp or
7372 date range matching the selected date. Deadlines will
7373 also be listed, on the expiration day.
7374
7375 :deadline List any deadlines past due, or due within
7376 `org-deadline-warning-days'. The listing occurs only
7377 in the diary for *today*, not at any other date. If
7378 an entry is marked DONE, it is no longer listed.
7379
7380 :scheduled List all items which are scheduled for the given date.
7381 The diary for *today* also contains items which were
7382 scheduled earlier and are not yet marked DONE.
7383
7384 :todo List all TODO items from the org-file. This may be a
7385 long list - so this is not turned on by default.
7386 Like deadlines, these entries only show up in the
7387 diary for *today*, not at any other date.
7388
7389 The call in the diary file should look like this:
7390
7391 &%%(org-diary) ~/path/to/some/orgfile.org
7392
7393 Use a separate line for each org file to check. Or, if you omit the file name,
7394 all files listed in `org-agenda-files' will be checked automatically:
7395
7396 &%%(org-diary)
7397
7398 If you don't give any arguments (as in the example above), the default
7399 arguments (:deadline :scheduled :timestamp) are used. So the example above may
7400 also be written as
7401
7402 &%%(org-diary :deadline :timestamp :scheduled)
7403
7404 The function expects the lisp variables `entry' and `date' to be provided
7405 by the caller, because this is how the calendar works. Don't use this
7406 function from a program - use `org-agenda-get-day-entries' instead."
7407 (org-agenda-maybe-reset-markers)
7408 (org-compile-prefix-format org-agenda-prefix-format)
7409 (setq args (or args '(:deadline :scheduled :timestamp)))
7410 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
7411 (list entry)
7412 (org-agenda-files t)))
7413 file rtn results)
7414 ;; If this is called during org-agenda, don't return any entries to
7415 ;; the calendar. Org Agenda will list these entries itself.
7416 (if org-disable-agenda-to-diary (setq files nil))
7417 (while (setq file (pop files))
7418 (setq rtn (apply 'org-agenda-get-day-entries file date args))
7419 (setq results (append results rtn)))
7420 (if results
7421 (concat (org-finalize-agenda-entries results) "\n"))))
7422 (defvar org-category-table nil)
7423 (defun org-get-category-table ()
7424 "Get the table of categories and positions in current buffer."
7425 (let (tbl)
7426 (save-excursion
7427 (goto-char (point-min))
7428 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
7429 (push (cons (point) (org-trim (match-string 2))) tbl)))
7430 tbl))
7431 (defun org-get-category (&optional pos)
7432 "Get the category applying to position POS."
7433 (if (not org-category-table)
7434 (cond
7435 ((null org-category)
7436 (setq org-category
7437 (if buffer-file-name
7438 (file-name-sans-extension
7439 (file-name-nondirectory buffer-file-name))
7440 "???")))
7441 ((symbolp org-category) (symbol-name org-category))
7442 (t org-category))
7443 (let ((tbl org-category-table)
7444 (pos (or pos (point))))
7445 (while (and tbl (> (caar tbl) pos))
7446 (pop tbl))
7447 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
7448 org-category-table))))))
7449
7450 (defun org-agenda-get-day-entries (file date &rest args)
7451 "Does the work for `org-diary' and `org-agenda'.
7452 FILE is the path to a file to be checked for entries. DATE is date like
7453 the one returned by `calendar-current-date'. ARGS are symbols indicating
7454 which kind of entries should be extracted. For details about these, see
7455 the documentation of `org-diary'."
7456 (setq args (or args '(:deadline :scheduled :timestamp)))
7457 (let* ((org-startup-with-deadline-check nil)
7458 (org-startup-folded nil)
7459 (org-startup-align-all-tables nil)
7460 (buffer (if (file-exists-p file)
7461 (org-get-agenda-file-buffer file)
7462 (error "No such file %s" file)))
7463 arg results rtn)
7464 (if (not buffer)
7465 ;; If file does not exist, make sure an error message ends up in diary
7466 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7467 (with-current-buffer buffer
7468 (unless (org-mode-p)
7469 (error "Agenda file %s is not in `org-mode'" file))
7470 (setq org-category-table (org-get-category-table))
7471 (let ((case-fold-search nil))
7472 (save-excursion
7473 (save-restriction
7474 (if org-respect-restriction
7475 (if (org-region-active-p)
7476 ;; Respect a region to restrict search
7477 (narrow-to-region (region-beginning) (region-end)))
7478 ;; If we work for the calendar or many files,
7479 ;; get rid of any restriction
7480 (widen))
7481 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
7482 (while (setq arg (pop args))
7483 (cond
7484 ((and (eq arg :todo)
7485 (equal date (calendar-current-date)))
7486 (setq rtn (org-agenda-get-todos))
7487 (setq results (append results rtn)))
7488 ((eq arg :timestamp)
7489 (setq rtn (org-agenda-get-blocks))
7490 (setq results (append results rtn))
7491 (setq rtn (org-agenda-get-timestamps))
7492 (setq results (append results rtn)))
7493 ((eq arg :scheduled)
7494 (setq rtn (org-agenda-get-scheduled))
7495 (setq results (append results rtn)))
7496 ((eq arg :closed)
7497 (setq rtn (org-agenda-get-closed))
7498 (setq results (append results rtn)))
7499 ((and (eq arg :deadline)
7500 (equal date (calendar-current-date)))
7501 (setq rtn (org-agenda-get-deadlines))
7502 (setq results (append results rtn))))))))
7503 results))))
7504
7505 (defun org-entry-is-done-p ()
7506 "Is the current entry marked DONE?"
7507 (save-excursion
7508 (and (re-search-backward "[\r\n]\\*" nil t)
7509 (looking-at org-nl-done-regexp))))
7510
7511 (defun org-at-date-range-p ()
7512 "Is the cursor inside a date range?"
7513 (interactive)
7514 (save-excursion
7515 (catch 'exit
7516 (let ((pos (point)))
7517 (skip-chars-backward "^<\r\n")
7518 (skip-chars-backward "<")
7519 (and (looking-at org-tr-regexp)
7520 (>= (match-end 0) pos)
7521 (throw 'exit t))
7522 (skip-chars-backward "^<\r\n")
7523 (skip-chars-backward "<")
7524 (and (looking-at org-tr-regexp)
7525 (>= (match-end 0) pos)
7526 (throw 'exit t)))
7527 nil)))
7528
7529 (defun org-agenda-get-todos ()
7530 "Return the TODO information for agenda display."
7531 (let* ((props (list 'face nil
7532 'done-face 'org-done
7533 'org-not-done-regexp org-not-done-regexp
7534 'mouse-face 'highlight
7535 'keymap org-agenda-keymap
7536 'help-echo
7537 (format "mouse-2 or RET jump to org file %s"
7538 (abbreviate-file-name buffer-file-name))))
7539 (regexp (concat "[\n\r]\\*+ *\\("
7540 (if org-select-this-todo-keyword
7541 (concat "\\<\\(" org-select-this-todo-keyword
7542 "\\)\\>")
7543 org-not-done-regexp)
7544 "[^\n\r]*\\)"))
7545 (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
7546 marker priority category tags
7547 ee txt)
7548 (goto-char (point-min))
7549 (while (re-search-forward regexp nil t)
7550 (catch :skip
7551 (when (and org-agenda-todo-ignore-scheduled
7552 (looking-at sched-re))
7553 ;; FIXME: the following test also happens below, but we need it here
7554 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
7555 (throw :skip nil))
7556 (org-agenda-skip)
7557 (goto-char (match-beginning 1))
7558 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
7559 category (org-get-category)
7560 tags (org-get-tags-at (point))
7561 txt (org-format-agenda-item "" (match-string 1) category tags)
7562 priority
7563 (+ (org-get-priority txt)
7564 (if org-todo-kwd-priority-p
7565 (- org-todo-kwd-max-priority -2
7566 (length
7567 (member (match-string 2) org-todo-keywords)))
7568 1)))
7569 (org-add-props txt props
7570 'org-marker marker 'org-hd-marker marker
7571 'priority priority 'category category)
7572 (push txt ee)
7573 (if org-agenda-todo-list-sublevels
7574 (goto-char (match-end 1))
7575 (org-end-of-subtree 'invisible))))
7576 (nreverse ee)))
7577
7578 (defconst org-agenda-no-heading-message
7579 "No heading for this item in buffer or region.")
7580
7581 (defun org-agenda-get-timestamps ()
7582 "Return the date stamp information for agenda display."
7583 (let* ((props (list 'face nil
7584 'org-not-done-regexp org-not-done-regexp
7585 'mouse-face 'highlight
7586 'keymap org-agenda-keymap
7587 'help-echo
7588 (format "mouse-2 or RET jump to org file %s"
7589 (abbreviate-file-name buffer-file-name))))
7590 (regexp (regexp-quote
7591 (substring
7592 (format-time-string
7593 (car org-time-stamp-formats)
7594 (apply 'encode-time ; DATE bound by calendar
7595 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7596 0 11)))
7597 marker hdmarker deadlinep scheduledp donep tmp priority category
7598 ee txt timestr tags)
7599 (goto-char (point-min))
7600 (while (re-search-forward regexp nil t)
7601 (catch :skip
7602 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
7603 (org-agenda-skip)
7604 (setq marker (org-agenda-new-marker (match-beginning 0))
7605 category (org-get-category (match-beginning 0))
7606 tmp (buffer-substring (max (point-min)
7607 (- (match-beginning 0)
7608 org-ds-keyword-length))
7609 (match-beginning 0))
7610 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7611 deadlinep (string-match org-deadline-regexp tmp)
7612 scheduledp (string-match org-scheduled-regexp tmp)
7613 donep (org-entry-is-done-p))
7614 (if (string-match ">" timestr)
7615 ;; substring should only run to end of time stamp
7616 (setq timestr (substring timestr 0 (match-end 0))))
7617 (save-excursion
7618 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7619 (progn
7620 (goto-char (match-end 1))
7621 (setq hdmarker (org-agenda-new-marker)
7622 tags (org-get-tags-at))
7623 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7624 (setq txt (org-format-agenda-item
7625 (format "%s%s"
7626 (if deadlinep "Deadline: " "")
7627 (if scheduledp "Scheduled: " ""))
7628 (match-string 1) category tags timestr)))
7629 (setq txt org-agenda-no-heading-message))
7630 (setq priority (org-get-priority txt))
7631 (org-add-props txt props
7632 'org-marker marker 'org-hd-marker hdmarker)
7633 (if deadlinep
7634 (org-add-props txt nil
7635 'face (if donep 'org-done 'org-warning)
7636 'undone-face 'org-warning 'done-face 'org-done
7637 'category category 'priority (+ 100 priority))
7638 (if scheduledp
7639 (org-add-props txt nil
7640 'face 'org-scheduled-today
7641 'undone-face 'org-scheduled-today 'done-face 'org-done
7642 'category category 'priority (+ 99 priority))
7643 (org-add-props txt nil 'priority priority 'category category)))
7644 (push txt ee))
7645 (outline-next-heading)))
7646 (nreverse ee)))
7647
7648 (defun org-agenda-get-closed ()
7649 "Return the logged TODO entries for agenda display."
7650 (let* ((props (list 'mouse-face 'highlight
7651 'org-not-done-regexp org-not-done-regexp
7652 'keymap org-agenda-keymap
7653 'help-echo
7654 (format "mouse-2 or RET jump to org file %s"
7655 (abbreviate-file-name buffer-file-name))))
7656 (regexp (concat
7657 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
7658 (regexp-quote
7659 (substring
7660 (format-time-string
7661 (car org-time-stamp-formats)
7662 (apply 'encode-time ; DATE bound by calendar
7663 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7664 1 11))))
7665 marker hdmarker priority category tags closedp
7666 ee txt timestr)
7667 (goto-char (point-min))
7668 (while (re-search-forward regexp nil t)
7669 (catch :skip
7670 (org-agenda-skip)
7671 (setq marker (org-agenda-new-marker (match-beginning 0))
7672 closedp (equal (match-string 1) org-closed-string)
7673 category (org-get-category (match-beginning 0))
7674 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7675 ;; donep (org-entry-is-done-p)
7676 )
7677 (if (string-match "\\]" timestr)
7678 ;; substring should only run to end of time stamp
7679 (setq timestr (substring timestr 0 (match-end 0))))
7680 (save-excursion
7681 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7682 (progn
7683 (goto-char (match-end 1))
7684 (setq hdmarker (org-agenda-new-marker)
7685 tags (org-get-tags-at))
7686 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7687 (setq txt (org-format-agenda-item
7688 (if closedp "Closed: " "Clocked: ")
7689 (match-string 1) category tags timestr)))
7690 (setq txt org-agenda-no-heading-message))
7691 (setq priority 100000)
7692 (org-add-props txt props
7693 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
7694 'priority priority 'category category
7695 'undone-face 'org-warning 'done-face 'org-done)
7696 (push txt ee))
7697 (outline-next-heading)))
7698 (nreverse ee)))
7699
7700 (defun org-agenda-get-deadlines ()
7701 "Return the deadline information for agenda display."
7702 (let* ((wdays org-deadline-warning-days)
7703 (props (list 'mouse-face 'highlight
7704 'org-not-done-regexp org-not-done-regexp
7705 'keymap org-agenda-keymap
7706 'help-echo
7707 (format "mouse-2 or RET jump to org file %s"
7708 (abbreviate-file-name buffer-file-name))))
7709 (regexp org-deadline-time-regexp)
7710 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7711 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7712 d2 diff pos pos1 category tags
7713 ee txt head face)
7714 (goto-char (point-min))
7715 (while (re-search-forward regexp nil t)
7716 (catch :skip
7717 (org-agenda-skip)
7718 (setq pos (1- (match-beginning 1))
7719 d2 (time-to-days
7720 (org-time-string-to-time (match-string 1)))
7721 diff (- d2 d1))
7722 ;; When to show a deadline in the calendar:
7723 ;; If the expiration is within wdays warning time.
7724 ;; Past-due deadlines are only shown on the current date
7725 (if (and (< diff wdays) todayp (not (= diff 0)))
7726 (save-excursion
7727 (setq category (org-get-category))
7728 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7729 (progn
7730 (goto-char (match-end 0))
7731 (setq pos1 (match-end 1))
7732 (setq tags (org-get-tags-at pos1))
7733 (setq head (buffer-substring-no-properties
7734 (point)
7735 (progn (skip-chars-forward "^\r\n")
7736 (point))))
7737 (if (string-match org-looking-at-done-regexp head)
7738 (setq txt nil)
7739 (setq txt (org-format-agenda-item
7740 (format "In %3d d.: " diff) head category tags))))
7741 (setq txt org-agenda-no-heading-message))
7742 (when txt
7743 (setq face (cond ((<= diff 0) 'org-warning)
7744 ((<= diff 5) 'org-upcoming-deadline)
7745 (t nil)))
7746 (org-add-props txt props
7747 'org-marker (org-agenda-new-marker pos)
7748 'org-hd-marker (org-agenda-new-marker pos1)
7749 'priority (+ (- 10 diff) (org-get-priority txt))
7750 'category category
7751 'face face 'undone-face face 'done-face 'org-done)
7752 (push txt ee))))))
7753 ee))
7754
7755 (defun org-agenda-get-scheduled ()
7756 "Return the scheduled information for agenda display."
7757 (let* ((props (list 'face 'org-scheduled-previously
7758 'org-not-done-regexp org-not-done-regexp
7759 'undone-face 'org-scheduled-previously
7760 'done-face 'org-done
7761 'mouse-face 'highlight
7762 'keymap org-agenda-keymap
7763 'help-echo
7764 (format "mouse-2 or RET jump to org file %s"
7765 (abbreviate-file-name buffer-file-name))))
7766 (regexp org-scheduled-time-regexp)
7767 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7768 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7769 d2 diff pos pos1 category tags
7770 ee txt head)
7771 (goto-char (point-min))
7772 (while (re-search-forward regexp nil t)
7773 (catch :skip
7774 (org-agenda-skip)
7775 (setq pos (1- (match-beginning 1))
7776 d2 (time-to-days
7777 (org-time-string-to-time (match-string 1)))
7778 diff (- d2 d1))
7779 ;; When to show a scheduled item in the calendar:
7780 ;; If it is on or past the date.
7781 (if (and (< diff 0) todayp)
7782 (save-excursion
7783 (setq category (org-get-category))
7784 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7785 (progn
7786 (goto-char (match-end 0))
7787 (setq pos1 (match-end 1))
7788 (setq tags (org-get-tags-at))
7789 (setq head (buffer-substring-no-properties
7790 (point)
7791 (progn (skip-chars-forward "^\r\n") (point))))
7792 (if (string-match org-looking-at-done-regexp head)
7793 (setq txt nil)
7794 (setq txt (org-format-agenda-item
7795 (format "Sched.%2dx: " (- 1 diff)) head
7796 category tags))))
7797 (setq txt org-agenda-no-heading-message))
7798 (when txt
7799 (org-add-props txt props
7800 'org-marker (org-agenda-new-marker pos)
7801 'org-hd-marker (org-agenda-new-marker pos1)
7802 'priority (+ (- 5 diff) (org-get-priority txt))
7803 'category category)
7804 (push txt ee))))))
7805 ee))
7806
7807 (defun org-agenda-get-blocks ()
7808 "Return the date-range information for agenda display."
7809 (let* ((props (list 'face nil
7810 'org-not-done-regexp org-not-done-regexp
7811 'mouse-face 'highlight
7812 'keymap org-agenda-keymap
7813 'help-echo
7814 (format "mouse-2 or RET jump to org file %s"
7815 (abbreviate-file-name buffer-file-name))))
7816 (regexp org-tr-regexp)
7817 (d0 (calendar-absolute-from-gregorian date))
7818 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
7819 (goto-char (point-min))
7820 (while (re-search-forward regexp nil t)
7821 (catch :skip
7822 (org-agenda-skip)
7823 (setq pos (point))
7824 (setq timestr (match-string 0)
7825 s1 (match-string 1)
7826 s2 (match-string 2)
7827 d1 (time-to-days (org-time-string-to-time s1))
7828 d2 (time-to-days (org-time-string-to-time s2)))
7829 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
7830 ;; Only allow days between the limits, because the normal
7831 ;; date stamps will catch the limits.
7832 (save-excursion
7833 (setq marker (org-agenda-new-marker (point)))
7834 (setq category (org-get-category))
7835 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7836 (progn
7837 (setq hdmarker (org-agenda-new-marker (match-end 1)))
7838 (goto-char (match-end 1))
7839 (setq tags (org-get-tags-at))
7840 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7841 (setq txt (org-format-agenda-item
7842 (format (if (= d1 d2) "" "(%d/%d): ")
7843 (1+ (- d0 d1)) (1+ (- d2 d1)))
7844 (match-string 1) category tags
7845 (if (= d0 d1) timestr))))
7846 (setq txt org-agenda-no-heading-message))
7847 (org-add-props txt props
7848 'org-marker marker 'org-hd-marker hdmarker
7849 'priority (org-get-priority txt) 'category category)
7850 (push txt ee)))
7851 (goto-char pos)))
7852 ; (outline-next-heading))) ;FIXME: correct to be removed??????
7853 ;; Sort the entries by expiration date.
7854 (nreverse ee)))
7855
7856 (defconst org-plain-time-of-day-regexp
7857 (concat
7858 "\\(\\<[012]?[0-9]"
7859 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7860 "\\(--?"
7861 "\\(\\<[012]?[0-9]"
7862 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
7863 "\\)?")
7864 "Regular expression to match a plain time or time range.
7865 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
7866 groups carry important information:
7867 0 the full match
7868 1 the first time, range or not
7869 8 the second time, if it is a range.")
7870
7871 (defconst org-stamp-time-of-day-regexp
7872 (concat
7873 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
7874 "\\([012][0-9]:[0-5][0-9]\\)>"
7875 "\\(--?"
7876 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
7877 "Regular expression to match a timestamp time or time range.
7878 After a match, the following groups carry important information:
7879 0 the full match
7880 1 date plus weekday, for backreferencing to make sure both times on same day
7881 2 the first time, range or not
7882 4 the second time, if it is a range.")
7883
7884 (defvar org-prefix-has-time nil
7885 "A flag, set by `org-compile-prefix-format'.
7886 The flag is set if the currently compiled format contains a `%t'.")
7887 (defvar org-prefix-has-tag nil
7888 "A flag, set by `org-compile-prefix-format'.
7889 The flag is set if the currently compiled format contains a `%T'.")
7890
7891 (defun org-format-agenda-item (extra txt &optional category tags dotime noprefix)
7892 "Format TXT to be inserted into the agenda buffer.
7893 In particular, it adds the prefix and corresponding text properties. EXTRA
7894 must be a string and replaces the `%s' specifier in the prefix format.
7895 CATEGORY (string, symbol or nil) may be used to overrule the default
7896 category taken from local variable or file name. It will replace the `%c'
7897 specifier in the format. DOTIME, when non-nil, indicates that a
7898 time-of-day should be extracted from TXT for sorting of this entry, and for
7899 the `%t' specifier in the format. When DOTIME is a string, this string is
7900 searched for a time before TXT is. NOPREFIX is a flag and indicates that
7901 only the correctly processes TXT should be returned - this is used by
7902 `org-agenda-change-all-lines'. TAG can be the tag of the headline."
7903 (save-match-data
7904 ;; Diary entries sometimes have extra whitespace at the beginning
7905 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
7906 (let* ((category (or category
7907 org-category
7908 (if buffer-file-name
7909 (file-name-sans-extension
7910 (file-name-nondirectory buffer-file-name))
7911 "")))
7912 (tag (if tags (nth (1- (length tags)) tags) ""))
7913 time ;; needed for the eval of the prefix format
7914 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
7915 (time-of-day (and dotime (org-get-time-of-day ts)))
7916 stamp plain s0 s1 s2 rtn)
7917 (when (and dotime time-of-day org-prefix-has-time)
7918 ;; Extract starting and ending time and move them to prefix
7919 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
7920 (setq plain (string-match org-plain-time-of-day-regexp ts)))
7921 (setq s0 (match-string 0 ts)
7922 s1 (match-string (if plain 1 2) ts)
7923 s2 (match-string (if plain 8 4) ts))
7924
7925 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
7926 ;; them, we might want to remove them there to avoid duplication.
7927 ;; The user can turn this off with a variable.
7928 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
7929 (string-match (concat (regexp-quote s0) " *") txt)
7930 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
7931 (= (match-beginning 0) 0)
7932 t))
7933 (setq txt (replace-match "" nil nil txt))))
7934 ;; Normalize the time(s) to 24 hour
7935 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
7936 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
7937
7938 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
7939 ;; Tags are in the string
7940 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
7941 (and org-agenda-remove-tags-when-in-prefix
7942 org-prefix-has-tag))
7943 (setq txt (replace-match "" t t txt))
7944 (setq txt (replace-match
7945 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
7946 (match-string 2 txt))
7947 t t txt))))
7948
7949 ;; Create the final string
7950 (if noprefix
7951 (setq rtn txt)
7952 ;; Prepare the variables needed in the eval of the compiled format
7953 (setq time (cond (s2 (concat s1 "-" s2))
7954 (s1 (concat s1 "......"))
7955 (t ""))
7956 extra (or extra "")
7957 category (if (symbolp category) (symbol-name category) category))
7958 ;; Evaluate the compiled format
7959 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
7960
7961 ;; And finally add the text properties
7962 (org-add-props rtn nil
7963 'category (downcase category) 'tags tags
7964 'prefix-length (- (length rtn) (length txt))
7965 'time-of-day time-of-day
7966 'dotime dotime))))
7967
7968 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
7969 (catch 'exit
7970 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
7971 ((and todayp (member 'today (car org-agenda-time-grid))))
7972 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
7973 ((member 'weekly (car org-agenda-time-grid)))
7974 (t (throw 'exit list)))
7975 (let* ((have (delq nil (mapcar
7976 (lambda (x) (get-text-property 1 'time-of-day x))
7977 list)))
7978 (string (nth 1 org-agenda-time-grid))
7979 (gridtimes (nth 2 org-agenda-time-grid))
7980 (req (car org-agenda-time-grid))
7981 (remove (member 'remove-match req))
7982 new time)
7983 (if (and (member 'require-timed req) (not have))
7984 ;; don't show empty grid
7985 (throw 'exit list))
7986 (while (setq time (pop gridtimes))
7987 (unless (and remove (member time have))
7988 (setq time (int-to-string time))
7989 (push (org-format-agenda-item
7990 nil string "" nil
7991 (concat (substring time 0 -2) ":" (substring time -2)))
7992 new)
7993 (put-text-property
7994 1 (length (car new)) 'face 'org-time-grid (car new))))
7995 (if (member 'time-up org-agenda-sorting-strategy)
7996 (append new list)
7997 (append list new)))))
7998
7999 (defun org-compile-prefix-format (format)
8000 "Compile the prefix format into a Lisp form that can be evaluated.
8001 The resulting form is returned and stored in the variable
8002 `org-prefix-format-compiled'."
8003 (setq org-prefix-has-time nil org-prefix-has-tag nil)
8004 (let ((start 0) varform vars var (s format)e c f opt)
8005 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
8006 s start)
8007 (setq var (cdr (assoc (match-string 4 s)
8008 '(("c" . category) ("t" . time) ("s" . extra)
8009 ("T" . tag))))
8010 c (or (match-string 3 s) "")
8011 opt (match-beginning 1)
8012 start (1+ (match-beginning 0)))
8013 (if (equal var 'time) (setq org-prefix-has-time t))
8014 (if (equal var 'tag) (setq org-prefix-has-tag t))
8015 (setq f (concat "%" (match-string 2 s) "s"))
8016 (if opt
8017 (setq varform
8018 `(if (equal "" ,var)
8019 ""
8020 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
8021 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
8022 (setq s (replace-match "%s" t nil s))
8023 (push varform vars))
8024 (setq vars (nreverse vars))
8025 (setq org-prefix-format-compiled `(format ,s ,@vars))))
8026
8027 (defun org-get-time-of-day (s &optional string mod24)
8028 "Check string S for a time of day.
8029 If found, return it as a military time number between 0 and 2400.
8030 If not found, return nil.
8031 The optional STRING argument forces conversion into a 5 character wide string
8032 HH:MM."
8033 (save-match-data
8034 (when
8035 (or
8036 (string-match
8037 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
8038 (string-match
8039 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
8040 (let* ((h (string-to-number (match-string 1 s)))
8041 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
8042 (ampm (if (match-end 4) (downcase (match-string 4 s))))
8043 (am-p (equal ampm "am"))
8044 (h1 (cond ((not ampm) h)
8045 ((= h 12) (if am-p 0 12))
8046 (t (+ h (if am-p 0 12)))))
8047 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
8048 (mod h1 24) h1))
8049 (t0 (+ (* 100 h2) m))
8050 (t1 (concat (if (>= h1 24) "+" " ")
8051 (if (< t0 100) "0" "")
8052 (if (< t0 10) "0" "")
8053 (int-to-string t0))))
8054 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
8055
8056 (defun org-finalize-agenda-entries (list)
8057 "Sort and concatenate the agenda items."
8058 (setq list (mapcar 'org-agenda-highlight-todo list))
8059 (mapconcat 'identity (sort list 'org-entries-lessp) "\n"))
8060
8061 (defun org-agenda-highlight-todo (x)
8062 (let (re pl)
8063 (if (eq x 'line)
8064 (save-excursion
8065 (beginning-of-line 1)
8066 (setq re (get-text-property (point) 'org-not-done-regexp))
8067 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
8068 (and (looking-at (concat "[ \t]*" re))
8069 (add-text-properties (match-beginning 0) (match-end 0)
8070 '(face org-todo))))
8071 (setq re (get-text-property 0 'org-not-done-regexp x)
8072 pl (get-text-property 0 'prefix-length x))
8073 (and re (equal (string-match re x pl) pl)
8074 (add-text-properties (match-beginning 0) (match-end 0)
8075 '(face org-todo) x))
8076 x)))
8077
8078 (defsubst org-cmp-priority (a b)
8079 "Compare the priorities of string A and B."
8080 (let ((pa (or (get-text-property 1 'priority a) 0))
8081 (pb (or (get-text-property 1 'priority b) 0)))
8082 (cond ((> pa pb) +1)
8083 ((< pa pb) -1)
8084 (t nil))))
8085
8086 (defsubst org-cmp-category (a b)
8087 "Compare the string values of categories of strings A and B."
8088 (let ((ca (or (get-text-property 1 'category a) ""))
8089 (cb (or (get-text-property 1 'category b) "")))
8090 (cond ((string-lessp ca cb) -1)
8091 ((string-lessp cb ca) +1)
8092 (t nil))))
8093
8094 (defsubst org-cmp-time (a b)
8095 "Compare the time-of-day values of strings A and B."
8096 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
8097 (ta (or (get-text-property 1 'time-of-day a) def))
8098 (tb (or (get-text-property 1 'time-of-day b) def)))
8099 (cond ((< ta tb) -1)
8100 ((< tb ta) +1)
8101 (t nil))))
8102
8103 (defun org-entries-lessp (a b)
8104 "Predicate for sorting agenda entries."
8105 ;; The following variables will be used when the form is evaluated.
8106 (let* ((time-up (org-cmp-time a b))
8107 (time-down (if time-up (- time-up) nil))
8108 (priority-up (org-cmp-priority a b))
8109 (priority-down (if priority-up (- priority-up) nil))
8110 (category-up (org-cmp-category a b))
8111 (category-down (if category-up (- category-up) nil))
8112 (category-keep (if category-up +1 nil)))
8113 (cdr (assoc
8114 (eval (cons 'or org-agenda-sorting-strategy))
8115 '((-1 . t) (1 . nil) (nil . nil))))))
8116
8117 (defun org-agenda-show-priority ()
8118 "Show the priority of the current item.
8119 This priority is composed of the main priority given with the [#A] cookies,
8120 and by additional input from the age of a schedules or deadline entry."
8121 (interactive)
8122 (let* ((pri (get-text-property (point-at-bol) 'priority)))
8123 (message "Priority is %d" (if pri pri -1000))))
8124
8125 (defun org-agenda-show-tags ()
8126 "Show the tags applicable to the current item."
8127 (interactive)
8128 (let* ((tags (get-text-property (point-at-bol) 'tags)))
8129 (if tags
8130 (message "Tags are :%s:"
8131 (org-no-properties (mapconcat 'identity tags ":")))
8132 (message "No tags associated with this line"))))
8133
8134 (defun org-agenda-goto (&optional highlight)
8135 "Go to the Org-mode file which contains the item at point."
8136 (interactive)
8137 (let* ((marker (or (get-text-property (point) 'org-marker)
8138 (org-agenda-error)))
8139 (buffer (marker-buffer marker))
8140 (pos (marker-position marker)))
8141 (switch-to-buffer-other-window buffer)
8142 (widen)
8143 (goto-char pos)
8144 (when (org-mode-p)
8145 (org-show-hidden-entry)
8146 (save-excursion
8147 (and (outline-next-heading)
8148 (org-flag-heading nil)))) ; show the next heading
8149 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
8150
8151 (defun org-agenda-switch-to ()
8152 "Go to the Org-mode file which contains the item at point."
8153 (interactive)
8154 (let* ((marker (or (get-text-property (point) 'org-marker)
8155 (org-agenda-error)))
8156 (buffer (marker-buffer marker))
8157 (pos (marker-position marker)))
8158 (switch-to-buffer buffer)
8159 (delete-other-windows)
8160 (widen)
8161 (goto-char pos)
8162 (when (org-mode-p)
8163 (org-show-hidden-entry)
8164 (save-excursion
8165 (and (outline-next-heading)
8166 (org-flag-heading nil)))))) ; show the next heading
8167
8168 (defun org-agenda-goto-mouse (ev)
8169 "Go to the Org-mode file which contains the item at the mouse click."
8170 (interactive "e")
8171 (mouse-set-point ev)
8172 (org-agenda-goto))
8173
8174 (defun org-agenda-show ()
8175 "Display the Org-mode file which contains the item at point."
8176 (interactive)
8177 (let ((win (selected-window)))
8178 (org-agenda-goto t)
8179 (select-window win)))
8180
8181 (defun org-agenda-recenter (arg)
8182 "Display the Org-mode file which contains the item at point and recenter."
8183 (interactive "P")
8184 (let ((win (selected-window)))
8185 (org-agenda-goto t)
8186 (recenter arg)
8187 (select-window win)))
8188
8189 (defun org-agenda-show-mouse (ev)
8190 "Display the Org-mode file which contains the item at the mouse click."
8191 (interactive "e")
8192 (mouse-set-point ev)
8193 (org-agenda-show))
8194
8195 (defun org-agenda-check-no-diary ()
8196 "Check if the entry is a diary link and abort if yes."
8197 (if (get-text-property (point) 'org-agenda-diary-link)
8198 (org-agenda-error)))
8199
8200 (defun org-agenda-error ()
8201 (error "Command not allowed in this line"))
8202
8203 (defvar org-last-heading-marker (make-marker)
8204 "Marker pointing to the headline that last changed its TODO state
8205 by a remote command from the agenda.")
8206
8207 (defun org-agenda-todo (&optional arg)
8208 "Cycle TODO state of line at point, also in Org-mode file.
8209 This changes the line at point, all other lines in the agenda referring to
8210 the same tree node, and the headline of the tree node in the Org-mode file."
8211 (interactive "P")
8212 (org-agenda-check-no-diary)
8213 (let* ((col (current-column))
8214 (marker (or (get-text-property (point) 'org-marker)
8215 (org-agenda-error)))
8216 (buffer (marker-buffer marker))
8217 (pos (marker-position marker))
8218 (hdmarker (get-text-property (point) 'org-hd-marker))
8219 (buffer-read-only nil)
8220 newhead)
8221 (with-current-buffer buffer
8222 (widen)
8223 (goto-char pos)
8224 (org-show-hidden-entry)
8225 (save-excursion
8226 (and (outline-next-heading)
8227 (org-flag-heading nil))) ; show the next heading
8228 (org-todo arg)
8229 (and (bolp) (forward-char 1))
8230 (setq newhead (org-get-heading))
8231 (save-excursion
8232 (org-back-to-heading)
8233 (move-marker org-last-heading-marker (point))))
8234 (beginning-of-line 1)
8235 (save-excursion
8236 (org-agenda-change-all-lines newhead hdmarker 'fixface))
8237 (move-to-column col)))
8238
8239 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
8240 "Change all lines in the agenda buffer which match HDMARKER.
8241 The new content of the line will be NEWHEAD (as modified by
8242 `org-format-agenda-item'). HDMARKER is checked with
8243 `equal' against all `org-hd-marker' text properties in the file.
8244 If FIXFACE is non-nil, the face of each item is modified acording to
8245 the new TODO state."
8246 (let* (props m pl undone-face done-face finish new dotime cat tags)
8247 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
8248 (save-excursion
8249 (goto-char (point-max))
8250 (beginning-of-line 1)
8251 (while (not finish)
8252 (setq finish (bobp))
8253 (when (and (setq m (get-text-property (point) 'org-hd-marker))
8254 (equal m hdmarker))
8255 (setq props (text-properties-at (point))
8256 dotime (get-text-property (point) 'dotime)
8257 cat (get-text-property (point) 'category)
8258 tags (get-text-property (point) 'tags)
8259 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
8260 pl (get-text-property (point) 'prefix-length)
8261 undone-face (get-text-property (point) 'undone-face)
8262 done-face (get-text-property (point) 'done-face))
8263 (move-to-column pl)
8264 (if (looking-at ".*")
8265 (progn
8266 (replace-match new t t)
8267 (beginning-of-line 1)
8268 (add-text-properties (point-at-bol) (point-at-eol) props)
8269 (when fixface
8270 (add-text-properties
8271 (point-at-bol) (point-at-eol)
8272 (list 'face
8273 (if org-last-todo-state-is-todo
8274 undone-face done-face)))
8275 (org-agenda-highlight-todo 'line))
8276 (beginning-of-line 1))
8277 (error "Line update did not work")))
8278 (beginning-of-line 0)))))
8279
8280 (defun org-agenda-priority-up ()
8281 "Increase the priority of line at point, also in Org-mode file."
8282 (interactive)
8283 (org-agenda-priority 'up))
8284
8285 (defun org-agenda-priority-down ()
8286 "Decrease the priority of line at point, also in Org-mode file."
8287 (interactive)
8288 (org-agenda-priority 'down))
8289
8290 (defun org-agenda-priority (&optional force-direction)
8291 "Set the priority of line at point, also in Org-mode file.
8292 This changes the line at point, all other lines in the agenda referring to
8293 the same tree node, and the headline of the tree node in the Org-mode file."
8294 (interactive)
8295 (org-agenda-check-no-diary)
8296 (let* ((marker (or (get-text-property (point) 'org-marker)
8297 (org-agenda-error)))
8298 (buffer (marker-buffer marker))
8299 (pos (marker-position marker))
8300 (hdmarker (get-text-property (point) 'org-hd-marker))
8301 (buffer-read-only nil)
8302 newhead)
8303 (with-current-buffer buffer
8304 (widen)
8305 (goto-char pos)
8306 (org-show-hidden-entry)
8307 (save-excursion
8308 (and (outline-next-heading)
8309 (org-flag-heading nil))) ; show the next heading
8310 (funcall 'org-priority force-direction)
8311 (end-of-line 1)
8312 (setq newhead (org-get-heading)))
8313 (org-agenda-change-all-lines newhead hdmarker)
8314 (beginning-of-line 1)))
8315
8316 (defun org-get-tags-at (&optional pos)
8317 "Get a list of all headline tags applicable at POS.
8318 POS defaults to point. If tags are inherited, the list contains
8319 the targets in the same sequence as the headlines appear, i.e.
8320 the tags of the current headline come last."
8321 (interactive)
8322 (let (tags)
8323 (save-excursion
8324 (goto-char (or pos (point)))
8325 (save-match-data
8326 (org-back-to-heading t)
8327 (condition-case nil
8328 (while t
8329 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
8330 (setq tags (append (org-split-string
8331 (org-match-string-no-properties 1) ":")
8332 tags)))
8333 (or org-use-tag-inheritance (error ""))
8334 (org-up-heading-all 1))
8335 (error nil))))
8336 (message "%s" tags)
8337 tags))
8338
8339 (defun org-agenda-set-tags ()
8340 "Set tags for the current headline."
8341 (interactive)
8342 (org-agenda-check-no-diary)
8343 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
8344 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
8345 (org-agenda-error)))
8346 (buffer (marker-buffer hdmarker))
8347 (pos (marker-position hdmarker))
8348 (buffer-read-only nil)
8349 newhead)
8350 (with-current-buffer buffer
8351 (widen)
8352 (goto-char pos)
8353 (org-show-hidden-entry)
8354 (save-excursion
8355 (and (outline-next-heading)
8356 (org-flag-heading nil))) ; show the next heading
8357 (call-interactively 'org-set-tags)
8358 (end-of-line 1)
8359 (setq newhead (org-get-heading)))
8360 (org-agenda-change-all-lines newhead hdmarker)
8361 (beginning-of-line 1)))
8362
8363 (defun org-agenda-date-later (arg &optional what)
8364 "Change the date of this item to one day later."
8365 (interactive "p")
8366 (org-agenda-check-type t 'agenda 'timeline)
8367 (org-agenda-check-no-diary)
8368 (let* ((marker (or (get-text-property (point) 'org-marker)
8369 (org-agenda-error)))
8370 (buffer (marker-buffer marker))
8371 (pos (marker-position marker)))
8372 (with-current-buffer buffer
8373 (widen)
8374 (goto-char pos)
8375 (if (not (org-at-timestamp-p))
8376 (error "Cannot find time stamp"))
8377 (org-timestamp-change arg (or what 'day))
8378 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8379
8380 (defun org-agenda-date-earlier (arg &optional what)
8381 "Change the date of this item to one day earlier."
8382 (interactive "p")
8383 (org-agenda-date-later (- arg) what))
8384
8385 (defun org-agenda-date-prompt (arg)
8386 "Change the date of this item. Date is prompted for, with default today.
8387 The prefix ARG is passed to the `org-time-stamp' command and can therefore
8388 be used to request time specification in the time stamp."
8389 (interactive "P")
8390 (org-agenda-check-type t 'agenda 'timeline)
8391 (org-agenda-check-no-diary)
8392 (let* ((marker (or (get-text-property (point) 'org-marker)
8393 (org-agenda-error)))
8394 (buffer (marker-buffer marker))
8395 (pos (marker-position marker)))
8396 (with-current-buffer buffer
8397 (widen)
8398 (goto-char pos)
8399 (if (not (org-at-timestamp-p))
8400 (error "Cannot find time stamp"))
8401 (org-time-stamp arg)
8402 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8403
8404 (defun org-agenda-schedule (arg)
8405 "Schedule the item at point."
8406 (interactive "P")
8407 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8408 (org-agenda-check-no-diary)
8409 (let* ((marker (or (get-text-property (point) 'org-marker)
8410 (org-agenda-error)))
8411 (buffer (marker-buffer marker))
8412 (pos (marker-position marker))
8413 (org-insert-labeled-timestamps-at-point nil)
8414 ts)
8415 (with-current-buffer buffer
8416 (widen)
8417 (goto-char pos)
8418 (setq ts (org-schedule))
8419 (message "Item scheduled for %s" ts))))
8420
8421 (defun org-agenda-deadline (arg)
8422 "Schedule the item at point."
8423 (interactive "P")
8424 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8425 (org-agenda-check-no-diary)
8426 (let* ((marker (or (get-text-property (point) 'org-marker)
8427 (org-agenda-error)))
8428 (buffer (marker-buffer marker))
8429 (pos (marker-position marker))
8430 (org-insert-labeled-timestamps-at-point nil)
8431 ts)
8432 (with-current-buffer buffer
8433 (widen)
8434 (goto-char pos)
8435 (setq ts (org-deadline))
8436 (message "Deadline for this item set to %s" ts))))
8437
8438 (defun org-get-heading ()
8439 "Return the heading of the current entry, without the stars."
8440 (save-excursion
8441 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
8442 (if (and (re-search-backward "[\r\n]\\*" nil t)
8443 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
8444 (match-string 1)
8445 "")))
8446
8447 (defun org-agenda-clock-in (&optional arg)
8448 "Start the clock on the currently selected item."
8449 (interactive "P")
8450 (org-agenda-check-no-diary)
8451 (let* ((marker (or (get-text-property (point) 'org-marker)
8452 (org-agenda-error)))
8453 (pos (marker-position marker)))
8454 (with-current-buffer (marker-buffer marker)
8455 (widen)
8456 (goto-char pos)
8457 (org-clock-in))))
8458
8459 (defun org-agenda-diary-entry ()
8460 "Make a diary entry, like the `i' command from the calendar.
8461 All the standard commands work: block, weekly etc."
8462 (interactive)
8463 (org-agenda-check-type t 'agenda 'timeline)
8464 (require 'diary-lib)
8465 (let* ((char (progn
8466 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
8467 (read-char-exclusive)))
8468 (cmd (cdr (assoc char
8469 '((?d . insert-diary-entry)
8470 (?w . insert-weekly-diary-entry)
8471 (?m . insert-monthly-diary-entry)
8472 (?y . insert-yearly-diary-entry)
8473 (?a . insert-anniversary-diary-entry)
8474 (?b . insert-block-diary-entry)
8475 (?c . insert-cyclic-diary-entry)))))
8476 (oldf (symbol-function 'calendar-cursor-to-date))
8477 (point (point))
8478 (mark (or (mark t) (point))))
8479 (unless cmd
8480 (error "No command associated with <%c>" char))
8481 (unless (and (get-text-property point 'day)
8482 (or (not (equal ?b char))
8483 (get-text-property mark 'day)))
8484 (error "Don't know which date to use for diary entry"))
8485 ;; We implement this by hacking the `calendar-cursor-to-date' function
8486 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
8487 (let ((calendar-mark-ring
8488 (list (calendar-gregorian-from-absolute
8489 (or (get-text-property mark 'day)
8490 (get-text-property point 'day))))))
8491 (unwind-protect
8492 (progn
8493 (fset 'calendar-cursor-to-date
8494 (lambda (&optional error)
8495 (calendar-gregorian-from-absolute
8496 (get-text-property point 'day))))
8497 (call-interactively cmd))
8498 (fset 'calendar-cursor-to-date oldf)))))
8499
8500
8501 (defun org-agenda-execute-calendar-command (cmd)
8502 "Execute a calendar command from the agenda, with the date associated to
8503 the cursor position."
8504 (org-agenda-check-type t 'agenda 'timeline)
8505 (require 'diary-lib)
8506 (unless (get-text-property (point) 'day)
8507 (error "Don't know which date to use for calendar command"))
8508 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
8509 (point (point))
8510 (date (calendar-gregorian-from-absolute
8511 (get-text-property point 'day)))
8512 (displayed-day (extract-calendar-day date))
8513 (displayed-month (extract-calendar-month date))
8514 (displayed-year (extract-calendar-year date)))
8515 (unwind-protect
8516 (progn
8517 (fset 'calendar-cursor-to-date
8518 (lambda (&optional error)
8519 (calendar-gregorian-from-absolute
8520 (get-text-property point 'day))))
8521 (call-interactively cmd))
8522 (fset 'calendar-cursor-to-date oldf))))
8523
8524 (defun org-agenda-phases-of-moon ()
8525 "Display the phases of the moon for the 3 months around the cursor date."
8526 (interactive)
8527 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
8528
8529 (defun org-agenda-holidays ()
8530 "Display the holidays for the 3 months around the cursor date."
8531 (interactive)
8532 (org-agenda-execute-calendar-command 'list-calendar-holidays))
8533
8534 (defun org-agenda-sunrise-sunset (arg)
8535 "Display sunrise and sunset for the cursor date.
8536 Latitude and longitude can be specified with the variables
8537 `calendar-latitude' and `calendar-longitude'. When called with prefix
8538 argument, latitude and longitude will be prompted for."
8539 (interactive "P")
8540 (let ((calendar-longitude (if arg nil calendar-longitude))
8541 (calendar-latitude (if arg nil calendar-latitude))
8542 (calendar-location-name
8543 (if arg "the given coordinates" calendar-location-name)))
8544 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
8545
8546 (defun org-agenda-goto-calendar ()
8547 "Open the Emacs calendar with the date at the cursor."
8548 (interactive)
8549 (org-agenda-check-type t 'agenda 'timeline)
8550 (let* ((day (or (get-text-property (point) 'day)
8551 (error "Don't know which date to open in calendar")))
8552 (date (calendar-gregorian-from-absolute day))
8553 (calendar-move-hook nil)
8554 (view-calendar-holidays-initially nil)
8555 (view-diary-entries-initially nil))
8556 (calendar)
8557 (calendar-goto-date date)))
8558
8559 (defun org-calendar-goto-agenda ()
8560 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
8561 This is a command that has to be installed in `calendar-mode-map'."
8562 (interactive)
8563 (org-agenda-list nil (calendar-absolute-from-gregorian
8564 (calendar-cursor-to-date))
8565 nil t))
8566
8567 (defun org-agenda-convert-date ()
8568 (interactive)
8569 (org-agenda-check-type t 'agenda 'timeline)
8570 (let ((day (get-text-property (point) 'day))
8571 date s)
8572 (unless day
8573 (error "Don't know which date to convert"))
8574 (setq date (calendar-gregorian-from-absolute day))
8575 (setq s (concat
8576 "Gregorian: " (calendar-date-string date) "\n"
8577 "ISO: " (calendar-iso-date-string date) "\n"
8578 "Day of Yr: " (calendar-day-of-year-string date) "\n"
8579 "Julian: " (calendar-julian-date-string date) "\n"
8580 "Astron. JD: " (calendar-astro-date-string date)
8581 " (Julian date number at noon UTC)\n"
8582 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
8583 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
8584 "French: " (calendar-french-date-string date) "\n"
8585 "Mayan: " (calendar-mayan-date-string date) "\n"
8586 "Coptic: " (calendar-coptic-date-string date) "\n"
8587 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
8588 "Persian: " (calendar-persian-date-string date) "\n"
8589 "Chinese: " (calendar-chinese-date-string date) "\n"))
8590 (with-output-to-temp-buffer "*Dates*"
8591 (princ s))
8592 (if (fboundp 'fit-window-to-buffer)
8593 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
8594
8595 ;;; Tags
8596
8597 (defun org-scan-tags (action matcher &optional todo-only)
8598 "Scan headline tags with inheritance and produce output ACTION.
8599 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8600 evaluated, testing if a given set of tags qualifies a headline for
8601 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8602 are included in the output."
8603 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8604 (mapconcat 'regexp-quote
8605 (nreverse (cdr (reverse org-todo-keywords)))
8606 "\\|")
8607 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
8608 (props (list 'face nil
8609 'done-face 'org-done
8610 'undone-face nil
8611 'mouse-face 'highlight
8612 'keymap org-agenda-keymap
8613 'help-echo
8614 (format "mouse-2 or RET jump to org file %s"
8615 (abbreviate-file-name buffer-file-name))))
8616 lspos
8617 tags tags-list tags-alist (llast 0) rtn level category i txt
8618 todo marker)
8619 (save-excursion
8620 (goto-char (point-min))
8621 (when (eq action 'sparse-tree) (org-overview))
8622 (while (re-search-forward re nil t)
8623 (catch :skip
8624 (and (eq action 'agenda) (org-agenda-skip))
8625 (setq todo (if (match-end 1) (match-string 2))
8626 tags (if (match-end 4) (match-string 4)))
8627 (goto-char (setq lspos (1+ (match-beginning 0))))
8628 (setq level (funcall outline-level)
8629 category (org-get-category))
8630 (setq i llast llast level)
8631 ;; remove tag lists from same and sublevels
8632 (while (>= i level)
8633 (when (setq entry (assoc i tags-alist))
8634 (setq tags-alist (delete entry tags-alist)))
8635 (setq i (1- i)))
8636 ;; add the nex tags
8637 (when tags
8638 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8639 tags-alist
8640 (cons (cons level tags) tags-alist)))
8641 ;; compile tags for current headline
8642 (setq tags-list
8643 (if org-use-tag-inheritance
8644 (apply 'append (mapcar 'cdr tags-alist))
8645 tags))
8646 (when (and (or (not todo-only) todo)
8647 (eval matcher)
8648 (or (not org-agenda-skip-archived-trees)
8649 (not (member org-archive-tag tags-list))))
8650 ;; list this headline
8651 (if (eq action 'sparse-tree)
8652 (progn
8653 (org-show-hierarchy-above))
8654 (setq txt (org-format-agenda-item
8655 ""
8656 (concat
8657 (if org-tags-match-list-sublevels
8658 (make-string (1- level) ?.) "")
8659 (org-get-heading))
8660 category tags-list))
8661 (goto-char lspos)
8662 (setq marker (org-agenda-new-marker))
8663 (org-add-props txt props
8664 'org-marker marker 'org-hd-marker marker 'category category)
8665 (push txt rtn))
8666 ;; if we are to skip sublevels, jump to end of subtree
8667 (point)
8668 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8669 (when (and (eq action 'sparse-tree)
8670 (not org-sparse-tree-open-archived-trees))
8671 (org-hide-archived-subtrees (point-min) (point-max)))
8672 (nreverse rtn)))
8673
8674 (defun org-tags-sparse-tree (&optional arg match)
8675 "Create a sparse tree according to tags search string MATCH.
8676 MATCH can contain positive and negative selection of tags, like
8677 \"+WORK+URGENT-WITHBOSS\"."
8678 (interactive "P")
8679 (let ((org-show-following-heading nil)
8680 (org-show-hierarchy-above nil))
8681 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
8682
8683 (defun org-make-tags-matcher (match)
8684 "Create the TAGS matcher form for the tags-selecting string MATCH."
8685 (unless match
8686 ;; Get a new match request, with completion
8687 (setq org-last-tags-completion-table
8688 (or (org-get-buffer-tags)
8689 org-last-tags-completion-table))
8690 (setq match (completing-read
8691 "Tags: " 'org-tags-completion-function nil nil nil
8692 'org-tags-history)))
8693 ;; parse the string and create a lisp form
8694 (let ((match0 match) minus tag mm matcher orterms term orlist)
8695 (setq orterms (org-split-string match "|"))
8696 (while (setq term (pop orterms))
8697 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
8698 (setq minus (and (match-end 1)
8699 (equal (match-string 1 term) "-"))
8700 tag (match-string 2 term)
8701 term (substring term (match-end 0))
8702 mm (list 'member (downcase tag) 'tags-list)
8703 mm (if minus (list 'not mm) mm))
8704 (push mm matcher))
8705 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
8706 orlist)
8707 (setq matcher nil))
8708 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8709 ;; Return the string and lisp forms of the matcher
8710 (cons match0 matcher)))
8711
8712 ;;;###autoload
8713 (defun org-tags-view (&optional todo-only match keep-modes)
8714 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
8715 The prefix arg TODO-ONLY limits the search to TODO entries."
8716 (interactive "P")
8717 (org-agenda-maybe-reset-markers 'force)
8718 (org-compile-prefix-format org-agenda-prefix-format)
8719 (let* ((org-agenda-keep-modes keep-modes)
8720 (org-tags-match-list-sublevels
8721 (if todo-only t org-tags-match-list-sublevels))
8722 (win (selected-window))
8723 (completion-ignore-case t)
8724 rtn rtnall files file pos matcher
8725 buffer)
8726 (setq matcher (org-make-tags-matcher match)
8727 match (car matcher) matcher (cdr matcher))
8728 (if (not (equal (current-buffer) (get-buffer org-agenda-buffer-name)))
8729 (progn
8730 (delete-other-windows)
8731 (switch-to-buffer-other-window
8732 (get-buffer-create org-agenda-buffer-name))))
8733 (setq buffer-read-only nil)
8734 (erase-buffer)
8735 (org-agenda-mode) (setq buffer-read-only nil)
8736 (org-set-local 'org-agenda-type 'tags)
8737 (org-set-local 'org-agenda-redo-command
8738 (list 'org-tags-view (list 'quote todo-only)
8739 (list 'if 'current-prefix-arg nil match) t))
8740 (setq files (org-agenda-files)
8741 rtnall nil)
8742 (org-prepare-agenda-buffers files)
8743 (while (setq file (pop files))
8744 (catch 'nextfile
8745 (org-check-agenda-file file)
8746 (setq buffer (if (file-exists-p file)
8747 (org-get-agenda-file-buffer file)
8748 (error "No such file %s" file)))
8749 (if (not buffer)
8750 ;; If file does not exist, merror message to agenda
8751 (setq rtn (list
8752 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
8753 rtnall (append rtnall rtn))
8754 (with-current-buffer buffer
8755 (unless (org-mode-p)
8756 (error "Agenda file %s is not in `org-mode'" file))
8757 (setq org-category-table (org-get-category-table))
8758 (save-excursion
8759 (save-restriction
8760 (if org-respect-restriction
8761 (if (org-region-active-p)
8762 ;; Respect a region to restrict search
8763 (narrow-to-region (region-beginning) (region-end)))
8764 ;; If we work for the calendar or many files,
8765 ;; get rid of any restriction
8766 (widen))
8767 (setq rtn (org-scan-tags 'agenda matcher todo-only))
8768 (setq rtnall (append rtnall rtn))))))))
8769 (insert "Headlines with TAGS match: ")
8770 (add-text-properties (point-min) (1- (point))
8771 (list 'face 'org-level-3))
8772 (setq pos (point))
8773 (insert match "\n")
8774 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
8775 (setq pos (point))
8776 (insert "Press `C-u r' to search again with new search string\n")
8777 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
8778 (when rtnall
8779 (insert (mapconcat 'identity rtnall "\n")))
8780 (goto-char (point-min))
8781 (setq buffer-read-only t)
8782 (org-fit-agenda-window)
8783 (if (not org-select-agenda-window) (select-window win))))
8784
8785 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8786 (defun org-set-tags (&optional arg just-align)
8787 "Set the tags for the current headline.
8788 With prefix ARG, realign all tags in headings in the current buffer."
8789 (interactive "P")
8790 (let* ((re (concat "^" outline-regexp))
8791 (col (current-column))
8792 (current (org-get-tags))
8793 table current-tags inherited-tags ; computed below when needed
8794 tags hd empty invis)
8795 (if arg
8796 (save-excursion
8797 (goto-char (point-min))
8798 (while (re-search-forward re nil t)
8799 (org-set-tags nil t))
8800 (message "All tags realigned to column %d" org-tags-column))
8801 (if just-align
8802 (setq tags current)
8803 (setq table (or org-tag-alist (org-get-buffer-tags))
8804 org-last-tags-completion-table table
8805 current-tags (org-split-string current ":")
8806 inherited-tags (nreverse
8807 (nthcdr (length current-tags)
8808 (nreverse (org-get-tags-at))))
8809 tags
8810 (if (or (eq t org-use-fast-tag-selection)
8811 (and org-use-fast-tag-selection
8812 (delq nil (mapcar 'cdr table))))
8813 (org-fast-tag-selection current-tags inherited-tags table)
8814 (let ((org-add-colon-after-tag-completion t))
8815 (completing-read "Tags: " 'org-tags-completion-function
8816 nil nil current 'org-tags-history))))
8817 (while (string-match "[-+&]+" tags)
8818 (setq tags (replace-match ":" t t tags))))
8819
8820 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
8821 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
8822 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
8823 (if (equal current "")
8824 (progn
8825 (end-of-line 1)
8826 (or empty (insert-before-markers " ")))
8827 (beginning-of-line 1)
8828 (setq invis (org-invisible-p))
8829 (looking-at (concat "\\(.*\\)\\(" (regexp-quote current) "\\)[ \t]*"))
8830 (setq hd (match-string 1))
8831 (delete-region (match-beginning 0) (match-end 0))
8832 (insert-before-markers (org-trim hd) (if empty "" " ")))
8833 (if (equal tags "")
8834 (save-excursion
8835 (beginning-of-line 1)
8836 (skip-chars-forward "*")
8837 (if (= (char-after) ?\ ) (forward-char 1))
8838 (and (re-search-forward "[ \t]+$" (point-at-eol) t)
8839 (replace-match "")))
8840 (move-to-column (max (current-column)
8841 (if (> org-tags-column 0)
8842 org-tags-column
8843 (- (- org-tags-column) (length tags))))
8844 t)
8845 (insert-before-markers tags)
8846 (if (and (not invis) (org-invisible-p))
8847 (outline-flag-region (point-at-bol) (point) nil)))
8848 (move-to-column col))))
8849
8850 (defun org-tags-completion-function (string predicate &optional flag)
8851 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
8852 (confirm (lambda (x) (stringp (car x)))))
8853 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
8854 (setq s1 (match-string 1 string)
8855 s2 (match-string 2 string))
8856 (setq s1 "" s2 string))
8857 (cond
8858 ((eq flag nil)
8859 ;; try completion
8860 (setq rtn (try-completion s2 ctable confirm))
8861 (if (stringp rtn)
8862 (concat s1 s2 (substring rtn (length s2))
8863 (if (and org-add-colon-after-tag-completion
8864 (assoc rtn ctable))
8865 ":" "")))
8866 )
8867 ((eq flag t)
8868 ;; all-completions
8869 (all-completions s2 ctable confirm)
8870 )
8871 ((eq flag 'lambda)
8872 ;; exact match?
8873 (assoc s2 ctable)))
8874 ))
8875
8876 (defun org-fast-tag-insert (kwd tags face &optional end)
8877 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
8878 (insert (format "%-12s" (concat kwd ":"))
8879 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
8880 (or end "")))
8881
8882 (defun org-fast-tag-selection (current inherited table)
8883 "Fast tag selection with single keys.
8884 CURRENT is the current list of tags in the headline, INHERITED is the
8885 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
8886 possibly with grouping information.
8887 If the keys are nil, a-z are automatically assigned.
8888 Returns the new tags string, or nil to not change the current settings."
8889 (let* ((maxlen (apply 'max (mapcar
8890 (lambda (x)
8891 (if (stringp (car x)) (string-width (car x)) 0))
8892 table)))
8893 (fwidth (+ maxlen 3 1 3))
8894 (ncol (/ (- (window-width) 4) fwidth))
8895 (i-face 'org-done)
8896 (c-face 'org-tag)
8897 tg cnt e c char c1 c2 ntable tbl rtn
8898 groups ingroup)
8899 (save-window-excursion
8900 (delete-other-windows)
8901 (split-window-vertically)
8902 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
8903 (erase-buffer)
8904 (org-fast-tag-insert "Inherited" inherited i-face "\n")
8905 (org-fast-tag-insert "Current" current c-face "\n\n")
8906 (setq tbl table char ?a cnt 0)
8907 (while (setq e (pop tbl))
8908 (cond
8909 ((equal e '(:startgroup))
8910 (push '() groups) (setq ingroup t)
8911 (when (not (= cnt 0))
8912 (setq cnt 0)
8913 (insert "\n"))
8914 (insert "{ "))
8915 ((equal e '(:endgroup))
8916 (setq ingroup nil cnt 0)
8917 (insert "}\n"))
8918 (t
8919 (setq tg (car e) c2 nil)
8920 (if (cdr e)
8921 (setq c (cdr e))
8922 ;; automatically assign a character.
8923 (setq c1 (string-to-char
8924 (downcase (substring
8925 tg (if (= (string-to-char tg) ?@) 1 0)))))
8926 (if (or (rassoc c1 ntable) (rassoc c1 table))
8927 (while (or (rassoc char ntable) (rassoc char table))
8928 (setq char (1+ char)))
8929 (setq c2 c1))
8930 (setq c (or c2 char)))
8931 (if ingroup (push tg (car groups)))
8932 (setq tg (org-add-props tg nil 'face
8933 (cond
8934 ((member tg current) c-face)
8935 ((member tg inherited) i-face)
8936 (t nil))))
8937 (if (and (= cnt 0) (not ingroup)) (insert " "))
8938 (insert "[" c "] " tg (make-string
8939 (- fwidth 4 (length tg)) ?\ ))
8940 (push (cons tg c) ntable)
8941 (when (= (setq cnt (1+ cnt)) ncol)
8942 (insert "\n")
8943 (if ingroup (insert " "))
8944 (setq cnt 0)))))
8945 (setq ntable (nreverse ntable))
8946 (insert "\n")
8947 (goto-char (point-min))
8948 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
8949 (setq rtn
8950 (catch 'exit
8951 (while t
8952 (message "[key]:Toggle SPC: clear current RET accept%s"
8953 (if groups " [!] ignore goups" ""))
8954 (setq c (read-char-exclusive))
8955 (cond
8956 ((= c ?\r) (throw 'exit t))
8957 ((= c ?!)
8958 (setq groups nil)
8959 (goto-char (point-min))
8960 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
8961 ((or (= c ?\C-g)
8962 (and (= c ?q) (not (rassoc c ntable))))
8963 (setq quit-flag t))
8964 ((= c ?\ ) (setq current nil))
8965 ((setq e (rassoc c ntable) tg (car e))
8966 (if (member tg current)
8967 (setq current (delete tg current))
8968 (loop for g in groups do
8969 (if (member tg g)
8970 (mapcar (lambda (x)
8971 (setq current (delete x current)))
8972 g)))
8973 (setq current (cons tg current)))))
8974 ;; Create a sorted list
8975 (setq current
8976 (sort current
8977 (lambda (a b)
8978 (assoc b (cdr (memq (assoc a ntable) ntable))))))
8979 (goto-char (point-min))
8980 (beginning-of-line 2)
8981 (delete-region (point) (point-at-eol))
8982 (org-fast-tag-insert "Current" current c-face)
8983 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
8984 (setq tg (match-string 1))
8985 (add-text-properties (match-beginning 1) (match-end 1)
8986 (list 'face
8987 (cond
8988 ((member tg current) c-face)
8989 ((member tg inherited) i-face)
8990 (t nil)))))
8991 (goto-char (point-min)))))
8992 (if rtn
8993 (mapconcat 'identity current ":")
8994 nil))))
8995
8996 (defun org-get-tags ()
8997 "Get the TAGS string in the current headline."
8998 (unless (org-on-heading-p)
8999 (error "Not on a heading"))
9000 (save-excursion
9001 (beginning-of-line 1)
9002 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
9003 (org-match-string-no-properties 1)
9004 "")))
9005
9006 (defun org-get-buffer-tags ()
9007 "Get a table of all tags used in the buffer, for completion."
9008 (let (tags)
9009 (save-excursion
9010 (goto-char (point-min))
9011 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
9012 (mapc (lambda (x) (add-to-list 'tags x))
9013 (org-split-string (org-match-string-no-properties 1) ":"))))
9014 (mapcar 'list tags)))
9015
9016 ;;; Link Stuff
9017
9018 (defvar org-create-file-search-functions nil
9019 "List of functions to construct the right search string for a file link.
9020 These functions are called in turn with point at the location to
9021 which the link should point.
9022
9023 A function in the hook should first test if it would like to
9024 handle this file type, for example by checking the major-mode or
9025 the file extension. If it decides not to handle this file, it
9026 should just return nil to give other functions a chance. If it
9027 does handle the file, it must return the search string to be used
9028 when following the link. The search string will be part of the
9029 file link, given after a double colon, and `org-open-at-point'
9030 will automatically search for it. If special measures must be
9031 taken to make the search successful, another function should be
9032 added to the companion hook `org-execute-file-search-functions',
9033 which see.
9034
9035 A function in this hook may also use `setq' to set the variable
9036 `description' to provide a suggestion for the descriptive text to
9037 be used for this link when it gets inserted into an Org-mode
9038 buffer with \\[org-insert-link].")
9039
9040 (defvar org-execute-file-search-functions nil
9041 "List of functions to execute a file search triggered by a link.
9042
9043 Functions added to this hook must accept a single argument, the
9044 search string that was part of the file link, the part after the
9045 double colon. The function must first check if it would like to
9046 handle this search, for example by checking the major-mode or the
9047 file extension. If it decides not to handle this search, it
9048 should just return nil to give other functions a chance. If it
9049 does handle the search, it must return a non-nil value to keep
9050 other functions from trying.
9051
9052 Each function can access the current prefix argument through the
9053 variable `current-prefix-argument'. Note that a single prefix is
9054 used to force opening a link in Emacs, so it may be good to only
9055 use a numeric or double prefix to guide the search function.
9056
9057 In case this is needed, a function in this hook can also restore
9058 the window configuration before `org-open-at-point' was called using:
9059
9060 (set-window-configuration org-window-config-before-follow-link)")
9061
9062 (defun org-find-file-at-mouse (ev)
9063 "Open file link or URL at mouse."
9064 (interactive "e")
9065 (mouse-set-point ev)
9066 (org-open-at-point 'in-emacs))
9067
9068 (defun org-open-at-mouse (ev)
9069 "Open file link or URL at mouse."
9070 (interactive "e")
9071 (mouse-set-point ev)
9072 (org-open-at-point))
9073
9074 (defvar org-window-config-before-follow-link nil
9075 "The window configuration before following a link.
9076 This is saved in case the need arises to restore it.")
9077
9078 (defun org-open-at-point (&optional in-emacs)
9079 "Open link at or after point.
9080 If there is no link at point, this function will search forward up to
9081 the end of the current subtree.
9082 Normally, files will be opened by an appropriate application. If the
9083 optional argument IN-EMACS is non-nil, Emacs will visit the file."
9084 (interactive "P")
9085 (setq org-window-config-before-follow-link (current-window-configuration))
9086 (org-remove-occur-highlights nil nil t)
9087 (if (org-at-timestamp-p)
9088 (org-agenda-list nil (time-to-days (org-time-string-to-time
9089 (substring (match-string 1) 0 10)))
9090 1)
9091 (let (type path link line search (pos (point)))
9092 (catch 'match
9093 (save-excursion
9094 (skip-chars-forward "^]\n\r")
9095 (when (and (re-search-backward "\\[\\[" nil t)
9096 (looking-at org-bracket-link-regexp)
9097 (<= (match-beginning 0) pos)
9098 (>= (match-end 0) pos))
9099 (setq link (org-link-unescape (org-match-string-no-properties 1)))
9100 (while (string-match " *\n *" link)
9101 (setq link (replace-match " " t t link)))
9102 (if (string-match org-link-re-with-space2 link)
9103 (setq type (match-string 1 link)
9104 path (match-string 2 link))
9105 (setq type "thisfile"
9106 path link))
9107 (throw 'match t)))
9108
9109 (when (get-text-property (point) 'org-linked-text)
9110 (setq type "thisfile"
9111 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9112 (1+ (point)) (point))
9113 path (buffer-substring
9114 (previous-single-property-change pos 'org-linked-text)
9115 (next-single-property-change pos 'org-linked-text)))
9116 (throw 'match t))
9117
9118 (save-excursion
9119 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
9120 (if (equal (char-before) ?<) (backward-char 1))
9121 (when (or (looking-at org-angle-link-re)
9122 (looking-at org-plain-link-re)
9123 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
9124 (re-search-forward org-plain-link-re (point-at-eol) t))
9125 (<= (match-beginning 0) pos)
9126 (>= (match-end 0) pos)))
9127 (setq type (match-string 1)
9128 path (match-string 2))
9129 (throw 'match t)))
9130 (save-excursion
9131 (skip-chars-backward "^ \t\n\r")
9132 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
9133 (setq type "tags"
9134 path (match-string 1))
9135 (while (string-match ":" path)
9136 (setq path (replace-match "+" t t path)))
9137 (throw 'match t)))
9138 (save-excursion
9139 (skip-chars-backward "a-zA-Z_")
9140 (when (and (memq 'camel org-activate-links)
9141 (looking-at org-camel-regexp))
9142 (setq type "camel" path (match-string 0))
9143 (if (equal (char-before) ?*)
9144 (setq path (concat "*" path))))
9145 (throw 'match t)))
9146 (unless path
9147 (error "No link found"))
9148 ;; Remove any trailing spaces in path
9149 (if (string-match " +\\'" path)
9150 (setq path (replace-match "" t t path)))
9151
9152 (cond
9153
9154 ((member type '("http" "https" "ftp" "mailto" "news"))
9155 (browse-url (concat type ":" path)))
9156
9157 ((string= type "tags")
9158 (org-tags-view in-emacs path))
9159 ((or (string= type "camel")
9160 (string= type "thisfile"))
9161 (org-mark-ring-push)
9162 (org-link-search
9163 path
9164 (cond ((equal in-emacs '(4)) 'occur)
9165 ((equal in-emacs '(16)) 'org-occur)
9166 (t nil))))
9167
9168 ((string= type "file")
9169 (if (string-match "::\\([0-9]+\\)\\'" path)
9170 (setq line (string-to-number (match-string 1 path))
9171 path (substring path 0 (match-beginning 0)))
9172 (if (string-match "::\\(.+\\)\\'" path)
9173 (setq search (match-string 1 path)
9174 path (substring path 0 (match-beginning 0)))))
9175 (org-open-file path in-emacs line search))
9176
9177 ((string= type "news")
9178 (org-follow-gnus-link path))
9179
9180 ((string= type "bbdb")
9181 (org-follow-bbdb-link path))
9182
9183 ((string= type "info")
9184 (org-follow-info-link path))
9185
9186 ((string= type "gnus")
9187 (let (group article)
9188 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9189 (error "Error in Gnus link"))
9190 (setq group (match-string 1 path)
9191 article (match-string 3 path))
9192 (org-follow-gnus-link group article)))
9193
9194 ((string= type "vm")
9195 (let (folder article)
9196 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9197 (error "Error in VM link"))
9198 (setq folder (match-string 1 path)
9199 article (match-string 3 path))
9200 ;; in-emacs is the prefix arg, will be interpreted as read-only
9201 (org-follow-vm-link folder article in-emacs)))
9202
9203 ((string= type "wl")
9204 (let (folder article)
9205 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9206 (error "Error in Wanderlust link"))
9207 (setq folder (match-string 1 path)
9208 article (match-string 3 path))
9209 (org-follow-wl-link folder article)))
9210
9211 ((string= type "mhe")
9212 (let (folder article)
9213 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9214 (error "Error in MHE link"))
9215 (setq folder (match-string 1 path)
9216 article (match-string 3 path))
9217 (org-follow-mhe-link folder article)))
9218
9219 ((string= type "rmail")
9220 (let (folder article)
9221 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9222 (error "Error in RMAIL link"))
9223 (setq folder (match-string 1 path)
9224 article (match-string 3 path))
9225 (org-follow-rmail-link folder article)))
9226
9227 ((string= type "shell")
9228 (let ((cmd path))
9229 (while (string-match "@{" cmd)
9230 (setq cmd (replace-match "<" t t cmd)))
9231 (while (string-match "@}" cmd)
9232 (setq cmd (replace-match ">" t t cmd)))
9233 (if (or (not org-confirm-shell-link-function)
9234 (funcall org-confirm-shell-link-function
9235 (format "Execute \"%s\" in shell? "
9236 (org-add-props cmd nil
9237 'face 'org-warning))))
9238 (progn
9239 (message "Executing %s" cmd)
9240 (shell-command cmd))
9241 (error "Abort"))))
9242
9243 ((string= type "elisp")
9244 (let ((cmd path))
9245 (if (or (not org-confirm-elisp-link-function)
9246 (funcall org-confirm-elisp-link-function
9247 (format "Execute \"%s\" as elisp? "
9248 (org-add-props cmd nil
9249 'face 'org-warning))))
9250 (message "%s => %s" cmd (eval (read cmd)))
9251 (error "Abort"))))
9252
9253 (t
9254 (browse-url-at-point))))))
9255
9256 (defun org-link-search (s &optional type)
9257 "Search for a link search option.
9258 When S is a CamelCaseWord, search for a target, or for a sentence containing
9259 the words. If S is surrounded by forward slashes, it is interpreted as a
9260 regular expression. In org-mode files, this will create an `org-occur'
9261 sparse tree. In ordinary files, `occur' will be used to list matches.
9262 If the current buffer is in `dired-mode', grep will be used to search
9263 in all files."
9264 (let ((case-fold-search t)
9265 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9266 (pos (point))
9267 (pre "") (post "")
9268 words re0 re1 re2 re3 re4 re5 re2a reall camel)
9269 (cond
9270 ;; First check if there are any special
9271 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9272 ;; Now try the builtin stuff
9273 ((save-excursion
9274 (goto-char (point-min))
9275 (and
9276 (re-search-forward
9277 (concat "<<" (regexp-quote s0) ">>") nil t)
9278 (setq pos (match-beginning 0))))
9279 ;; There is an exact target for this
9280 (goto-char pos))
9281 ((string-match "^/\\(.*\\)/$" s)
9282 ;; A regular expression
9283 (cond
9284 ((org-mode-p)
9285 (org-occur (match-string 1 s)))
9286 ;;((eq major-mode 'dired-mode)
9287 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9288 (t (org-do-occur (match-string 1 s)))))
9289 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
9290 t)
9291 ;; A camel or a normal search string
9292 (when (equal (string-to-char s) ?*)
9293 ;; Anchor on headlines, post may include tags.
9294 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
9295 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
9296 s (substring s 1)))
9297 (remove-text-properties
9298 0 (length s)
9299 '(face nil mouse-face nil keymap nil fontified nil) s)
9300 ;; Make a series of regular expressions to find a match
9301 (setq words
9302 (if camel
9303 (org-camel-to-words s)
9304 (org-split-string s "[ \n\r\t]+"))
9305 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9306 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
9307 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9308 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9309 re1 (concat pre re2 post)
9310 re3 (concat pre re4 post)
9311 re5 (concat pre ".*" re4)
9312 re2 (concat pre re2)
9313 re2a (concat pre re2a)
9314 re4 (concat pre re4)
9315 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9316 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9317 re5 "\\)"
9318 ))
9319 (cond
9320 ((eq type 'org-occur) (org-occur reall))
9321 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9322 (t (goto-char (point-min))
9323 (if (or (org-search-not-link re0 nil t)
9324 (org-search-not-link re1 nil t)
9325 (org-search-not-link re2 nil t)
9326 (org-search-not-link re2a nil t)
9327 (org-search-not-link re3 nil t)
9328 (org-search-not-link re4 nil t)
9329 (org-search-not-link re5 nil t)
9330 )
9331 (goto-char (match-beginning 1))
9332 (goto-char pos)
9333 (error "No match")))))
9334 (t
9335 ;; Normal string-search
9336 (goto-char (point-min))
9337 (if (search-forward s nil t)
9338 (goto-char (match-beginning 0))
9339 (error "No match"))))
9340 (and (org-mode-p) (org-show-hierarchy-above))))
9341
9342 (defun org-search-not-link (&rest args)
9343 "Execute `re-search-forward', but only accept matches that are not a link."
9344 (catch 'exit
9345 (let (p1)
9346 (while (apply 're-search-forward args)
9347 (setq p1 (point))
9348 (if (not (save-match-data
9349 (and (re-search-backward "\\[\\[" nil t)
9350 (looking-at org-bracket-link-regexp)
9351 (<= (match-beginning 0) p1)
9352 (>= (match-end 0) p1))))
9353 (progn (goto-char (match-end 0))
9354 (throw 'exit (point)))
9355 (goto-char (match-end 0)))))))
9356
9357 (defun org-do-occur (regexp &optional cleanup)
9358 "Call the Emacs command `occur'.
9359 If CLEANUP is non-nil, remove the printout of the regular expression
9360 in the *Occur* buffer. This is useful if the regex is long and not useful
9361 to read."
9362 (occur regexp)
9363 (when cleanup
9364 (let ((cwin (selected-window)) win beg end)
9365 (when (setq win (get-buffer-window "*Occur*"))
9366 (select-window win))
9367 (goto-char (point-min))
9368 (when (re-search-forward "match[a-z]+" nil t)
9369 (setq beg (match-end 0))
9370 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9371 (setq end (1- (match-beginning 0)))))
9372 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
9373 (goto-char (point-min))
9374 (select-window cwin))))
9375
9376 (defvar org-mark-ring nil
9377 "Mark ring for positions before jumps in Org-mode.")
9378 (defvar org-mark-ring-last-goto nil
9379 "Last position in the mark ring used to go back.")
9380 ;; Fill and close the ring
9381 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9382 (loop for i from 1 to org-mark-ring-length do
9383 (push (make-marker) org-mark-ring))
9384 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9385 org-mark-ring)
9386
9387 (defun org-mark-ring-push (&optional pos buffer)
9388 "Put the current position or POS into the mark ring and rotate it."
9389 (interactive)
9390 (setq pos (or pos (point)))
9391 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9392 (move-marker (car org-mark-ring)
9393 (or pos (point))
9394 (or buffer (current-buffer)))
9395 (message
9396 (substitute-command-keys
9397 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9398
9399 (defun org-mark-ring-goto (&optional n)
9400 "Jump to the previous position in the mark ring.
9401 With prefix arg N, jump back that many stored positions. When
9402 called several times in succession, walk through the entire ring.
9403 Org-mode commands jumping to a different position in the current file,
9404 or to another Org-mode file, automatically push the old position
9405 onto the ring."
9406 (interactive "p")
9407 (let (p m)
9408 (if (eq last-command this-command)
9409 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9410 (setq p org-mark-ring))
9411 (setq org-mark-ring-last-goto p)
9412 (setq m (car p))
9413 (switch-to-buffer (marker-buffer m))
9414 (goto-char m)
9415 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
9416
9417 (defun org-camel-to-words (s)
9418 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
9419 (let ((case-fold-search nil)
9420 words)
9421 (while (string-match "[a-z][A-Z]" s)
9422 (push (substring s 0 (1+ (match-beginning 0))) words)
9423 (setq s (substring s (1+ (match-beginning 0)))))
9424 (nreverse (cons s words))))
9425
9426 (defun org-remove-angle-brackets (s)
9427 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9428 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9429 s)
9430 (defun org-add-angle-brackets (s)
9431 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9432 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9433 s)
9434
9435 (defun org-follow-bbdb-link (name)
9436 "Follow a BBDB link to NAME."
9437 (require 'bbdb)
9438 (let ((inhibit-redisplay t)
9439 (bbdb-electric-p nil))
9440 (catch 'exit
9441 ;; Exact match on name
9442 (bbdb-name (concat "\\`" name "\\'") nil)
9443 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9444 ;; Exact match on name
9445 (bbdb-company (concat "\\`" name "\\'") nil)
9446 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9447 ;; Partial match on name
9448 (bbdb-name name nil)
9449 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9450 ;; Partial match on company
9451 (bbdb-company name nil)
9452 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9453 ;; General match including network address and notes
9454 (bbdb name nil)
9455 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
9456 (delete-window (get-buffer-window "*BBDB*"))
9457 (error "No matching BBDB record")))))
9458
9459
9460 (defun org-follow-info-link (name)
9461 "Follow an info file & node link to NAME."
9462 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
9463 (string-match "\\(.*\\)" name))
9464 (progn
9465 (require 'info)
9466 (if (match-string 2 name) ; If there isn't a node, choose "Top"
9467 (Info-find-node (match-string 1 name) (match-string 2 name))
9468 (Info-find-node (match-string 1 name) "Top")))
9469 (message (concat "Could not open: " name))))
9470
9471 (defun org-follow-gnus-link (&optional group article)
9472 "Follow a Gnus link to GROUP and ARTICLE."
9473 (require 'gnus)
9474 (funcall (cdr (assq 'gnus org-link-frame-setup)))
9475 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
9476 (if group (gnus-fetch-group group))
9477 (if article
9478 (or (gnus-summary-goto-article article nil 'force)
9479 (if (fboundp 'gnus-summary-insert-cached-articles)
9480 (progn
9481 (gnus-summary-insert-cached-articles)
9482 (gnus-summary-goto-article article nil 'force))
9483 (message "Message could not be found.")))))
9484
9485 (defun org-follow-vm-link (&optional folder article readonly)
9486 "Follow a VM link to FOLDER and ARTICLE."
9487 (require 'vm)
9488 (setq article (org-add-angle-brackets article))
9489 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
9490 ;; ange-ftp or efs or tramp access
9491 (let ((user (or (match-string 1 folder) (user-login-name)))
9492 (host (match-string 2 folder))
9493 (file (match-string 3 folder)))
9494 (cond
9495 ((featurep 'tramp)
9496 ;; use tramp to access the file
9497 (if (featurep 'xemacs)
9498 (setq folder (format "[%s@%s]%s" user host file))
9499 (setq folder (format "/%s@%s:%s" user host file))))
9500 (t
9501 ;; use ange-ftp or efs
9502 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
9503 (setq folder (format "/%s@%s:%s" user host file))))))
9504 (when folder
9505 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
9506 (sit-for 0.1)
9507 (when article
9508 (vm-select-folder-buffer)
9509 (widen)
9510 (let ((case-fold-search t))
9511 (goto-char (point-min))
9512 (if (not (re-search-forward
9513 (concat "^" "message-id: *" (regexp-quote article))))
9514 (error "Could not find the specified message in this folder"))
9515 (vm-isearch-update)
9516 (vm-isearch-narrow)
9517 (vm-beginning-of-message)
9518 (vm-summarize)))))
9519
9520 (defun org-follow-wl-link (folder article)
9521 "Follow a Wanderlust link to FOLDER and ARTICLE."
9522 (setq article (org-add-angle-brackets article))
9523 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
9524 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
9525 (wl-summary-redisplay))
9526
9527 (defun org-follow-rmail-link (folder article)
9528 "Follow an RMAIL link to FOLDER and ARTICLE."
9529 (setq article (org-add-angle-brackets article))
9530 (let (message-number)
9531 (save-excursion
9532 (save-window-excursion
9533 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9534 (setq message-number
9535 (save-restriction
9536 (widen)
9537 (goto-char (point-max))
9538 (if (re-search-backward
9539 (concat "^Message-ID:\\s-+" (regexp-quote
9540 (or article "")))
9541 nil t)
9542 (rmail-what-message))))))
9543 (if message-number
9544 (progn
9545 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9546 (rmail-show-message message-number)
9547 message-number)
9548 (error "Message not found"))))
9549
9550 ;; mh-e integration based on planner-mode
9551 (defun org-mhe-get-message-real-folder ()
9552 "Return the name of the current message real folder, so if you use
9553 sequences, it will now work."
9554 (save-excursion
9555 (let* ((folder
9556 (if (equal major-mode 'mh-folder-mode)
9557 mh-current-folder
9558 ;; Refer to the show buffer
9559 mh-show-folder-buffer))
9560 (end-index
9561 (if (boundp 'mh-index-folder)
9562 (min (length mh-index-folder) (length folder))))
9563 )
9564 ;; a simple test on mh-index-data does not work, because
9565 ;; mh-index-data is always nil in a show buffer.
9566 (if (and (boundp 'mh-index-folder)
9567 (string= mh-index-folder (substring folder 0 end-index)))
9568 (if (equal major-mode 'mh-show-mode)
9569 (save-window-excursion
9570 (when (buffer-live-p (get-buffer folder))
9571 (progn
9572 (pop-to-buffer folder)
9573 (org-mhe-get-message-folder-from-index)
9574 )
9575 ))
9576 (org-mhe-get-message-folder-from-index)
9577 )
9578 folder
9579 )
9580 )))
9581
9582 (defun org-mhe-get-message-folder-from-index ()
9583 "Returns the name of the message folder in a index folder buffer."
9584 (save-excursion
9585 (mh-index-previous-folder)
9586 (re-search-forward "^\\(+.*\\)$" nil t)
9587 (message (match-string 1))))
9588
9589 (defun org-mhe-get-message-folder ()
9590 "Return the name of the current message folder. Be careful if you
9591 use sequences."
9592 (save-excursion
9593 (if (equal major-mode 'mh-folder-mode)
9594 mh-current-folder
9595 ;; Refer to the show buffer
9596 mh-show-folder-buffer)))
9597
9598 (defun org-mhe-get-message-num ()
9599 "Return the number of the current message. Be careful if you
9600 use sequences."
9601 (save-excursion
9602 (if (equal major-mode 'mh-folder-mode)
9603 (mh-get-msg-num nil)
9604 ;; Refer to the show buffer
9605 (mh-show-buffer-message-number))))
9606
9607 (defun org-mhe-get-header (header)
9608 "Return a header of the message in folder mode. This will create a
9609 show buffer for the corresponding message. If you have a more clever
9610 idea..."
9611 (let* ((folder (org-mhe-get-message-folder))
9612 (num (org-mhe-get-message-num))
9613 (buffer (get-buffer-create (concat "show-" folder)))
9614 (header-field))
9615 (with-current-buffer buffer
9616 (mh-display-msg num folder)
9617 (if (equal major-mode 'mh-folder-mode)
9618 (mh-header-display)
9619 (mh-show-header-display))
9620 (set-buffer buffer)
9621 (setq header-field (mh-get-header-field header))
9622 (if (equal major-mode 'mh-folder-mode)
9623 (mh-show)
9624 (mh-show-show))
9625 header-field)))
9626
9627 (defun org-follow-mhe-link (folder article)
9628 "Follow an MHE link to FOLDER and ARTICLE.
9629 If ARTICLE is nil FOLDER is shown. If the configuration variable
9630 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
9631 ARTICLE is searched in all folders. Indexed searches (swish++,
9632 namazu, and others supported by MH-E) will always search in all
9633 folders."
9634 (require 'mh-e)
9635 (require 'mh-search)
9636 (require 'mh-utils)
9637 (mh-find-path)
9638 (if (not article)
9639 (mh-visit-folder (mh-normalize-folder-name folder))
9640 (setq article (org-add-angle-brackets article))
9641 (mh-search-choose)
9642 (if (equal mh-searcher 'pick)
9643 (progn
9644 (mh-search folder (list "--message-id" article))
9645 (when (and org-mhe-search-all-folders
9646 (not (org-mhe-get-message-real-folder)))
9647 (kill-this-buffer)
9648 (mh-search "+" (list "--message-id" article))))
9649 (mh-search "+" article))
9650 (if (org-mhe-get-message-real-folder)
9651 (mh-show-msg 1)
9652 (kill-this-buffer)
9653 (error "Message not found"))))
9654
9655 ;; BibTeX links
9656
9657 ;; Use the custom search meachnism to construct and use search strings for
9658 ;; file links to BibTeX database entries.
9659
9660 (defun org-create-file-search-in-bibtex ()
9661 "Create the search string and description for a BibTeX database entry."
9662 (when (eq major-mode 'bibtex-mode)
9663 ;; yes, we want to construct this search string.
9664 ;; Make a good description for this entry, using names, year and the title
9665 ;; Put it into the `description' variable which is dynamically scoped.
9666 (let ((bibtex-autokey-names 1)
9667 (bibtex-autokey-names-stretch 1)
9668 (bibtex-autokey-name-case-convert-function 'identity)
9669 (bibtex-autokey-name-separator " & ")
9670 (bibtex-autokey-additional-names " et al.")
9671 (bibtex-autokey-year-length 4)
9672 (bibtex-autokey-name-year-separator " ")
9673 (bibtex-autokey-titlewords 3)
9674 (bibtex-autokey-titleword-separator " ")
9675 (bibtex-autokey-titleword-case-convert-function 'identity)
9676 (bibtex-autokey-titleword-length 'infty)
9677 (bibtex-autokey-year-title-separator ": "))
9678 (setq description (bibtex-generate-autokey)))
9679 ;; Now parse the entry, get the key and return it.
9680 (save-excursion
9681 (bibtex-beginning-of-entry)
9682 (cdr (assoc "=key=" (bibtex-parse-entry))))))
9683
9684 (defun org-execute-file-search-in-bibtex (s)
9685 "Find the link search string S as a key for a database entry."
9686 (when (eq major-mode 'bibtex-mode)
9687 ;; Yes, we want to do the search in this file.
9688 ;; We construct a regexp that searches for "@entrytype{" followed by the key
9689 (goto-char (point-min))
9690 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
9691 (regexp-quote s) "[ \t\n]*,") nil t)
9692 (goto-char (match-beginning 0)))
9693 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
9694 ;; Use double prefix to indicate that any web link should be browsed
9695 (let ((b (current-buffer)) (p (point)))
9696 ;; Restore the window configuration because we just use the web link
9697 (set-window-configuration org-window-config-before-follow-link)
9698 (save-excursion (set-buffer b) (goto-char p)
9699 (bibtex-url)))
9700 (recenter 0)) ; Move entry start to beginning of window
9701 ;; return t to indicate that the search is done.
9702 t))
9703
9704 ;; Finally add the functions to the right hooks.
9705 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
9706 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
9707
9708 ;; end of Bibtex link setup
9709
9710 (defun org-upgrade-old-links (&optional query-description)
9711 "Transfer old <...> style links to new [[...]] style links.
9712 With arg query-description, ask at each match for a description text to use
9713 for this link."
9714 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
9715 (save-excursion
9716 (goto-char (point-min))
9717 (let ((re (concat "\\([^[]\\)<\\("
9718 "\\(" (mapconcat 'identity org-link-types "\\|")
9719 "\\):"
9720 "[^" org-non-link-chars "]+\\)>"))
9721 l1 l2 (cnt 0))
9722 (while (re-search-forward re nil t)
9723 (setq cnt (1+ cnt)
9724 l1 (org-match-string-no-properties 2)
9725 l2 (save-match-data (org-link-escape l1)))
9726 (when query-description (setq l1 (read-string "Desc: " l1)))
9727 (if (equal l1 l2)
9728 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
9729 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
9730 (message "%d matches have beed treated" cnt))))
9731
9732 (defun org-open-file (path &optional in-emacs line search)
9733 "Open the file at PATH.
9734 First, this expands any special file name abbreviations. Then the
9735 configuration variable `org-file-apps' is checked if it contains an
9736 entry for this file type, and if yes, the corresponding command is launched.
9737 If no application is found, Emacs simply visits the file.
9738 With optional argument IN-EMACS, Emacs will visit the file.
9739 Optional LINE specifies a line to go to, optional SEARCH a string to
9740 search for. If LINE or SEARCH is given, the file will always be
9741 opened in Emacs.
9742 If the file does not exist, an error is thrown."
9743 (setq in-emacs (or in-emacs line search))
9744 (let* ((file (if (equal path "")
9745 buffer-file-name
9746 path))
9747 (apps (append org-file-apps (org-default-apps)))
9748 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9749 (dirp (if remp nil (file-directory-p file)))
9750 (dfile (downcase file))
9751 (old-buffer (current-buffer))
9752 (old-pos (point))
9753 (old-mode major-mode)
9754 ext cmd)
9755 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9756 (setq ext (match-string 1 dfile))
9757 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9758 (setq ext (match-string 1 dfile))))
9759 (if in-emacs
9760 (setq cmd 'emacs)
9761 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9762 (and dirp (cdr (assoc 'directory apps)))
9763 (cdr (assoc ext apps))
9764 (cdr (assoc t apps)))))
9765 (when (eq cmd 'mailcap)
9766 (require 'mailcap)
9767 (mailcap-parse-mailcaps)
9768 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9769 (command (mailcap-mime-info mime-type)))
9770 (if (stringp command)
9771 (setq cmd command)
9772 (setq cmd 'emacs))))
9773 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
9774 (not (file-exists-p file))
9775 (not org-open-non-existing-files))
9776 (error "No such file: %s" file))
9777 (cond
9778 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9779 ;; Normalize use of quote, this can vary.
9780 (if (string-match "['\"]%s['\"]" cmd)
9781 (setq cmd (replace-match "'%s'" t t cmd)))
9782 (setq cmd (format cmd file))
9783 (save-window-excursion
9784 (shell-command (concat cmd " &"))))
9785 ((or (stringp cmd)
9786 (eq cmd 'emacs))
9787 ; (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
9788 ; (funcall (cdr (assq 'file org-link-frame-setup)) file))
9789 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9790 (if line (goto-line line)
9791 (if search (org-link-search search))))
9792 ((consp cmd)
9793 (eval cmd))
9794 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9795 (and (org-mode-p) (eq old-mode 'org-mode)
9796 (or (not (equal old-buffer (current-buffer)))
9797 (not (equal old-pos (point))))
9798 (org-mark-ring-push old-pos old-buffer))))
9799
9800 (defun org-default-apps ()
9801 "Return the default applications for this operating system."
9802 (cond
9803 ((eq system-type 'darwin)
9804 org-file-apps-defaults-macosx)
9805 ((eq system-type 'windows-nt)
9806 org-file-apps-defaults-windowsnt)
9807 (t org-file-apps-defaults-gnu)))
9808
9809 (defun org-expand-file-name (path)
9810 "Replace special path abbreviations and expand the file name."
9811 (expand-file-name path))
9812
9813 (defun org-file-remote-p (file)
9814 "Test whether FILE specifies a location on a remote system.
9815 Return non-nil if the location is indeed remote.
9816
9817 For example, the filename \"/user@host:/foo\" specifies a location
9818 on the system \"/user@host:\"."
9819 (cond ((fboundp 'file-remote-p)
9820 (file-remote-p file))
9821 ((fboundp 'tramp-handle-file-remote-p)
9822 (tramp-handle-file-remote-p file))
9823 ((and (boundp 'ange-ftp-name-format)
9824 (string-match (car ange-ftp-name-format) file))
9825 t)
9826 (t nil)))
9827
9828 (defvar org-insert-link-history nil
9829 "Minibuffer history for links inserted with `org-insert-link'.")
9830
9831 (defvar org-stored-links nil
9832 "Contains the links stored with `org-store-link'.")
9833
9834 ;;;###autoload
9835 (defun org-store-link (arg)
9836 "\\<org-mode-map>Store an org-link to the current location.
9837 This link can later be inserted into an org-buffer with
9838 \\[org-insert-link].
9839 For some link types, a prefix arg is interpreted:
9840 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
9841 For file links, arg negates `org-context-in-file-links'."
9842 (interactive "P")
9843 (let (link cpltxt desc description search txt (pos (point)))
9844 (cond
9845
9846 ((eq major-mode 'bbdb-mode)
9847 (setq cpltxt (concat
9848 "bbdb:"
9849 (or (bbdb-record-name (bbdb-current-record))
9850 (bbdb-record-company (bbdb-current-record))))
9851 link (org-make-link cpltxt)))
9852
9853 ((eq major-mode 'Info-mode)
9854 (setq link (org-make-link "info:"
9855 (file-name-nondirectory Info-current-file)
9856 ":" Info-current-node))
9857 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
9858 ":" Info-current-node)))
9859
9860 ((eq major-mode 'calendar-mode)
9861 (let ((cd (calendar-cursor-to-date)))
9862 (setq link
9863 (format-time-string
9864 (car org-time-stamp-formats)
9865 (apply 'encode-time
9866 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
9867 nil nil nil))))))
9868
9869 ((or (eq major-mode 'vm-summary-mode)
9870 (eq major-mode 'vm-presentation-mode))
9871 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
9872 (vm-follow-summary-cursor)
9873 (save-excursion
9874 (vm-select-folder-buffer)
9875 (let* ((message (car vm-message-pointer))
9876 (folder buffer-file-name)
9877 (subject (vm-su-subject message))
9878 (author (vm-su-full-name message))
9879 (message-id (vm-su-message-id message)))
9880 (setq message-id (org-remove-angle-brackets message-id))
9881 (setq folder (abbreviate-file-name folder))
9882 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
9883 folder)
9884 (setq folder (replace-match "" t t folder)))
9885 (setq cpltxt (concat author " on: " subject))
9886 (setq link (org-make-link "vm:" folder "#" message-id)))))
9887
9888 ((eq major-mode 'wl-summary-mode)
9889 (let* ((msgnum (wl-summary-message-number))
9890 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
9891 msgnum 'message-id))
9892 (wl-message-entity (elmo-msgdb-overview-get-entity
9893 msgnum (wl-summary-buffer-msgdb)))
9894 (author (wl-summary-line-from)) ; FIXME: correct?
9895 (subject "???")) ; FIXME:
9896 (setq message-id (org-remove-angle-brackets message-id))
9897 (setq cpltxt (concat author " on: " subject))
9898 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
9899 "#" message-id))))
9900
9901 ((or (equal major-mode 'mh-folder-mode)
9902 (equal major-mode 'mh-show-mode))
9903 (let ((from-header (org-mhe-get-header "From:"))
9904 (to-header (org-mhe-get-header "To:"))
9905 (subject (org-mhe-get-header "Subject:")))
9906 (setq cpltxt (concat from-header " on: " subject))
9907 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
9908 (org-remove-angle-brackets
9909 (org-mhe-get-header "Message-Id:"))))))
9910
9911 ((eq major-mode 'rmail-mode)
9912 (save-excursion
9913 (save-restriction
9914 (rmail-narrow-to-non-pruned-header)
9915 (let ((folder buffer-file-name)
9916 (message-id (mail-fetch-field "message-id"))
9917 (author (mail-fetch-field "from"))
9918 (subject (mail-fetch-field "subject")))
9919 (setq message-id (org-remove-angle-brackets message-id))
9920 (setq cpltxt (concat author " on: " subject))
9921 (setq link (org-make-link "rmail:" folder "#" message-id))))))
9922
9923 ((eq major-mode 'gnus-group-mode)
9924 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
9925 (gnus-group-group-name)) ; version
9926 ((fboundp 'gnus-group-name)
9927 (gnus-group-name))
9928 (t "???"))))
9929 (setq cpltxt (concat
9930 (if (org-xor arg org-usenet-links-prefer-google)
9931 "http://groups.google.com/groups?group="
9932 "gnus:")
9933 group)
9934 link (org-make-link cpltxt))))
9935
9936 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
9937 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
9938 (gnus-summary-beginning-of-article)
9939 (let* ((group (car gnus-article-current))
9940 (article (cdr gnus-article-current))
9941 (header (gnus-summary-article-header article))
9942 (author (mail-header-from header))
9943 (message-id (mail-header-id header))
9944 (date (mail-header-date header))
9945 (subject (gnus-summary-subject-string)))
9946 (setq cpltxt (concat author " on: " subject))
9947 (if (org-xor arg org-usenet-links-prefer-google)
9948 (setq link
9949 (concat
9950 cpltxt "\n "
9951 (format "http://groups.google.com/groups?as_umsgid=%s"
9952 (org-fixup-message-id-for-http message-id))))
9953 (setq link (org-make-link "gnus:" group
9954 "#" (number-to-string article))))))
9955
9956 ((eq major-mode 'w3-mode)
9957 (setq cpltxt (url-view-url t)
9958 link (org-make-link cpltxt)))
9959 ((eq major-mode 'w3m-mode)
9960 (setq cpltxt (or w3m-current-title w3m-current-url)
9961 link (org-make-link w3m-current-url)))
9962
9963 ((setq search (run-hook-with-args-until-success
9964 'org-create-file-search-functions))
9965 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
9966 "::" search))
9967 (setq cpltxt (or description link)))
9968
9969 ((eq major-mode 'image-mode)
9970 (setq cpltxt (concat "file:"
9971 (abbreviate-file-name buffer-file-name))
9972 link (org-make-link cpltxt)))
9973
9974 ((org-mode-p)
9975 ;; Just link to current headline
9976 (setq cpltxt (concat "file:"
9977 (abbreviate-file-name buffer-file-name)))
9978 ;; Add a context search string
9979 (when (org-xor org-context-in-file-links arg)
9980 ;; Check if we are on a target
9981 (if (save-excursion
9982 (skip-chars-forward "^>\n\r")
9983 (and (re-search-backward "<<" nil t)
9984 (looking-at "<<\\(.*?\\)>>")
9985 (<= (match-beginning 0) pos)
9986 (>= (match-end 0) pos)))
9987 (setq cpltxt (concat cpltxt "::" (match-string 1)))
9988 (setq txt (cond
9989 ((org-on-heading-p) nil)
9990 ((org-region-active-p)
9991 (buffer-substring (region-beginning) (region-end)))
9992 (t (buffer-substring (point-at-bol) (point-at-eol)))))
9993 (when (or (null txt) (string-match "\\S-" txt))
9994 (setq cpltxt
9995 (concat cpltxt "::"
9996 (if org-file-link-context-use-camel-case
9997 (org-make-org-heading-camel txt)
9998 (org-make-org-heading-search-string txt)))
9999 desc "NONE"))))
10000 (if (string-match "::\\'" cpltxt)
10001 (setq cpltxt (substring cpltxt 0 -2)))
10002 (setq link (org-make-link cpltxt)))
10003
10004 (buffer-file-name
10005 ;; Just link to this file here.
10006 (setq cpltxt (concat "file:"
10007 (abbreviate-file-name buffer-file-name)))
10008 ;; Add a context string
10009 (when (org-xor org-context-in-file-links arg)
10010 (setq txt (if (org-region-active-p)
10011 (buffer-substring (region-beginning) (region-end))
10012 (buffer-substring (point-at-bol) (point-at-eol))))
10013 ;; Only use search option if there is some text.
10014 (when (string-match "\\S-" txt)
10015 (setq cpltxt
10016 (concat cpltxt "::"
10017 (if org-file-link-context-use-camel-case
10018 (org-make-org-heading-camel txt)
10019 (org-make-org-heading-search-string txt)))
10020 desc "NONE")))
10021 (setq link (org-make-link cpltxt)))
10022
10023 ((interactive-p)
10024 (error "Cannot link to a buffer which is not visiting a file"))
10025
10026 (t (setq link nil)))
10027
10028 (if (consp link) (setq cpltxt (car link) link (cdr link)))
10029 (setq link (or link cpltxt)
10030 desc (or desc cpltxt))
10031 (if (equal desc "NONE") (setq desc nil))
10032
10033 (if (and (interactive-p) link)
10034 (progn
10035 (setq org-stored-links
10036 (cons (list cpltxt link desc) org-stored-links))
10037 (message "Stored: %s" (or cpltxt link)))
10038 (org-make-link-string link desc))))
10039
10040 (defun org-make-org-heading-search-string (&optional string heading)
10041 "Make search string for STRING or current headline."
10042 (interactive)
10043 (let ((s (or string (org-get-heading))))
10044 (unless (and string (not heading))
10045 ;; We are using a headline, clean up garbage in there.
10046 (if (string-match org-todo-regexp s)
10047 (setq s (replace-match "" t t s)))
10048 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10049 (setq s (replace-match "" t t s)))
10050 (setq s (org-trim s))
10051 (if (string-match (concat "^\\(" org-quote-string "\\|"
10052 org-comment-string "\\)") s)
10053 (setq s (replace-match "" t t s)))
10054 (while (string-match org-ts-regexp s)
10055 (setq s (replace-match "" t t s))))
10056 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
10057 (setq s (replace-match " " t t s)))
10058 (or string (setq s (concat "*" s))) ; Add * for headlines
10059 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10060
10061 (defun org-make-org-heading-camel (&optional string heading)
10062 "Make a CamelCase string for STRING or the current headline."
10063 (interactive)
10064 (let ((s (or string (org-get-heading))))
10065 (unless (and string (not heading))
10066 ;; We are using a headline, clean up garbage in there.
10067 (if (string-match org-todo-regexp s)
10068 (setq s (replace-match "" t t s)))
10069 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10070 (setq s (replace-match "" t t s)))
10071 (setq s (org-trim s))
10072 (if (string-match (concat "^\\(" org-quote-string "\\|"
10073 org-comment-string "\\)") s)
10074 (setq s (replace-match "" t t s)))
10075 (while (string-match org-ts-regexp s)
10076 (setq s (replace-match "" t t s))))
10077 (while (string-match "[^a-zA-Z_ \t]+" s)
10078 (setq s (replace-match " " t t s)))
10079 (or string (setq s (concat "*" s))) ; Add * for headlines
10080 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
10081
10082 (defun org-make-link (&rest strings)
10083 "Concatenate STRINGS, format resulting string with `org-link-format'."
10084 (format org-link-format (apply 'concat strings)))
10085
10086 (defun org-make-link-string (link &optional description)
10087 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10088 (if (eq org-link-style 'plain)
10089 (if (equal description link)
10090 link
10091 (concat description "\n" link))
10092 (when (stringp description)
10093 ;; Remove brackets from the description, they are fatal.
10094 (while (string-match "\\[\\|\\]" description)
10095 (setq description (replace-match "" t t description))))
10096 (when (equal (org-link-escape link) description)
10097 ;; No description needed, it is identical
10098 (setq description nil))
10099 (when (and (not description)
10100 (not (equal link (org-link-escape link))))
10101 (setq description link))
10102 (concat "[[" (org-link-escape link) "]"
10103 (if description (concat "[" description "]") "")
10104 "]")))
10105
10106 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
10107 "Association list of escapes for some characters problematic in links.")
10108
10109 (defun org-link-escape (text)
10110 "Escape charaters in TEXT that are problematic for links."
10111 (when text
10112 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
10113 org-link-escape-chars "\\|")))
10114 (while (string-match re text)
10115 (setq text
10116 (replace-match
10117 (cdr (assoc (match-string 0 text) org-link-escape-chars))
10118 t t text)))
10119 text)))
10120
10121 (defun org-link-unescape (text)
10122 "Reverse the action of `org-link-escape'."
10123 (when text
10124 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
10125 org-link-escape-chars "\\|")))
10126 (while (string-match re text)
10127 (setq text
10128 (replace-match
10129 (car (rassoc (match-string 0 text) org-link-escape-chars))
10130 t t text)))
10131 text)))
10132
10133 (defun org-xor (a b)
10134 "Exclusive or."
10135 (if a (not b) b))
10136
10137 (defun org-get-header (header)
10138 "Find a header field in the current buffer."
10139 (save-excursion
10140 (goto-char (point-min))
10141 (let ((case-fold-search t) s)
10142 (cond
10143 ((eq header 'from)
10144 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
10145 (setq s (match-string 1)))
10146 (while (string-match "\"" s)
10147 (setq s (replace-match "" t t s)))
10148 (if (string-match "[<(].*" s)
10149 (setq s (replace-match "" t t s))))
10150 ((eq header 'message-id)
10151 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
10152 (setq s (match-string 1))))
10153 ((eq header 'subject)
10154 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
10155 (setq s (match-string 1)))))
10156 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
10157 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
10158 s)))
10159
10160
10161 (defun org-fixup-message-id-for-http (s)
10162 "Replace special characters in a message id, so it can be used in an http query."
10163 (while (string-match "<" s)
10164 (setq s (replace-match "%3C" t t s)))
10165 (while (string-match ">" s)
10166 (setq s (replace-match "%3E" t t s)))
10167 (while (string-match "@" s)
10168 (setq s (replace-match "%40" t t s)))
10169 s)
10170
10171 (defun org-insert-link (&optional complete-file)
10172 "Insert a link. At the prompt, enter the link.
10173
10174 Completion can be used to select a link previously stored with
10175 `org-store-link'. When the empty string is entered (i.e. if you just
10176 press RET at the prompt), the link defaults to the most recently
10177 stored link. As SPC triggers completion in the minibuffer, you need to
10178 use M-SPC or C-q SPC to force the insertion of a space character.
10179
10180 You will also be prompted for a description, and if one is given, it will
10181 be displayed in the buffer instead of the link.
10182
10183 If there is already a link at point, this command will allow you to edit link
10184 and description parts.
10185
10186 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
10187 selected using completion. The path to the file will be relative to
10188 the current directory if the file is in the current directory or a
10189 subdirectory. Otherwise, the link will be the absolute path as
10190 completed in the minibuffer (i.e. normally ~/path/to/file).
10191
10192 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
10193 is in the current directory or below.
10194 With three \\[universal-argument] prefixes, negate the meaning of
10195 `org-keep-stored-link-after-insertion'."
10196 (interactive "P")
10197 (let (link desc entry remove file (pos (point)))
10198 (cond
10199 ((save-excursion
10200 (skip-chars-forward "^]\n\r")
10201 (and (re-search-backward "\\[\\[" nil t)
10202 (looking-at org-bracket-link-regexp)
10203 (<= (match-beginning 0) pos)
10204 (>= (match-end 0) pos)))
10205 ;; We do have a link at point, and we are going to edit it.
10206 (setq remove (list (match-beginning 0) (match-end 0)))
10207 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10208 (setq link (read-string "Link: "
10209 (org-link-unescape
10210 (org-match-string-no-properties 1)))))
10211 ((equal complete-file '(4))
10212 ;; Completing read for file names.
10213 (setq file (read-file-name "File: "))
10214 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10215 (pwd1 (file-name-as-directory (abbreviate-file-name
10216 (expand-file-name ".")))))
10217 (cond
10218 ((equal complete-file '(16))
10219 (setq link (org-make-link
10220 "file:"
10221 (abbreviate-file-name (expand-file-name file)))))
10222 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10223 (setq link (org-make-link "file:" (match-string 1 file))))
10224 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10225 (expand-file-name file))
10226 (setq link (org-make-link
10227 "file:" (match-string 1 (expand-file-name file)))))
10228 (t (setq link (org-make-link "file:" file))))))
10229 (t
10230 ;; Read link, with completion for stored links.
10231 (setq link (org-completing-read
10232 "Link: " org-stored-links nil nil nil
10233 org-insert-link-history
10234 (or (car (car org-stored-links)))))
10235 (setq entry (assoc link org-stored-links))
10236 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10237 (not org-keep-stored-link-after-insertion))
10238 (setq org-stored-links (delq (assoc link org-stored-links)
10239 org-stored-links)))
10240 (setq link (if entry (nth 1 entry) link)
10241 desc (or desc (nth 2 entry)))))
10242
10243 (if (string-match org-plain-link-re link)
10244 ;; URL-like link, normalize the use of angular brackets.
10245 (setq link (org-make-link (org-remove-angle-brackets link))))
10246
10247 ;; Check if we are linking to the current file with a search option
10248 ;; If yes, simplify the link by using only the search option.
10249 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
10250 (let* ((path (match-string 1 link))
10251 (case-fold-search nil)
10252 (search (match-string 2 link)))
10253 (save-match-data
10254 (if (equal (file-truename buffer-file-name) (file-truename path))
10255 ;; We are linking to this same file, with a search option
10256 (setq link search)))))
10257
10258 ;; Check if we can/should use a relative path. If yes, simplify the link
10259 (when (string-match "\\<file:\\(.*\\)" link)
10260 (let* ((path (match-string 1 link))
10261 (case-fold-search nil))
10262 (cond
10263 ((eq org-link-file-path-type 'absolute)
10264 (setq path (abbreviate-file-name (expand-file-name path))))
10265 ((eq org-link-file-path-type 'noabbrev)
10266 (setq path (expand-file-name path)))
10267 ((eq org-link-file-path-type 'relative)
10268 (setq path (file-relative-name path)))
10269 (t
10270 (save-match-data
10271 (if (string-match (concat "^" (regexp-quote
10272 (file-name-as-directory
10273 (expand-file-name "."))))
10274 (expand-file-name path))
10275 ;; We are linking a file with relative path name.
10276 (setq path (substring (expand-file-name path)
10277 (match-end 0)))))))
10278 (setq link (concat "file:" path))))
10279
10280 (setq desc (read-string "Description: " desc))
10281 (unless (string-match "\\S-" desc) (setq desc nil))
10282 (if remove (apply 'delete-region remove))
10283 (insert (org-make-link-string link desc))))
10284
10285 (defun org-completing-read (&rest args)
10286 (let ((minibuffer-local-completion-map
10287 (copy-keymap minibuffer-local-completion-map)))
10288 (define-key minibuffer-local-completion-map " " 'self-insert-command)
10289 (apply 'completing-read args)))
10290
10291 ;;; Hooks for remember.el
10292
10293 (defvar org-finish-function nil)
10294
10295 ;;;###autoload
10296 (defun org-remember-annotation ()
10297 "Return a link to the current location as an annotation for remember.el.
10298 If you are using Org-mode files as target for data storage with
10299 remember.el, then the annotations should include a link compatible with the
10300 conventions in Org-mode. This function returns such a link."
10301 (org-store-link nil))
10302
10303 (defconst org-remember-help
10304 "Select a destination location for the note.
10305 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
10306 RET at beg-of-buf -> Append to file as level 2 headline
10307 RET on headline -> Store as sublevel entry to current headline
10308 <left>/<right> -> before/after current headline, same headings level")
10309
10310 ;;;###autoload
10311 (defun org-remember-apply-template ()
10312 "Initialize *remember* buffer with template, invoke `org-mode'.
10313 This function should be placed into `remember-mode-hook' and in fact requires
10314 to be run from that hook to fucntion properly."
10315 (if org-remember-templates
10316
10317 (let* ((entry (if (= (length org-remember-templates) 1)
10318 (cdar org-remember-templates)
10319 (message "Select template: %s"
10320 (mapconcat
10321 (lambda (x) (char-to-string (car x)))
10322 org-remember-templates " "))
10323 (cdr (assoc (read-char-exclusive) org-remember-templates))))
10324 (tpl (car entry))
10325 (file (if (consp (cdr entry)) (nth 1 entry)))
10326 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10327 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10328 (v-u (concat "[" (substring v-t 1 -1) "]"))
10329 (v-U (concat "[" (substring v-T 1 -1) "]"))
10330 (v-a annotation) ; defined in `remember-mode'
10331 (v-i initial) ; defined in `remember-mode'
10332 (v-n user-full-name)
10333 )
10334 (unless tpl (setq tpl "") (message "No template") (ding))
10335 (insert tpl) (goto-char (point-min))
10336 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
10337 (when (and initial (equal (match-string 0) "%i"))
10338 (save-match-data
10339 (let* ((lead (buffer-substring
10340 (point-at-bol) (match-beginning 0))))
10341 (setq v-i (mapconcat 'identity
10342 (org-split-string initial "\n")
10343 (concat "\n" lead))))))
10344 (replace-match
10345 (or (eval (intern (concat "v-" (match-string 1)))) "")
10346 t t))
10347 (let ((org-startup-folded nil)
10348 (org-startup-with-deadline-check nil))
10349 (org-mode))
10350 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10351 (org-set-local 'org-default-notes-file file))
10352 (goto-char (point-min))
10353 (if (re-search-forward "%\\?" nil t) (replace-match "")))
10354 (let ((org-startup-folded nil)
10355 (org-startup-with-deadline-check nil))
10356 (org-mode)))
10357 (org-set-local 'org-finish-function 'remember-buffer))
10358
10359 ;;;###autoload
10360 (defun org-remember-handler ()
10361 "Store stuff from remember.el into an org file.
10362 First prompts for an org file. If the user just presses return, the value
10363 of `org-default-notes-file' is used.
10364 Then the command offers the headings tree of the selected file in order to
10365 file the text at a specific location.
10366 You can either immediately press RET to get the note appended to the
10367 file, or you can use vertical cursor motion and visibility cycling (TAB) to
10368 find a better place. Then press RET or <left> or <right> in insert the note.
10369
10370 Key Cursor position Note gets inserted
10371 -----------------------------------------------------------------------------
10372 RET buffer-start as level 2 heading at end of file
10373 RET on headline as sublevel of the heading at cursor
10374 RET no heading at cursor position, level taken from context.
10375 Or use prefix arg to specify level manually.
10376 <left> on headline as same level, before current heading
10377 <right> on headline as same level, after current heading
10378
10379 So the fastest way to store the note is to press RET RET to append it to
10380 the default file. This way your current train of thought is not
10381 interrupted, in accordance with the principles of remember.el. But with
10382 little extra effort, you can push it directly to the correct location.
10383
10384 Before being stored away, the function ensures that the text has a
10385 headline, i.e. a first line that starts with a \"*\". If not, a headline
10386 is constructed from the current date and some additional data.
10387
10388 If the variable `org-adapt-indentation' is non-nil, the entire text is
10389 also indented so that it starts in the same column as the headline
10390 \(i.e. after the stars).
10391
10392 See also the variable `org-reverse-note-order'."
10393 (catch 'quit
10394 (let* ((txt (buffer-substring (point-min) (point-max)))
10395 (fastp current-prefix-arg)
10396 (file (if fastp org-default-notes-file (org-get-org-file)))
10397 (visiting (find-buffer-visiting file))
10398 (org-startup-with-deadline-check nil)
10399 (org-startup-folded nil)
10400 (org-startup-align-all-tables nil)
10401 spos level indent reversed)
10402 ;; Modify text so that it becomes a nice subtree which can be inserted
10403 ;; into an org tree.
10404 (let* ((lines (split-string txt "\n"))
10405 first)
10406 ;; remove empty lines at the beginning
10407 (while (and lines (string-match "^[ \t]*\n" (car lines)))
10408 (setq lines (cdr lines)))
10409 (setq first (car lines) lines (cdr lines))
10410 (if (string-match "^\\*+" first)
10411 ;; Is already a headline
10412 (setq indent nil)
10413 ;; We need to add a headline: Use time and first buffer line
10414 (setq lines (cons first lines)
10415 first (concat "* " (current-time-string)
10416 " (" (remember-buffer-desc) ")")
10417 indent " "))
10418 (if (and org-adapt-indentation indent)
10419 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
10420 (setq txt (concat first "\n"
10421 (mapconcat 'identity lines "\n"))))
10422 ;; Find the file
10423 (if (not visiting)
10424 (find-file-noselect file))
10425 (with-current-buffer (get-file-buffer file)
10426 (save-excursion (and (goto-char (point-min))
10427 (not (re-search-forward "^\\* " nil t))
10428 (insert "\n* Notes\n")))
10429 (setq reversed (org-notes-order-reversed-p))
10430 (save-excursion
10431 (save-restriction
10432 (widen)
10433 ;; Ask the User for a location
10434 (setq spos (if fastp 1 (org-get-location
10435 (current-buffer)
10436 org-remember-help)))
10437 (if (not spos) (throw 'quit nil)) ; return nil to show we did
10438 ; not handle this note
10439 (goto-char spos)
10440 (cond ((bobp)
10441 ;; Put it at the start or end, as level 2
10442 (save-restriction
10443 (widen)
10444 (goto-char (if reversed (point-min) (point-max)))
10445 (if (not (bolp)) (newline))
10446 (org-paste-subtree 2 txt)))
10447 ((and (org-on-heading-p nil) (not current-prefix-arg))
10448 ;; Put it below this entry, at the beg/end of the subtree
10449 (org-back-to-heading)
10450 (setq level (funcall outline-level))
10451 (if reversed
10452 (outline-end-of-heading)
10453 (outline-end-of-subtree))
10454 (if (not (bolp)) (newline))
10455 (beginning-of-line 1)
10456 (org-paste-subtree (1+ level) txt))
10457 (t
10458 ;; Put it right there, with automatic level determined by
10459 ;; org-paste-subtree or from prefix arg
10460 (org-paste-subtree current-prefix-arg txt)))
10461 (when remember-save-after-remembering
10462 (save-buffer)
10463 (if (not visiting) (kill-buffer (current-buffer)))))))))
10464 t) ;; return t to indicate that we took care of this note.
10465
10466 (defun org-get-org-file ()
10467 "Read a filename, with default directory `org-directory'."
10468 (let ((default (or org-default-notes-file remember-data-file)))
10469 (read-file-name (format "File name [%s]: " default)
10470 (file-name-as-directory org-directory)
10471 default)))
10472
10473 (defun org-notes-order-reversed-p ()
10474 "Check if the current file should receive notes in reversed order."
10475 (cond
10476 ((not org-reverse-note-order) nil)
10477 ((eq t org-reverse-note-order) t)
10478 ((not (listp org-reverse-note-order)) nil)
10479 (t (catch 'exit
10480 (let ((all org-reverse-note-order)
10481 entry)
10482 (while (setq entry (pop all))
10483 (if (string-match (car entry) buffer-file-name)
10484 (throw 'exit (cdr entry))))
10485 nil)))))
10486
10487 ;;; Tables
10488
10489 ;; Watch out: Here we are talking about two different kind of tables.
10490 ;; Most of the code is for the tables created with the Org-mode table editor.
10491 ;; Sometimes, we talk about tables created and edited with the table.el
10492 ;; Emacs package. We call the former org-type tables, and the latter
10493 ;; table.el-type tables.
10494
10495
10496 (defun org-before-change-function (beg end)
10497 "Every change indicates that a table might need an update."
10498 (setq org-table-may-need-update t))
10499
10500 (defconst org-table-line-regexp "^[ \t]*|"
10501 "Detects an org-type table line.")
10502 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
10503 "Detects an org-type table line.")
10504 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
10505 "Detects a table line marked for automatic recalculation.")
10506 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
10507 "Detects a table line marked for automatic recalculation.")
10508 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
10509 "Detects a table line marked for automatic recalculation.")
10510 (defconst org-table-hline-regexp "^[ \t]*|-"
10511 "Detects an org-type table hline.")
10512 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
10513 "Detects a table-type table hline.")
10514 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
10515 "Detects an org-type or table-type table.")
10516 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
10517 "Searching from within a table (any type) this finds the first line
10518 outside the table.")
10519 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
10520 "Searching from within a table (any type) this finds the first line
10521 outside the table.")
10522
10523 (defun org-table-create-with-table.el ()
10524 "Use the table.el package to insert a new table.
10525 If there is already a table at point, convert between Org-mode tables
10526 and table.el tables."
10527 (interactive)
10528 (require 'table)
10529 (cond
10530 ((org-at-table.el-p)
10531 (if (y-or-n-p "Convert table to Org-mode table? ")
10532 (org-table-convert)))
10533 ((org-at-table-p)
10534 (if (y-or-n-p "Convert table to table.el table? ")
10535 (org-table-convert)))
10536 (t (call-interactively 'table-insert))))
10537
10538 (defun org-table-create-or-convert-from-region (arg)
10539 "Convert region to table, or create an empty table.
10540 If there is an active region, convert it to a table. If there is no such
10541 region, create an empty table."
10542 (interactive "P")
10543 (if (org-region-active-p)
10544 (org-table-convert-region (region-beginning) (region-end) arg)
10545 (org-table-create arg)))
10546
10547 (defun org-table-create (&optional size)
10548 "Query for a size and insert a table skeleton.
10549 SIZE is a string Columns x Rows like for example \"3x2\"."
10550 (interactive "P")
10551 (unless size
10552 (setq size (read-string
10553 (concat "Table size Columns x Rows [e.g. "
10554 org-table-default-size "]: ")
10555 "" nil org-table-default-size)))
10556
10557 (let* ((pos (point))
10558 (indent (make-string (current-column) ?\ ))
10559 (split (org-split-string size " *x *"))
10560 (rows (string-to-number (nth 1 split)))
10561 (columns (string-to-number (car split)))
10562 (line (concat (apply 'concat indent "|" (make-list columns " |"))
10563 "\n")))
10564 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
10565 (point-at-bol) (point)))
10566 (beginning-of-line 1)
10567 (newline))
10568 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
10569 (dotimes (i rows) (insert line))
10570 (goto-char pos)
10571 (if (> rows 1)
10572 ;; Insert a hline after the first row.
10573 (progn
10574 (end-of-line 1)
10575 (insert "\n|-")
10576 (goto-char pos)))
10577 (org-table-align)))
10578
10579 (defun org-table-convert-region (beg0 end0 &optional nspace)
10580 "Convert region to a table.
10581 The region goes from BEG0 to END0, but these borders will be moved
10582 slightly, to make sure a beginning of line in the first line is included.
10583 When NSPACE is non-nil, it indicates the minimum number of spaces that
10584 separate columns (default: just one space)."
10585 (interactive "rP")
10586 (let* ((beg (min beg0 end0))
10587 (end (max beg0 end0))
10588 (tabsep t)
10589 re)
10590 (goto-char beg)
10591 (beginning-of-line 1)
10592 (setq beg (move-marker (make-marker) (point)))
10593 (goto-char end)
10594 (if (bolp) (backward-char 1) (end-of-line 1))
10595 (setq end (move-marker (make-marker) (point)))
10596 ;; Lets see if this is tab-separated material. If every nonempty line
10597 ;; contains a tab, we will assume that it is tab-separated material
10598 (if nspace
10599 (setq tabsep nil)
10600 (goto-char beg)
10601 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
10602 (if nspace (setq tabsep nil))
10603 (if tabsep
10604 (setq re "^\\|\t")
10605 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
10606 (max 1 (prefix-numeric-value nspace)))))
10607 (goto-char beg)
10608 (while (re-search-forward re end t)
10609 (replace-match "|" t t))
10610 (goto-char beg)
10611 (insert " ")
10612 (org-table-align)))
10613
10614 (defun org-table-import (file arg)
10615 "Import FILE as a table.
10616 The file is assumed to be tab-separated. Such files can be produced by most
10617 spreadsheet and database applications. If no tabs (at least one per line)
10618 are found, lines will be split on whitespace into fields."
10619 (interactive "f\nP")
10620 (or (bolp) (newline))
10621 (let ((beg (point))
10622 (pm (point-max)))
10623 (insert-file-contents file)
10624 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
10625
10626 (defun org-table-export ()
10627 "Export table as a tab-separated file.
10628 Such a file can be imported into a spreadsheet program like Excel."
10629 (interactive)
10630 (let* ((beg (org-table-begin))
10631 (end (org-table-end))
10632 (table (buffer-substring beg end))
10633 (file (read-file-name "Export table to: "))
10634 buf)
10635 (unless (or (not (file-exists-p file))
10636 (y-or-n-p (format "Overwrite file %s? " file)))
10637 (error "Abort"))
10638 (with-current-buffer (find-file-noselect file)
10639 (setq buf (current-buffer))
10640 (erase-buffer)
10641 (fundamental-mode)
10642 (insert table)
10643 (goto-char (point-min))
10644 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
10645 (replace-match "" t t)
10646 (end-of-line 1))
10647 (goto-char (point-min))
10648 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
10649 (replace-match "" t t)
10650 (goto-char (min (1+ (point)) (point-max))))
10651 (goto-char (point-min))
10652 (while (re-search-forward "^-[-+]*$" nil t)
10653 (replace-match "")
10654 (if (looking-at "\n")
10655 (delete-char 1)))
10656 (goto-char (point-min))
10657 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
10658 (replace-match "\t" t t))
10659 (save-buffer))
10660 (kill-buffer buf)))
10661
10662 (defvar org-table-aligned-begin-marker (make-marker)
10663 "Marker at the beginning of the table last aligned.
10664 Used to check if cursor still is in that table, to minimize realignment.")
10665 (defvar org-table-aligned-end-marker (make-marker)
10666 "Marker at the end of the table last aligned.
10667 Used to check if cursor still is in that table, to minimize realignment.")
10668 (defvar org-table-last-alignment nil
10669 "List of flags for flushright alignment, from the last re-alignment.
10670 This is being used to correctly align a single field after TAB or RET.")
10671 (defvar org-table-last-column-widths nil
10672 "List of max width of fields in each column.
10673 This is being used to correctly align a single field after TAB or RET.")
10674
10675 (defvar org-last-recalc-line nil)
10676 (defconst org-narrow-column-arrow "=>"
10677 "Used as display property in narrowed table columns.")
10678
10679 (defun org-table-align ()
10680 "Align the table at point by aligning all vertical bars."
10681 (interactive)
10682 (let* (
10683 ;; Limits of table
10684 (beg (org-table-begin))
10685 (end (org-table-end))
10686 ;; Current cursor position
10687 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10688 (colpos (org-table-current-column))
10689 (winstart (window-start))
10690 lines (new "") lengths l typenums ty fields maxfields i
10691 column
10692 (indent "") cnt frac
10693 rfmt hfmt
10694 (spaces '(1 . 1))
10695 (sp1 (car spaces))
10696 (sp2 (cdr spaces))
10697 (rfmt1 (concat
10698 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
10699 (hfmt1 (concat
10700 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
10701 emptystrings links narrow fmax f1 len c e)
10702 (untabify beg end)
10703 (remove-text-properties beg end '(org-cwidth t display t))
10704 ;; Check if we have links
10705 (goto-char beg)
10706 (setq links (re-search-forward org-bracket-link-regexp end t))
10707 ;; Make sure the link properties are right
10708 (when links (goto-char beg) (while (org-activate-bracket-links end)))
10709 ;; Check if we are narrowing any columns
10710 (goto-char beg)
10711 (setq narrow (and org-format-transports-properties-p
10712 (re-search-forward "<[0-9]+>" end t)))
10713 ;; Get the rows
10714 (setq lines (org-split-string
10715 (buffer-substring beg end) "\n"))
10716 ;; Store the indentation of the first line
10717 (if (string-match "^ *" (car lines))
10718 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
10719 ;; Mark the hlines by setting the corresponding element to nil
10720 ;; At the same time, we remove trailing space.
10721 (setq lines (mapcar (lambda (l)
10722 (if (string-match "^ *|-" l)
10723 nil
10724 (if (string-match "[ \t]+$" l)
10725 (substring l 0 (match-beginning 0))
10726 l)))
10727 lines))
10728 ;; Get the data fields by splitting the lines.
10729 (setq fields (mapcar
10730 (lambda (l)
10731 (org-split-string l " *| *"))
10732 (delq nil (copy-sequence lines))))
10733 ;; How many fields in the longest line?
10734 (condition-case nil
10735 (setq maxfields (apply 'max (mapcar 'length fields)))
10736 (error
10737 (kill-region beg end)
10738 (org-table-create org-table-default-size)
10739 (error "Empty table - created default table")))
10740 ;; A list of empty string to fill any short rows on output
10741 (setq emptystrings (make-list maxfields ""))
10742 ;; Check for special formatting.
10743 (setq i -1)
10744 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
10745 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
10746 ;; Check if there is an explicit width specified
10747 (when (and org-table-limit-column-width narrow)
10748 (setq c column fmax nil)
10749 (while c
10750 (setq e (pop c))
10751 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
10752 (setq fmax (string-to-number (match-string 1 e)) c nil)))
10753 ;; Find fields that are wider than fmax, and shorten them
10754 (when fmax
10755 (loop for xx in column do
10756 (when (and (stringp xx)
10757 (> (org-string-width xx) fmax))
10758 (org-add-props xx nil
10759 'help-echo
10760 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
10761 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
10762 (unless (> f1 1)
10763 (error "Cannot narrow field starting with wide link \"%s\""
10764 (match-string 0 xx)))
10765 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
10766 (add-text-properties (- f1 2) f1
10767 (list 'display org-narrow-column-arrow)
10768 xx)))))
10769 ;; Get the maximum width for each column
10770 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
10771 ;; Get the fraction of numbers, to decide about alignment of the column
10772 (setq cnt 0 frac 0.0)
10773 (loop for x in column do
10774 (if (equal x "")
10775 nil
10776 (setq frac ( / (+ (* frac cnt)
10777 (if (string-match org-table-number-regexp x) 1 0))
10778 (setq cnt (1+ cnt))))))
10779 (push (>= frac org-table-number-fraction) typenums))
10780 (setq lengths (nreverse lengths) typenums (nreverse typenums))
10781
10782 ;; Store the alignment of this table, for later editing of single fields
10783 (setq org-table-last-alignment typenums
10784 org-table-last-column-widths lengths)
10785
10786 ;; With invisible characters, `format' does not get the field width right
10787 ;; So we need to make these fields wide by hand.
10788 (when links
10789 (loop for i from 0 upto (1- maxfields) do
10790 (setq len (nth i lengths))
10791 (loop for j from 0 upto (1- (length fields)) do
10792 (setq c (nthcdr i (car (nthcdr j fields))))
10793 (if (and (stringp (car c))
10794 (string-match org-bracket-link-regexp (car c))
10795 (< (org-string-width (car c)) len))
10796 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
10797
10798 ;; Compute the formats needed for output of the table
10799 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
10800 (while (setq l (pop lengths))
10801 (setq ty (if (pop typenums) "" "-")) ; number types flushright
10802 (setq rfmt (concat rfmt (format rfmt1 ty l))
10803 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
10804 (setq rfmt (concat rfmt "\n")
10805 hfmt (concat (substring hfmt 0 -1) "|\n"))
10806
10807 (setq new (mapconcat
10808 (lambda (l)
10809 (if l (apply 'format rfmt
10810 (append (pop fields) emptystrings))
10811 hfmt))
10812 lines ""))
10813 ;; Replace the old one
10814 (delete-region beg end)
10815 (move-marker end nil)
10816 (move-marker org-table-aligned-begin-marker (point))
10817 (insert new)
10818 (move-marker org-table-aligned-end-marker (point))
10819 (when (and orgtbl-mode (not (org-mode-p)))
10820 (goto-char org-table-aligned-begin-marker)
10821 (while (org-hide-wide-columns org-table-aligned-end-marker)))
10822 ;; Try to move to the old location (approximately)
10823 (goto-line linepos)
10824 (set-window-start (selected-window) winstart 'noforce)
10825 (org-table-goto-column colpos)
10826 (setq org-table-may-need-update nil)
10827 ))
10828
10829 (defun org-string-width (s)
10830 "Compute width of string, ignoring invisible characters.
10831 This ignores character with invisibility property `org-link', and also
10832 characters with property `org-cwidth', because these will become invisible
10833 upon the next fontification round."
10834 (let (b)
10835 (when (or (eq t buffer-invisibility-spec)
10836 (assq 'org-link buffer-invisibility-spec))
10837 (while (setq b (text-property-any 0 (length s)
10838 'invisible 'org-link s))
10839 (setq s (concat (substring s 0 b)
10840 (substring s (or (next-single-property-change
10841 b 'invisible s) (length s)))))))
10842 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
10843 (setq s (concat (substring s 0 b)
10844 (substring s (or (next-single-property-change
10845 b 'org-cwidth s) (length s))))))
10846 (string-width s)))
10847
10848 (defun org-table-begin (&optional table-type)
10849 "Find the beginning of the table and return its position.
10850 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
10851 (save-excursion
10852 (if (not (re-search-backward
10853 (if table-type org-table-any-border-regexp
10854 org-table-border-regexp)
10855 nil t))
10856 (progn (goto-char (point-min)) (point))
10857 (goto-char (match-beginning 0))
10858 (beginning-of-line 2)
10859 (point))))
10860
10861 (defun org-table-end (&optional table-type)
10862 "Find the end of the table and return its position.
10863 With argument TABLE-TYPE, go to the end of a table.el-type table."
10864 (save-excursion
10865 (if (not (re-search-forward
10866 (if table-type org-table-any-border-regexp
10867 org-table-border-regexp)
10868 nil t))
10869 (goto-char (point-max))
10870 (goto-char (match-beginning 0)))
10871 (point-marker)))
10872
10873 (defun org-table-justify-field-maybe (&optional new)
10874 "Justify the current field, text to left, number to right.
10875 Optional argument NEW may specify text to replace the current field content."
10876 (cond
10877 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
10878 ((org-at-table-hline-p))
10879 ((and (not new)
10880 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
10881 (current-buffer)))
10882 (< (point) org-table-aligned-begin-marker)
10883 (>= (point) org-table-aligned-end-marker)))
10884 ;; This is not the same table, force a full re-align
10885 (setq org-table-may-need-update t))
10886 (t ;; realign the current field, based on previous full realign
10887 (let* ((pos (point)) s
10888 (col (org-table-current-column))
10889 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
10890 l f n o e)
10891 (when (> col 0)
10892 (skip-chars-backward "^|\n")
10893 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
10894 (progn
10895 (setq s (match-string 1)
10896 o (match-string 0)
10897 l (max 1 (- (match-end 0) (match-beginning 0) 3))
10898 e (not (= (match-beginning 2) (match-end 2))))
10899 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
10900 l (if e "|" (setq org-table-may-need-update t) ""))
10901 n (format f s))
10902 (if new
10903 (if (<= (length new) l) ;; FIXME: length -> str-width?
10904 (setq n (format f new))
10905 (setq n (concat new "|") org-table-may-need-update t)))
10906 (or (equal n o)
10907 (let (org-table-may-need-update)
10908 (replace-match n))))
10909 (setq org-table-may-need-update t))
10910 (goto-char pos))))))
10911
10912 (defun org-table-next-field ()
10913 "Go to the next field in the current table, creating new lines as needed.
10914 Before doing so, re-align the table if necessary."
10915 (interactive)
10916 (org-table-maybe-eval-formula)
10917 (org-table-maybe-recalculate-line)
10918 (if (and org-table-automatic-realign
10919 org-table-may-need-update)
10920 (org-table-align))
10921 (let ((end (org-table-end)))
10922 (if (org-at-table-hline-p)
10923 (end-of-line 1))
10924 (condition-case nil
10925 (progn
10926 (re-search-forward "|" end)
10927 (if (looking-at "[ \t]*$")
10928 (re-search-forward "|" end))
10929 (if (and (looking-at "-")
10930 org-table-tab-jumps-over-hlines
10931 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
10932 (goto-char (match-beginning 1)))
10933 (if (looking-at "-")
10934 (progn
10935 (beginning-of-line 0)
10936 (org-table-insert-row 'below))
10937 (if (looking-at " ") (forward-char 1))))
10938 (error
10939 (org-table-insert-row 'below)))))
10940
10941 (defun org-table-previous-field ()
10942 "Go to the previous field in the table.
10943 Before doing so, re-align the table if necessary."
10944 (interactive)
10945 (org-table-justify-field-maybe)
10946 (org-table-maybe-recalculate-line)
10947 (if (and org-table-automatic-realign
10948 org-table-may-need-update)
10949 (org-table-align))
10950 (if (org-at-table-hline-p)
10951 (end-of-line 1))
10952 (re-search-backward "|" (org-table-begin))
10953 (re-search-backward "|" (org-table-begin))
10954 (while (looking-at "|\\(-\\|[ \t]*$\\)")
10955 (re-search-backward "|" (org-table-begin)))
10956 (if (looking-at "| ?")
10957 (goto-char (match-end 0))))
10958
10959 (defun org-table-next-row ()
10960 "Go to the next row (same column) in the current table.
10961 Before doing so, re-align the table if necessary."
10962 (interactive)
10963 (org-table-maybe-eval-formula)
10964 (org-table-maybe-recalculate-line)
10965 (if (or (looking-at "[ \t]*$")
10966 (save-excursion (skip-chars-backward " \t") (bolp)))
10967 (newline)
10968 (if (and org-table-automatic-realign
10969 org-table-may-need-update)
10970 (org-table-align))
10971 (let ((col (org-table-current-column)))
10972 (beginning-of-line 2)
10973 (if (or (not (org-at-table-p))
10974 (org-at-table-hline-p))
10975 (progn
10976 (beginning-of-line 0)
10977 (org-table-insert-row 'below)))
10978 (org-table-goto-column col)
10979 (skip-chars-backward "^|\n\r")
10980 (if (looking-at " ") (forward-char 1)))))
10981
10982 (defun org-table-copy-down (n)
10983 "Copy a field down in the current column.
10984 If the field at the cursor is empty, copy into it the content of the nearest
10985 non-empty field above. With argument N, use the Nth non-empty field.
10986 If the current field is not empty, it is copied down to the next row, and
10987 the cursor is moved with it. Therefore, repeating this command causes the
10988 column to be filled row-by-row.
10989 If the variable `org-table-copy-increment' is non-nil and the field is an
10990 integer, it will be incremented while copying."
10991 (interactive "p")
10992 (let* ((colpos (org-table-current-column))
10993 (field (org-table-get-field))
10994 (non-empty (string-match "[^ \t]" field))
10995 (beg (org-table-begin))
10996 txt)
10997 (org-table-check-inside-data-field)
10998 (if non-empty
10999 (progn
11000 (setq txt (org-trim field))
11001 (org-table-next-row)
11002 (org-table-blank-field))
11003 (save-excursion
11004 (setq txt
11005 (catch 'exit
11006 (while (progn (beginning-of-line 1)
11007 (re-search-backward org-table-dataline-regexp
11008 beg t))
11009 (org-table-goto-column colpos t)
11010 (if (and (looking-at
11011 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
11012 (= (setq n (1- n)) 0))
11013 (throw 'exit (match-string 1))))))))
11014 (if txt
11015 (progn
11016 (if (and org-table-copy-increment
11017 (string-match "^[0-9]+$" txt))
11018 (setq txt (format "%d" (+ (string-to-number txt) 1))))
11019 (insert txt)
11020 (org-table-maybe-recalculate-line)
11021 (org-table-align))
11022 (error "No non-empty field found"))))
11023
11024 (defun org-table-check-inside-data-field ()
11025 "Is point inside a table data field?
11026 I.e. not on a hline or before the first or after the last column?
11027 This actually throws an error, so it aborts the current command."
11028 (if (or (not (org-at-table-p))
11029 (= (org-table-current-column) 0)
11030 (org-at-table-hline-p)
11031 (looking-at "[ \t]*$"))
11032 (error "Not in table data field")))
11033
11034 (defvar org-table-clip nil
11035 "Clipboard for table regions.")
11036
11037 (defun org-table-blank-field ()
11038 "Blank the current table field or active region."
11039 (interactive)
11040 (org-table-check-inside-data-field)
11041 (if (and (interactive-p) (org-region-active-p))
11042 (let (org-table-clip)
11043 (org-table-cut-region (region-beginning) (region-end)))
11044 (skip-chars-backward "^|")
11045 (backward-char 1)
11046 (if (looking-at "|[^|\n]+")
11047 (let* ((pos (match-beginning 0))
11048 (match (match-string 0))
11049 (len (org-string-width match)))
11050 (replace-match (concat "|" (make-string (1- len) ?\ )))
11051 (goto-char (+ 2 pos))
11052 (substring match 1)))))
11053
11054 (defun org-table-get-field (&optional n replace)
11055 "Return the value of the field in column N of current row.
11056 N defaults to current field.
11057 If REPLACE is a string, replace field with this value. The return value
11058 is always the old value."
11059 (and n (org-table-goto-column n))
11060 (skip-chars-backward "^|\n")
11061 (backward-char 1)
11062 (if (looking-at "|[^|\r\n]*")
11063 (let* ((pos (match-beginning 0))
11064 (val (buffer-substring (1+ pos) (match-end 0))))
11065 (if replace
11066 (replace-match (concat "|" replace)))
11067 (goto-char (min (point-at-eol) (+ 2 pos)))
11068 val)
11069 (forward-char 1) ""))
11070
11071 (defun org-table-current-column ()
11072 "Find out which column we are in.
11073 When called interactively, column is also displayed in echo area."
11074 (interactive)
11075 (if (interactive-p) (org-table-check-inside-data-field))
11076 (save-excursion
11077 (let ((cnt 0) (pos (point)))
11078 (beginning-of-line 1)
11079 (while (search-forward "|" pos t)
11080 (setq cnt (1+ cnt)))
11081 (if (interactive-p) (message "This is table column %d" cnt))
11082 cnt)))
11083
11084 (defun org-table-goto-column (n &optional on-delim force)
11085 "Move the cursor to the Nth column in the current table line.
11086 With optional argument ON-DELIM, stop with point before the left delimiter
11087 of the field.
11088 If there are less than N fields, just go to after the last delimiter.
11089 However, when FORCE is non-nil, create new columns if necessary."
11090 (interactive "p")
11091 (let ((pos (point-at-eol)))
11092 (beginning-of-line 1)
11093 (when (> n 0)
11094 (while (and (> (setq n (1- n)) -1)
11095 (or (search-forward "|" pos t)
11096 (and force
11097 (progn (end-of-line 1)
11098 (skip-chars-backward "^|")
11099 (insert " | "))))))
11100 ; (backward-char 2) t)))))
11101 (when (and force (not (looking-at ".*|")))
11102 (save-excursion (end-of-line 1) (insert " | ")))
11103 (if on-delim
11104 (backward-char 1)
11105 (if (looking-at " ") (forward-char 1))))))
11106
11107 (defun org-at-table-p (&optional table-type)
11108 "Return t if the cursor is inside an org-type table.
11109 If TABLE-TYPE is non-nil, also check for table.el-type tables."
11110 (if org-enable-table-editor
11111 (save-excursion
11112 (beginning-of-line 1)
11113 (looking-at (if table-type org-table-any-line-regexp
11114 org-table-line-regexp)))
11115 nil))
11116
11117 (defun org-at-table.el-p ()
11118 "Return t if and only if we are at a table.el table."
11119 (and (org-at-table-p 'any)
11120 (save-excursion
11121 (goto-char (org-table-begin 'any))
11122 (looking-at org-table1-hline-regexp))))
11123
11124 (defun org-table-recognize-table.el ()
11125 "If there is a table.el table nearby, recognize it and move into it."
11126 (if org-table-tab-recognizes-table.el
11127 (if (org-at-table.el-p)
11128 (progn
11129 (beginning-of-line 1)
11130 (if (looking-at org-table-dataline-regexp)
11131 nil
11132 (if (looking-at org-table1-hline-regexp)
11133 (progn
11134 (beginning-of-line 2)
11135 (if (looking-at org-table-any-border-regexp)
11136 (beginning-of-line -1)))))
11137 (if (re-search-forward "|" (org-table-end t) t)
11138 (progn
11139 (require 'table)
11140 (if (table--at-cell-p (point))
11141 t
11142 (message "recognizing table.el table...")
11143 (table-recognize-table)
11144 (message "recognizing table.el table...done")))
11145 (error "This should not happen..."))
11146 t)
11147 nil)
11148 nil))
11149
11150 (defun org-at-table-hline-p ()
11151 "Return t if the cursor is inside a hline in a table."
11152 (if org-enable-table-editor
11153 (save-excursion
11154 (beginning-of-line 1)
11155 (looking-at org-table-hline-regexp))
11156 nil))
11157
11158 (defun org-table-insert-column ()
11159 "Insert a new column into the table."
11160 (interactive)
11161 (if (not (org-at-table-p))
11162 (error "Not at a table"))
11163 (org-table-find-dataline)
11164 (let* ((col (max 1 (org-table-current-column)))
11165 (beg (org-table-begin))
11166 (end (org-table-end))
11167 ;; Current cursor position
11168 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11169 (colpos col))
11170 (goto-char beg)
11171 (while (< (point) end)
11172 (if (org-at-table-hline-p)
11173 nil
11174 (org-table-goto-column col t)
11175 (insert "| "))
11176 (beginning-of-line 2))
11177 (move-marker end nil)
11178 (goto-line linepos)
11179 (org-table-goto-column colpos)
11180 (org-table-align)
11181 (org-table-modify-formulas 'insert col)))
11182
11183 (defun org-table-find-dataline ()
11184 "Find a dataline in the current table, which is needed for column commands."
11185 (if (and (org-at-table-p)
11186 (not (org-at-table-hline-p)))
11187 t
11188 (let ((col (current-column))
11189 (end (org-table-end)))
11190 (move-to-column col)
11191 (while (and (< (point) end)
11192 (or (not (= (current-column) col))
11193 (org-at-table-hline-p)))
11194 (beginning-of-line 2)
11195 (move-to-column col))
11196 (if (and (org-at-table-p)
11197 (not (org-at-table-hline-p)))
11198 t
11199 (error
11200 "Please position cursor in a data line for column operations")))))
11201
11202 (defun org-table-delete-column ()
11203 "Delete a column from the table."
11204 (interactive)
11205 (if (not (org-at-table-p))
11206 (error "Not at a table"))
11207 (org-table-find-dataline)
11208 (org-table-check-inside-data-field)
11209 (let* ((col (org-table-current-column))
11210 (beg (org-table-begin))
11211 (end (org-table-end))
11212 ;; Current cursor position
11213 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11214 (colpos col))
11215 (goto-char beg)
11216 (while (< (point) end)
11217 (if (org-at-table-hline-p)
11218 nil
11219 (org-table-goto-column col t)
11220 (and (looking-at "|[^|\n]+|")
11221 (replace-match "|")))
11222 (beginning-of-line 2))
11223 (move-marker end nil)
11224 (goto-line linepos)
11225 (org-table-goto-column colpos)
11226 (org-table-align)
11227 (org-table-modify-formulas 'remove col)))
11228
11229 (defun org-table-move-column-right ()
11230 "Move column to the right."
11231 (interactive)
11232 (org-table-move-column nil))
11233 (defun org-table-move-column-left ()
11234 "Move column to the left."
11235 (interactive)
11236 (org-table-move-column 'left))
11237
11238 (defun org-table-move-column (&optional left)
11239 "Move the current column to the right. With arg LEFT, move to the left."
11240 (interactive "P")
11241 (if (not (org-at-table-p))
11242 (error "Not at a table"))
11243 (org-table-find-dataline)
11244 (org-table-check-inside-data-field)
11245 (let* ((col (org-table-current-column))
11246 (col1 (if left (1- col) col))
11247 (beg (org-table-begin))
11248 (end (org-table-end))
11249 ;; Current cursor position
11250 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11251 (colpos (if left (1- col) (1+ col))))
11252 (if (and left (= col 1))
11253 (error "Cannot move column further left"))
11254 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
11255 (error "Cannot move column further right"))
11256 (goto-char beg)
11257 (while (< (point) end)
11258 (if (org-at-table-hline-p)
11259 nil
11260 (org-table-goto-column col1 t)
11261 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
11262 (replace-match "|\\2|\\1|")))
11263 (beginning-of-line 2))
11264 (move-marker end nil)
11265 (goto-line linepos)
11266 (org-table-goto-column colpos)
11267 (org-table-align)
11268 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
11269
11270 (defun org-table-move-row-down ()
11271 "Move table row down."
11272 (interactive)
11273 (org-table-move-row nil))
11274 (defun org-table-move-row-up ()
11275 "Move table row up."
11276 (interactive)
11277 (org-table-move-row 'up))
11278
11279 (defun org-table-move-row (&optional up)
11280 "Move the current table line down. With arg UP, move it up."
11281 (interactive "P")
11282 (let ((col (current-column))
11283 (pos (point))
11284 (tonew (if up 0 2))
11285 txt)
11286 (beginning-of-line tonew)
11287 (if (not (org-at-table-p))
11288 (progn
11289 (goto-char pos)
11290 (error "Cannot move row further")))
11291 (goto-char pos)
11292 (beginning-of-line 1)
11293 (setq pos (point))
11294 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
11295 (delete-region (point) (1+ (point-at-eol)))
11296 (beginning-of-line tonew)
11297 (insert txt)
11298 (beginning-of-line 0)
11299 (move-to-column col)))
11300
11301 (defun org-table-insert-row (&optional arg)
11302 "Insert a new row above the current line into the table.
11303 With prefix ARG, insert below the current line."
11304 (interactive "P")
11305 (if (not (org-at-table-p))
11306 (error "Not at a table"))
11307 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
11308 (new (org-table-clean-line line)))
11309 ;; Fix the first field if necessary
11310 (if (string-match "^[ \t]*| *[#$] *|" line)
11311 (setq new (replace-match (match-string 0 line) t t new)))
11312 (beginning-of-line (if arg 2 1))
11313 (let (org-table-may-need-update) (insert-before-markers new "\n"))
11314 (beginning-of-line 0)
11315 (re-search-forward "| ?" (point-at-eol) t)
11316 (and org-table-may-need-update (org-table-align))))
11317
11318 (defun org-table-insert-hline (&optional arg)
11319 "Insert a horizontal-line below the current line into the table.
11320 With prefix ARG, insert above the current line."
11321 (interactive "P")
11322 (if (not (org-at-table-p))
11323 (error "Not at a table"))
11324 (let ((line (org-table-clean-line
11325 (buffer-substring (point-at-bol) (point-at-eol))))
11326 (col (current-column)))
11327 (while (string-match "|\\( +\\)|" line)
11328 (setq line (replace-match
11329 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
11330 ?-) "|") t t line)))
11331 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
11332 (beginning-of-line (if arg 1 2))
11333 (insert line "\n")
11334 (beginning-of-line (if arg 1 -1))
11335 (move-to-column col)))
11336
11337 (defun org-table-clean-line (s)
11338 "Convert a table line S into a string with only \"|\" and space.
11339 In particular, this does handle wide and invisible characters."
11340 (if (string-match "^[ \t]*|-" s)
11341 ;; It's a hline, just map the characters
11342 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
11343 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
11344 (setq s (replace-match
11345 (concat "|" (make-string (org-string-width (match-string 1 s))
11346 ?\ ) "|")
11347 t t s)))
11348 s))
11349
11350 (defun org-table-kill-row ()
11351 "Delete the current row or horizontal line from the table."
11352 (interactive)
11353 (if (not (org-at-table-p))
11354 (error "Not at a table"))
11355 (let ((col (current-column)))
11356 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
11357 (if (not (org-at-table-p)) (beginning-of-line 0))
11358 (move-to-column col)))
11359
11360 (defun org-table-sort-lines (beg end numericp)
11361 "Sort table lines in region.
11362 Point and mark define the first and last line to include. Both point and
11363 mark should be in the column that is used for sorting. For example, to
11364 sort according to column 3, put the mark in the first line to sort, in
11365 table column 3. Put point into the last line to be included in the sorting,
11366 also in table column 3. The command will prompt for the sorting method
11367 \(n for numerical, a for alphanumeric)."
11368 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
11369 (setq numericp (string-match "[nN]" numericp))
11370 (org-table-align) ;; Just to be safe
11371 (let* (bcol ecol cmp column lns)
11372 (goto-char beg)
11373 (org-table-check-inside-data-field)
11374 (setq column (org-table-current-column)
11375 beg (move-marker (make-marker) (point-at-bol)))
11376 (goto-char end)
11377 (org-table-check-inside-data-field)
11378 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
11379 (untabify beg end)
11380 (goto-char beg)
11381 (org-table-goto-column column)
11382 (skip-chars-backward "^|")
11383 (setq bcol (current-column))
11384 (org-table-goto-column (1+ column))
11385 (skip-chars-backward "^|")
11386 (setq ecol (1- (current-column)))
11387 (setq cmp (if numericp
11388 (lambda (a b) (< (car a) (car b)))
11389 (lambda (a b) (string< (car a) (car b)))))
11390 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
11391 (org-split-string (buffer-substring beg end) "\n")))
11392 (if numericp
11393 (setq lns (mapcar (lambda(x)
11394 (cons (string-to-number (car x)) (cdr x)))
11395 lns)))
11396 (delete-region beg end)
11397 (move-marker beg nil)
11398 (move-marker end nil)
11399 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
11400 (message "%d lines sorted %s based on column %d"
11401 (length lns)
11402 (if numericp "numerically" "alphabetically") column)))
11403
11404 (defun org-table-cut-region (beg end)
11405 "Copy region in table to the clipboard and blank all relevant fields."
11406 (interactive "r")
11407 (org-table-copy-region beg end 'cut))
11408
11409 (defun org-table-copy-region (beg end &optional cut)
11410 "Copy rectangular region in table to clipboard.
11411 A special clipboard is used which can only be accessed
11412 with `org-table-paste-rectangle'."
11413 (interactive "rP")
11414 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
11415 region cols
11416 (rpl (if cut " " nil)))
11417 (goto-char beg)
11418 (org-table-check-inside-data-field)
11419 (setq l01 (count-lines (point-min) (point))
11420 c01 (org-table-current-column))
11421 (goto-char end)
11422 (org-table-check-inside-data-field)
11423 (setq l02 (count-lines (point-min) (point))
11424 c02 (org-table-current-column))
11425 (setq l1 (min l01 l02) l2 (max l01 l02)
11426 c1 (min c01 c02) c2 (max c01 c02))
11427 (catch 'exit
11428 (while t
11429 (catch 'nextline
11430 (if (> l1 l2) (throw 'exit t))
11431 (goto-line l1)
11432 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
11433 (setq cols nil ic1 c1 ic2 c2)
11434 (while (< ic1 (1+ ic2))
11435 (push (org-table-get-field ic1 rpl) cols)
11436 (setq ic1 (1+ ic1)))
11437 (push (nreverse cols) region)
11438 (setq l1 (1+ l1)))))
11439 (setq org-table-clip (nreverse region))
11440 (if cut (org-table-align))
11441 org-table-clip))
11442
11443 (defun org-table-paste-rectangle ()
11444 "Paste a rectangular region into a table.
11445 The upper right corner ends up in the current field. All involved fields
11446 will be overwritten. If the rectangle does not fit into the present table,
11447 the table is enlarged as needed. The process ignores horizontal separator
11448 lines."
11449 (interactive)
11450 (unless (and org-table-clip (listp org-table-clip))
11451 (error "First cut/copy a region to paste!"))
11452 (org-table-check-inside-data-field)
11453 (let* ((clip org-table-clip)
11454 (line (count-lines (point-min) (point)))
11455 (col (org-table-current-column))
11456 (org-enable-table-editor t)
11457 (org-table-automatic-realign nil)
11458 c cols field)
11459 (while (setq cols (pop clip))
11460 (while (org-at-table-hline-p) (beginning-of-line 2))
11461 (if (not (org-at-table-p))
11462 (progn (end-of-line 0) (org-table-next-field)))
11463 (setq c col)
11464 (while (setq field (pop cols))
11465 (org-table-goto-column c nil 'force)
11466 (org-table-get-field nil field)
11467 (setq c (1+ c)))
11468 (beginning-of-line 2))
11469 (goto-line line)
11470 (org-table-goto-column col)
11471 (org-table-align)))
11472
11473 (defun org-table-convert ()
11474 "Convert from `org-mode' table to table.el and back.
11475 Obviously, this only works within limits. When an Org-mode table is
11476 converted to table.el, all horizontal separator lines get lost, because
11477 table.el uses these as cell boundaries and has no notion of horizontal lines.
11478 A table.el table can be converted to an Org-mode table only if it does not
11479 do row or column spanning. Multiline cells will become multiple cells.
11480 Beware, Org-mode does not test if the table can be successfully converted - it
11481 blindly applies a recipe that works for simple tables."
11482 (interactive)
11483 (require 'table)
11484 (if (org-at-table.el-p)
11485 ;; convert to Org-mode table
11486 (let ((beg (move-marker (make-marker) (org-table-begin t)))
11487 (end (move-marker (make-marker) (org-table-end t))))
11488 (table-unrecognize-region beg end)
11489 (goto-char beg)
11490 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
11491 (replace-match ""))
11492 (goto-char beg))
11493 (if (org-at-table-p)
11494 ;; convert to table.el table
11495 (let ((beg (move-marker (make-marker) (org-table-begin)))
11496 (end (move-marker (make-marker) (org-table-end))))
11497 ;; first, get rid of all horizontal lines
11498 (goto-char beg)
11499 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
11500 (replace-match ""))
11501 ;; insert a hline before first
11502 (goto-char beg)
11503 (org-table-insert-hline 'above)
11504 (beginning-of-line -1)
11505 ;; insert a hline after each line
11506 (while (progn (beginning-of-line 3) (< (point) end))
11507 (org-table-insert-hline))
11508 (goto-char beg)
11509 (setq end (move-marker end (org-table-end)))
11510 ;; replace "+" at beginning and ending of hlines
11511 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
11512 (replace-match "\\1+-"))
11513 (goto-char beg)
11514 (while (re-search-forward "-|[ \t]*$" end t)
11515 (replace-match "-+"))
11516 (goto-char beg)))))
11517
11518 (defun org-table-wrap-region (arg)
11519 "Wrap several fields in a column like a paragraph.
11520 This is useful if you'd like to spread the contents of a field over several
11521 lines, in order to keep the table compact.
11522
11523 If there is an active region, and both point and mark are in the same column,
11524 the text in the column is wrapped to minimum width for the given number of
11525 lines. Generally, this makes the table more compact. A prefix ARG may be
11526 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
11527 formats the selected text to two lines. If the region was longer than two
11528 lines, the remaining lines remain empty. A negative prefix argument reduces
11529 the current number of lines by that amount. The wrapped text is pasted back
11530 into the table. If you formatted it to more lines than it was before, fields
11531 further down in the table get overwritten - so you might need to make space in
11532 the table first.
11533
11534 If there is no region, the current field is split at the cursor position and
11535 the text fragment to the right of the cursor is prepended to the field one
11536 line down.
11537
11538 If there is no region, but you specify a prefix ARG, the current field gets
11539 blank, and the content is appended to the field above."
11540 (interactive "P")
11541 (org-table-check-inside-data-field)
11542 (if (org-region-active-p)
11543 ;; There is a region: fill as a paragraph
11544 (let ((beg (region-beginning))
11545 nlines)
11546 (org-table-cut-region (region-beginning) (region-end))
11547 (if (> (length (car org-table-clip)) 1)
11548 (error "Region must be limited to single column"))
11549 (setq nlines (if arg
11550 (if (< arg 1)
11551 (+ (length org-table-clip) arg)
11552 arg)
11553 (length org-table-clip)))
11554 (setq org-table-clip
11555 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
11556 nil nlines)))
11557 (goto-char beg)
11558 (org-table-paste-rectangle))
11559 ;; No region, split the current field at point
11560 (if arg
11561 ;; combine with field above
11562 (let ((s (org-table-blank-field))
11563 (col (org-table-current-column)))
11564 (beginning-of-line 0)
11565 (while (org-at-table-hline-p) (beginning-of-line 0))
11566 (org-table-goto-column col)
11567 (skip-chars-forward "^|")
11568 (skip-chars-backward " ")
11569 (insert " " (org-trim s))
11570 (org-table-align))
11571 ;; split field
11572 (when (looking-at "\\([^|]+\\)+|")
11573 (let ((s (match-string 1)))
11574 (replace-match " |")
11575 (goto-char (match-beginning 0))
11576 (org-table-next-row)
11577 (insert (org-trim s) " ")
11578 (org-table-align))))))
11579
11580 (defvar org-field-marker nil)
11581
11582 (defun org-table-edit-field (arg)
11583 "Edit table field in a different window.
11584 This is mainly useful for fields that contain hidden parts.
11585 When called with a \\[universal-argument] prefix, just make the full field visible so that
11586 it can be edited in place."
11587 (interactive "P")
11588 (if arg
11589 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
11590 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
11591 (remove-text-properties b e '(org-cwidth t invisible t
11592 display t intangible t))
11593 (if (and (boundp 'font-lock-mode) font-lock-mode)
11594 (font-lock-fontify-block)))
11595 (let ((pos (move-marker (make-marker) (point)))
11596 (field (org-table-get-field))
11597 (cw (current-window-configuration))
11598 p)
11599 (switch-to-buffer-other-window "*Org tmp*")
11600 (erase-buffer)
11601 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
11602 (org-mode)
11603 (goto-char (setq p (point-max)))
11604 (insert (org-trim field))
11605 (remove-text-properties p (point-max)
11606 '(invisible t org-cwidth t display t
11607 intangible t))
11608 (goto-char p)
11609 (org-set-local 'org-finish-function
11610 'org-table-finish-edit-field)
11611 (org-set-local 'org-window-configuration cw)
11612 (org-set-local 'org-field-marker pos)
11613 (message "Edit and finish with C-c C-c"))))
11614
11615 (defun org-table-finish-edit-field ()
11616 "Finish editing a table data field.
11617 Remove all newline characters, insert the result into the table, realign
11618 the table and kill the editing buffer."
11619 (let ((pos org-field-marker)
11620 (cw org-window-configuration)
11621 (cb (current-buffer))
11622 text)
11623 (goto-char (point-min))
11624 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
11625 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
11626 (replace-match " "))
11627 (setq text (org-trim (buffer-string)))
11628 (set-window-configuration cw)
11629 (kill-buffer cb)
11630 (select-window (get-buffer-window (marker-buffer pos)))
11631 (goto-char pos)
11632 (move-marker pos nil)
11633 (org-table-check-inside-data-field)
11634 (org-table-get-field nil text)
11635 (org-table-align)
11636 (message "New field value inserted")))
11637
11638 (defun org-trim (s)
11639 "Remove whitespace at beginning and end of string."
11640 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
11641 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
11642 s)
11643
11644 (defun org-wrap (string &optional width lines)
11645 "Wrap string to either a number of lines, or a width in characters.
11646 If WIDTH is non-nil, the string is wrapped to that width, however many lines
11647 that costs. If there is a word longer than WIDTH, the text is actually
11648 wrapped to the length of that word.
11649 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
11650 many lines, whatever width that takes.
11651 The return value is a list of lines, without newlines at the end."
11652 (let* ((words (org-split-string string "[ \t\n]+"))
11653 (maxword (apply 'max (mapcar 'org-string-width words)))
11654 w ll)
11655 (cond (width
11656 (org-do-wrap words (max maxword width)))
11657 (lines
11658 (setq w maxword)
11659 (setq ll (org-do-wrap words maxword))
11660 (if (<= (length ll) lines)
11661 ll
11662 (setq ll words)
11663 (while (> (length ll) lines)
11664 (setq w (1+ w))
11665 (setq ll (org-do-wrap words w)))
11666 ll))
11667 (t (error "Cannot wrap this")))))
11668
11669
11670 (defun org-do-wrap (words width)
11671 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
11672 (let (lines line)
11673 (while words
11674 (setq line (pop words))
11675 (while (and words (< (+ (length line) (length (car words))) width))
11676 (setq line (concat line " " (pop words))))
11677 (setq lines (push line lines)))
11678 (nreverse lines)))
11679
11680 (defun org-split-string (string &optional separators)
11681 "Splits STRING into substrings at SEPARATORS.
11682 No empty strings are returned if there are matches at the beginning
11683 and end of string."
11684 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
11685 (start 0)
11686 notfirst
11687 (list nil))
11688 (while (and (string-match rexp string
11689 (if (and notfirst
11690 (= start (match-beginning 0))
11691 (< start (length string)))
11692 (1+ start) start))
11693 (< (match-beginning 0) (length string)))
11694 (setq notfirst t)
11695 (or (eq (match-beginning 0) 0)
11696 (and (eq (match-beginning 0) (match-end 0))
11697 (eq (match-beginning 0) start))
11698 (setq list
11699 (cons (substring string start (match-beginning 0))
11700 list)))
11701 (setq start (match-end 0)))
11702 (or (eq start (length string))
11703 (setq list
11704 (cons (substring string start)
11705 list)))
11706 (nreverse list)))
11707
11708 (defun org-table-map-tables (function)
11709 "Apply FUNCTION to the start of all tables in the buffer."
11710 (save-excursion
11711 (save-restriction
11712 (widen)
11713 (goto-char (point-min))
11714 (while (re-search-forward org-table-any-line-regexp nil t)
11715 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
11716 (beginning-of-line 1)
11717 (if (looking-at org-table-line-regexp)
11718 (save-excursion (funcall function)))
11719 (re-search-forward org-table-any-border-regexp nil 1))))
11720 (message "Mapping tables: done"))
11721
11722 (defun org-table-sum (&optional beg end nlast)
11723 "Sum numbers in region of current table column.
11724 The result will be displayed in the echo area, and will be available
11725 as kill to be inserted with \\[yank].
11726
11727 If there is an active region, it is interpreted as a rectangle and all
11728 numbers in that rectangle will be summed. If there is no active
11729 region and point is located in a table column, sum all numbers in that
11730 column.
11731
11732 If at least one number looks like a time HH:MM or HH:MM:SS, all other
11733 numbers are assumed to be times as well (in decimal hours) and the
11734 numbers are added as such.
11735
11736 If NLAST is a number, only the NLAST fields will actually be summed."
11737 (interactive)
11738 (save-excursion
11739 (let (col (timecnt 0) diff h m s org-table-clip)
11740 (cond
11741 ((and beg end)) ; beg and end given explicitly
11742 ((org-region-active-p)
11743 (setq beg (region-beginning) end (region-end)))
11744 (t
11745 (setq col (org-table-current-column))
11746 (goto-char (org-table-begin))
11747 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
11748 (error "No table data"))
11749 (org-table-goto-column col)
11750 ;not needed? (skip-chars-backward "^|")
11751 (setq beg (point))
11752 (goto-char (org-table-end))
11753 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
11754 (error "No table data"))
11755 (org-table-goto-column col)
11756 ;not needed? (skip-chars-forward "^|")
11757 (setq end (point))))
11758 (let* ((items (apply 'append (org-table-copy-region beg end)))
11759 (items1 (cond ((not nlast) items)
11760 ((>= nlast (length items)) items)
11761 (t (setq items (reverse items))
11762 (setcdr (nthcdr (1- nlast) items) nil)
11763 (nreverse items))))
11764 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
11765 items1)))
11766 (res (apply '+ numbers))
11767 (sres (if (= timecnt 0)
11768 (format "%g" res)
11769 (setq diff (* 3600 res)
11770 h (floor (/ diff 3600)) diff (mod diff 3600)
11771 m (floor (/ diff 60)) diff (mod diff 60)
11772 s diff)
11773 (format "%d:%02d:%02d" h m s))))
11774 (kill-new sres)
11775 (if (interactive-p)
11776 (message "%s"
11777 (substitute-command-keys
11778 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
11779 (length numbers) sres))))
11780 sres))))
11781
11782 (defun org-table-get-number-for-summing (s)
11783 (let (n)
11784 (if (string-match "^ *|? *" s)
11785 (setq s (replace-match "" nil nil s)))
11786 (if (string-match " *|? *$" s)
11787 (setq s (replace-match "" nil nil s)))
11788 (setq n (string-to-number s))
11789 (cond
11790 ((and (string-match "0" s)
11791 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
11792 ((string-match "\\`[ \t]+\\'" s) nil)
11793 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
11794 (let ((h (string-to-number (or (match-string 1 s) "0")))
11795 (m (string-to-number (or (match-string 2 s) "0")))
11796 (s (string-to-number (or (match-string 4 s) "0"))))
11797 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
11798 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
11799 ((equal n 0) nil)
11800 (t n))))
11801
11802 (defun org-table-get-vertical-vector (desc &optional tbeg col)
11803 "Get a calc vector from a column, accorting to descriptor DESC.
11804 Optional arguments TBEG and COL can give the beginning of the table and
11805 the current column, to avoid unnecessary parsing."
11806 (save-excursion
11807 (or tbeg (setq tbeg (org-table-begin)))
11808 (or col (setq col (org-table-current-column)))
11809 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
11810 (cond
11811 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
11812 (setq n1 (- (match-end 1) (match-beginning 1)))
11813 (if (match-beginning 3)
11814 (setq n2 (- (match-end 2) (match-beginning 3))))
11815 (setq n (if n2 (max n1 n2) n1))
11816 (setq n1 (if n2 (min n1 n2)))
11817 (setq nn n)
11818 (while (and (> nn 0)
11819 (re-search-backward org-table-hline-regexp tbeg t))
11820 (push (org-current-line) hline-list)
11821 (setq nn (1- nn)))
11822 (setq hline-list (nreverse hline-list))
11823 (goto-line (nth (1- n) hline-list))
11824 (when (re-search-forward org-table-dataline-regexp)
11825 (org-table-goto-column col)
11826 (setq beg (point)))
11827 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
11828 (when (re-search-backward org-table-dataline-regexp)
11829 (org-table-goto-column col)
11830 (setq end (point)))
11831 (setq l (apply 'append (org-table-copy-region beg end)))
11832 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
11833 (if (equal x "") "0" x))
11834 l ",") "]"))
11835 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
11836 (setq n1 (string-to-number (match-string 1 desc))
11837 n2 (string-to-number (match-string 2 desc)))
11838 (beginning-of-line 1)
11839 (save-excursion
11840 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
11841 (org-table-goto-column col)
11842 (setq beg (point))))
11843 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
11844 (org-table-goto-column col)
11845 (setq end (point)))
11846 (setq l (apply 'append (org-table-copy-region beg end)))
11847 (concat "[" (mapconcat
11848 (lambda (x) (setq x (org-trim x))
11849 (if (equal x "") "0" x))
11850 l ",") "]"))
11851 ((string-match "\\([0-9]+\\)" desc)
11852 (beginning-of-line 1)
11853 (when (re-search-backward org-table-dataline-regexp tbeg t
11854 (string-to-number (match-string 0 desc)))
11855 (org-table-goto-column col)
11856 (org-trim (org-table-get-field))))))))
11857
11858 (defvar org-table-formula-history nil)
11859
11860 (defvar org-table-column-names nil
11861 "Alist with column names, derived from the `!' line.")
11862 (defvar org-table-column-name-regexp nil
11863 "Regular expression matching the current column names.")
11864 (defvar org-table-local-parameters nil
11865 "Alist with parameter names, derived from the `$' line.")
11866 (defvar org-table-named-field-locations nil
11867 "Alist with locations of named fields.")
11868
11869 (defun org-table-get-formula (&optional equation named)
11870 "Read a formula from the minibuffer, offer stored formula as default."
11871 (let* ((name (car (rassoc (list (org-current-line)
11872 (org-table-current-column))
11873 org-table-named-field-locations)))
11874 (scol (if named
11875 (if name name
11876 (error "Not in a named field"))
11877 (int-to-string (org-table-current-column))))
11878 (dummy (and name (not named)
11879 (not (y-or-n-p "Replace named-field formula with column equation? " ))
11880 (error "Abort")))
11881 (org-table-may-need-update nil)
11882 (stored-list (org-table-get-stored-formulas))
11883 (stored (cdr (assoc scol stored-list)))
11884 (eq (cond
11885 ((and stored equation (string-match "^ *=? *$" equation))
11886 stored)
11887 ((stringp equation)
11888 equation)
11889 (t (read-string
11890 (format "%s formula $%s=" (if named "Field" "Column") scol)
11891 (or stored "") 'org-table-formula-history
11892 ;stored
11893 ))))
11894 mustsave)
11895 (when (not (string-match "\\S-" eq))
11896 ;; remove formula
11897 (setq stored-list (delq (assoc scol stored-list) stored-list))
11898 (org-table-store-formulas stored-list)
11899 (error "Formula removed"))
11900 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
11901 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
11902 (if (and name (not named))
11903 ;; We set the column equation, delete the named one.
11904 (setq stored-list (delq (assoc name stored-list) stored-list)
11905 mustsave t))
11906 (if stored
11907 (setcdr (assoc scol stored-list) eq)
11908 (setq stored-list (cons (cons scol eq) stored-list)))
11909 (if (or mustsave (not (equal stored eq)))
11910 (org-table-store-formulas stored-list))
11911 eq))
11912
11913 (defun org-table-store-formulas (alist)
11914 "Store the list of formulas below the current table."
11915 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
11916 (save-excursion
11917 (goto-char (org-table-end))
11918 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
11919 (delete-region (point) (match-end 0)))
11920 (insert "#+TBLFM: "
11921 (mapconcat (lambda (x)
11922 (concat "$" (car x) "=" (cdr x)))
11923 alist "::")
11924 "\n")))
11925
11926 (defun org-table-get-stored-formulas ()
11927 "Return an alist with the stored formulas directly after current table."
11928 (interactive)
11929 (let (scol eq eq-alist strings string seen)
11930 (save-excursion
11931 (goto-char (org-table-end))
11932 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
11933 (setq strings (org-split-string (match-string 2) " *:: *"))
11934 (while (setq string (pop strings))
11935 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
11936 (setq scol (match-string 1 string)
11937 eq (match-string 2 string)
11938 eq-alist (cons (cons scol eq) eq-alist))
11939 (if (member scol seen)
11940 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
11941 (push scol seen))))))
11942 (nreverse eq-alist)))
11943
11944 (defun org-table-modify-formulas (action &rest columns)
11945 "Modify the formulas stored below the current table.
11946 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
11947 expected, for the other actions only a single column number is needed."
11948 (let ((list (org-table-get-stored-formulas))
11949 (nmax (length (org-split-string
11950 (buffer-substring (point-at-bol) (point-at-eol))
11951 "|")))
11952 col col1 col2 scol si sc1 sc2)
11953 (cond
11954 ((null list)) ; No action needed if there are no stored formulas
11955 ((eq action 'remove)
11956 (setq col (car columns)
11957 scol (int-to-string col))
11958 (org-table-replace-in-formulas list scol "INVALID")
11959 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
11960 (loop for i from (1+ col) upto nmax by 1 do
11961 (setq si (int-to-string i))
11962 (org-table-replace-in-formulas list si (int-to-string (1- i)))
11963 (if (assoc si list) (setcar (assoc si list)
11964 (int-to-string (1- i))))))
11965 ((eq action 'insert)
11966 (setq col (car columns))
11967 (loop for i from nmax downto col by 1 do
11968 (setq si (int-to-string i))
11969 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
11970 (if (assoc si list) (setcar (assoc si list)
11971 (int-to-string (1+ i))))))
11972 ((eq action 'swap)
11973 (setq col1 (car columns) col2 (nth 1 columns)
11974 sc1 (int-to-string col1) sc2 (int-to-string col2))
11975 ;; Hopefully, ZqZtZ will never be a name in a table
11976 (org-table-replace-in-formulas list sc1 "ZqZtZ")
11977 (org-table-replace-in-formulas list sc2 sc1)
11978 (org-table-replace-in-formulas list "ZqZtZ" sc2)
11979 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
11980 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
11981 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
11982 (t (error "Invalid action in `org-table-modify-formulas'")))
11983 (if list (org-table-store-formulas list))))
11984
11985 (defun org-table-replace-in-formulas (list s1 s2)
11986 (let (elt re s)
11987 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
11988 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
11989 re (concat (regexp-quote s1) "\\>"))
11990 (while (setq elt (pop list))
11991 (setq s (cdr elt))
11992 (while (string-match re s)
11993 (setq s (replace-match s2 t t s)))
11994 (setcdr elt s))))
11995
11996 (defun org-table-get-specials ()
11997 "Get the column names and local parameters for this table."
11998 (save-excursion
11999 (let ((beg (org-table-begin)) (end (org-table-end))
12000 names name fields fields1 field cnt c v line col)
12001 (setq org-table-column-names nil
12002 org-table-local-parameters nil
12003 org-table-named-field-locations nil)
12004 (goto-char beg)
12005 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
12006 (setq names (org-split-string (match-string 1) " *| *")
12007 cnt 1)
12008 (while (setq name (pop names))
12009 (setq cnt (1+ cnt))
12010 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
12011 (push (cons name (int-to-string cnt)) org-table-column-names))))
12012 (setq org-table-column-names (nreverse org-table-column-names))
12013 (setq org-table-column-name-regexp
12014 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
12015 (goto-char beg)
12016 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
12017 (setq fields (org-split-string (match-string 1) " *| *"))
12018 (while (setq field (pop fields))
12019 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
12020 (push (cons (match-string 1 field) (match-string 2 field))
12021 org-table-local-parameters))))
12022 (goto-char beg)
12023 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
12024 (setq c (match-string 1)
12025 fields (org-split-string (match-string 2) " *| *"))
12026 (save-excursion
12027 (beginning-of-line (if (equal c "_") 2 0))
12028 (setq line (org-current-line) col 1)
12029 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
12030 (setq fields1 (org-split-string (match-string 1) " *| *"))))
12031 (while (and fields1 (setq field (pop fields)))
12032 (setq v (pop fields1) col (1+ col))
12033 (when (and (stringp field) (stringp v)
12034 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
12035 (push (cons field v) org-table-local-parameters)
12036 (push (list field line col) org-table-named-field-locations)))))))
12037
12038 (defun org-this-word ()
12039 ;; Get the current word
12040 (save-excursion
12041 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
12042 (end (progn (skip-chars-forward "^ \t\n") (point))))
12043 (buffer-substring-no-properties beg end))))
12044
12045 (defun org-table-maybe-eval-formula ()
12046 "Check if the current field starts with \"=\" or \":=\".
12047 If yes, store the formula and apply it."
12048 ;; We already know we are in a table. Get field will only return a formula
12049 ;; when appropriate. It might return a separator line, but no problem.
12050 (when org-table-formula-evaluate-inline
12051 (let* ((field (org-trim (or (org-table-get-field) "")))
12052 named eq)
12053 (when (string-match "^:?=\\(.*\\)" field)
12054 (setq named (equal (string-to-char field) ?:)
12055 eq (match-string 1 field))
12056 (if (fboundp 'calc-eval)
12057 (org-table-eval-formula (if named '(4) nil) eq))))))
12058
12059 (defvar org-recalc-commands nil
12060 "List of commands triggering the recalculation of a line.
12061 Will be filled automatically during use.")
12062
12063 (defvar org-recalc-marks
12064 '((" " . "Unmarked: no special line, no automatic recalculation")
12065 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
12066 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
12067 ("!" . "Column name definition line. Reference in formula as $name.")
12068 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
12069 ("_" . "Names for values in row below this one.")
12070 ("^" . "Names for values in row above this one.")))
12071
12072 (defun org-table-rotate-recalc-marks (&optional newchar)
12073 "Rotate the recalculation mark in the first column.
12074 If in any row, the first field is not consistent with a mark,
12075 insert a new column for the markers.
12076 When there is an active region, change all the lines in the region,
12077 after prompting for the marking character.
12078 After each change, a message will be displayed indicating the meaning
12079 of the new mark."
12080 (interactive)
12081 (unless (org-at-table-p) (error "Not at a table"))
12082 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
12083 (beg (org-table-begin))
12084 (end (org-table-end))
12085 (l (org-current-line))
12086 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
12087 (l2 (if (org-region-active-p) (org-current-line (region-end))))
12088 (have-col
12089 (save-excursion
12090 (goto-char beg)
12091 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
12092 (col (org-table-current-column))
12093 (forcenew (car (assoc newchar org-recalc-marks)))
12094 epos new)
12095 (when l1
12096 (message "Change region to what mark? Type # * ! $ or SPC: ")
12097 (setq newchar (char-to-string (read-char-exclusive))
12098 forcenew (car (assoc newchar org-recalc-marks))))
12099 (if (and newchar (not forcenew))
12100 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
12101 newchar))
12102 (if l1 (goto-line l1))
12103 (save-excursion
12104 (beginning-of-line 1)
12105 (unless (looking-at org-table-dataline-regexp)
12106 (error "Not at a table data line")))
12107 (unless have-col
12108 (org-table-goto-column 1)
12109 (org-table-insert-column)
12110 (org-table-goto-column (1+ col)))
12111 (setq epos (point-at-eol))
12112 (save-excursion
12113 (beginning-of-line 1)
12114 (org-table-get-field
12115 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
12116 (concat " "
12117 (setq new (or forcenew
12118 (cadr (member (match-string 1) marks))))
12119 " ")
12120 " # ")))
12121 (if (and l1 l2)
12122 (progn
12123 (goto-line l1)
12124 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
12125 (and (looking-at org-table-dataline-regexp)
12126 (org-table-get-field 1 (concat " " new " "))))
12127 (goto-line l1)))
12128 (if (not (= epos (point-at-eol))) (org-table-align))
12129 (goto-line l)
12130 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
12131
12132 (defun org-table-maybe-recalculate-line ()
12133 "Recompute the current line if marked for it, and if we haven't just done it."
12134 (interactive)
12135 (and org-table-allow-automatic-line-recalculation
12136 (not (and (memq last-command org-recalc-commands)
12137 (equal org-last-recalc-line (org-current-line))))
12138 (save-excursion (beginning-of-line 1)
12139 (looking-at org-table-auto-recalculate-regexp))
12140 (fboundp 'calc-eval)
12141 (org-table-recalculate) t))
12142
12143 (defvar org-table-formula-debug nil
12144 "Non-nil means, debug table formulas.
12145 When nil, simply write \"#ERROR\" in corrupted fields.")
12146
12147 (defvar modes)
12148 (defsubst org-set-calc-mode (var &optional value)
12149 (if (stringp var)
12150 (setq var (assoc var '(("D" calc-angle-mode deg)
12151 ("R" calc-angle-mode rad)
12152 ("F" calc-prefer-frac t)
12153 ("S" calc-symbolic-mode t)))
12154 value (nth 2 var) var (nth 1 var)))
12155 (if (memq var modes)
12156 (setcar (cdr (memq var modes)) value)
12157 (cons var (cons value modes)))
12158 modes)
12159
12160 (defun org-table-eval-formula (&optional arg equation
12161 suppress-align suppress-const
12162 suppress-store)
12163 "Replace the table field value at the cursor by the result of a calculation.
12164
12165 This function makes use of Dave Gillespie's Calc package, in my view the
12166 most exciting program ever written for GNU Emacs. So you need to have Calc
12167 installed in order to use this function.
12168
12169 In a table, this command replaces the value in the current field with the
12170 result of a formula. It also installs the formula as the \"current\" column
12171 formula, by storing it in a special line below the table. When called
12172 with a `C-u' prefix, the current field must ba a named field, and the
12173 formula is installed as valid in only this specific field.
12174
12175 When called, the command first prompts for a formula, which is read in
12176 the minibuffer. Previously entered formulas are available through the
12177 history list, and the last used formula is offered as a default.
12178 These stored formulas are adapted correctly when moving, inserting, or
12179 deleting columns with the corresponding commands.
12180
12181 The formula can be any algebraic expression understood by the Calc package.
12182 For details, see the Org-mode manual.
12183
12184 This function can also be called from Lisp programs and offers
12185 additional arguments: EQUATION can be the formula to apply. If this
12186 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
12187 used to speed-up recursive calls by by-passing unnecessary aligns.
12188 SUPPRESS-CONST suppresses the interpretation of constants in the
12189 formula, assuming that this has been done already outside the function.
12190 SUPPRESS-STORE means the formula should not be stored, either because
12191 it is already stored, or because it is a modified equation that should
12192 not overwrite the stored one."
12193 (interactive "P")
12194 (require 'calc)
12195 (org-table-check-inside-data-field)
12196 (org-table-get-specials)
12197 (let* (fields
12198 (ndown (if (integerp arg) arg 1))
12199 (org-table-automatic-realign nil)
12200 (case-fold-search nil)
12201 (down (> ndown 1))
12202 (formula (if (and equation suppress-store)
12203 equation
12204 (org-table-get-formula equation (equal arg '(4)))))
12205 (n0 (org-table-current-column))
12206 (modes (copy-sequence org-calc-default-modes))
12207 n form fmt x ev orig c lispp)
12208 ;; Parse the format string. Since we have a lot of modes, this is
12209 ;; a lot of work. However, I think calc still uses most of the time.
12210 (if (string-match ";" formula)
12211 (let ((tmp (org-split-string formula ";")))
12212 (setq formula (car tmp)
12213 fmt (concat (cdr (assoc "%" org-table-local-parameters))
12214 (nth 1 tmp)))
12215 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
12216 (setq c (string-to-char (match-string 1 fmt))
12217 n (string-to-number (match-string 2 fmt)))
12218 (if (= c ?p)
12219 (setq modes (org-set-calc-mode 'calc-internal-prec n))
12220 (setq modes (org-set-calc-mode
12221 'calc-float-format
12222 (list (cdr (assoc c '((?n . float) (?f . fix)
12223 (?s . sci) (?e . eng))))
12224 n))))
12225 (setq fmt (replace-match "" t t fmt)))
12226 (while (string-match "[DRFS]" fmt)
12227 (setq modes (org-set-calc-mode (match-string 0 fmt)))
12228 (setq fmt (replace-match "" t t fmt)))
12229 (unless (string-match "\\S-" fmt)
12230 (setq fmt nil))))
12231 (if (and (not suppress-const) org-table-formula-use-constants)
12232 (setq formula (org-table-formula-substitute-names formula)))
12233 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
12234 (while (> ndown 0)
12235 (setq fields (org-split-string
12236 (buffer-substring
12237 (point-at-bol) (point-at-eol)) " *| *"))
12238 (if org-table-formula-numbers-only
12239 (setq fields (mapcar
12240 (lambda (x) (number-to-string (string-to-number x)))
12241 fields)))
12242 (setq ndown (1- ndown))
12243 (setq form (copy-sequence formula)
12244 lispp (equal (substring form 0 2) "'("))
12245 ;; Insert the references to fields in same row
12246 (while (string-match "\\$\\([0-9]+\\)?" form)
12247 (setq n (if (match-beginning 1)
12248 (string-to-number (match-string 1 form))
12249 n0)
12250 x (nth (1- n) fields))
12251 (unless x (error "Invalid field specifier \"%s\""
12252 (match-string 0 form)))
12253 (if (equal x "") (setq x "0"))
12254 (setq form (replace-match
12255 (if lispp x (concat "(" x ")"))
12256 t t form)))
12257 ;; Insert ranges in current column
12258 (while (string-match "\\&[-I0-9]+" form)
12259 (setq form (replace-match
12260 (save-match-data
12261 (org-table-get-vertical-vector (match-string 0 form)
12262 nil n0))
12263 t t form)))
12264 (if lispp
12265 (setq ev (eval (eval (read form)))
12266 ev (if (numberp ev) (number-to-string ev) ev))
12267 (setq ev (calc-eval (cons form modes)
12268 (if org-table-formula-numbers-only 'num))))
12269
12270 (when org-table-formula-debug
12271 (with-output-to-temp-buffer "*Help*"
12272 (princ (format "Substitution history of formula
12273 Orig: %s
12274 $xyz-> %s
12275 $1-> %s\n" orig formula form))
12276 (if (listp ev)
12277 (princ (format " %s^\nError: %s"
12278 (make-string (car ev) ?\-) (nth 1 ev)))
12279 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
12280 ev (or fmt "NONE")
12281 (if fmt (format fmt (string-to-number ev)) ev)))))
12282 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
12283 (unless (and (interactive-p) (not ndown))
12284 (unless (let (inhibit-redisplay)
12285 (y-or-n-p "Debugging Formula. Continue to next? "))
12286 (org-table-align)
12287 (error "Abort"))
12288 (delete-window (get-buffer-window "*Help*"))
12289 (message "")))
12290 (if (listp ev) (setq fmt nil ev "#ERROR"))
12291 (org-table-justify-field-maybe
12292 (if fmt (format fmt (string-to-number ev)) ev))
12293 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
12294 (call-interactively 'org-return)
12295 (setq ndown 0)))
12296 (and down (org-table-maybe-recalculate-line))
12297 (or suppress-align (and org-table-may-need-update
12298 (org-table-align)))))
12299
12300 (defun org-table-recalculate (&optional all noalign)
12301 "Recalculate the current table line by applying all stored formulas.
12302 With prefix arg ALL, do this for all lines in the table."
12303 (interactive "P")
12304 (or (memq this-command org-recalc-commands)
12305 (setq org-recalc-commands (cons this-command org-recalc-commands)))
12306 (unless (org-at-table-p) (error "Not at a table"))
12307 (org-table-get-specials)
12308 (let* ((eqlist (sort (org-table-get-stored-formulas)
12309 (lambda (a b) (string< (car a) (car b)))))
12310 (inhibit-redisplay t)
12311 (line-re org-table-dataline-regexp)
12312 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
12313 (thiscol (org-table-current-column))
12314 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
12315 ;; Insert constants in all formulas
12316 (setq eqlist
12317 (mapcar (lambda (x)
12318 (setcdr x (org-table-formula-substitute-names (cdr x)))
12319 x)
12320 eqlist))
12321 ;; Split the equation list
12322 (while (setq eq (pop eqlist))
12323 (if (<= (string-to-char (car eq)) ?9)
12324 (push eq eqlnum)
12325 (push eq eqlname)))
12326 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
12327 (if all
12328 (progn
12329 (setq end (move-marker (make-marker) (1+ (org-table-end))))
12330 (goto-char (setq beg (org-table-begin)))
12331 (if (re-search-forward org-table-calculate-mark-regexp end t)
12332 ;; This is a table with marked lines, only compute selected lines
12333 (setq line-re org-table-recalculate-regexp)
12334 ;; Move forward to the first non-header line
12335 (if (and (re-search-forward org-table-dataline-regexp end t)
12336 (re-search-forward org-table-hline-regexp end t)
12337 (re-search-forward org-table-dataline-regexp end t))
12338 (setq beg (match-beginning 0))
12339 nil))) ;; just leave beg where it is
12340 (setq beg (point-at-bol)
12341 end (move-marker (make-marker) (1+ (point-at-eol)))))
12342 (goto-char beg)
12343 (and all (message "Re-applying formulas to full table..."))
12344 (while (re-search-forward line-re end t)
12345 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
12346 ;; Unprotected line, recalculate
12347 (and all (message "Re-applying formulas to full table...(line %d)"
12348 (setq cnt (1+ cnt))))
12349 (setq org-last-recalc-line (org-current-line))
12350 (setq eql eqlnum)
12351 (while (setq entry (pop eql))
12352 (goto-line org-last-recalc-line)
12353 (org-table-goto-column (string-to-number (car entry)) nil 'force)
12354 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
12355 (goto-line thisline)
12356 (org-table-goto-column thiscol)
12357 (or noalign (and org-table-may-need-update (org-table-align))
12358 (and all (message "Re-applying formulas to %d lines...done" cnt)))
12359 ;; Now do the names fields
12360 (while (setq eq (pop eqlname))
12361 (setq name (car eq)
12362 a (assoc name org-table-named-field-locations))
12363 (when a
12364 (message "Re-applying formula to named field: %s" name)
12365 (goto-line (nth 1 a))
12366 (org-table-goto-column (nth 2 a))
12367 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
12368 ;; back to initial position
12369 (goto-line thisline)
12370 (org-table-goto-column thiscol)
12371 (or noalign (and org-table-may-need-update (org-table-align))
12372 (and all (message "Re-applying formulas...done")))))
12373
12374 (defun org-table-formula-substitute-names (f)
12375 "Replace $const with values in string F."
12376 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
12377 ;; First, check for column names
12378 (while (setq start (string-match org-table-column-name-regexp f start))
12379 (setq start (1+ start))
12380 (setq a (assoc (match-string 1 f) org-table-column-names))
12381 (setq f (replace-match (concat "$" (cdr a)) t t f)))
12382 ;; Expand ranges to vectors
12383 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
12384 (setq n1 (string-to-number (match-string 1 f))
12385 n2 (string-to-number (match-string 2 f))
12386 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
12387 s (concat "[($" (number-to-string (1- nn1)) ")"))
12388 (loop for i from nn1 upto nn2 do
12389 (setq s (concat s ",($" (int-to-string i) ")")))
12390 (setq s (concat s "]"))
12391 (if (< n2 n1) (setq s (concat "rev(" s ")")))
12392 (setq f (replace-match s t t f)))
12393 ;; Parameters and constants
12394 (setq start 0)
12395 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
12396 (setq start (1+ start))
12397 (if (setq a (save-match-data
12398 (org-table-get-constant (match-string 1 f))))
12399 (setq f (replace-match (concat "(" a ")") t t f))))
12400 (if org-table-formula-debug
12401 (put-text-property 0 (length f) :orig-formula f1 f))
12402 f))
12403
12404 (defun org-table-get-constant (const)
12405 "Find the value for a parameter or constant in a formula.
12406 Parameters get priority."
12407 (or (cdr (assoc const org-table-local-parameters))
12408 (cdr (assoc const org-table-formula-constants))
12409 (and (fboundp 'constants-get) (constants-get const))
12410 "#UNDEFINED_NAME"))
12411
12412 (defvar org-edit-formulas-map (make-sparse-keymap))
12413 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
12414 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
12415 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
12416
12417 (defvar org-pos)
12418
12419 (defun org-table-edit-formulas ()
12420 "Edit the formulas of the current table in a separate buffer."
12421 (interactive)
12422 (unless (org-at-table-p)
12423 (error "Not at a table"))
12424 (org-table-get-specials)
12425 (let ((eql (org-table-get-stored-formulas))
12426 (pos (move-marker (make-marker) (point)))
12427 (wc (current-window-configuration))
12428 entry loc s)
12429 (switch-to-buffer-other-window "*Edit Formulas*")
12430 (erase-buffer)
12431 (fundamental-mode)
12432 (org-set-local 'org-pos pos)
12433 (org-set-local 'org-window-configuration wc)
12434 (use-local-map org-edit-formulas-map)
12435 (setq s "# Edit formulas and finish with `C-c C-c'.
12436 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
12437 # Use `C-c ?' to get information about $name at point.
12438 # To cancel editing, press `C-c C-q'.\n")
12439 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12440 (insert s)
12441 (while (setq entry (pop eql))
12442 (when (setq loc (assoc (car entry) org-table-named-field-locations))
12443 (setq s (format "# Named formula, referring to column %d in line %d\n"
12444 (nth 2 loc) (nth 1 loc)))
12445 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12446 (insert s))
12447 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
12448 (remove-text-properties 0 (length s) '(face nil) s)
12449 (insert s))
12450 (goto-char (point-min))
12451 (message "Edit formulas and finish with `C-c C-c'.")))
12452
12453 (defun org-show-variable ()
12454 "Show the location/value of the $ expression at point."
12455 (interactive)
12456 (let (var (pos org-pos) (win (selected-window)) e)
12457 (save-excursion
12458 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
12459 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
12460 (setq var (match-string 1))
12461 (error "No variable at point")))
12462 (cond
12463 ((setq e (assoc var org-table-named-field-locations))
12464 (switch-to-buffer-other-window (marker-buffer pos))
12465 (goto-line (nth 1 e))
12466 (org-table-goto-column (nth 2 e))
12467 (select-window win)
12468 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
12469 ((setq e (assoc var org-table-column-names))
12470 (switch-to-buffer-other-window (marker-buffer pos))
12471 (goto-char pos)
12472 (goto-char (org-table-begin))
12473 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
12474 (org-table-end) t)
12475 (progn
12476 (goto-char (match-beginning 1))
12477 (message "Named column (column %s)" (cdr e)))
12478 (error "Column name not found"))
12479 (select-window win))
12480 ((string-match "^[0-9]$" var)
12481 ;; column number
12482 (switch-to-buffer-other-window (marker-buffer pos))
12483 (goto-char pos)
12484 (goto-char (org-table-begin))
12485 (recenter 1)
12486 (if (re-search-forward org-table-dataline-regexp
12487 (org-table-end) t)
12488 (progn
12489 (goto-char (match-beginning 0))
12490 (org-table-goto-column (string-to-number var))
12491 (message "Column %s" var))
12492 (error "Column name not found"))
12493 (select-window win))
12494 ((setq e (assoc var org-table-local-parameters))
12495 (switch-to-buffer-other-window (marker-buffer pos))
12496 (goto-char pos)
12497 (goto-char (org-table-begin))
12498 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
12499 (progn
12500 (goto-char (match-beginning 1))
12501 (message "Local parameter."))
12502 (error "Parameter not found"))
12503 (select-window win))
12504 (t
12505 (cond
12506 ((setq e (assoc var org-table-formula-constants))
12507 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
12508 ((setq e (and (fboundp 'constants-get) (constants-get var)))
12509 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
12510 (t (error "Undefined name $%s" var)))))))
12511
12512 (defun org-finish-edit-formulas (&optional arg)
12513 "Parse the buffer for formula definitions and install them.
12514 With prefix ARG, apply the new formulas to the table."
12515 (interactive "P")
12516 (let ((pos org-pos) eql)
12517 (goto-char (point-min))
12518 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
12519 (push (cons (match-string 1) (match-string 2)) eql))
12520 (set-window-configuration org-window-configuration)
12521 (select-window (get-buffer-window (marker-buffer pos)))
12522 (goto-char pos)
12523 (unless (org-at-table-p)
12524 (error "Lost table position - cannot install formulae"))
12525 (org-table-store-formulas eql)
12526 (move-marker pos nil)
12527 (kill-buffer "*Edit Formulas*")
12528 (if arg
12529 (org-table-recalculate 'all)
12530 (message "New formulas installed - press C-u C-c C-c to apply."))))
12531
12532 (defun org-abort-edit-formulas ()
12533 "Abort editing formulas, without installing the changes."
12534 (interactive)
12535 (let ((pos org-pos))
12536 (set-window-configuration org-window-configuration)
12537 (select-window (get-buffer-window (marker-buffer pos)))
12538 (goto-char pos)
12539 (message "Formula editing aborted without installing changes")))
12540
12541 ;;; The orgtbl minor mode
12542
12543 ;; Define a minor mode which can be used in other modes in order to
12544 ;; integrate the org-mode table editor.
12545
12546 ;; This is really a hack, because the org-mode table editor uses several
12547 ;; keys which normally belong to the major mode, for example the TAB and
12548 ;; RET keys. Here is how it works: The minor mode defines all the keys
12549 ;; necessary to operate the table editor, but wraps the commands into a
12550 ;; function which tests if the cursor is currently inside a table. If that
12551 ;; is the case, the table editor command is executed. However, when any of
12552 ;; those keys is used outside a table, the function uses `key-binding' to
12553 ;; look up if the key has an associated command in another currently active
12554 ;; keymap (minor modes, major mode, global), and executes that command.
12555 ;; There might be problems if any of the keys used by the table editor is
12556 ;; otherwise used as a prefix key.
12557
12558 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
12559 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
12560 ;; addresses this by checking explicitly for both bindings.
12561
12562 ;; The optimized version (see variable `orgtbl-optimized') takes over
12563 ;; all keys which are bound to `self-insert-command' in the *global map*.
12564 ;; Some modes bind other commands to simple characters, for example
12565 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
12566 ;; active, this binding is ignored inside tables and replaced with a
12567 ;; modified self-insert.
12568
12569 (defvar orgtbl-mode nil
12570 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
12571 table editor in arbitrary modes.")
12572 (make-variable-buffer-local 'orgtbl-mode)
12573
12574 (defvar orgtbl-mode-map (make-keymap)
12575 "Keymap for `orgtbl-mode'.")
12576
12577 ;;;###autoload
12578 (defun turn-on-orgtbl ()
12579 "Unconditionally turn on `orgtbl-mode'."
12580 (orgtbl-mode 1))
12581
12582 ;;;###autoload
12583 (defun orgtbl-mode (&optional arg)
12584 "The `org-mode' table editor as a minor mode for use in other modes."
12585 (interactive)
12586 (if (org-mode-p)
12587 ;; Exit without error, in case some hook functions calls this
12588 ;; by accident in org-mode.
12589 (message "Orgtbl-mode is not useful in org-mode, command ignored")
12590 (setq orgtbl-mode
12591 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
12592 (if orgtbl-mode
12593 (progn
12594 (and (orgtbl-setup) (defun orgtbl-setup () nil))
12595 ;; Make sure we are first in minor-mode-map-alist
12596 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
12597 (and c (setq minor-mode-map-alist
12598 (cons c (delq c minor-mode-map-alist)))))
12599 (org-set-local (quote org-table-may-need-update) t)
12600 (org-add-hook 'before-change-functions 'org-before-change-function
12601 nil 'local)
12602 (org-set-local 'org-old-auto-fill-inhibit-regexp
12603 auto-fill-inhibit-regexp)
12604 (org-set-local 'auto-fill-inhibit-regexp
12605 (if auto-fill-inhibit-regexp
12606 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
12607 "[ \t]*|"))
12608 (org-add-to-invisibility-spec '(org-cwidth))
12609 (easy-menu-add orgtbl-mode-menu)
12610 (run-hooks 'orgtbl-mode-hook))
12611 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
12612 (org-cleanup-narrow-column-properties)
12613 (org-remove-from-invisibility-spec '(org-cwidth))
12614 (remove-hook 'before-change-functions 'org-before-change-function t)
12615 (easy-menu-remove orgtbl-mode-menu)
12616 (force-mode-line-update 'all))))
12617
12618 (defun org-cleanup-narrow-column-properties ()
12619 "Remove all properties related to narrow-column invisibility."
12620 (let ((s 1))
12621 (while (setq s (text-property-any s (point-max)
12622 'display org-narrow-column-arrow))
12623 (remove-text-properties s (1+ s) '(display t)))
12624 (setq s 1)
12625 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
12626 (remove-text-properties s (1+ s) '(org-cwidth t)))
12627 (setq s 1)
12628 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
12629 (remove-text-properties s (1+ s) '(invisible t)))))
12630
12631 ;; Install it as a minor mode.
12632 (put 'orgtbl-mode :included t)
12633 (put 'orgtbl-mode :menu-tag "Org Table Mode")
12634 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
12635
12636 (defun orgtbl-make-binding (fun n &rest keys)
12637 "Create a function for binding in the table minor mode.
12638 FUN is the command to call inside a table. N is used to create a unique
12639 command name. KEYS are keys that should be checked in for a command
12640 to execute outside of tables."
12641 (eval
12642 (list 'defun
12643 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
12644 '(arg)
12645 (concat "In tables, run `" (symbol-name fun) "'.\n"
12646 "Outside of tables, run the binding of `"
12647 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
12648 "'.")
12649 '(interactive "p")
12650 (list 'if
12651 '(org-at-table-p)
12652 (list 'call-interactively (list 'quote fun))
12653 (list 'let '(orgtbl-mode)
12654 (list 'call-interactively
12655 (append '(or)
12656 (mapcar (lambda (k)
12657 (list 'key-binding k))
12658 keys)
12659 '('orgtbl-error))))))))
12660
12661 (defun orgtbl-error ()
12662 "Error when there is no default binding for a table key."
12663 (interactive)
12664 (error "This key is has no function outside tables"))
12665
12666 (defun orgtbl-setup ()
12667 "Setup orgtbl keymaps."
12668 (let ((nfunc 0)
12669 (bindings
12670 (list
12671 '([(meta shift left)] org-table-delete-column)
12672 '([(meta left)] org-table-move-column-left)
12673 '([(meta right)] org-table-move-column-right)
12674 '([(meta shift right)] org-table-insert-column)
12675 '([(meta shift up)] org-table-kill-row)
12676 '([(meta shift down)] org-table-insert-row)
12677 '([(meta up)] org-table-move-row-up)
12678 '([(meta down)] org-table-move-row-down)
12679 '("\C-c\C-w" org-table-cut-region)
12680 '("\C-c\M-w" org-table-copy-region)
12681 '("\C-c\C-y" org-table-paste-rectangle)
12682 '("\C-c-" org-table-insert-hline)
12683 ; '([(shift tab)] org-table-previous-field)
12684 '("\C-m" org-table-next-row)
12685 (list (org-key 'S-return) 'org-table-copy-down)
12686 '([(meta return)] org-table-wrap-region)
12687 '("\C-c\C-q" org-table-wrap-region)
12688 '("\C-c?" org-table-current-column)
12689 '("\C-c " org-table-blank-field)
12690 '("\C-c+" org-table-sum)
12691 '("\C-c=" org-table-eval-formula)
12692 '("\C-c'" org-table-edit-formulas)
12693 '("\C-c`" org-table-edit-field)
12694 '("\C-c*" org-table-recalculate)
12695 '("\C-c|" org-table-create-or-convert-from-region)
12696 '("\C-c^" org-table-sort-lines)
12697 '([(control ?#)] org-table-rotate-recalc-marks)))
12698 elt key fun cmd)
12699 (while (setq elt (pop bindings))
12700 (setq nfunc (1+ nfunc))
12701 (setq key (car elt)
12702 fun (nth 1 elt)
12703 cmd (orgtbl-make-binding fun nfunc key))
12704 (define-key orgtbl-mode-map key cmd))
12705 ;; Special treatment needed for TAB and RET
12706 (define-key orgtbl-mode-map [(return)]
12707 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
12708 (define-key orgtbl-mode-map "\C-m"
12709 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
12710 (define-key orgtbl-mode-map [(tab)]
12711 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
12712 (define-key orgtbl-mode-map "\C-i"
12713 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
12714 (define-key orgtbl-mode-map "\C-i"
12715 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
12716 (define-key orgtbl-mode-map "\C-c\C-c"
12717 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
12718 (when orgtbl-optimized
12719 ;; If the user wants maximum table support, we need to hijack
12720 ;; some standard editing functions
12721 (org-remap orgtbl-mode-map
12722 'self-insert-command 'orgtbl-self-insert-command
12723 'delete-char 'org-delete-char
12724 'delete-backward-char 'org-delete-backward-char)
12725 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
12726 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
12727 '("OrgTbl"
12728 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
12729 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
12730 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
12731 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
12732 "--"
12733 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
12734 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
12735 ["Copy Field from Above"
12736 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
12737 "--"
12738 ("Column"
12739 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
12740 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
12741 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
12742 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
12743 "--"
12744 ["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])
12745 ("Row"
12746 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
12747 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
12748 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
12749 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
12750 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
12751 "--"
12752 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
12753 ("Rectangle"
12754 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
12755 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
12756 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
12757 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
12758 "--"
12759 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
12760 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12761 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
12762 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
12763 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
12764 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
12765 ["Sum Column/Rectangle" org-table-sum
12766 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
12767 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
12768 ["Debug Formulas"
12769 (setq org-table-formula-debug (not org-table-formula-debug))
12770 :style toggle :selected org-table-formula-debug]
12771 ))
12772 t)
12773
12774 (defun orgtbl-tab (arg)
12775 "Justification and field motion for `orgtbl-mode'."
12776 (interactive "P")
12777 (if arg (org-table-edit-field t)
12778 (org-table-justify-field-maybe)
12779 (org-table-next-field)))
12780
12781 (defun orgtbl-ret ()
12782 "Justification and field motion for `orgtbl-mode'."
12783 (interactive)
12784 (org-table-justify-field-maybe)
12785 (org-table-next-row))
12786
12787 (defun orgtbl-self-insert-command (N)
12788 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12789 If the cursor is in a table looking at whitespace, the whitespace is
12790 overwritten, and the table is not marked as requiring realignment."
12791 (interactive "p")
12792 (if (and (org-at-table-p)
12793 (or
12794 (and org-table-auto-blank-field
12795 (member last-command
12796 '(orgtbl-hijacker-command-100
12797 orgtbl-hijacker-command-101
12798 orgtbl-hijacker-command-102
12799 orgtbl-hijacker-command-103
12800 orgtbl-hijacker-command-104
12801 orgtbl-hijacker-command-105))
12802 (org-table-blank-field))
12803 t)
12804 (eq N 1)
12805 (looking-at "[^|\n]* +|"))
12806 (let (org-table-may-need-update)
12807 (goto-char (1- (match-end 0)))
12808 (delete-backward-char 1)
12809 (goto-char (match-beginning 0))
12810 (self-insert-command N))
12811 (setq org-table-may-need-update t)
12812 (let (orgtbl-mode)
12813 (call-interactively (key-binding (vector last-input-event))))))
12814
12815 (defun org-force-self-insert (N)
12816 "Needed to enforce self-insert under remapping."
12817 (interactive "p")
12818 (self-insert-command N))
12819
12820 ;;; Exporting
12821
12822 (defconst org-level-max 20)
12823
12824 (defvar org-export-html-preamble nil
12825 "Preamble, to be inserted just after <body>. Set by publishing functions.")
12826 (defvar org-export-html-postamble nil
12827 "Preamble, to be inserted just before </body>. Set by publishing functions.")
12828 (defvar org-export-html-auto-preamble t
12829 "Should default preamble be inserted? Set by publishing functions.")
12830 (defvar org-export-html-auto-postamble t
12831 "Should default postamble be inserted? Set by publishing functions.")
12832
12833 (defconst org-export-plist-vars
12834 '((:language . org-export-default-language)
12835 (:headline-levels . org-export-headline-levels)
12836 (:section-numbers . org-export-with-section-numbers)
12837 (:table-of-contents . org-export-with-toc)
12838 (:archived-trees . org-export-with-archived-trees)
12839 (:emphasize . org-export-with-emphasize)
12840 (:sub-superscript . org-export-with-sub-superscripts)
12841 (:TeX-macros . org-export-with-TeX-macros)
12842 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
12843 (:fixed-width . org-export-with-fixed-width)
12844 (:timestamps . org-export-with-timestamps)
12845 (:tables . org-export-with-tables)
12846 (:table-auto-headline . org-export-highlight-first-table-line)
12847 (:style . org-export-html-style)
12848 (:convert-org-links . org-export-html-link-org-files-as-html)
12849 (:inline-images . org-export-html-inline-images)
12850 (:expand-quoted-html . org-export-html-expand)
12851 (:timestamp . org-export-html-with-timestamp)
12852 (:publishing-directory . org-export-publishing-directory)
12853 (:preamble . org-export-html-preamble)
12854 (:postamble . org-export-html-postamble)
12855 (:auto-preamble . org-export-html-auto-preamble)
12856 (:auto-postamble . org-export-html-auto-postamble)
12857 (:author . user-full-name)
12858 (:email . user-mail-address)))
12859
12860 (defun org-default-export-plist ()
12861 "Return the property list with default settings for the export variables."
12862 (let ((l org-export-plist-vars) rtn e)
12863 (while (setq e (pop l))
12864 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
12865 rtn))
12866
12867 (defun org-infile-export-plist ()
12868 "Return the property list with file-local settings for export."
12869 (save-excursion
12870 (goto-char 0)
12871 (let ((re (org-make-options-regexp
12872 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
12873 p key val text options)
12874 (while (re-search-forward re nil t)
12875 (setq key (org-match-string-no-properties 1)
12876 val (org-match-string-no-properties 2))
12877 (cond
12878 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
12879 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
12880 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
12881 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
12882 ((string-equal key "TEXT")
12883 (setq text (if text (concat text "\n" val) val)))
12884 ((string-equal key "OPTIONS") (setq options val))))
12885 (setq p (plist-put p :text text))
12886 (when options
12887 (let ((op '(("H" . :headline-levels)
12888 ("num" . :section-numbers)
12889 ("toc" . :table-of-contents)
12890 ("\\n" . :preserve-breaks)
12891 ("@" . :expand-quoted-html)
12892 (":" . :fixed-width)
12893 ("|" . :tables)
12894 ("^" . :sub-superscript)
12895 ("*" . :emphasize)
12896 ("TeX" . :TeX-macros)
12897 ("LaTeX" . :LaTeX-fragments)))
12898 o)
12899 (while (setq o (pop op))
12900 (if (string-match (concat (regexp-quote (car o))
12901 ":\\([^ \t\n\r;,.]*\\)")
12902 options)
12903 (setq p (plist-put p (cdr o)
12904 (car (read-from-string
12905 (match-string 1 options)))))))))
12906 p)))
12907
12908 (defun org-combine-plists (&rest plists)
12909 "Create a single property list from all plists in PLISTS.
12910 The process starts by copying the last list, and then setting properties
12911 from the other lists. Settings in the first list are the most significant
12912 ones and overrule settings in the other lists."
12913 (let ((rtn (copy-sequence (pop plists)))
12914 p v ls)
12915 (while plists
12916 (setq ls (pop plists))
12917 (while ls
12918 (setq p (pop ls) v (pop ls))
12919 (setq rtn (plist-put rtn p v))))
12920 rtn))
12921
12922 (defun org-export-directory (type plist)
12923 (let* ((val (plist-get plist :publishing-directory))
12924 (dir (if (listp val)
12925 (or (cdr (assoc type val)) ".")
12926 val)))
12927 dir))
12928
12929 (defun org-export-find-first-heading-line (list)
12930 "Remove all lines from LIST which are before the first headline."
12931 (let ((orig-list list)
12932 (re (concat "^" outline-regexp)))
12933 (while (and list
12934 (not (string-match re (car list))))
12935 (pop list))
12936 (or list orig-list)))
12937
12938 (defun org-skip-comments (lines)
12939 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
12940 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
12941 (re2 "^\\(\\*+\\)[ \t\n\r]")
12942 rtn line level)
12943 (while (setq line (pop lines))
12944 (cond
12945 ((and (string-match re1 line)
12946 (setq level (- (match-end 1) (match-beginning 1))))
12947 ;; Beginning of a COMMENT subtree. Skip it.
12948 (while (and (setq line (pop lines))
12949 (or (not (string-match re2 line))
12950 (> (- (match-end 1) (match-beginning 1)) level))))
12951 (setq lines (cons line lines)))
12952 ((string-match "^#" line)
12953 ;; an ordinary comment line
12954 )
12955 ((and org-export-table-remove-special-lines
12956 (string-match "^[ \t]*|" line)
12957 (or (string-match "^[ \t]*| *[!_^] *|" line)
12958 (and (string-match "| *<[0-9]+> *|" line)
12959 (not (string-match "| *[^ <|]" line)))))
12960 ;; a special table line that should be removed
12961 )
12962 (t (setq rtn (cons line rtn)))))
12963 (nreverse rtn)))
12964
12965 (defun org-export (&optional arg)
12966 (interactive)
12967 (let ((help "[t] insert the export option template
12968 \[v] limit export to visible part of outline tree
12969
12970 \[a] export as ASCII
12971 \[h] export as HTML
12972 \[b] export as HTML and browse immediately
12973 \[x] export as XOXO
12974
12975 \[i] export current file as iCalendar file
12976 \[I] export all agenda files as iCalendar files
12977 \[c] export agenda files into combined iCalendar file
12978
12979 \[F] publish current file
12980 \[P] publish current project
12981 \[X] publish... (project will be prompted for)
12982 \[A] publish all projects")
12983 (cmds
12984 '((?t . org-insert-export-options-template)
12985 (?v . org-export-visible)
12986 (?a . org-export-as-ascii)
12987 (?h . org-export-as-html)
12988 (?b . org-export-as-html-and-open)
12989 (?x . org-export-as-xoxo)
12990 (?i . org-export-icalendar-this-file)
12991 (?I . org-export-icalendar-all-agenda-files)
12992 (?c . org-export-icalendar-combine-agenda-files)
12993 (?F . org-publish-current-file)
12994 (?P . org-publish-current-project)
12995 (?X . org-publish)
12996 (?A . org-publish-all)))
12997 r1 r2 ass)
12998 (save-window-excursion
12999 (delete-other-windows)
13000 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
13001 (princ help))
13002 (message "Select command: ")
13003 (setq r1 (read-char-exclusive)))
13004 (setq r2 (if (< r1 27) (+ r1 96) r1))
13005 (if (setq ass (assq r2 cmds))
13006 (call-interactively (cdr ass))
13007 (error "No command associated with key %c" r1))))
13008
13009 ;; ASCII
13010
13011 (defconst org-html-entities
13012 '(("nbsp")
13013 ("iexcl")
13014 ("cent")
13015 ("pound")
13016 ("curren")
13017 ("yen")
13018 ("brvbar")
13019 ("sect")
13020 ("uml")
13021 ("copy")
13022 ("ordf")
13023 ("laquo")
13024 ("not")
13025 ("shy")
13026 ("reg")
13027 ("macr")
13028 ("deg")
13029 ("plusmn")
13030 ("sup2")
13031 ("sup3")
13032 ("acute")
13033 ("micro")
13034 ("para")
13035 ("middot")
13036 ("odot"."o")
13037 ("star"."*")
13038 ("cedil")
13039 ("sup1")
13040 ("ordm")
13041 ("raquo")
13042 ("frac14")
13043 ("frac12")
13044 ("frac34")
13045 ("iquest")
13046 ("Agrave")
13047 ("Aacute")
13048 ("Acirc")
13049 ("Atilde")
13050 ("Auml")
13051 ("Aring") ("AA"."&Aring;")
13052 ("AElig")
13053 ("Ccedil")
13054 ("Egrave")
13055 ("Eacute")
13056 ("Ecirc")
13057 ("Euml")
13058 ("Igrave")
13059 ("Iacute")
13060 ("Icirc")
13061 ("Iuml")
13062 ("ETH")
13063 ("Ntilde")
13064 ("Ograve")
13065 ("Oacute")
13066 ("Ocirc")
13067 ("Otilde")
13068 ("Ouml")
13069 ("times")
13070 ("Oslash")
13071 ("Ugrave")
13072 ("Uacute")
13073 ("Ucirc")
13074 ("Uuml")
13075 ("Yacute")
13076 ("THORN")
13077 ("szlig")
13078 ("agrave")
13079 ("aacute")
13080 ("acirc")
13081 ("atilde")
13082 ("auml")
13083 ("aring")
13084 ("aelig")
13085 ("ccedil")
13086 ("egrave")
13087 ("eacute")
13088 ("ecirc")
13089 ("euml")
13090 ("igrave")
13091 ("iacute")
13092 ("icirc")
13093 ("iuml")
13094 ("eth")
13095 ("ntilde")
13096 ("ograve")
13097 ("oacute")
13098 ("ocirc")
13099 ("otilde")
13100 ("ouml")
13101 ("divide")
13102 ("oslash")
13103 ("ugrave")
13104 ("uacute")
13105 ("ucirc")
13106 ("uuml")
13107 ("yacute")
13108 ("thorn")
13109 ("yuml")
13110 ("fnof")
13111 ("Alpha")
13112 ("Beta")
13113 ("Gamma")
13114 ("Delta")
13115 ("Epsilon")
13116 ("Zeta")
13117 ("Eta")
13118 ("Theta")
13119 ("Iota")
13120 ("Kappa")
13121 ("Lambda")
13122 ("Mu")
13123 ("Nu")
13124 ("Xi")
13125 ("Omicron")
13126 ("Pi")
13127 ("Rho")
13128 ("Sigma")
13129 ("Tau")
13130 ("Upsilon")
13131 ("Phi")
13132 ("Chi")
13133 ("Psi")
13134 ("Omega")
13135 ("alpha")
13136 ("beta")
13137 ("gamma")
13138 ("delta")
13139 ("epsilon")
13140 ("varepsilon"."&epsilon;")
13141 ("zeta")
13142 ("eta")
13143 ("theta")
13144 ("iota")
13145 ("kappa")
13146 ("lambda")
13147 ("mu")
13148 ("nu")
13149 ("xi")
13150 ("omicron")
13151 ("pi")
13152 ("rho")
13153 ("sigmaf") ("varsigma"."&sigmaf;")
13154 ("sigma")
13155 ("tau")
13156 ("upsilon")
13157 ("phi")
13158 ("chi")
13159 ("psi")
13160 ("omega")
13161 ("thetasym") ("vartheta"."&thetasym;")
13162 ("upsih")
13163 ("piv")
13164 ("bull") ("bullet"."&bull;")
13165 ("hellip") ("dots"."&hellip;")
13166 ("prime")
13167 ("Prime")
13168 ("oline")
13169 ("frasl")
13170 ("weierp")
13171 ("image")
13172 ("real")
13173 ("trade")
13174 ("alefsym")
13175 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
13176 ("uarr") ("uparrow"."&uarr;")
13177 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
13178 ("darr")("downarrow"."&darr;")
13179 ("harr") ("leftrightarrow"."&harr;")
13180 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
13181 ("lArr") ("Leftarrow"."&lArr;")
13182 ("uArr") ("Uparrow"."&uArr;")
13183 ("rArr") ("Rightarrow"."&rArr;")
13184 ("dArr") ("Downarrow"."&dArr;")
13185 ("hArr") ("Leftrightarrow"."&hArr;")
13186 ("forall")
13187 ("part") ("partial"."&part;")
13188 ("exist") ("exists"."&exist;")
13189 ("empty") ("emptyset"."&empty;")
13190 ("nabla")
13191 ("isin") ("in"."&isin;")
13192 ("notin")
13193 ("ni")
13194 ("prod")
13195 ("sum")
13196 ("minus")
13197 ("lowast") ("ast"."&lowast;")
13198 ("radic")
13199 ("prop") ("proptp"."&prop;")
13200 ("infin") ("infty"."&infin;")
13201 ("ang") ("angle"."&ang;")
13202 ("and") ("vee"."&and;")
13203 ("or") ("wedge"."&or;")
13204 ("cap")
13205 ("cup")
13206 ("int")
13207 ("there4")
13208 ("sim")
13209 ("cong") ("simeq"."&cong;")
13210 ("asymp")("approx"."&asymp;")
13211 ("ne") ("neq"."&ne;")
13212 ("equiv")
13213 ("le")
13214 ("ge")
13215 ("sub") ("subset"."&sub;")
13216 ("sup") ("supset"."&sup;")
13217 ("nsub")
13218 ("sube")
13219 ("supe")
13220 ("oplus")
13221 ("otimes")
13222 ("perp")
13223 ("sdot") ("cdot"."&sdot;")
13224 ("lceil")
13225 ("rceil")
13226 ("lfloor")
13227 ("rfloor")
13228 ("lang")
13229 ("rang")
13230 ("loz") ("Diamond"."&loz;")
13231 ("spades") ("spadesuit"."&spades;")
13232 ("clubs") ("clubsuit"."&clubs;")
13233 ("hearts") ("diamondsuit"."&hearts;")
13234 ("diams") ("diamondsuit"."&diams;")
13235 ("quot")
13236 ("amp")
13237 ("lt")
13238 ("gt")
13239 ("OElig")
13240 ("oelig")
13241 ("Scaron")
13242 ("scaron")
13243 ("Yuml")
13244 ("circ")
13245 ("tilde")
13246 ("ensp")
13247 ("emsp")
13248 ("thinsp")
13249 ("zwnj")
13250 ("zwj")
13251 ("lrm")
13252 ("rlm")
13253 ("ndash")
13254 ("mdash")
13255 ("lsquo")
13256 ("rsquo")
13257 ("sbquo")
13258 ("ldquo")
13259 ("rdquo")
13260 ("bdquo")
13261 ("dagger")
13262 ("Dagger")
13263 ("permil")
13264 ("lsaquo")
13265 ("rsaquo")
13266 ("euro")
13267
13268 ("arccos"."arccos")
13269 ("arcsin"."arcsin")
13270 ("arctan"."arctan")
13271 ("arg"."arg")
13272 ("cos"."cos")
13273 ("cosh"."cosh")
13274 ("cot"."cot")
13275 ("coth"."coth")
13276 ("csc"."csc")
13277 ("deg"."deg")
13278 ("det"."det")
13279 ("dim"."dim")
13280 ("exp"."exp")
13281 ("gcd"."gcd")
13282 ("hom"."hom")
13283 ("inf"."inf")
13284 ("ker"."ker")
13285 ("lg"."lg")
13286 ("lim"."lim")
13287 ("liminf"."liminf")
13288 ("limsup"."limsup")
13289 ("ln"."ln")
13290 ("log"."log")
13291 ("max"."max")
13292 ("min"."min")
13293 ("Pr"."Pr")
13294 ("sec"."sec")
13295 ("sin"."sin")
13296 ("sinh"."sinh")
13297 ("sup"."sup")
13298 ("tan"."tan")
13299 ("tanh"."tanh")
13300 )
13301 "Entities for TeX->HTML translation.
13302 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
13303 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
13304 In that case, \"\\ent\" will be translated to \"&other;\".
13305 The list contains HTML entities for Latin-1, Greek and other symbols.
13306 It is supplemented by a number of commonly used TeX macros with appropriate
13307 translations. There is currently no way for users to extend this.")
13308
13309 (defun org-cleaned-string-for-export (string &rest parameters)
13310 "Cleanup a buffer substring so that links can be created safely."
13311 (interactive)
13312 (let* ((re-radio (and org-target-link-regexp
13313 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
13314 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
13315 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
13316 (re-archive (concat ":" org-archive-tag ":"))
13317 rtn)
13318 (save-excursion
13319 (set-buffer (get-buffer-create " org-mode-tmp"))
13320 (erase-buffer)
13321 (insert string)
13322 (let ((org-inhibit-startup t)) (org-mode))
13323
13324 ;; Get rid of archived trees
13325 (when (not (eq org-export-with-archived-trees t))
13326 (goto-char (point-min))
13327 (while (re-search-forward re-archive nil t)
13328 (if (not (org-on-heading-p))
13329 (org-end-of-subtree t)
13330 (beginning-of-line 1)
13331 (delete-region
13332 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
13333 (org-end-of-subtree)))))
13334
13335 ;; Find targets in comments and move them out of comments,
13336 ;; but mark them as targets that should be invisible
13337 (goto-char (point-min))
13338 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
13339 (replace-match "\\1(INVISIBLE)"))
13340
13341 ;; Find matches for radio targets and turn them into internal links
13342 (goto-char (point-min))
13343 (when re-radio
13344 (while (re-search-forward re-radio nil t)
13345 (replace-match "\\1[[\\2]]")))
13346
13347 ;; Find all links that contain a newline and put them into a single line
13348 (goto-char (point-min))
13349 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
13350 (replace-match "\\1 \\3")
13351 (goto-char (match-beginning 0)))
13352
13353 ;; Convert LaTeX fragments to images
13354 (when (memq :LaTeX-fragments parameters)
13355 (org-format-latex
13356 (concat "ltxpng/" (file-name-sans-extension
13357 (file-name-nondirectory
13358 org-current-export-file)))
13359 org-current-export-dir nil "Creating LaTeX image %s"))
13360 (message "Exporting...")
13361
13362 ;; Normalize links: Convert angle and plain links into bracket links
13363 (goto-char (point-min))
13364 (while (re-search-forward re-plain-link nil t)
13365 (replace-match
13366 (concat
13367 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13368 t t))
13369 (goto-char (point-min))
13370 (while (re-search-forward re-angle-link nil t)
13371 (replace-match
13372 (concat
13373 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13374 t t))
13375
13376 ;; Find multiline emphasis and put them into single line
13377 (when (memq :emph-multiline parameters)
13378 (goto-char (point-min))
13379 (while (re-search-forward org-emph-re nil t)
13380 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
13381 (goto-char (1- (match-end 0)))))
13382
13383 ;; Remove comments
13384 (goto-char (point-min))
13385 (while (re-search-forward "^#.*\n?" nil t)
13386 (replace-match ""))
13387 (setq rtn (buffer-string)))
13388 (kill-buffer " org-mode-tmp")
13389 rtn))
13390
13391 (defun org-solidify-link-text (s &optional alist)
13392 "Take link text and make a safe target out of it."
13393 (save-match-data
13394 (let* ((rtn
13395 (mapconcat
13396 'identity
13397 (org-split-string s "[ \t\r\n]+") "--"))
13398 (a (assoc rtn alist)))
13399 (or (cdr a) rtn))))
13400
13401 (defun org-convert-to-odd-levels ()
13402 "Convert an org-mode file with all levels allowed to one with odd levels.
13403 This will leave level 1 alone, convert level 2 to level 3, level 3 to
13404 level 5 etc."
13405 (interactive)
13406 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
13407 (let ((org-odd-levels-only nil) n)
13408 (save-excursion
13409 (goto-char (point-min))
13410 (while (re-search-forward "^\\*\\*+" nil t)
13411 (setq n (1- (length (match-string 0))))
13412 (while (>= (setq n (1- n)) 0)
13413 (org-demote))
13414 (end-of-line 1))))))
13415
13416
13417 (defun org-convert-to-oddeven-levels ()
13418 "Convert an org-mode file with only odd levels to one with odd and even levels.
13419 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
13420 section with an even level, conversion would destroy the structure of the file. An error
13421 is signaled in this case."
13422 (interactive)
13423 (goto-char (point-min))
13424 ;; First check if there are no even levels
13425 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
13426 (org-show-hierarchy-above)
13427 (error "Not all levels are odd in this file. Conversion not possible."))
13428 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
13429 (let ((org-odd-levels-only nil) n)
13430 (save-excursion
13431 (goto-char (point-min))
13432 (while (re-search-forward "^\\*\\*+" nil t)
13433 (setq n (/ (length (match-string 0)) 2))
13434 (while (>= (setq n (1- n)) 0)
13435 (org-promote))
13436 (end-of-line 1))))))
13437
13438 (defun org-tr-level (n)
13439 "Make N odd if required."
13440 (if org-odd-levels-only (1+ (/ n 2)) n))
13441
13442 (defvar org-last-level nil) ; dynamically scoped variable
13443 (defvar org-ascii-current-indentation nil) ; For communication
13444
13445 (defun org-export-as-ascii (arg)
13446 "Export the outline as a pretty ASCII file.
13447 If there is an active region, export only the region.
13448 The prefix ARG specifies how many levels of the outline should become
13449 underlined headlines. The default is 3."
13450 (interactive "P")
13451 (setq-default org-todo-line-regexp org-todo-line-regexp)
13452 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13453 (org-infile-export-plist)))
13454 (region
13455 (buffer-substring
13456 (if (org-region-active-p) (region-beginning) (point-min))
13457 (if (org-region-active-p) (region-end) (point-max))))
13458 (lines (org-export-find-first-heading-line
13459 (org-skip-comments
13460 (org-split-string
13461 (org-cleaned-string-for-export region)
13462 "[\r\n]"))))
13463 (org-ascii-current-indentation '(0 . 0))
13464 (org-startup-with-deadline-check nil)
13465 (level 0) line txt
13466 (umax nil)
13467 (case-fold-search nil)
13468 (filename (concat (file-name-as-directory
13469 (org-export-directory :ascii opt-plist))
13470 (file-name-sans-extension
13471 (file-name-nondirectory buffer-file-name))
13472 ".txt"))
13473 (buffer (find-file-noselect filename))
13474 (levels-open (make-vector org-level-max nil))
13475 (odd org-odd-levels-only)
13476 (date (format-time-string "%Y/%m/%d" (current-time)))
13477 (time (format-time-string "%X" (org-current-time)))
13478 (author (plist-get opt-plist :author))
13479 (title (or (plist-get opt-plist :title)
13480 (file-name-sans-extension
13481 (file-name-nondirectory buffer-file-name))))
13482 (email (plist-get opt-plist :email))
13483 (language (plist-get opt-plist :language))
13484 (text nil)
13485 (todo nil)
13486 (lang-words nil))
13487
13488 (setq org-last-level 1)
13489 (org-init-section-numbers)
13490
13491 (find-file-noselect filename)
13492
13493 (setq lang-words (or (assoc language org-export-language-setup)
13494 (assoc "en" org-export-language-setup)))
13495 (if org-export-ascii-show-new-buffer
13496 (switch-to-buffer-other-window buffer)
13497 (set-buffer buffer))
13498 (erase-buffer)
13499 (fundamental-mode)
13500 ;; create local variables for all options, to make sure all called
13501 ;; functions get the correct information
13502 (mapcar (lambda (x)
13503 (set (make-local-variable (cdr x))
13504 (plist-get opt-plist (car x))))
13505 org-export-plist-vars)
13506 (org-set-local 'org-odd-levels-only odd)
13507 (setq umax (if arg (prefix-numeric-value arg)
13508 org-export-headline-levels))
13509
13510 ;; File header
13511 (if title (org-insert-centered title ?=))
13512 (insert "\n")
13513 (if (or author email)
13514 (insert (concat (nth 1 lang-words) ": " (or author "")
13515 (if email (concat " <" email ">") "")
13516 "\n")))
13517 (if (and date time)
13518 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
13519 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
13520
13521 (insert "\n\n")
13522
13523 (if org-export-with-toc
13524 (progn
13525 (insert (nth 3 lang-words) "\n"
13526 (make-string (length (nth 3 lang-words)) ?=) "\n")
13527 (mapcar '(lambda (line)
13528 (if (string-match org-todo-line-regexp
13529 line)
13530 ;; This is a headline
13531 (progn
13532 (setq level (- (match-end 1) (match-beginning 1))
13533 level (org-tr-level level)
13534 txt (match-string 3 line)
13535 todo
13536 (or (and org-export-mark-todo-in-toc
13537 (match-beginning 2)
13538 (not (equal (match-string 2 line)
13539 org-done-string)))
13540 ; TODO, not DONE
13541 (and org-export-mark-todo-in-toc
13542 (= level umax)
13543 (org-search-todo-below
13544 line lines level))))
13545 (setq txt (org-html-expand-for-ascii txt))
13546
13547 (if org-export-with-section-numbers
13548 (setq txt (concat (org-section-number level)
13549 " " txt)))
13550 (if (<= level umax)
13551 (progn
13552 (insert
13553 (make-string (* (1- level) 4) ?\ )
13554 (format (if todo "%s (*)\n" "%s\n") txt))
13555 (setq org-last-level level))
13556 ))))
13557 lines)))
13558
13559 (org-init-section-numbers)
13560 (while (setq line (pop lines))
13561 ;; Remove the quoted HTML tags.
13562 (setq line (org-html-expand-for-ascii line))
13563 ;; Remove targets
13564 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
13565 (setq line (replace-match "" t t line)))
13566 ;; Replace internal links
13567 (while (string-match org-bracket-link-regexp line)
13568 (setq line (replace-match
13569 (if (match-end 3) "[\\3]" "[\\1]")
13570 t nil line)))
13571 (cond
13572 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
13573 ;; a Headline
13574 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
13575 txt (match-string 2 line))
13576 (org-ascii-level-start level txt umax lines))
13577 (t
13578 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
13579 (normal-mode)
13580 (save-buffer)
13581 ;; remove display and invisible chars
13582 (let (beg end)
13583 (goto-char (point-min))
13584 (while (setq beg (next-single-property-change (point) 'display))
13585 (setq end (next-single-property-change beg 'display))
13586 (delete-region beg end)
13587 (goto-char beg)
13588 (insert "=>"))
13589 (goto-char (point-min))
13590 (while (setq beg (next-single-property-change (point) 'org-cwidth))
13591 (setq end (next-single-property-change beg 'org-cwidth))
13592 (delete-region beg end)
13593 (goto-char beg)))
13594 (goto-char (point-min))))
13595
13596 (defun org-search-todo-below (line lines level)
13597 "Search the subtree below LINE for any TODO entries."
13598 (let ((rest (cdr (memq line lines)))
13599 (re org-todo-line-regexp)
13600 line lv todo)
13601 (catch 'exit
13602 (while (setq line (pop rest))
13603 (if (string-match re line)
13604 (progn
13605 (setq lv (- (match-end 1) (match-beginning 1))
13606 todo (and (match-beginning 2)
13607 (not (equal (match-string 2 line)
13608 org-done-string))))
13609 ; TODO, not DONE
13610 (if (<= lv level) (throw 'exit nil))
13611 (if todo (throw 'exit t))))))))
13612
13613 (defun org-html-expand-for-ascii (line)
13614 "Handle quoted HTML for ASCII export."
13615 (if org-export-html-expand
13616 (while (string-match "@<[^<>\n]*>" line)
13617 ;; We just remove the tags for now.
13618 (setq line (replace-match "" nil nil line))))
13619 line)
13620
13621 (defun org-insert-centered (s &optional underline)
13622 "Insert the string S centered and underline it with character UNDERLINE."
13623 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
13624 (insert (make-string ind ?\ ) s "\n")
13625 (if underline
13626 (insert (make-string ind ?\ )
13627 (make-string (string-width s) underline)
13628 "\n"))))
13629
13630 (defun org-ascii-level-start (level title umax &optional lines)
13631 "Insert a new level in ASCII export."
13632 (let (char (n (- level umax 1)) (ind 0))
13633 (if (> level umax)
13634 (progn
13635 (insert (make-string (* 2 n) ?\ )
13636 (char-to-string (nth (% n (length org-export-ascii-bullets))
13637 org-export-ascii-bullets))
13638 " " title "\n")
13639 ;; find the indentation of the next non-empty line
13640 (catch 'stop
13641 (while lines
13642 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
13643 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
13644 (throw 'stop (setq ind (org-get-indentation (car lines)))))
13645 (pop lines)))
13646 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
13647 (if (or (not (equal (char-before) ?\n))
13648 (not (equal (char-before (1- (point))) ?\n)))
13649 (insert "\n"))
13650 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
13651 (if org-export-with-section-numbers
13652 (setq title (concat (org-section-number level) " " title)))
13653 (insert title "\n" (make-string (string-width title) char) "\n")
13654 (setq org-ascii-current-indentation '(0 . 0)))))
13655
13656 (defun org-export-visible (type arg)
13657 "Create a copy of the visible part of the current buffer, and export it.
13658 The copy is created in a temporary buffer and removed after use.
13659 TYPE is the final key (as a string) that also select the export command in
13660 the `C-c C-e' export dispatcher.
13661 As a special case, if the you type SPC at the prompt, the temporary
13662 org-mode file will not be removed but presented to you so that you can
13663 continue to use it. The prefix arg ARG is passed through to the exporting
13664 command."
13665 (interactive
13666 (list (progn
13667 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
13668 (read-char-exclusive))
13669 current-prefix-arg))
13670 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
13671 (error "Invalid export key"))
13672 (let* ((binding (cdr (assoc type
13673 '((?a . org-export-as-ascii)
13674 (?\C-a . org-export-as-ascii)
13675 (?b . org-export-as-html-and-open)
13676 (?\C-b . org-export-as-html-and-open)
13677 (?h . org-export-as-html)
13678 (?x . org-export-as-xoxo)))))
13679 (keepp (equal type ?\ ))
13680 (file buffer-file-name)
13681 (buffer (get-buffer-create "*Org Export Visible*"))
13682 s e)
13683 (with-current-buffer buffer (erase-buffer))
13684 (save-excursion
13685 (setq s (goto-char (point-min)))
13686 (while (not (= (point) (point-max)))
13687 (goto-char (org-find-invisible))
13688 (append-to-buffer buffer s (point))
13689 (setq s (goto-char (org-find-visible))))
13690 (goto-char (point-min))
13691 (unless keepp
13692 ;; Copy all comment lines to the end, to make sure #+ settings are
13693 ;; still available for the second export step. Kind of a hack, but
13694 ;; does do the trick.
13695 (if (looking-at "#[^\r\n]*")
13696 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
13697 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
13698 (append-to-buffer buffer (1+ (match-beginning 0))
13699 (min (point-max) (1+ (match-end 0))))))
13700 (set-buffer buffer)
13701 (let ((buffer-file-name file)
13702 (org-inhibit-startup t))
13703 (org-mode)
13704 (show-all)
13705 (unless keepp (funcall binding arg))))
13706 (if (not keepp)
13707 (kill-buffer buffer)
13708 (switch-to-buffer-other-window buffer)
13709 (goto-char (point-min)))))
13710
13711 (defun org-find-visible ()
13712 (let ((s (point)))
13713 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13714 (get-char-property s 'invisible)))
13715 s))
13716 (defun org-find-invisible ()
13717 (let ((s (point)))
13718 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13719 (not (get-char-property s 'invisible))))
13720 s))
13721
13722 ;; HTML
13723
13724 (defun org-get-current-options ()
13725 "Return a string with current options as keyword options.
13726 Does include HTML export options as well as TODO and CATEGORY stuff."
13727 (format
13728 "#+TITLE: %s
13729 #+AUTHOR: %s
13730 #+EMAIL: %s
13731 #+LANGUAGE: %s
13732 #+TEXT: Some descriptive text to be emitted. Several lines OK.
13733 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
13734 #+CATEGORY: %s
13735 #+SEQ_TODO: %s
13736 #+TYP_TODO: %s
13737 #+STARTUP: %s %s %s %s %s %s
13738 #+TAGS: %s
13739 #+ARCHIVE: %s
13740 "
13741 (buffer-name) (user-full-name) user-mail-address org-export-default-language
13742 org-export-headline-levels
13743 org-export-with-section-numbers
13744 org-export-with-toc
13745 org-export-preserve-breaks
13746 org-export-html-expand
13747 org-export-with-fixed-width
13748 org-export-with-tables
13749 org-export-with-sub-superscripts
13750 org-export-with-emphasize
13751 org-export-with-TeX-macros
13752 org-export-with-LaTeX-fragments
13753 (file-name-nondirectory buffer-file-name)
13754 (if (equal org-todo-interpretation 'sequence)
13755 (mapconcat 'identity org-todo-keywords " ")
13756 "TODO FEEDBACK VERIFY DONE")
13757 (if (equal org-todo-interpretation 'type)
13758 (mapconcat 'identity org-todo-keywords " ")
13759 "Me Jason Marie DONE")
13760 (cdr (assoc org-startup-folded
13761 '((nil . "showall") (t . "overview") (content . "content"))))
13762 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
13763 (if org-odd-levels-only "odd" "oddeven")
13764 (if org-hide-leading-stars "hidestars" "showstars")
13765 (if org-startup-align-all-tables "align" "noalign")
13766 (if org-log-done "logging" "nologging")
13767 (if org-tag-alist (mapconcat 'car org-tag-alist " ") "")
13768 org-archive-location
13769 ))
13770
13771 (defun org-insert-export-options-template ()
13772 "Insert into the buffer a template with information for exporting."
13773 (interactive)
13774 (if (not (bolp)) (newline))
13775 (let ((s (org-get-current-options)))
13776 (and (string-match "#\\+CATEGORY" s)
13777 (setq s (substring s 0 (match-beginning 0))))
13778 (insert s)))
13779
13780 (defun org-toggle-fixed-width-section (arg)
13781 "Toggle the fixed-width export.
13782 If there is no active region, the QUOTE keyword at the current headline is
13783 inserted or removed. When present, it causes the text between this headline
13784 and the next to be exported as fixed-width text, and unmodified.
13785 If there is an active region, this command adds or removes a colon as the
13786 first character of this line. If the first character of a line is a colon,
13787 this line is also exported in fixed-width font."
13788 (interactive "P")
13789 (let* ((cc 0)
13790 (regionp (org-region-active-p))
13791 (beg (if regionp (region-beginning) (point)))
13792 (end (if regionp (region-end)))
13793 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13794 (re "[ \t]*\\(:\\)")
13795 off)
13796 (if regionp
13797 (save-excursion
13798 (goto-char beg)
13799 (setq cc (current-column))
13800 (beginning-of-line 1)
13801 (setq off (looking-at re))
13802 (while (> nlines 0)
13803 (setq nlines (1- nlines))
13804 (beginning-of-line 1)
13805 (cond
13806 (arg
13807 (move-to-column cc t)
13808 (insert ":\n")
13809 (forward-line -1))
13810 ((and off (looking-at re))
13811 (replace-match "" t t nil 1))
13812 ((not off) (move-to-column cc t) (insert ":")))
13813 (forward-line 1)))
13814 (save-excursion
13815 (org-back-to-heading)
13816 (if (looking-at (concat outline-regexp
13817 "\\( +\\<" org-quote-string "\\>\\)"))
13818 (replace-match "" t t nil 1)
13819 (if (looking-at outline-regexp)
13820 (progn
13821 (goto-char (match-end 0))
13822 (insert " " org-quote-string))))))))
13823
13824 (defun org-export-as-html-and-open (arg)
13825 "Export the outline as HTML and immediately open it with a browser.
13826 If there is an active region, export only the region.
13827 The prefix ARG specifies how many levels of the outline should become
13828 headlines. The default is 3. Lower levels will become bulleted lists."
13829 (interactive "P")
13830 (org-export-as-html arg 'hidden)
13831 (org-open-file buffer-file-name))
13832
13833 (defun org-export-as-html-batch ()
13834 "Call `org-export-as-html', may be used in batch processing as
13835 emacs --batch
13836 --load=$HOME/lib/emacs/org.el
13837 --eval \"(setq org-export-headline-levels 2)\"
13838 --visit=MyFile --funcall org-export-as-html-batch"
13839 (org-export-as-html org-export-headline-levels 'hidden))
13840
13841 (defun org-export-as-html (arg &optional hidden ext-plist)
13842 "Export the outline as a pretty HTML file.
13843 If there is an active region, export only the region.
13844 The prefix ARG specifies how many levels of the outline should become
13845 headlines. The default is 3. Lower levels will become bulleted lists.
13846 When HIDDEN is non-nil, don't display the HTML buffer.
13847 EXT-PLIST is a property list with external parameters overriding
13848 org-mode's default settings, but still inferior to file-local settings."
13849 (interactive "P")
13850 (message "Exporting...")
13851 (setq-default org-todo-line-regexp org-todo-line-regexp)
13852 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
13853 (setq-default org-done-string org-done-string)
13854 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13855 ext-plist
13856 (org-infile-export-plist)))
13857
13858 (style (plist-get opt-plist :style))
13859 (link-validate (plist-get opt-plist :link-validation-function))
13860 valid
13861 (odd org-odd-levels-only)
13862 (region-p (org-region-active-p))
13863 (region
13864 (buffer-substring
13865 (if region-p (region-beginning) (point-min))
13866 (if region-p (region-end) (point-max))))
13867 ;; The following two are dynamically scoped into other
13868 ;; routines below.
13869 (org-current-export-dir (org-export-directory :html opt-plist))
13870 (org-current-export-file buffer-file-name)
13871 (all_lines
13872 (org-skip-comments (org-split-string
13873 (org-cleaned-string-for-export
13874 region :emph-multiline
13875 (if (plist-get opt-plist :LaTeX-fragments)
13876 :LaTeX-fragments))
13877 "[\r\n]")))
13878 (lines (org-export-find-first-heading-line all_lines))
13879 (level 0) (line "") (origline "") txt todo
13880 (umax nil)
13881 (filename (concat (file-name-as-directory
13882 (org-export-directory :html opt-plist))
13883 (file-name-sans-extension
13884 (file-name-nondirectory buffer-file-name))
13885 ".html"))
13886 (current-dir (file-name-directory buffer-file-name))
13887 (buffer (find-file-noselect filename))
13888 (levels-open (make-vector org-level-max nil))
13889 (date (format-time-string "%Y/%m/%d" (current-time)))
13890 (time (format-time-string "%X" (org-current-time)))
13891 (author (plist-get opt-plist :author))
13892 (title (or (plist-get opt-plist :title)
13893 (file-name-sans-extension
13894 (file-name-nondirectory buffer-file-name))))
13895 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
13896 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
13897 (inquote nil)
13898 (infixed nil)
13899 (in-local-list nil)
13900 (local-list-num nil)
13901 (local-list-indent nil)
13902 (llt org-plain-list-ordered-item-terminator)
13903 (email (plist-get opt-plist :email))
13904 (language (plist-get opt-plist :language))
13905 (text (plist-get opt-plist :text))
13906 (lang-words nil)
13907 (target-alist nil) tg
13908 (head-count 0) cnt
13909 (start 0)
13910 (coding-system (and (fboundp 'coding-system-get)
13911 (boundp 'buffer-file-coding-system)
13912 buffer-file-coding-system))
13913 (coding-system-for-write (or coding-system coding-system-for-write))
13914 (save-buffer-coding-system (or coding-system save-buffer-coding-system))
13915 (charset (and coding-system
13916 (coding-system-get coding-system 'mime-charset)))
13917 table-open type
13918 table-buffer table-orig-buffer
13919 ind start-is-num starter
13920 rpl path desc descp desc1 desc2 link
13921 )
13922 (message "Exporting...")
13923
13924 (setq org-last-level 1)
13925 (org-init-section-numbers)
13926
13927 ;; Get the language-dependent settings
13928 (setq lang-words (or (assoc language org-export-language-setup)
13929 (assoc "en" org-export-language-setup)))
13930
13931 ;; Switch to the output buffer
13932 (if (or hidden (not org-export-html-show-new-buffer))
13933 (set-buffer buffer)
13934 (switch-to-buffer-other-window buffer))
13935 (erase-buffer)
13936 (fundamental-mode)
13937 (let ((case-fold-search nil)
13938 (org-odd-levels-only odd))
13939 ;; create local variables for all options, to make sure all called
13940 ;; functions get the correct information
13941 (mapcar (lambda (x)
13942 (set (make-local-variable (cdr x))
13943 (plist-get opt-plist (car x))))
13944 org-export-plist-vars)
13945 (setq umax (if arg (prefix-numeric-value arg)
13946 org-export-headline-levels))
13947
13948 ;; File header
13949 (insert (format
13950 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
13951 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
13952 <html xmlns=\"http://www.w3.org/1999/xhtml\"
13953 lang=\"%s\" xml:lang=\"%s\">
13954 <head>
13955 <title>%s</title>
13956 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
13957 <meta name=\"generator\" content=\"Org-mode\"/>
13958 <meta name=\"generated\" content=\"%s %s\"/>
13959 <meta name=\"author\" content=\"%s\"/>
13960 %s
13961 </head><body>
13962 "
13963 language language (org-html-expand title) (or charset "iso-8859-1")
13964 date time author style))
13965
13966
13967 (insert (or (plist-get opt-plist :preamble) ""))
13968
13969 (when (plist-get opt-plist :auto-preamble)
13970 (if title (insert (format org-export-html-title-format
13971 (org-html-expand title))))
13972 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
13973
13974 (if org-export-with-toc
13975 (progn
13976 (insert (format "<h%d>%s</h%d>\n"
13977 org-export-html-toplevel-hlevel
13978 (nth 3 lang-words)
13979 org-export-html-toplevel-hlevel))
13980 (insert "<ul>\n<li>")
13981 (setq lines
13982 (mapcar '(lambda (line)
13983 (if (string-match org-todo-line-regexp line)
13984 ;; This is a headline
13985 (progn
13986 (setq level (- (match-end 1) (match-beginning 1))
13987 level (org-tr-level level)
13988 txt (save-match-data
13989 (org-html-expand
13990 (org-export-cleanup-toc-line
13991 (match-string 3 line))))
13992 todo
13993 (or (and org-export-mark-todo-in-toc
13994 (match-beginning 2)
13995 (not (equal (match-string 2 line)
13996 org-done-string)))
13997 ; TODO, not DONE
13998 (and org-export-mark-todo-in-toc
13999 (= level umax)
14000 (org-search-todo-below
14001 line lines level))))
14002 (if org-export-with-section-numbers
14003 (setq txt (concat (org-section-number level)
14004 " " txt)))
14005 (if (<= level umax)
14006 (progn
14007 (setq head-count (+ head-count 1))
14008 (if (> level org-last-level)
14009 (progn
14010 (setq cnt (- level org-last-level))
14011 (while (>= (setq cnt (1- cnt)) 0)
14012 (insert "\n<ul>\n<li>"))
14013 (insert "\n")))
14014 (if (< level org-last-level)
14015 (progn
14016 (setq cnt (- org-last-level level))
14017 (while (>= (setq cnt (1- cnt)) 0)
14018 (insert "</li>\n</ul>"))
14019 (insert "\n")))
14020 ;; Check for targets
14021 (while (string-match org-target-regexp line)
14022 (setq tg (match-string 1 line)
14023 line (replace-match
14024 (concat "@<span class=\"target\">" tg "@</span> ")
14025 t t line))
14026 (push (cons (org-solidify-link-text tg)
14027 (format "sec-%d" head-count))
14028 target-alist))
14029 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
14030 (setq txt (replace-match "" t t txt)))
14031 (insert
14032 (format
14033 (if todo
14034 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
14035 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
14036 head-count txt))
14037
14038 (setq org-last-level level))
14039 )))
14040 line)
14041 lines))
14042 (while (> org-last-level 0)
14043 (setq org-last-level (1- org-last-level))
14044 (insert "</li>\n</ul>\n"))
14045 ))
14046 (setq head-count 0)
14047 (org-init-section-numbers)
14048
14049 (while (setq line (pop lines) origline line)
14050 (catch 'nextline
14051
14052 ;; end of quote section?
14053 (when (and inquote (string-match "^\\*+" line))
14054 (insert "</pre>\n")
14055 (setq inquote nil))
14056 ;; inside a quote section?
14057 (when inquote
14058 (insert (org-html-protect line) "\n")
14059 (throw 'nextline nil))
14060
14061 ;; verbatim lines
14062 (when (and org-export-with-fixed-width
14063 (string-match "^[ \t]*:\\(.*\\)" line))
14064 (when (not infixed)
14065 (setq infixed t)
14066 (insert "<pre>\n"))
14067 (insert (org-html-protect (match-string 1 line)) "\n")
14068 (when (and lines
14069 (not (string-match "^[ \t]*\\(:.*\\)"
14070 (car lines))))
14071 (setq infixed nil)
14072 (insert "</pre>\n"))
14073 (throw 'nextline nil))
14074
14075
14076 ;; make targets to anchors
14077 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
14078 (cond
14079 ((match-end 2)
14080 (setq line (replace-match
14081 (concat "@<a name=\""
14082 (org-solidify-link-text (match-string 1 line))
14083 "\">\\nbsp@</a>")
14084 t t line)))
14085 ((and org-export-with-toc (equal (string-to-char line) ?*))
14086 (setq line (replace-match
14087 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
14088 ; (concat "@<i>" (match-string 1 line) "@</i> ")
14089 t t line)))
14090 (t
14091 (setq line (replace-match
14092 (concat "@<a name=\""
14093 (org-solidify-link-text (match-string 1 line))
14094 "\" class=\"target\">" (match-string 1 line) "@</a> ")
14095 t t line)))))
14096
14097 (setq line (org-html-handle-time-stamps line))
14098
14099 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
14100 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
14101 ;; Also handle sub_superscripts and checkboxes
14102 (setq line (org-html-expand line))
14103
14104 ;; Format the links
14105 (setq start 0)
14106 (while (string-match org-bracket-link-analytic-regexp line start)
14107 (setq start (match-beginning 0))
14108 (setq type (if (match-end 2) (match-string 2 line) "internal"))
14109 (setq path (match-string 3 line))
14110 (setq desc1 (if (match-end 5) (match-string 5 line))
14111 desc2 (if (match-end 2) (concat type ":" path) path)
14112 descp (and desc1 (not (equal desc1 desc2)))
14113 desc (or desc1 desc2))
14114 ;; FIXME: do we need to unescape here somewhere?
14115 (cond
14116 ((equal type "internal")
14117 (setq rpl
14118 (concat
14119 "<a href=\"#"
14120 (org-solidify-link-text path target-alist)
14121 "\">" desc "</a>")))
14122 ((member type '("http" "https" "ftp" "mailto" "news"))
14123 ;; standard URL
14124 (setq link (concat type ":" path))
14125 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
14126 ((string= type "file")
14127 ;; FILE link
14128 (let* ((filename path)
14129 (abs-p (file-name-absolute-p filename))
14130 thefile file-is-image-p search)
14131 (save-match-data
14132 (if (string-match "::\\(.*\\)" filename)
14133 (setq search (match-string 1 filename)
14134 filename (replace-match "" t nil filename)))
14135 (setq valid
14136 (if (functionp link-validate)
14137 (funcall link-validate filename current-dir)
14138 t))
14139 (setq file-is-image-p
14140 (string-match (org-image-file-name-regexp) filename))
14141 (setq thefile (if abs-p (expand-file-name filename) filename))
14142 (when (and org-export-html-link-org-files-as-html
14143 (string-match "\\.org$" thefile))
14144 (setq thefile (concat (substring thefile 0
14145 (match-beginning 0))
14146 ".html"))
14147 (if (and search
14148 ;; make sure this is can be used as target search
14149 (not (string-match "^[0-9]*$" search))
14150 (not (string-match "^\\*" search))
14151 (not (string-match "^/.*/$" search)))
14152 (setq thefile (concat thefile "#"
14153 (org-solidify-link-text
14154 (org-link-unescape search)))))
14155 (when (string-match "^file:" desc)
14156 (setq desc (replace-match "" t t desc))
14157 (if (string-match "\\.org$" desc)
14158 (setq desc (replace-match "" t t desc))))))
14159 (setq rpl (if (and file-is-image-p
14160 (or (eq t org-export-html-inline-images)
14161 (and org-export-html-inline-images
14162 (not descp))))
14163 (concat "<img src=\"" thefile "\"/>")
14164 (concat "<a href=\"" thefile "\">" desc "</a>")))
14165 (if (not valid) (setq rpl desc))))
14166 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
14167 (setq rpl (concat "<i>&lt;" type ":"
14168 (save-match-data (org-link-unescape path))
14169 "&gt;</i>"))))
14170 (setq line (replace-match rpl t t line)
14171 start (+ start (length rpl))))
14172 ;; TODO items
14173 (if (and (string-match org-todo-line-regexp line)
14174 (match-beginning 2))
14175 (if (equal (match-string 2 line) org-done-string)
14176 (setq line (replace-match
14177 "<span class=\"done\">\\2</span>"
14178 t nil line 2))
14179 (setq line (replace-match "<span class=\"todo\">\\2</span>"
14180 t nil line 2))))
14181
14182 (cond
14183 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
14184 ;; This is a headline
14185 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
14186 txt (match-string 2 line))
14187 (if (string-match quote-re0 txt)
14188 (setq txt (replace-match "" t t txt)))
14189 (if (<= level umax) (setq head-count (+ head-count 1)))
14190 (when in-local-list
14191 ;; Close any local lists before inserting a new header line
14192 (while local-list-num
14193 (org-close-li)
14194 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14195 (pop local-list-num))
14196 (setq local-list-indent nil
14197 in-local-list nil))
14198 (org-html-level-start level txt umax
14199 (and org-export-with-toc (<= level umax))
14200 head-count)
14201 ;; QUOTES
14202 (when (string-match quote-re line)
14203 (insert "<pre>")
14204 (setq inquote t)))
14205
14206 ((and org-export-with-tables
14207 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
14208 (if (not table-open)
14209 ;; New table starts
14210 (setq table-open t table-buffer nil table-orig-buffer nil))
14211 ;; Accumulate lines
14212 (setq table-buffer (cons line table-buffer)
14213 table-orig-buffer (cons origline table-orig-buffer))
14214 (when (or (not lines)
14215 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
14216 (car lines))))
14217 (setq table-open nil
14218 table-buffer (nreverse table-buffer)
14219 table-orig-buffer (nreverse table-orig-buffer))
14220 (org-close-par-maybe)
14221 (insert (org-format-table-html table-buffer table-orig-buffer))))
14222 (t
14223 ;; Normal lines
14224 (when (string-match
14225 (cond
14226 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14227 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14228 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14229 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
14230 line)
14231 (setq ind (org-get-string-indentation line)
14232 start-is-num (match-beginning 4)
14233 starter (if (match-beginning 2)
14234 (substring (match-string 2 line) 0 -1))
14235 line (substring line (match-beginning 5)))
14236 (unless (string-match "[^ \t]" line)
14237 ;; empty line. Pretend indentation is large.
14238 (setq ind (1+ (or (car local-list-indent) 1))))
14239 (while (and in-local-list
14240 (or (and (= ind (car local-list-indent))
14241 (not starter))
14242 (< ind (car local-list-indent))))
14243 (org-close-li)
14244 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14245 (pop local-list-num) (pop local-list-indent)
14246 (setq in-local-list local-list-indent))
14247 (cond
14248 ((and starter
14249 (or (not in-local-list)
14250 (> ind (car local-list-indent))))
14251 ;; Start new (level of ) list
14252 (org-close-par-maybe)
14253 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
14254 (push start-is-num local-list-num)
14255 (push ind local-list-indent)
14256 (setq in-local-list t))
14257 (starter
14258 ;; continue current list
14259 (org-close-li)
14260 (insert "<li>\n")))
14261 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
14262 (setq line
14263 (replace-match
14264 (if (equal (match-string 1 line) "X")
14265 "<b>[X]</b>"
14266 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
14267 t t line))))
14268
14269 ;; Empty lines start a new paragraph. If hand-formatted lists
14270 ;; are not fully interpreted, lines starting with "-", "+", "*"
14271 ;; also start a new paragraph.
14272 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
14273
14274 ;; Check if the line break needs to be conserved
14275 (cond
14276 ((string-match "\\\\\\\\[ \t]*$" line)
14277 (setq line (replace-match "<br/>" t t line)))
14278 (org-export-preserve-breaks
14279 (setq line (concat line "<br/>"))))
14280
14281 (insert line "\n")))))
14282
14283 ;; Properly close all local lists and other lists
14284 (when inquote (insert "</pre>\n"))
14285 (when in-local-list
14286 ;; Close any local lists before inserting a new header line
14287 (while local-list-num
14288 (org-close-li)
14289 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
14290 (pop local-list-num))
14291 (setq local-list-indent nil
14292 in-local-list nil))
14293 (org-html-level-start 1 nil umax
14294 (and org-export-with-toc (<= level umax))
14295 head-count)
14296
14297 (when (plist-get opt-plist :auto-postamble)
14298 (when author
14299 (insert "<p class=\"author\"> "
14300 (nth 1 lang-words) ": " author "\n")
14301 (when email
14302 (insert "<a href=\"mailto:" email "\">&lt;"
14303 email "&gt;</a>\n"))
14304 (insert "</p>\n"))
14305 (when (and date time)
14306 (insert "<p class=\"date\"> "
14307 (nth 2 lang-words) ": "
14308 date " " time "</p>\n")))
14309
14310 (if org-export-html-with-timestamp
14311 (insert org-export-html-html-helper-timestamp))
14312 (insert (or (plist-get opt-plist :postamble) ""))
14313 (insert "</body>\n</html>\n")
14314 (normal-mode)
14315 ;; remove empty paragraphs and lists
14316 (goto-char (point-min))
14317 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
14318 (replace-match ""))
14319 (goto-char (point-min))
14320 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
14321 (replace-match ""))
14322 (save-buffer)
14323 (goto-char (point-min))
14324 (message "Exporting... done"))))
14325
14326
14327 (defun org-format-table-html (lines olines)
14328 "Find out which HTML converter to use and return the HTML code."
14329 (if (string-match "^[ \t]*|" (car lines))
14330 ;; A normal org table
14331 (org-format-org-table-html lines)
14332 ;; Table made by table.el - test for spanning
14333 (let* ((hlines (delq nil (mapcar
14334 (lambda (x)
14335 (if (string-match "^[ \t]*\\+-" x) x
14336 nil))
14337 lines)))
14338 (first (car hlines))
14339 (ll (and (string-match "\\S-+" first)
14340 (match-string 0 first)))
14341 (re (concat "^[ \t]*" (regexp-quote ll)))
14342 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
14343 hlines))))
14344 (if (and (not spanning)
14345 (not org-export-prefer-native-exporter-for-tables))
14346 ;; We can use my own converter with HTML conversions
14347 (org-format-table-table-html lines)
14348 ;; Need to use the code generator in table.el, with the original text.
14349 (org-format-table-table-html-using-table-generate-source olines)))))
14350
14351 (defun org-format-org-table-html (lines)
14352 "Format a table into HTML."
14353 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14354 (setq lines (nreverse lines))
14355 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14356 (setq lines (nreverse lines))
14357 (when org-export-table-remove-special-lines
14358 ;; Check if the table has a marking column. If yes remove the
14359 ;; column and the special lines
14360 (let* ((special
14361 (not
14362 (memq nil
14363 (mapcar
14364 (lambda (x)
14365 (or (string-match "^[ \t]*|-" x)
14366 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
14367 lines)))))
14368 (if special
14369 (setq lines
14370 (delq nil
14371 (mapcar
14372 (lambda (x)
14373 (if (string-match "^[ \t]*| *[!_^] *|" x)
14374 nil ; ignore this line
14375 (and (or (string-match "^[ \t]*|-+\\+" x)
14376 (string-match "^[ \t]*|[^|]*|" x))
14377 (replace-match "|" t t x))))
14378 lines))))))
14379
14380 (let ((head (and org-export-highlight-first-table-line
14381 (delq nil (mapcar
14382 (lambda (x) (string-match "^[ \t]*|-" x))
14383 (cdr lines)))))
14384 line fields html)
14385 (setq html (concat org-export-html-table-tag "\n"))
14386 (while (setq line (pop lines))
14387 (catch 'next-line
14388 (if (string-match "^[ \t]*|-" line)
14389 (progn
14390 (setq head nil) ;; head ends here, first time around
14391 ;; ignore this line
14392 (throw 'next-line t)))
14393 ;; Break the line into fields
14394 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14395 (setq html (concat
14396 html
14397 "<tr>"
14398 (mapconcat (lambda (x)
14399 (if head
14400 (concat "<th>" x "</th>")
14401 (concat "<td>" x "</td>")))
14402 fields "")
14403 "</tr>\n"))))
14404 (setq html (concat html "</table>\n"))
14405 html))
14406
14407 (defun org-fake-empty-table-line (line)
14408 "Replace everything except \"|\" with spaces."
14409 (let ((i (length line))
14410 (newstr (copy-sequence line)))
14411 (while (> i 0)
14412 (setq i (1- i))
14413 (if (not (eq (aref newstr i) ?|))
14414 (aset newstr i ?\ )))
14415 newstr))
14416
14417 (defun org-format-table-table-html (lines)
14418 "Format a table generated by table.el into HTML.
14419 This conversion does *not* use `table-generate-source' from table.el.
14420 This has the advantage that Org-mode's HTML conversions can be used.
14421 But it has the disadvantage, that no cell- or row-spanning is allowed."
14422 (let (line field-buffer
14423 (head org-export-highlight-first-table-line)
14424 fields html empty)
14425 (setq html (concat org-export-html-table-tag "\n"))
14426 (while (setq line (pop lines))
14427 (setq empty "&nbsp;")
14428 (catch 'next-line
14429 (if (string-match "^[ \t]*\\+-" line)
14430 (progn
14431 (if field-buffer
14432 (progn
14433 (setq html (concat
14434 html
14435 "<tr>"
14436 (mapconcat
14437 (lambda (x)
14438 (if (equal x "") (setq x empty))
14439 (if head
14440 (concat "<th>" x "</th>\n")
14441 (concat "<td>" x "</td>\n")))
14442 field-buffer "\n")
14443 "</tr>\n"))
14444 (setq head nil)
14445 (setq field-buffer nil)))
14446 ;; Ignore this line
14447 (throw 'next-line t)))
14448 ;; Break the line into fields and store the fields
14449 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14450 (if field-buffer
14451 (setq field-buffer (mapcar
14452 (lambda (x)
14453 (concat x "<br/>" (pop fields)))
14454 field-buffer))
14455 (setq field-buffer fields))))
14456 (setq html (concat html "</table>\n"))
14457 html))
14458
14459 (defun org-format-table-table-html-using-table-generate-source (lines)
14460 "Format a table into html, using `table-generate-source' from table.el.
14461 This has the advantage that cell- or row-spanning is allowed.
14462 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
14463 (require 'table)
14464 (with-current-buffer (get-buffer-create " org-tmp1 ")
14465 (erase-buffer)
14466 (insert (mapconcat 'identity lines "\n"))
14467 (goto-char (point-min))
14468 (if (not (re-search-forward "|[^+]" nil t))
14469 (error "Error processing table"))
14470 (table-recognize-table)
14471 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
14472 (table-generate-source 'html " org-tmp2 ")
14473 (set-buffer " org-tmp2 ")
14474 (buffer-substring (point-min) (point-max))))
14475
14476 (defun org-html-handle-time-stamps (s)
14477 "Format time stamps in string S, or remove them."
14478 (catch 'exit
14479 (let (r b)
14480 (while (string-match org-maybe-keyword-time-regexp s)
14481 ;; FIXME: is it good to never export CLOCK, or do we need control?
14482 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
14483 (throw 'exit ""))
14484 (or b (setq b (substring s 0 (match-beginning 0))))
14485 (if (not org-export-with-timestamps)
14486 (setq r (concat r (substring s 0 (match-beginning 0)))
14487 s (substring s (match-end 0)))
14488 (setq r (concat
14489 r (substring s 0 (match-beginning 0))
14490 (if (match-end 1)
14491 (format "@<span class=\"timestamp-kwd\">%s @</span>"
14492 (match-string 1 s)))
14493 (format " @<span class=\"timestamp\">%s@</span>"
14494 (substring (match-string 3 s) 1 -1)))
14495 s (substring s (match-end 0)))))
14496 ;; Line break if line started and ended with time stamp stuff
14497 (if (not r)
14498 s
14499 (setq r (concat r s))
14500 (unless (string-match "\\S-" (concat b s))
14501 (setq r (concat r "@<br/>")))
14502 r))))
14503
14504 (defun org-html-protect (s)
14505 ;; convert & to &amp;, < to &lt; and > to &gt;
14506 (let ((start 0))
14507 (while (string-match "&" s start)
14508 (setq s (replace-match "&amp;" t t s)
14509 start (1+ (match-beginning 0))))
14510 (while (string-match "<" s)
14511 (setq s (replace-match "&lt;" t t s)))
14512 (while (string-match ">" s)
14513 (setq s (replace-match "&gt;" t t s))))
14514 s)
14515
14516 (defun org-export-cleanup-toc-line (s)
14517 "Remove tags and time staps from lines going into the toc."
14518 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
14519 (setq s (replace-match "" t t s)))
14520 (when org-export-remove-timestamps-from-toc
14521 (while (string-match org-maybe-keyword-time-regexp s)
14522 (setq s (replace-match "" t t s))))
14523 s)
14524
14525 (defun org-html-expand (string)
14526 "Prepare STRING for HTML export. Applies all active conversions.
14527 If there are links in the string, don't modify these."
14528 (let* (m s l res)
14529 (while (setq m (string-match org-bracket-link-regexp string))
14530 (setq s (substring string 0 m)
14531 l (match-string 0 string)
14532 string (substring string (match-end 0)))
14533 (push (org-html-do-expand s) res)
14534 (push l res))
14535 (push (org-html-do-expand string) res)
14536 (apply 'concat (nreverse res))))
14537
14538 (defun org-html-do-expand (s)
14539 "Apply all active conversions to translate special ASCII to HTML."
14540 (setq s (org-html-protect s))
14541 (if org-export-html-expand
14542 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
14543 (setq s (replace-match "<\\1>" t nil s))))
14544 (if org-export-with-emphasize
14545 (setq s (org-export-html-convert-emphasize s)))
14546 (if org-export-with-sub-superscripts
14547 (setq s (org-export-html-convert-sub-super s)))
14548 (if org-export-with-TeX-macros
14549 (let ((start 0) wd ass)
14550 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
14551 (setq wd (match-string 1 s))
14552 (if (setq ass (assoc wd org-html-entities))
14553 (setq s (replace-match (or (cdr ass)
14554 (concat "&" (car ass) ";"))
14555 t t s))
14556 (setq start (+ start (length wd)))))))
14557 s)
14558
14559 (defun org-create-multibrace-regexp (left right n)
14560 "Create a regular expression which will match a balanced sexp.
14561 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
14562 as single character strings.
14563 The regexp returned will match the entire expression including the
14564 delimiters. It will also define a single group which contains the
14565 match except for the outermost delimiters. The maximum depth of
14566 stacked delimiters is N. Escaping delimiters is not possible."
14567 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
14568 (or "\\|")
14569 (re nothing)
14570 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
14571 (while (> n 1)
14572 (setq n (1- n)
14573 re (concat re or next)
14574 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
14575 (concat left "\\(" re "\\)" right)))
14576
14577 (defvar org-match-substring-regexp
14578 (concat
14579 "\\([^\\]\\)\\([_^]\\)\\("
14580 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
14581 "\\|"
14582 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
14583 "\\|"
14584 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
14585 "The regular expression matching a sub- or superscript.")
14586
14587 (defun org-export-html-convert-sub-super (string)
14588 "Convert sub- and superscripts in STRING to HTML."
14589 (let (key c)
14590 (while (string-match org-match-substring-regexp string)
14591 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
14592 (setq c (or (match-string 8 string)
14593 (match-string 6 string)
14594 (match-string 5 string)))
14595 (setq string (replace-match
14596 (concat (match-string 1 string)
14597 "<" key ">" c "</" key ">")
14598 t t string)))
14599 (while (string-match "\\\\\\([_^]\\)" string)
14600 (setq string (replace-match (match-string 1 string) t t string))))
14601 string)
14602
14603 (defun org-export-html-convert-emphasize (string)
14604 "Apply emphasis."
14605 (while (string-match org-emph-re string)
14606 (setq string (replace-match (concat "\\1" (nth 2 (assoc (match-string 3 string) org-emphasis-alist)) "\\4" (nth 3 (assoc (match-string 3 string) org-emphasis-alist)) "\\5") t nil string)))
14607 string)
14608
14609 (defvar org-par-open nil)
14610 (defun org-open-par ()
14611 "Insert <p>, but first close previous paragraph if any."
14612 (org-close-par-maybe)
14613 (insert "\n<p>")
14614 (setq org-par-open t))
14615 (defun org-close-par-maybe ()
14616 "Close paragraph if there is one open."
14617 (when org-par-open
14618 (insert "</p>")
14619 (setq org-par-open nil)))
14620 (defun org-close-li ()
14621 "Close <li> if necessary."
14622 (org-close-par-maybe)
14623 (insert "</li>\n"))
14624 ; (when (save-excursion
14625 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
14626 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
14627 ; (insert "</li>"))))
14628
14629 (defun org-html-level-start (level title umax with-toc head-count)
14630 "Insert a new level in HTML export.
14631 When TITLE is nil, just close all open levels."
14632 (org-close-par-maybe)
14633 (let ((l (1+ (max level umax))))
14634 (while (<= l org-level-max)
14635 (if (aref levels-open (1- l))
14636 (progn
14637 (org-html-level-close l)
14638 (aset levels-open (1- l) nil)))
14639 (setq l (1+ l)))
14640 (when title
14641 ;; If title is nil, this means this function is called to close
14642 ;; all levels, so the rest is done only if title is given
14643 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
14644 (setq title (replace-match
14645 (if org-export-with-tags
14646 (save-match-data
14647 (concat
14648 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
14649 (mapconcat 'identity (org-split-string
14650 (match-string 1 title) ":")
14651 "&nbsp;")
14652 "</span>"))
14653 "")
14654 t t title)))
14655 (if (> level umax)
14656 (progn
14657 (if (aref levels-open (1- level))
14658 (progn
14659 (org-close-li)
14660 (insert "<li>" title "<br/>\n"))
14661 (aset levels-open (1- level) t)
14662 (org-close-par-maybe)
14663 (insert "<ul>\n<li>" title "<br/>\n")))
14664 (if org-export-with-section-numbers
14665 (setq title (concat (org-section-number level) " " title)))
14666 (setq level (+ level org-export-html-toplevel-hlevel -1))
14667 (if with-toc
14668 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
14669 level head-count title level))
14670 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
14671 (org-open-par)))))
14672
14673 (defun org-html-level-close (&rest args)
14674 "Terminate one level in HTML export."
14675 (org-close-li)
14676 (insert "</ul>"))
14677
14678 ;; Variable holding the vector with section numbers
14679 (defvar org-section-numbers (make-vector org-level-max 0))
14680
14681 (defun org-init-section-numbers ()
14682 "Initialize the vector for the section numbers."
14683 (let* ((level -1)
14684 (numbers (nreverse (org-split-string "" "\\.")))
14685 (depth (1- (length org-section-numbers)))
14686 (i depth) number-string)
14687 (while (>= i 0)
14688 (if (> i level)
14689 (aset org-section-numbers i 0)
14690 (setq number-string (or (car numbers) "0"))
14691 (if (string-match "\\`[A-Z]\\'" number-string)
14692 (aset org-section-numbers i
14693 (- (string-to-char number-string) ?A -1))
14694 (aset org-section-numbers i (string-to-number number-string)))
14695 (pop numbers))
14696 (setq i (1- i)))))
14697
14698 (defun org-section-number (&optional level)
14699 "Return a string with the current section number.
14700 When LEVEL is non-nil, increase section numbers on that level."
14701 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
14702 (when level
14703 (when (> level -1)
14704 (aset org-section-numbers
14705 level (1+ (aref org-section-numbers level))))
14706 (setq idx (1+ level))
14707 (while (<= idx depth)
14708 (if (not (= idx 1))
14709 (aset org-section-numbers idx 0))
14710 (setq idx (1+ idx))))
14711 (setq idx 0)
14712 (while (<= idx depth)
14713 (setq n (aref org-section-numbers idx))
14714 (setq string (concat string (if (not (string= string "")) "." "")
14715 (int-to-string n)))
14716 (setq idx (1+ idx)))
14717 (save-match-data
14718 (if (string-match "\\`\\([@0]\\.\\)+" string)
14719 (setq string (replace-match "" t nil string)))
14720 (if (string-match "\\(\\.0\\)+\\'" string)
14721 (setq string (replace-match "" t nil string))))
14722 string))
14723
14724
14725 ;;;###autoload
14726 (defun org-export-icalendar-this-file ()
14727 "Export current file as an iCalendar file.
14728 The iCalendar file will be located in the same directory as the Org-mode
14729 file, but with extension `.ics'."
14730 (interactive)
14731 (org-export-icalendar nil buffer-file-name))
14732
14733 (defun org-export-as-xoxo-insert-into (buffer &rest output)
14734 (with-current-buffer buffer
14735 (apply 'insert output)))
14736
14737 (defun org-export-as-xoxo (&optional buffer)
14738 "Export the org buffer as XOXO.
14739 The XOXO buffer is named *xoxo-<source buffer name>*"
14740 (interactive (list (current-buffer)))
14741 ;; A quickie abstraction
14742
14743 ;; Output everything as XOXO
14744 (with-current-buffer (get-buffer buffer)
14745 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
14746 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14747 (org-infile-export-plist)))
14748 (filename (concat (file-name-as-directory
14749 (org-export-directory :xoxo opt-plist))
14750 (file-name-sans-extension
14751 (file-name-nondirectory buffer-file-name))
14752 ".html"))
14753 (out (find-file-noselect filename))
14754 (last-level 1)
14755 (hanging-li nil))
14756 ;; Check the output buffer is empty.
14757 (with-current-buffer out (erase-buffer))
14758 ;; Kick off the output
14759 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
14760 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
14761 (let* ((hd (match-string-no-properties 1))
14762 (level (length hd))
14763 (text (concat
14764 (match-string-no-properties 2)
14765 (save-excursion
14766 (goto-char (match-end 0))
14767 (let ((str ""))
14768 (catch 'loop
14769 (while 't
14770 (forward-line)
14771 (if (looking-at "^[ \t]\\(.*\\)")
14772 (setq str (concat str (match-string-no-properties 1)))
14773 (throw 'loop str)))))))))
14774
14775 ;; Handle level rendering
14776 (cond
14777 ((> level last-level)
14778 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
14779
14780 ((< level last-level)
14781 (dotimes (- (- last-level level) 1)
14782 (if hanging-li
14783 (org-export-as-xoxo-insert-into out "</li>\n"))
14784 (org-export-as-xoxo-insert-into out "</ol>\n"))
14785 (when hanging-li
14786 (org-export-as-xoxo-insert-into out "</li>\n")
14787 (setq hanging-li nil)))
14788
14789 ((equal level last-level)
14790 (if hanging-li
14791 (org-export-as-xoxo-insert-into out "</li>\n")))
14792 )
14793
14794 (setq last-level level)
14795
14796 ;; And output the new li
14797 (setq hanging-li 't)
14798 (if (equal ?+ (elt text 0))
14799 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
14800 (org-export-as-xoxo-insert-into out "<li>" text))))
14801
14802 ;; Finally finish off the ol
14803 (dotimes (- last-level 1)
14804 (if hanging-li
14805 (org-export-as-xoxo-insert-into out "</li>\n"))
14806 (org-export-as-xoxo-insert-into out "</ol>\n"))
14807
14808 ;; Finish the buffer off and clean it up.
14809 (switch-to-buffer-other-window out)
14810 (indent-region (point-min) (point-max) nil)
14811 (save-buffer)
14812 (goto-char (point-min))
14813 )))
14814
14815 ;;;###autoload
14816 (defun org-export-icalendar-all-agenda-files ()
14817 "Export all files in `org-agenda-files' to iCalendar .ics files.
14818 Each iCalendar file will be located in the same directory as the Org-mode
14819 file, but with extension `.ics'."
14820 (interactive)
14821 (apply 'org-export-icalendar nil (org-agenda-files t)))
14822
14823 ;;;###autoload
14824 (defun org-export-icalendar-combine-agenda-files ()
14825 "Export all files in `org-agenda-files' to a single combined iCalendar file.
14826 The file is stored under the name `org-combined-agenda-icalendar-file'."
14827 (interactive)
14828 (apply 'org-export-icalendar t (org-agenda-files t)))
14829
14830 (defun org-export-icalendar (combine &rest files)
14831 "Create iCalendar files for all elements of FILES.
14832 If COMBINE is non-nil, combine all calendar entries into a single large
14833 file and store it under the name `org-combined-agenda-icalendar-file'."
14834 (save-excursion
14835 (let* ((dir (org-export-directory
14836 :ical (list :publishing-directory
14837 org-export-publishing-directory)))
14838 file ical-file ical-buffer category started org-agenda-new-buffers)
14839
14840 (when combine
14841 (setq ical-file
14842 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
14843 org-combined-agenda-icalendar-file
14844 (expand-file-name org-combined-agenda-icalendar-file dir))
14845 ical-buffer (org-get-agenda-file-buffer ical-file))
14846 (set-buffer ical-buffer) (erase-buffer))
14847 (while (setq file (pop files))
14848 (catch 'nextfile
14849 (org-check-agenda-file file)
14850 (set-buffer (org-get-agenda-file-buffer file))
14851 (unless combine
14852 (setq ical-file (concat (file-name-as-directory dir)
14853 (file-name-sans-extension
14854 (file-name-nondirectory buffer-file-name))
14855 ".ics"))
14856 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
14857 (with-current-buffer ical-buffer (erase-buffer)))
14858 (setq category (or org-category
14859 (file-name-sans-extension
14860 (file-name-nondirectory buffer-file-name))))
14861 (if (symbolp category) (setq category (symbol-name category)))
14862 (let ((standard-output ical-buffer))
14863 (if combine
14864 (and (not started) (setq started t)
14865 (org-start-icalendar-file org-icalendar-combined-name))
14866 (org-start-icalendar-file category))
14867 (org-print-icalendar-entries combine category)
14868 (when (or (and combine (not files)) (not combine))
14869 (org-finish-icalendar-file)
14870 (set-buffer ical-buffer)
14871 (save-buffer)
14872 (run-hooks 'org-after-save-iCalendar-file-hook)))))
14873 (org-release-buffers org-agenda-new-buffers))))
14874
14875 (defvar org-after-save-iCalendar-file-hook nil
14876 "Hook run after an iCalendar file has been saved.
14877 The iCalendar buffer is still current when this hook is run.
14878 A good way to use this is to tell a desktop calenndar application to re-read
14879 the iCalendar file.")
14880
14881 (defun org-print-icalendar-entries (&optional combine category)
14882 "Print iCalendar entries for the current Org-mode file to `standard-output'.
14883 When COMBINE is non nil, add the category to each line."
14884 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
14885 (dts (org-ical-ts-to-string
14886 (format-time-string (cdr org-time-stamp-formats) (current-time))
14887 "DTSTART"))
14888 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
14889 (save-excursion
14890 (goto-char (point-min))
14891 (while (re-search-forward org-ts-regexp nil t)
14892 (setq pos (match-beginning 0)
14893 ts (match-string 0)
14894 inc t
14895 hd (org-get-heading))
14896 (if (looking-at re2)
14897 (progn
14898 (goto-char (match-end 0))
14899 (setq ts2 (match-string 1) inc nil))
14900 (setq ts2 ts
14901 tmp (buffer-substring (max (point-min)
14902 (- pos org-ds-keyword-length))
14903 pos)
14904 deadlinep (string-match org-deadline-regexp tmp)
14905 scheduledp (string-match org-scheduled-regexp tmp)
14906 ;; donep (org-entry-is-done-p)
14907 ))
14908 (if (or (string-match org-tr-regexp hd)
14909 (string-match org-ts-regexp hd))
14910 (setq hd (replace-match "" t t hd)))
14911 (if combine
14912 (setq hd (concat hd " (category " category ")")))
14913 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
14914 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
14915 (princ (format "BEGIN:VEVENT
14916 %s
14917 %s
14918 SUMMARY:%s
14919 END:VEVENT\n"
14920 (org-ical-ts-to-string ts "DTSTART")
14921 (org-ical-ts-to-string ts2 "DTEND" inc)
14922 hd)))
14923 (when org-icalendar-include-todo
14924 (goto-char (point-min))
14925 (while (re-search-forward org-todo-line-regexp nil t)
14926 (setq state (match-string 1))
14927 (unless (equal state org-done-string)
14928 (setq hd (match-string 3))
14929 (if (string-match org-priority-regexp hd)
14930 (setq pri (string-to-char (match-string 2 hd))
14931 hd (concat (substring hd 0 (match-beginning 1))
14932 (substring hd (- (match-end 1)))))
14933 (setq pri org-default-priority))
14934 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
14935 (- org-lowest-priority ?A))))))
14936
14937 (princ (format "BEGIN:VTODO
14938 %s
14939 SUMMARY:%s
14940 SEQUENCE:1
14941 PRIORITY:%d
14942 END:VTODO\n"
14943 dts hd pri))))))))
14944
14945 (defun org-start-icalendar-file (name)
14946 "Start an iCalendar file by inserting the header."
14947 (let ((user user-full-name)
14948 (name (or name "unknown"))
14949 (timezone (cadr (current-time-zone))))
14950 (princ
14951 (format "BEGIN:VCALENDAR
14952 VERSION:2.0
14953 X-WR-CALNAME:%s
14954 PRODID:-//%s//Emacs with Org-mode//EN
14955 X-WR-TIMEZONE:%s
14956 CALSCALE:GREGORIAN\n" name user timezone))))
14957
14958 (defun org-finish-icalendar-file ()
14959 "Finish an iCalendar file by inserting the END statement."
14960 (princ "END:VCALENDAR\n"))
14961
14962 (defun org-ical-ts-to-string (s keyword &optional inc)
14963 "Take a time string S and convert it to iCalendar format.
14964 KEYWORD is added in front, to make a complete line like DTSTART....
14965 When INC is non-nil, increase the hour by two (if time string contains
14966 a time), or the day by one (if it does not contain a time)."
14967 (let ((t1 (org-parse-time-string s 'nodefault))
14968 t2 fmt have-time time)
14969 (if (and (car t1) (nth 1 t1) (nth 2 t1))
14970 (setq t2 t1 have-time t)
14971 (setq t2 (org-parse-time-string s)))
14972 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
14973 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
14974 (when inc
14975 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
14976 (setq time (encode-time s mi h d m y)))
14977 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
14978 (concat keyword (format-time-string fmt time))))
14979
14980 ;;; LaTeX stuff
14981
14982 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14983 "Keymap for the minor `org-cdlatex-mode'.")
14984
14985 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14986 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14987 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14988 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14989 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14990
14991 (defvar org-cdlatex-texmathp-advice-is-done nil
14992 "Flag remembering if we have applied the advice to texmathp already.")
14993
14994 (define-minor-mode org-cdlatex-mode
14995 "Toggle the minor `org-cdlatex-mode'.
14996 This mode supports entering LaTeX environment and math in LaTeX fragments
14997 in Org-mode.
14998 \\{org-cdlatex-mode-map}"
14999 nil " OCDL" nil
15000 (when org-cdlatex-mode (require 'cdlatex))
15001 (unless org-cdlatex-texmathp-advice-is-done
15002 (setq org-cdlatex-texmathp-advice-is-done t)
15003 (defadvice texmathp (around org-math-always-on activate)
15004 "Always return t in org-mode buffers.
15005 This is because we want to insert math symbols without dollars even outside
15006 the LaTeX math segments. If Orgmode thinks that point is actually inside
15007 en embedded LaTeX fragement, let texmathp do its job.
15008 \\[org-cdlatex-mode-map]"
15009 (interactive)
15010 (let (p)
15011 (cond
15012 ((not (org-mode-p)) ad-do-it)
15013 ((eq this-command 'cdlatex-math-symbol)
15014 (setq ad-return-value t
15015 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15016 (t
15017 (let ((p (org-inside-LaTeX-fragment-p)))
15018 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15019 (setq ad-return-value t
15020 texmathp-why '("Org-mode embedded math" . 0))
15021 (if p ad-do-it)))))))))
15022
15023 (defun turn-on-org-cdlatex ()
15024 "Unconditionally turn on `org-cdlatex-mode'."
15025 (org-cdlatex-mode 1))
15026
15027 (defun org-inside-LaTeX-fragment-p ()
15028 "Test if point is inside a LaTeX fragment.
15029 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15030 sequence appearing also before point.
15031 Even though the matchers for math are configurable, this function assumes
15032 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15033 delimiters are skipped when they have been removed by customization.
15034 The return value is nil, or a cons cell with the delimiter and
15035 and the position of this delimiter.
15036
15037 This function does a reasonably good job, but can locally be fooled by
15038 for example currency specifications. For example it will assume being in
15039 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15040 fragments that are properly closed, but during editing, we have to live
15041 with the uncertainty caused by missing closing delimiters. This function
15042 looks only before point, not after."
15043 (catch 'exit
15044 (let ((pos (point))
15045 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15046 (lim (progn
15047 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15048 (point)))
15049 dd-on str (start 0) m re)
15050 (goto-char pos)
15051 (when dodollar
15052 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15053 re (nth 1 (assoc "$" org-latex-regexps)))
15054 (while (string-match re str start)
15055 (cond
15056 ((= (match-end 0) (length str))
15057 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
15058 ((= (match-end 0) (- (length str) 5))
15059 (throw 'exit nil))
15060 (t (setq start (match-end 0))))))
15061 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15062 (goto-char pos)
15063 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15064 (and (match-beginning 2) (throw 'exit nil))
15065 ;; count $$
15066 (while (re-search-backward "\\$\\$" lim t)
15067 (setq dd-on (not dd-on)))
15068 (goto-char pos)
15069 (if dd-on (cons "$$" m))))))
15070
15071
15072 (defun org-try-cdlatex-tab ()
15073 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15074 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15075 - inside a LaTeX fragment, or
15076 - after the first word in a line, where an abbreviation expansion could
15077 insert a LaTeX environment."
15078 ;; FIXME: This may still need refinement.
15079 (when org-cdlatex-mode
15080 (cond
15081 ((save-excursion
15082 (skip-chars-backward "a-zA-Z0-9*")
15083 (skip-chars-backward " \t")
15084 (bolp))
15085 (cdlatex-tab) t)
15086 ((org-inside-LaTeX-fragment-p)
15087 (cdlatex-tab) t)
15088 (t nil))))
15089
15090 (defun org-cdlatex-underscore-caret (&optional arg)
15091 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15092 Revert to the normal definition outside of these fragments."
15093 (interactive "P")
15094 (if (org-inside-LaTeX-fragment-p)
15095 (call-interactively 'cdlatex-sub-superscript)
15096 (let (org-cdlatex-mode)
15097 (call-interactively (key-binding (vector last-input-event))))))
15098
15099 (defun org-cdlatex-math-modify (&optional arg)
15100 "Execute `cdlatex-math-modify' in LaTeX fragments.
15101 Revert to the normal definition outside of these fragments."
15102 (interactive "P")
15103 (if (org-inside-LaTeX-fragment-p)
15104 (call-interactively 'cdlatex-math-modify)
15105 (let (org-cdlatex-mode)
15106 (call-interactively (key-binding (vector last-input-event))))))
15107
15108 (defvar org-latex-fragment-image-overlays nil
15109 "List of overlays carrying the images of latex fragments.")
15110 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15111
15112 (defun org-remove-latex-fragment-image-overlays ()
15113 "Remove all overlays with LaTeX fragment images in current buffer."
15114 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
15115 (setq org-latex-fragment-image-overlays nil))
15116
15117 (defun org-preview-latex-fragment (&optional subtree)
15118 "Preview the LaTeX fragment at point, or all locally or globally.
15119 If the cursor is in a LaTeX fragment, create the image and overlay
15120 it over the source code. If there is no fragment at point, display
15121 all fragments in the current text, from one headline to the next. With
15122 prefix SUBTREE, display all fragments in the current subtree. With a
15123 double prefix `C-u C-u', or when the cursor is before the first headline,
15124 display all fragments in the buffer.
15125 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15126 (interactive "P")
15127 (org-remove-latex-fragment-image-overlays)
15128 (save-excursion
15129 (save-restriction
15130 (let (beg end at msg)
15131 (cond
15132 ((or (equal subtree '(16))
15133 (not (save-excursion
15134 (re-search-backward (concat "^" outline-regexp) nil t))))
15135 (setq beg (point-min) end (point-max)
15136 msg "Creating images for buffer...%s"))
15137 ((equal subtree '(4))
15138 (org-back-to-heading)
15139 (setq beg (point) end (org-end-of-subtree)
15140 msg "Creating images for subtree...%s"))
15141 (t
15142 (if (setq at (org-inside-LaTeX-fragment-p))
15143 (goto-char (max (point-min) (- (cdr at) 2)))
15144 (org-back-to-heading))
15145 (setq beg (point) end (progn (outline-next-heading) (point))
15146 msg (if at "Creating image...%s"
15147 "Creating images for entry...%s"))))
15148 (message msg "")
15149 (narrow-to-region beg end)
15150 (org-format-latex
15151 (concat "ltxpng/" (file-name-sans-extension
15152 (file-name-nondirectory
15153 buffer-file-name)))
15154 default-directory 'overlays msg at)
15155 (message msg "done. Use `C-c C-c' to remove images.")))))
15156
15157 (defvar org-latex-regexps
15158 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15159 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15160 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15161 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
15162 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15163 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
15164 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
15165 "Regular expressions for matching embedded LaTeX.")
15166
15167 (defun org-format-latex (prefix &optional dir overlays msg at)
15168 "Replace LaTeX fragments with links to an image, and produce images."
15169 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15170 (let* ((prefixnodir (file-name-nondirectory prefix))
15171 (absprefix (expand-file-name prefix dir))
15172 (todir (file-name-directory absprefix))
15173 (opt org-format-latex-options)
15174 (matchers (plist-get opt :matchers))
15175 (re-list org-latex-regexps)
15176 (cnt 0) txt link beg end re e oldfiles
15177 m n block linkfile movefile ov)
15178 ;; Make sure the directory exists
15179 (or (file-directory-p todir) (make-directory todir))
15180 ;; Check if there are old images files with this prefix, and remove them
15181 (setq oldfiles (directory-files
15182 todir 'full
15183 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
15184 (while oldfiles (delete-file (pop oldfiles)))
15185 ;; Check the different regular expressions
15186 (while (setq e (pop re-list))
15187 (setq m (car e) re (nth 1 e) n (nth 2 e)
15188 block (if (nth 3 e) "\n\n" ""))
15189 (when (member m matchers)
15190 (goto-char (point-min))
15191 (while (re-search-forward re nil t)
15192 (when (or (not at) (equal (cdr at) (match-beginning n)))
15193 (setq txt (match-string n)
15194 beg (match-beginning n) end (match-end n)
15195 cnt (1+ cnt)
15196 linkfile (format "%s_%04d.png" prefix cnt)
15197 movefile (format "%s_%04d.png" absprefix cnt)
15198 link (concat block "[[file:" linkfile "]]" block))
15199 (if msg (message msg cnt))
15200 (goto-char beg)
15201 (org-create-formula-image
15202 txt movefile opt)
15203 (if overlays
15204 (progn
15205 (setq ov (org-make-overlay beg end))
15206 (if (featurep 'xemacs)
15207 (progn
15208 (org-overlay-put ov 'invisible t)
15209 (org-overlay-put
15210 ov 'end-glyph
15211 (make-glyph (vector 'png :file movefile))))
15212 (org-overlay-put
15213 ov 'display
15214 (list 'image :type 'png :file movefile :ascent 'center)))
15215 (push ov org-latex-fragment-image-overlays)
15216 (goto-char end))
15217 (delete-region beg end)
15218 (insert link))))))))
15219
15220 ;; This function borrows from Ganesh Swami's latex2png.el
15221 (defun org-create-formula-image (string tofile options)
15222 (let* ((tmpdir (if (featurep 'xemacs)
15223 (temp-directory)
15224 temporary-file-directory))
15225 (texfilebase (make-temp-name
15226 (expand-file-name "orgtex" tmpdir)))
15227
15228 ;(texfilebase (make-temp-file "orgtex"))
15229 ; (dummy (delete-file texfilebase))
15230 (texfile (concat texfilebase ".tex"))
15231 (dvifile (concat texfilebase ".dvi"))
15232 (pngfile (concat texfilebase ".png"))
15233 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
15234 (fg (or (plist-get options :foreground) "Black"))
15235 (bg (or (plist-get options :background) "Transparent")))
15236 (with-temp-file texfile
15237 (insert "\\documentclass{article}
15238 \\usepackage{fullpage}
15239 \\usepackage{amssymb}
15240 \\usepackage[usenames]{color}
15241 \\usepackage{amsmath}
15242 \\usepackage{latexsym}
15243 \\usepackage[mathscr]{eucal}
15244 \\pagestyle{empty}
15245 \\begin{document}\n" string "\n\\end{document}\n"))
15246 (let ((dir default-directory))
15247 (condition-case nil
15248 (progn
15249 (cd tmpdir)
15250 (call-process "latex" nil nil nil texfile))
15251 (error nil))
15252 (cd dir))
15253 (if (not (file-exists-p dvifile))
15254 (progn (message "Failed to create dvi file from %s" texfile) nil)
15255 (call-process "dvipng" nil nil nil
15256 "-E" "-fg" fg "-bg" bg
15257 "-x" scale "-y" scale "-T" "tight"
15258 "-o" pngfile
15259 dvifile)
15260 (if (not (file-exists-p pngfile))
15261 (progn (message "Failed to create png file from %s" texfile) nil)
15262 ;; Use the requested file name and clean up
15263 (copy-file pngfile tofile 'replace)
15264 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15265 (delete-file (concat texfilebase e)))
15266 pngfile))))
15267
15268 ;;; Key bindings
15269
15270 ;; - Bindings in Org-mode map are currently
15271 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
15272 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
15273 ;; e (?) useful from outline-mode
15274 ;; i k @ expendable from outline-mode
15275 ;; 0123456789 % & ()_{} " ` free
15276
15277 ;; Make `C-c C-x' a prefix key
15278 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
15279
15280 ;; TAB key with modifiers
15281 (define-key org-mode-map "\C-i" 'org-cycle)
15282 (define-key org-mode-map [(tab)] 'org-cycle)
15283 (define-key org-mode-map [(meta tab)] 'org-complete)
15284 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
15285 ;; The following line is necessary under Suse GNU/Linux
15286 (unless (featurep 'xemacs)
15287 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
15288 (define-key org-mode-map [(shift tab)] 'org-shifttab)
15289
15290 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
15291 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
15292 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15293 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
15294 (define-key org-mode-map [(meta return)] 'org-meta-return)
15295 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
15296 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
15297
15298 ;; Cursor keys with modifiers
15299 (define-key org-mode-map [(meta left)] 'org-metaleft)
15300 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
15301 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
15302 (define-key org-mode-map [(meta right)] 'org-metaright)
15303 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
15304 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
15305 (define-key org-mode-map [(meta up)] 'org-metaup)
15306 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
15307 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
15308 (define-key org-mode-map [(meta down)] 'org-metadown)
15309 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
15310 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
15311
15312 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15313 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
15314 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
15315 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
15316 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
15317 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
15318 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
15319 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
15320 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
15321 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
15322 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
15323 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
15324 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
15325 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
15326 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
15327 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
15328
15329 ;; All the other keys
15330
15331 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15332 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
15333 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
15334 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
15335 (define-key org-mode-map "\C-c\C-j" 'org-goto)
15336 (define-key org-mode-map "\C-c\C-t" 'org-todo)
15337 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
15338 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
15339 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
15340 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15341 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
15342 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
15343 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
15344 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
15345 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
15346 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
15347 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
15348 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
15349 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
15350 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
15351 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15352 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15353 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15354 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15355 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
15356 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
15357 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15358 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
15359 (define-key org-mode-map "\C-c]" 'org-remove-file)
15360 (define-key org-mode-map "\C-c\C-r" 'org-timeline)
15361 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
15362 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
15363 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15364 (define-key org-mode-map "\C-m" 'org-return)
15365 (define-key org-mode-map "\C-c?" 'org-table-current-column)
15366 (define-key org-mode-map "\C-c " 'org-table-blank-field)
15367 (define-key org-mode-map "\C-c+" 'org-table-sum)
15368 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
15369 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
15370 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
15371 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15372 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
15373 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15374 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
15375 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
15376 (define-key org-mode-map "\C-c\C-e" 'org-export)
15377 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15378
15379 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
15380 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15381 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15382 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15383
15384 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15385 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15386 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15387 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15388 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15389 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15390 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15391 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15392
15393 (when (featurep 'xemacs)
15394 (define-key org-mode-map 'button3 'popup-mode-menu))
15395
15396 (defsubst org-table-p () (org-at-table-p))
15397
15398 (defun org-self-insert-command (N)
15399 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15400 If the cursor is in a table looking at whitespace, the whitespace is
15401 overwritten, and the table is not marked as requiring realignment."
15402 (interactive "p")
15403 (if (and (org-table-p)
15404 (progn
15405 ;; check if we blank the field, and if that triggers align
15406 (and org-table-auto-blank-field
15407 (member last-command
15408 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
15409 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15410 ;; got extra space, this field does not determine column width
15411 (let (org-table-may-need-update) (org-table-blank-field))
15412 ;; no extra space, this field may determine column width
15413 (org-table-blank-field)))
15414 t)
15415 (eq N 1)
15416 (looking-at "[^|\n]* |"))
15417 (let (org-table-may-need-update)
15418 (goto-char (1- (match-end 0)))
15419 (delete-backward-char 1)
15420 (goto-char (match-beginning 0))
15421 (self-insert-command N))
15422 (setq org-table-may-need-update t)
15423 (self-insert-command N)))
15424
15425 (defun org-delete-backward-char (N)
15426 "Like `delete-backward-char', insert whitespace at field end in tables.
15427 When deleting backwards, in tables this function will insert whitespace in
15428 front of the next \"|\" separator, to keep the table aligned. The table will
15429 still be marked for re-alignment if the field did fill the entire column,
15430 because, in this case the deletion might narrow the column."
15431 (interactive "p")
15432 (if (and (org-table-p)
15433 (eq N 1)
15434 (string-match "|" (buffer-substring (point-at-bol) (point)))
15435 (looking-at ".*?|"))
15436 (let ((pos (point))
15437 (noalign (looking-at "[^|\n\r]* |"))
15438 (c org-table-may-need-update))
15439 (backward-delete-char N)
15440 (skip-chars-forward "^|")
15441 (insert " ")
15442 (goto-char (1- pos))
15443 ;; noalign: if there were two spaces at the end, this field
15444 ;; does not determine the width of the column.
15445 (if noalign (setq org-table-may-need-update c)))
15446 (backward-delete-char N)))
15447
15448 (defun org-delete-char (N)
15449 "Like `delete-char', but insert whitespace at field end in tables.
15450 When deleting characters, in tables this function will insert whitespace in
15451 front of the next \"|\" separator, to keep the table aligned. The table will
15452 still be marked for re-alignment if the field did fill the entire column,
15453 because, in this case the deletion might narrow the column."
15454 (interactive "p")
15455 (if (and (org-table-p)
15456 (not (bolp))
15457 (not (= (char-after) ?|))
15458 (eq N 1))
15459 (if (looking-at ".*?|")
15460 (let ((pos (point))
15461 (noalign (looking-at "[^|\n\r]* |"))
15462 (c org-table-may-need-update))
15463 (replace-match (concat
15464 (substring (match-string 0) 1 -1)
15465 " |"))
15466 (goto-char pos)
15467 ;; noalign: if there were two spaces at the end, this field
15468 ;; does not determine the width of the column.
15469 (if noalign (setq org-table-may-need-update c)))
15470 (delete-char N))
15471 (delete-char N)))
15472
15473 ;; How to do this: Measure non-white length of current string
15474 ;; If equal to column width, we should realign.
15475
15476 (defun org-remap (map &rest commands)
15477 "In MAP, remap the functions given in COMMANDS.
15478 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15479 (let (new old)
15480 (while commands
15481 (setq old (pop commands) new (pop commands))
15482 (if (fboundp 'command-remapping)
15483 (define-key map (vector 'remap old) new)
15484 (substitute-key-definition old new map global-map)))))
15485
15486 (when (eq org-enable-table-editor 'optimized)
15487 ;; If the user wants maximum table support, we need to hijack
15488 ;; some standard editing functions
15489 (org-remap org-mode-map
15490 'self-insert-command 'org-self-insert-command
15491 'delete-char 'org-delete-char
15492 'delete-backward-char 'org-delete-backward-char)
15493 (define-key org-mode-map "|" 'org-force-self-insert))
15494
15495 (defun org-shiftcursor-error ()
15496 "Throw an error because Shift-Cursor command was applied in wrong context."
15497 (error "This command is active in special context like tables, headlines or timestamps"))
15498
15499 (defun org-shifttab (&optional arg)
15500 "Global visibility cycling or move to previous table field.
15501 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15502 on context.
15503 See the individual commands for more information."
15504 (interactive "P")
15505 (cond
15506 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15507 (t (call-interactively 'org-global-cycle))))
15508
15509 (defun org-shiftmetaleft ()
15510 "Promote subtree or delete table column.
15511 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
15512 See the individual commands for more information."
15513 (interactive)
15514 (cond
15515 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15516 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15517 ((org-at-item-p) (call-interactively 'org-outdent-item))
15518 (t (org-shiftcursor-error))))
15519
15520 (defun org-shiftmetaright ()
15521 "Demote subtree or insert table column.
15522 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
15523 See the individual commands for more information."
15524 (interactive)
15525 (cond
15526 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15527 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15528 ((org-at-item-p) (call-interactively 'org-indent-item))
15529 (t (org-shiftcursor-error))))
15530
15531 (defun org-shiftmetaup (&optional arg)
15532 "Move subtree up or kill table row.
15533 Calls `org-move-subtree-up' or `org-table-kill-row' or
15534 `org-move-item-up' depending on context. See the individual commands
15535 for more information."
15536 (interactive "P")
15537 (cond
15538 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15539 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15540 ((org-at-item-p) (call-interactively 'org-move-item-up))
15541 (t (org-shiftcursor-error))))
15542 (defun org-shiftmetadown (&optional arg)
15543 "Move subtree down or insert table row.
15544 Calls `org-move-subtree-down' or `org-table-insert-row' or
15545 `org-move-item-down', depending on context. See the individual
15546 commands for more information."
15547 (interactive "P")
15548 (cond
15549 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15550 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15551 ((org-at-item-p) (call-interactively 'org-move-item-down))
15552 (t (org-shiftcursor-error))))
15553
15554 (defun org-metaleft (&optional arg)
15555 "Promote heading or move table column to left.
15556 Calls `org-do-promote' or `org-table-move-column', depending on context.
15557 With no specific context, calls the Emacs default `backward-word'.
15558 See the individual commands for more information."
15559 (interactive "P")
15560 (cond
15561 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15562 ((or (org-on-heading-p) (org-region-active-p))
15563 (call-interactively 'org-do-promote))
15564 (t (call-interactively 'backward-word))))
15565
15566 (defun org-metaright (&optional arg)
15567 "Demote subtree or move table column to right.
15568 Calls `org-do-demote' or `org-table-move-column', depending on context.
15569 With no specific context, calls the Emacs default `forward-word'.
15570 See the individual commands for more information."
15571 (interactive "P")
15572 (cond
15573 ((org-at-table-p) (call-interactively 'org-table-move-column))
15574 ((or (org-on-heading-p) (org-region-active-p))
15575 (call-interactively 'org-do-demote))
15576 (t (call-interactively 'forward-word))))
15577
15578 (defun org-metaup (&optional arg)
15579 "Move subtree up or move table row up.
15580 Calls `org-move-subtree-up' or `org-table-move-row' or
15581 `org-move-item-up', depending on context. See the individual commands
15582 for more information."
15583 (interactive "P")
15584 (cond
15585 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15586 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15587 ((org-at-item-p) (call-interactively 'org-move-item-up))
15588 (t (org-shiftcursor-error))))
15589
15590 (defun org-metadown (&optional arg)
15591 "Move subtree down or move table row down.
15592 Calls `org-move-subtree-down' or `org-table-move-row' or
15593 `org-move-item-down', depending on context. See the individual
15594 commands for more information."
15595 (interactive "P")
15596 (cond
15597 ((org-at-table-p) (call-interactively 'org-table-move-row))
15598 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15599 ((org-at-item-p) (call-interactively 'org-move-item-down))
15600 (t (org-shiftcursor-error))))
15601
15602 (defun org-shiftup (&optional arg)
15603 "Increase item in timestamp or increase priority of current headline.
15604 Calls `org-timestamp-up' or `org-priority-up', depending on context.
15605 See the individual commands for more information."
15606 (interactive "P")
15607 (cond
15608 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
15609 ((org-on-heading-p) (call-interactively 'org-priority-up))
15610 ((org-at-item-p) (call-interactively 'org-previous-item))
15611 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
15612
15613 (defun org-shiftdown (&optional arg)
15614 "Decrease item in timestamp or decrease priority of current headline.
15615 Calls `org-timestamp-down' or `org-priority-down', depending on context.
15616 See the individual commands for more information."
15617 (interactive "P")
15618 (cond
15619 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
15620 ((org-on-heading-p) (call-interactively 'org-priority-down))
15621 (t (call-interactively 'org-next-item))))
15622
15623 (defun org-shiftright ()
15624 "Next TODO keyword or timestamp one day later, depending on context."
15625 (interactive)
15626 (cond
15627 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15628 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
15629 (t (org-shiftcursor-error))))
15630
15631 (defun org-shiftleft ()
15632 "Previous TODO keyword or timestamp one day earlier, depending on context."
15633 (interactive)
15634 (cond
15635 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15636 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
15637 (t (org-shiftcursor-error))))
15638
15639 (defun org-copy-special ()
15640 "Copy region in table or copy current subtree.
15641 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15642 See the individual commands for more information."
15643 (interactive)
15644 (call-interactively
15645 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15646
15647 (defun org-cut-special ()
15648 "Cut region in table or cut current subtree.
15649 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15650 See the individual commands for more information."
15651 (interactive)
15652 (call-interactively
15653 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15654
15655 (defun org-paste-special (arg)
15656 "Paste rectangular region into table, or past subtree relative to level.
15657 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15658 See the individual commands for more information."
15659 (interactive "P")
15660 (if (org-at-table-p)
15661 (org-table-paste-rectangle)
15662 (org-paste-subtree arg)))
15663
15664 (defun org-ctrl-c-ctrl-c (&optional arg)
15665 "Set tags in headline, or update according to changed information at point.
15666
15667 This command does many different things, depending on context:
15668
15669 - If the cursor is in a headline, prompt for tags and insert them
15670 into the current line, aligned to `org-tags-column'. When called
15671 with prefix arg, realign all tags in the current buffer.
15672
15673 - If the cursor is in one of the special #+KEYWORD lines, this
15674 triggers scanning the buffer for these lines and updating the
15675 information.
15676
15677 - If the cursor is inside a table, realign the table. This command
15678 works even if the automatic table editor has been turned off.
15679
15680 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15681 the entire table.
15682
15683 - If the cursor is inside a table created by the table.el package,
15684 activate that table.
15685
15686 - If the current buffer is a remember buffer, close note and file it.
15687 with a prefix argument, file it without further interaction to the default
15688 location.
15689
15690 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15691 links in this buffer.
15692
15693 - If the cursor is on a numbered item in a plain list, renumber the
15694 ordered list."
15695 (interactive "P")
15696 (let ((org-enable-table-editor t))
15697 (cond
15698 ((or org-clock-overlays org-occur-highlights
15699 org-latex-fragment-image-overlays)
15700 (org-remove-clock-overlays)
15701 (org-remove-occur-highlights)
15702 (org-remove-latex-fragment-image-overlays)
15703 (message "Temporary highlights/overlays removed from current buffer"))
15704 ((and (local-variable-p 'org-finish-function (current-buffer))
15705 (fboundp org-finish-function))
15706 (funcall org-finish-function))
15707 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15708 ((org-on-heading-p) (call-interactively 'org-set-tags))
15709 ((org-at-table.el-p)
15710 (require 'table)
15711 (beginning-of-line 1)
15712 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15713 (call-interactively 'table-recognize-table))
15714 ((org-at-table-p)
15715 (org-table-maybe-eval-formula)
15716 (if arg
15717 (call-interactively 'org-table-recalculate)
15718 (org-table-maybe-recalculate-line))
15719 (call-interactively 'org-table-align))
15720 ((org-at-item-checkbox-p)
15721 (call-interactively 'org-toggle-checkbox))
15722 ((org-at-item-p)
15723 (call-interactively 'org-renumber-ordered-list))
15724 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
15725 (cond
15726 ((equal (match-string 1) "TBLFM")
15727 ;; Recalculate the table before this line
15728 (save-excursion
15729 (beginning-of-line 1)
15730 (skip-chars-backward " \r\n\t")
15731 (if (org-at-table-p)
15732 (org-call-with-arg 'org-table-recalculate t))))
15733 (t
15734 (call-interactively 'org-mode-restart))))
15735 (t (error "C-c C-c can do nothing useful at this location.")))))
15736
15737 (defun org-mode-restart ()
15738 "Restart Org-mode, to scan again for special lines.
15739 Also updates the keyword regular expressions."
15740 (interactive)
15741 (let ((org-inhibit-startup t)) (org-mode))
15742 (message "Org-mode restarted to refresh keyword and special line setup"))
15743
15744 (defun org-return ()
15745 "Goto next table row or insert a newline.
15746 Calls `org-table-next-row' or `newline', depending on context.
15747 See the individual commands for more information."
15748 (interactive)
15749 (cond
15750 ((org-at-table-p)
15751 (org-table-justify-field-maybe)
15752 (call-interactively 'org-table-next-row))
15753 (t (newline))))
15754
15755 (defun org-meta-return (&optional arg)
15756 "Insert a new heading or wrap a region in a table.
15757 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15758 See the individual commands for more information."
15759 (interactive "P")
15760 (cond
15761 ((org-at-table-p)
15762 (call-interactively 'org-table-wrap-region))
15763 (t (call-interactively 'org-insert-heading))))
15764
15765 ;;; Menu entries
15766
15767 ;; Define the Org-mode menus
15768 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15769 '("Tbl"
15770 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
15771 ["Next Field" org-cycle (org-at-table-p)]
15772 ["Previous Field" org-shifttab (org-at-table-p)]
15773 ["Next Row" org-return (org-at-table-p)]
15774 "--"
15775 ["Blank Field" org-table-blank-field (org-at-table-p)]
15776 ["Edit Field" org-table-edit-field (org-at-table-p)]
15777 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15778 "--"
15779 ("Column"
15780 ["Move Column Left" org-metaleft (org-at-table-p)]
15781 ["Move Column Right" org-metaright (org-at-table-p)]
15782 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15783 ["Insert Column" org-shiftmetaright (org-at-table-p)]
15784 "--"
15785 ["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])
15786 ("Row"
15787 ["Move Row Up" org-metaup (org-at-table-p)]
15788 ["Move Row Down" org-metadown (org-at-table-p)]
15789 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15790 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15791 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15792 "--"
15793 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
15794 ("Rectangle"
15795 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15796 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15797 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15798 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15799 "--"
15800 ("Calculate"
15801 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15802 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15803 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
15804 "--"
15805 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15806 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15807 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15808 "--"
15809 ["Sum Column/Rectangle" org-table-sum
15810 (or (org-at-table-p) (org-region-active-p))]
15811 ["Which Column?" org-table-current-column (org-at-table-p)])
15812 ["Debug Formulas"
15813 (setq org-table-formula-debug (not org-table-formula-debug))
15814 :style toggle :selected org-table-formula-debug]
15815 "--"
15816 ["Create" org-table-create (and (not (org-at-table-p))
15817 org-enable-table-editor)]
15818 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15819 ["Import from File" org-table-import (not (org-at-table-p))]
15820 ["Export to File" org-table-export (org-at-table-p)]
15821 "--"
15822 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15823
15824 (easy-menu-define org-org-menu org-mode-map "Org menu"
15825 '("Org"
15826 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
15827 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
15828 ["Sparse Tree" org-occur t]
15829 ["Show All" show-all t]
15830 "--"
15831 ["New Heading" org-insert-heading t]
15832 ("Navigate Headings"
15833 ["Up" outline-up-heading t]
15834 ["Next" outline-next-visible-heading t]
15835 ["Previous" outline-previous-visible-heading t]
15836 ["Next Same Level" outline-forward-same-level t]
15837 ["Previous Same Level" outline-backward-same-level t]
15838 "--"
15839 ["Jump" org-goto t])
15840 ("Edit Structure"
15841 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15842 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15843 "--"
15844 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15845 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15846 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15847 "--"
15848 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15849 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15850 ["Demote Heading" org-metaright (not (org-at-table-p))]
15851 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15852 "--"
15853 ["Convert to odd levels" org-convert-to-odd-levels t]
15854 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15855 ("Archive"
15856 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15857 ["Check and Tag Children" (org-toggle-archive-tag (4))
15858 :active t :keys "C-u C-c C-x C-a"]
15859 ["Sparse trees open ARCHIVE trees"
15860 (setq org-sparse-tree-open-archived-trees
15861 (not org-sparse-tree-open-archived-trees))
15862 :style toggle :selected org-sparse-tree-open-archived-trees]
15863 ["Cycling opens ARCHIVE trees"
15864 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15865 :style toggle :selected org-cycle-open-archived-trees]
15866 ["Agenda includes ARCHIVE trees"
15867 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
15868 :style toggle :selected (not org-agenda-skip-archived-trees)]
15869 "--"
15870 ["Move Subtree to Archive" org-archive-subtree t]
15871 ["Check and Move Children" (org-archive-subtree '(4))
15872 :active t :keys "C-u C-c $"])
15873 "--"
15874 ("TODO Lists"
15875 ["TODO/DONE/-" org-todo t]
15876 ("Select keyword"
15877 ["Next keyword" org-shiftright (org-on-heading-p)]
15878 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15879 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
15880 ["Show TODO Tree" org-show-todo-tree t]
15881 ["Global TODO list" org-todo-list t]
15882 "--"
15883 ["Set Priority" org-priority t]
15884 ["Priority Up" org-shiftup t]
15885 ["Priority Down" org-shiftdown t])
15886 ("Dates and Scheduling"
15887 ["Timestamp" org-time-stamp t]
15888 ["Timestamp (inactive)" org-time-stamp-inactive t]
15889 ("Change Date"
15890 ["1 Day Later" org-timestamp-up-day t]
15891 ["1 Day Earlier" org-timestamp-down-day t]
15892 ["1 ... Later" org-shiftup t]
15893 ["1 ... Earlier" org-shiftdown t])
15894 ["Compute Time Range" org-evaluate-time-range t]
15895 ["Schedule Item" org-schedule t]
15896 ["Deadline" org-deadline t]
15897 "--"
15898 ["Goto Calendar" org-goto-calendar t]
15899 ["Date from Calendar" org-date-from-calendar t])
15900 ("Logging work"
15901 ["Clock in" org-clock-in t]
15902 ["Clock out" org-clock-out t]
15903 ["Clock cancel" org-clock-cancel t]
15904 ["Display times" org-clock-display t]
15905 ["Create clock table" org-clock-report t]
15906 "--"
15907 ["Record DONE time"
15908 (progn (setq org-log-done (not org-log-done))
15909 (message "Switching to %s will %s record a timestamp"
15910 org-done-string
15911 (if org-log-done "automatically" "not")))
15912 :style toggle :selected org-log-done])
15913 "--"
15914 ["Agenda Command" org-agenda t]
15915 ("File List for Agenda")
15916 ("Special views current file"
15917 ["TODO Tree" org-show-todo-tree t]
15918 ["Check Deadlines" org-check-deadlines t]
15919 ["Timeline" org-timeline t]
15920 ["Tags Tree" org-tags-sparse-tree t])
15921 "--"
15922 ("Hyperlinks"
15923 ["Store Link (Global)" org-store-link t]
15924 ["Insert Link" org-insert-link t]
15925 ["Follow Link" org-open-at-point t]
15926 "--"
15927 ["Descriptive Links"
15928 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15929 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
15930 ["Literal Links"
15931 (progn
15932 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15933 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
15934 "--"
15935 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
15936 (save-excursion (goto-char (point-min))
15937 (re-search-forward "<[a-z]+:" nil t))])
15938 "--"
15939 ["Export/Publish" org-export t]
15940 ("LaTeX"
15941 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15942 :selected org-cdlatex-mode]
15943 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15944 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15945 ["Modify math symbol" org-cdlatex-math-modify
15946 (org-inside-LaTeX-fragment-p)]
15947 ["Export LaTeX fragments as images"
15948 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
15949 :style toggle :selected org-export-with-LaTeX-fragments])
15950 "--"
15951 ("Documentation"
15952 ["Show Version" org-version t]
15953 ["Info Documentation" org-info t])
15954 ("Customize"
15955 ["Browse Org Group" org-customize t]
15956 "--"
15957 ["Expand This Menu" org-create-customize-menu
15958 (fboundp 'customize-menu-create)])
15959 "--"
15960 ["Refresh setup" org-mode-restart t]
15961 ))
15962
15963 (defun org-info (&optional node)
15964 "Read documentation for Org-mode in the info system.
15965 With optional NODE, go directly to that node."
15966 (interactive)
15967 (require 'info)
15968 (Info-goto-node (format "(org)%s" (or node ""))))
15969
15970 (defun org-install-agenda-files-menu ()
15971 (let ((bl (buffer-list)))
15972 (save-excursion
15973 (while bl
15974 (set-buffer (pop bl))
15975 (if (org-mode-p) (setq bl nil)))
15976 (when (org-mode-p)
15977 (easy-menu-change
15978 '("Org") "File List for Agenda"
15979 (append
15980 (list
15981 ["Edit File List" (org-edit-agenda-file-list) t]
15982 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15983 ["Remove Current File from List" org-remove-file t]
15984 ["Cycle through agenda files" org-cycle-agenda-files t]
15985 "--")
15986 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15987
15988 ;;; Documentation
15989
15990 (defun org-customize ()
15991 "Call the customize function with org as argument."
15992 (interactive)
15993 (customize-browse 'org))
15994
15995 (defun org-create-customize-menu ()
15996 "Create a full customization menu for Org-mode, insert it into the menu."
15997 (interactive)
15998 (if (fboundp 'customize-menu-create)
15999 (progn
16000 (easy-menu-change
16001 '("Org") "Customize"
16002 `(["Browse Org group" org-customize t]
16003 "--"
16004 ,(customize-menu-create 'org)
16005 ["Set" Custom-set t]
16006 ["Save" Custom-save t]
16007 ["Reset to Current" Custom-reset-current t]
16008 ["Reset to Saved" Custom-reset-saved t]
16009 ["Reset to Standard Settings" Custom-reset-standard t]))
16010 (message "\"Org\"-menu now contains full customization menu"))
16011 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16012
16013 ;;; Miscellaneous stuff
16014
16015 (defun org-context ()
16016 "Return a list of contexts of the current cursor position.
16017 If several contexts apply, all are returned.
16018 Each context entry is a list with a symbol naming the context, and
16019 two positions indicating start and end of the context. Possible
16020 contexts are:
16021
16022 :headline anywhere in a headline
16023 :headline-stars on the leading stars in a headline
16024 :todo-keyword on a TODO keyword (including DONE) in a headline
16025 :tags on the TAGS in a headline
16026 :priority on the priority cookie in a headline
16027 :item on the first line of a plain list item
16028 :item-bullet on the bullet/number of a plain list item
16029 :checkbox on the checkbox in a plain list item
16030 :table in an org-mode table
16031 :table-special on a special filed in a table
16032 :table-table in a table.el table
16033 :link on a hyperline
16034 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16035 :target on a <<target>>
16036 :radio-target on a <<<radio-target>>>
16037 :latex-fragment on a LaTeX fragment
16038 :latex-preview on a LaTeX fragment with overlayed preview image
16039
16040 This function expects the position to be visible because it uses font-lock
16041 faces as a help to recognize the following contexts: :table-special, :link,
16042 and :keyword."
16043 (let* ((f (get-text-property (point) 'face))
16044 (faces (if (listp f) f (list f)))
16045 (p (point)) clist o)
16046 ;; First the large context
16047 (cond
16048 ((org-on-heading-p)
16049 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16050 (when (progn
16051 (beginning-of-line 1)
16052 (looking-at org-todo-line-tags-regexp))
16053 (push (org-point-in-group p 1 :headline-stars) clist)
16054 (push (org-point-in-group p 2 :todo-keyword) clist)
16055 (push (org-point-in-group p 4 :tags) clist))
16056 (goto-char p)
16057 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
16058 (if (looking-at "\\[#[A-Z]\\]")
16059 (push (org-point-in-group p 0 :priority) clist)))
16060
16061 ((org-at-item-p)
16062 (push (org-point-in-group p 2 :item-bullet) clist)
16063 (push (list :item (point-at-bol)
16064 (save-excursion (org-end-of-item) (point)))
16065 clist)
16066 (and (org-at-item-checkbox-p)
16067 (push (org-point-in-group p 0 :checkbox) clist)))
16068
16069 ((org-at-table-p)
16070 (push (list :table (org-table-begin) (org-table-end)) clist)
16071 (if (memq 'org-formula faces)
16072 (push (list :table-special
16073 (previous-single-property-change p 'face)
16074 (next-single-property-change p 'face)) clist)))
16075 ((org-at-table-p 'any)
16076 (push (list :table-table) clist)))
16077 (goto-char p)
16078
16079 ;; Now the small context
16080 (cond
16081 ((org-at-timestamp-p)
16082 (push (org-point-in-group p 0 :timestamp) clist))
16083 ((memq 'org-link faces)
16084 (push (list :link
16085 (previous-single-property-change p 'face)
16086 (next-single-property-change p 'face)) clist))
16087 ((memq 'org-special-keyword faces)
16088 (push (list :keyword
16089 (previous-single-property-change p 'face)
16090 (next-single-property-change p 'face)) clist))
16091 ((org-on-target-p)
16092 (push (org-point-in-group p 0 :target) clist)
16093 (goto-char (1- (match-beginning 0)))
16094 (if (looking-at org-radio-target-regexp)
16095 (push (org-point-in-group p 0 :radio-target) clist))
16096 (goto-char p))
16097 ((setq o (car (delq nil
16098 (mapcar
16099 (lambda (x)
16100 (if (memq x org-latex-fragment-image-overlays) x))
16101 (org-overlays-at (point))))))
16102 (push (list :latex-fragment
16103 (org-overlay-start o) (org-overlay-end o)) clist)
16104 (push (list :latex-preview
16105 (org-overlay-start o) (org-overlay-end o)) clist))
16106 ((org-inside-LaTeX-fragment-p)
16107 ;; FIXME: positions wring.
16108 (push (list :latex-fragment (point) (point)) clist)))
16109
16110 (setq clist (nreverse (delq nil clist)))
16111 clist))
16112
16113 (defun org-point-in-group (point group &optional context)
16114 "Check if POINT is in match-group GROUP.
16115 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16116 match. If the match group does ot exist or point is not inside it,
16117 return nil."
16118 (and (match-beginning group)
16119 (>= point (match-beginning group))
16120 (<= point (match-end group))
16121 (if context
16122 (list context (match-beginning group) (match-end group))
16123 t)))
16124
16125 (defun org-move-line-down (arg)
16126 "Move the current line down. With prefix argument, move it past ARG lines."
16127 (interactive "p")
16128 (let ((col (current-column))
16129 beg end pos)
16130 (beginning-of-line 1) (setq beg (point))
16131 (beginning-of-line 2) (setq end (point))
16132 (beginning-of-line (+ 1 arg))
16133 (setq pos (move-marker (make-marker) (point)))
16134 (insert (delete-and-extract-region beg end))
16135 (goto-char pos)
16136 (move-to-column col)))
16137
16138 (defun org-move-line-up (arg)
16139 "Move the current line up. With prefix argument, move it past ARG lines."
16140 (interactive "p")
16141 (let ((col (current-column))
16142 beg end pos)
16143 (beginning-of-line 1) (setq beg (point))
16144 (beginning-of-line 2) (setq end (point))
16145 (beginning-of-line (- arg))
16146 (setq pos (move-marker (make-marker) (point)))
16147 (insert (delete-and-extract-region beg end))
16148 (goto-char pos)
16149 (move-to-column col)))
16150
16151 ;; Paragraph filling stuff.
16152 ;; We want this to be just right, so use the full arsenal.
16153
16154 (defun org-set-autofill-regexps ()
16155 (interactive)
16156 ;; In the paragraph separator we include headlines, because filling
16157 ;; text in a line directly attached to a headline would otherwise
16158 ;; fill the headline as well.
16159 (org-set-local 'comment-start-skip "^#+[ \t]*")
16160 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
16161 ;; The paragraph starter includes hand-formatted lists.
16162 (org-set-local 'paragraph-start
16163 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
16164 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16165 ;; But only if the user has not turned off tables or fixed-width regions
16166 (org-set-local
16167 'auto-fill-inhibit-regexp
16168 (concat "\\*\\|#"
16169 "\\|[ \t]*" org-keyword-time-regexp
16170 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16171 (concat
16172 "\\|[ \t]*["
16173 (if org-enable-table-editor "|" "")
16174 (if org-enable-fixed-width-editor ":" "")
16175 "]"))))
16176 ;; We use our own fill-paragraph function, to make sure that tables
16177 ;; and fixed-width regions are not wrapped. That function will pass
16178 ;; through to `fill-paragraph' when appropriate.
16179 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16180 ; Adaptive filling: To get full control, first make sure that
16181 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16182 (org-set-local 'adaptive-fill-regexp "\000")
16183 (org-set-local 'adaptive-fill-function
16184 'org-adaptive-fill-function))
16185
16186 (defun org-fill-paragraph (&optional justify)
16187 "Re-align a table, pass through to fill-paragraph if no table."
16188 (let ((table-p (org-at-table-p))
16189 (table.el-p (org-at-table.el-p)))
16190 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
16191 (table.el-p t) ; skip table.el tables
16192 (table-p (org-table-align) t) ; align org-mode tables
16193 (t nil)))) ; call paragraph-fill
16194
16195 ;; For reference, this is the default value of adaptive-fill-regexp
16196 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16197
16198 (defun org-adaptive-fill-function ()
16199 "Return a fill prefix for org-mode files.
16200 In particular, this makes sure hanging paragraphs for hand-formatted lists
16201 work correctly."
16202 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
16203 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
16204
16205 ;; Functions needed for Emacs/XEmacs region compatibility
16206
16207 (defun org-add-hook (hook function &optional append local)
16208 "Add-hook, compatible with both Emacsen."
16209 (if (and local (featurep 'xemacs))
16210 (add-local-hook hook function append)
16211 (add-hook hook function append local)))
16212
16213 (defun org-region-active-p ()
16214 "Is `transient-mark-mode' on and the region active?
16215 Works on both Emacs and XEmacs."
16216 (if org-ignore-region
16217 nil
16218 (if (featurep 'xemacs)
16219 (and zmacs-regions (region-active-p))
16220 (and transient-mark-mode mark-active))))
16221
16222 (defun org-add-to-invisibility-spec (arg)
16223 "Add elements to `buffer-invisibility-spec'.
16224 See documentation for `buffer-invisibility-spec' for the kind of elements
16225 that can be added."
16226 (cond
16227 ((fboundp 'add-to-invisibility-spec)
16228 (add-to-invisibility-spec arg))
16229 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
16230 (setq buffer-invisibility-spec (list arg)))
16231 (t
16232 (setq buffer-invisibility-spec
16233 (cons arg buffer-invisibility-spec)))))
16234
16235 (defun org-remove-from-invisibility-spec (arg)
16236 "Remove elements from `buffer-invisibility-spec'."
16237 (if (fboundp 'remove-from-invisibility-spec)
16238 (remove-from-invisibility-spec arg)
16239 (if (consp buffer-invisibility-spec)
16240 (setq buffer-invisibility-spec
16241 (delete arg buffer-invisibility-spec)))))
16242
16243 (defun org-in-invisibility-spec-p (arg)
16244 "Is ARG a member of `buffer-invisibility-spec'?"
16245 (if (consp buffer-invisibility-spec)
16246 (member arg buffer-invisibility-spec)
16247 nil))
16248
16249 (defun org-image-file-name-regexp ()
16250 "Return regexp matching the file names of images."
16251 (if (fboundp 'image-file-name-regexp)
16252 (image-file-name-regexp)
16253 (let ((image-file-name-extensions
16254 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16255 "xbm" "xpm" "pbm" "pgm" "ppm")))
16256 (concat "\\."
16257 (regexp-opt (nconc (mapcar 'upcase
16258 image-file-name-extensions)
16259 image-file-name-extensions)
16260 t)
16261 "\\'"))))
16262
16263 ;; Functions extending outline functionality
16264
16265 ;; C-a should go to the beginning of a *visible* line, also in the
16266 ;; new outline.el. I guess this should be patched into Emacs?
16267 (defun org-beginning-of-line ()
16268 "Go to the beginning of the current line. If that is invisible, continue
16269 to a visible line beginning. This makes the function of C-a more intuitive."
16270 (interactive)
16271 (beginning-of-line 1)
16272 (if (bobp)
16273 nil
16274 (backward-char 1)
16275 (if (org-invisible-p)
16276 (while (and (not (bobp)) (org-invisible-p))
16277 (backward-char 1)
16278 (beginning-of-line 1))
16279 (forward-char 1))))
16280
16281 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16282
16283 (defun org-invisible-p ()
16284 "Check if point is at a character currently not visible."
16285 ;; Early versions of noutline don't have `outline-invisible-p'.
16286 (if (fboundp 'outline-invisible-p)
16287 (outline-invisible-p)
16288 (get-char-property (point) 'invisible)))
16289
16290 (defun org-invisible-p2 ()
16291 "Check if point is at a character currently not visible."
16292 (save-excursion
16293 (if (and (eolp) (not (bobp))) (backward-char 1))
16294 ;; Early versions of noutline don't have `outline-invisible-p'.
16295 (if (fboundp 'outline-invisible-p)
16296 (outline-invisible-p)
16297 (get-char-property (point) 'invisible))))
16298
16299 (defalias 'org-back-to-heading 'outline-back-to-heading)
16300 (defalias 'org-on-heading-p 'outline-on-heading-p)
16301
16302 (defun org-on-target-p ()
16303 (let ((pos (point)))
16304 (save-excursion
16305 (skip-chars-forward "<")
16306 (and (re-search-backward "<<" nil t)
16307 (or (looking-at org-radio-target-regexp)
16308 (looking-at org-target-regexp))
16309 (<= (match-beginning 0) pos)
16310 (>= (1+ (match-end 0)) pos)))))
16311
16312 (defun org-up-heading-all (arg)
16313 "Move to the heading line of which the present line is a subheading.
16314 This function considers both visible and invisible heading lines.
16315 With argument, move up ARG levels."
16316 (if (fboundp 'outline-up-heading-all)
16317 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16318 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16319
16320 (defun org-show-hidden-entry ()
16321 "Show an entry where even the heading is hidden."
16322 (save-excursion
16323 (org-show-entry)))
16324
16325 (defun org-flag-heading (flag &optional entry)
16326 "Flag the current heading. FLAG non-nil means make invisible.
16327 When ENTRY is non-nil, show the entire entry."
16328 (save-excursion
16329 (org-back-to-heading t)
16330 ;; Check if we should show the entire entry
16331 (if entry
16332 (progn
16333 (org-show-entry)
16334 (save-excursion
16335 (and (outline-next-heading)
16336 (org-flag-heading nil))))
16337 (outline-flag-region (max 1 (1- (point)))
16338 (save-excursion (outline-end-of-heading) (point))
16339 flag))))
16340
16341 (defun org-end-of-subtree (&optional invisible-OK)
16342 ;; This is an exact copy of the original function, but it uses
16343 ;; `org-back-to-heading', to make it work also in invisible
16344 ;; trees. And is uses an invisible-OK argument.
16345 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16346 (org-back-to-heading invisible-OK)
16347 (let ((first t)
16348 (level (funcall outline-level)))
16349 (while (and (not (eobp))
16350 (or first (> (funcall outline-level) level)))
16351 (setq first nil)
16352 (outline-next-heading))
16353 (if (memq (preceding-char) '(?\n ?\^M))
16354 (progn
16355 ;; Go to end of line before heading
16356 (forward-char -1)
16357 (if (memq (preceding-char) '(?\n ?\^M))
16358 ;; leave blank line before heading
16359 (forward-char -1)))))
16360 (point))
16361
16362 (defun org-show-subtree ()
16363 "Show everything after this heading at deeper levels."
16364 (outline-flag-region
16365 (point)
16366 (save-excursion
16367 (outline-end-of-subtree) (outline-next-heading) (point))
16368 nil))
16369
16370 (defun org-show-entry ()
16371 "Show the body directly following this heading.
16372 Show the heading too, if it is currently invisible."
16373 (interactive)
16374 (save-excursion
16375 (org-back-to-heading t)
16376 (outline-flag-region
16377 (max 1 (1- (point)))
16378 (save-excursion
16379 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
16380 (or (match-beginning 1) (point-max)))
16381 nil)))
16382
16383 (defun org-make-options-regexp (kwds)
16384 "Make a regular expression for keyword lines."
16385 (concat
16386 "^"
16387 "#?[ \t]*\\+\\("
16388 (mapconcat 'regexp-quote kwds "\\|")
16389 "\\):[ \t]*"
16390 "\\(.+\\)"))
16391
16392 ;; Make `bookmark-jump' show the jump location if it was hidden.
16393 (eval-after-load "bookmark"
16394 '(if (boundp 'bookmark-after-jump-hook)
16395 ;; We can use the hook
16396 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16397 ;; Hook not available, use advice
16398 (defadvice bookmark-jump (after org-make-visible activate)
16399 "Make the position visible."
16400 (org-bookmark-jump-unhide))))
16401
16402 (defun org-bookmark-jump-unhide ()
16403 "Unhide the current position, to show the bookmark location."
16404 (and (org-mode-p)
16405 (or (org-invisible-p)
16406 (save-excursion (goto-char (max (point-min) (1- (point))))
16407 (org-invisible-p)))
16408 (org-show-hierarchy-above)))
16409
16410 ;;; Experimental code
16411
16412
16413 ;;; Finish up
16414
16415 (provide 'org)
16416
16417 (run-hooks 'org-load-hook)
16418
16419 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16420 ;;; org.el ends here