Release 4.46
[org-mode.git] / org.el
blob60d63e10affc75903630360578bb1752db0f7867
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.46
9 ;;
10 ;; This file is part of GNU Emacs.
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.
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.
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
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.
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.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://staff.science.uva.nl/~dominik/Tools/org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; Recent changes
63 ;; --------------
64 ;; Version 4.46
65 ;; - Custom commands may produce an agenda which contains several blocks,
66 ;; each block created by a different agenda command.
67 ;; - Agenda commands can be restricted to the current file, region, subtree.
68 ;; - The timeline command must now be called through the agenda
69 ;; dispatcher (C-c a L). `C-c C-r' no longer works.
70 ;; - Agenda items can be sorted by tag. The *last* tag is used for this.
71 ;; - The prefix and the sorting strategy for agenda items can depend
72 ;; upon the agenda type.
73 ;; - The handling of `mailto:' links can be customized, see the new
74 ;; variable `org-link-mailto-program'.
75 ;; - `mailto' links can specify a subject after a double colon,
76 ;; like [[mailto:carsten@orgmode.org::Org-mode is buggy]].
77 ;; - In the #+STARTUP line, M-TAB completes valid keywords.
78 ;; - In the #+TAGS: line, M-TAB after ":" inserts all currently used tags.
79 ;; - Again full Emacs 21 support: Checkboxes and publishing are fixed.
80 ;; - More minor bug fixes.
81 ;;
82 ;; Version 4.45
83 ;; - Checkbox lists can show statistics about checked items.
84 ;; - C-TAB will cycle the visibility of archived subtrees.
85 ;;; - Documentation about checkboxes has been moved to chapter 5.
86 ;; - Bux fixes.
88 ;; Version 4.44
89 ;; - Clock table can be done for a limited time interval.
90 ;; - Obsolete support for the old outline mode has been removed.
91 ;; - Bug fixes and code cleaning.
93 ;; Version 4.43
94 ;; - Bug fixes
95 ;; - `s' key in the agenda saves all org-mode buffers.
97 ;; Version 4.41
98 ;; - Shift-curser keys can modify inactive time stamps (inactive time
99 ;; stamps are the ones in [...] brackets.
100 ;; - Toggle all checkboxes in a region/below a headline.
101 ;; - Bug fixes.
103 ;;; Code:
105 (eval-when-compile
106 (require 'cl)
107 (require 'calendar))
108 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
109 ;; the file noutline.el being loaded.
110 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
111 ;; We require noutline, which might be provided in outline.el
112 (require 'outline) (require 'noutline)
113 ;; Other stuff we need.
114 (require 'time-date)
115 (require 'easymenu)
117 ;;; Customization variables
119 (defvar org-version "4.46"
120 "The version number of the file org.el.")
121 (defun org-version ()
122 (interactive)
123 (message "Org-mode version %s" org-version))
125 ;; Compatibility constants
126 (defconst org-xemacs-p (featurep 'xemacs)) ; not used by org.el itself
127 (defconst org-format-transports-properties-p
128 (let ((x "a"))
129 (add-text-properties 0 1 '(test t) x)
130 (get-text-property 0 'test (format "%s" x)))
131 "Does format transport text properties?")
133 (defgroup org nil
134 "Outline-based notes management and organizer."
135 :tag "Org"
136 :group 'outlines
137 :group 'hypermedia
138 :group 'calendar)
140 (defgroup org-startup nil
141 "Options concerning startup of Org-mode."
142 :tag "Org Startup"
143 :group 'org)
145 (defcustom org-startup-folded t
146 "Non-nil means, entering Org-mode will switch to OVERVIEW.
147 This can also be configured on a per-file basis by adding one of
148 the following lines anywhere in the buffer:
150 #+STARTUP: fold
151 #+STARTUP: nofold
152 #+STARTUP: content"
153 :group 'org-startup
154 :type '(choice
155 (const :tag "nofold: show all" nil)
156 (const :tag "fold: overview" t)
157 (const :tag "content: all headlines" content)))
159 (defcustom org-startup-truncated t
160 "Non-nil means, entering Org-mode will set `truncate-lines'.
161 This is useful since some lines containing links can be very long and
162 uninteresting. Also tables look terrible when wrapped."
163 :group 'org-startup
164 :type 'boolean)
166 (defcustom org-startup-align-all-tables nil
167 "Non-nil means, align all tables when visiting a file.
168 This is useful when the column width in tables is forced with <N> cookies
169 in table fields. Such tables will look correct only after the first re-align.
170 This can also be configured on a per-file basis by adding one of
171 the following lines anywhere in the buffer:
172 #+STARTUP: align
173 #+STARTUP: noalign"
174 :group 'org-startup
175 :type 'boolean)
177 (defcustom org-startup-with-deadline-check nil
178 "Non-nil means, entering Org-mode will run the deadline check.
179 This means, if you start editing an org file, you will get an
180 immediate reminder of any due deadlines.
181 This can also be configured on a per-file basis by adding one of
182 the following lines anywhere in the buffer:
183 #+STARTUP: dlcheck
184 #+STARTUP: nodlcheck"
185 :group 'org-startup
186 :type 'boolean)
188 (defcustom org-insert-mode-line-in-empty-file nil
189 "Non-nil means insert the first line setting Org-mode in empty files.
190 When the function `org-mode' is called interactively in an empty file, this
191 normally means that the file name does not automatically trigger Org-mode.
192 To ensure that the file will always be in Org-mode in the future, a
193 line enforcing Org-mode will be inserted into the buffer, if this option
194 has been set."
195 :group 'org-startup
196 :type 'boolean)
198 (defcustom org-CUA-compatible nil
199 "Non-nil means use alternative key bindings for S-<cursor movement>.
200 Org-mode used S-<cursor movement> for changing timestamps and priorities.
201 S-<cursor movement> is also used for example by `CUA-mode' to select text.
202 If you want to use Org-mode together with `CUA-mode', Org-mode needs to use
203 alternative bindings. Setting this variable to t will replace the following
204 keys both in Org-mode and in the Org-agenda buffer.
206 S-RET -> C-S-RET
207 S-up -> M-p
208 S-down -> M-n
209 S-left -> M--
210 S-right -> M-+
212 If you do not like the alternative keys, take a look at the variable
213 `org-disputed-keys'.
215 This option is only relevant at load-time of Org-mode. Changing it requires
216 a restart of Emacs to become effective."
217 :group 'org-startup
218 :type 'boolean)
220 (defvar org-disputed-keys
221 '((S-up [(shift up)] [(meta ?p)])
222 (S-down [(shift down)] [(meta ?n)])
223 (S-left [(shift left)] [(meta ?-)])
224 (S-right [(shift right)] [(meta ?+)])
225 (S-return [(shift return)] [(control shift return)]))
226 "Keys for which Org-mode and other modes compete.
227 This is an alist, cars are symbols for lookup, 1st element is the default key,
228 second element will be used when `org-CUA-compatible' is t.")
230 (defun org-key (key)
231 "Select a key according to `org-CUA-compatible'."
232 (nth (if org-CUA-compatible 2 1)
233 (or (assq key org-disputed-keys)
234 (error "Invalid Key %s in `org-key'" key))))
236 (defcustom org-ellipsis nil
237 "The ellipsis to use in the Org-mode outline.
238 When nil, just use the standard three dots. When a string, use that instead,
239 and just in Org-mode (which will then use its own display table).
240 Changing this requires executing `M-x org-mode' in a buffer to become
241 effective."
242 :group 'org-startup
243 :type '(choice (const :tag "Default" nil)
244 (string :tag "String" :value "...#")))
246 (defvar org-display-table nil
247 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
249 (defgroup org-keywords nil
250 "Keywords in Org-mode."
251 :tag "Org Keywords"
252 :group 'org)
254 (defcustom org-deadline-string "DEADLINE:"
255 "String to mark deadline entries.
256 A deadline is this string, followed by a time stamp. Should be a word,
257 terminated by a colon. You can insert a schedule keyword and
258 a timestamp with \\[org-deadline].
259 Changes become only effective after restarting Emacs."
260 :group 'org-keywords
261 :type 'string)
263 (defcustom org-scheduled-string "SCHEDULED:"
264 "String to mark scheduled TODO entries.
265 A schedule is this string, followed by a time stamp. Should be a word,
266 terminated by a colon. You can insert a schedule keyword and
267 a timestamp with \\[org-schedule].
268 Changes become only effective after restarting Emacs."
269 :group 'org-keywords
270 :type 'string)
272 (defcustom org-closed-string "CLOSED:"
273 "String used as the prefix for timestamps logging closing a TODO entry."
274 :group 'org-keywords
275 :type 'string)
277 (defcustom org-clock-string "CLOCK:"
278 "String used as prefix for timestamps clocking work hours on an item."
279 :group 'org-keywords
280 :type 'string)
282 (defcustom org-comment-string "COMMENT"
283 "Entries starting with this keyword will never be exported.
284 An entry can be toggled between COMMENT and normal with
285 \\[org-toggle-comment].
286 Changes become only effective after restarting Emacs."
287 :group 'org-keywords
288 :type 'string)
290 (defcustom org-quote-string "QUOTE"
291 "Entries starting with this keyword will be exported in fixed-width font.
292 Quoting applies only to the text in the entry following the headline, and does
293 not extend beyond the next headline, even if that is lower level.
294 An entry can be toggled between QUOTE and normal with
295 \\[org-toggle-fixed-width-section]."
296 :group 'org-keywords
297 :type 'string)
299 (defgroup org-structure nil
300 "Options concerning the general structure of Org-mode files."
301 :tag "Org Structure"
302 :group 'org)
304 (defgroup org-cycle nil
305 "Options concerning visibility cycling in Org-mode."
306 :tag "Org Cycle"
307 :group 'org-structure)
309 (defcustom org-cycle-global-at-bob t
310 "Cycle globally if cursor is at beginning of buffer and not at a headline.
311 This makes it possible to do global cycling without having to use S-TAB or
312 C-u TAB. For this special case to work, the first line of the buffer
313 must not be a headline - it may be empty ot some other text. When used in
314 this way, `org-cycle-hook' is disables temporarily, to make sure the
315 cursor stays at the beginning of the buffer.
316 When this option is nil, don't do anything special at the beginning
317 of the buffer."
318 :group 'org-cycle
319 :type 'boolean)
321 (defcustom org-cycle-emulate-tab t
322 "Where should `org-cycle' emulate TAB.
323 nil Never
324 white Only in completely white lines
325 whitestart Only at the beginning of lines, before the first non-white char.
326 t Everywhere except in headlines
327 If TAB is used in a place where it does not emulate TAB, the current subtree
328 visibility is cycled."
329 :group 'org-cycle
330 :type '(choice (const :tag "Never" nil)
331 (const :tag "Only in completely white lines" white)
332 (const :tag "Before first char in a line" whitestart)
333 (const :tag "Everywhere except in headlines" t)
336 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
337 org-optimize-window-after-visibility-change)
338 "Hook that is run after `org-cycle' has changed the buffer visibility.
339 The function(s) in this hook must accept a single argument which indicates
340 the new state that was set by the most recent `org-cycle' command. The
341 argument is a symbol. After a global state change, it can have the values
342 `overview', `content', or `all'. After a local state change, it can have
343 the values `folded', `children', or `subtree'."
344 :group 'org-cycle
345 :type 'hook)
347 (defgroup org-edit-structure nil
348 "Options concerning structure editing in Org-mode."
349 :tag "Org Edit Structure"
350 :group 'org-structure)
352 (defcustom org-odd-levels-only nil
353 "Non-nil means, skip even levels and only use odd levels for the outline.
354 This has the effect that two stars are being added/taken away in
355 promotion/demotion commands. It also influences how levels are
356 handled by the exporters.
357 Changing it requires restart of `font-lock-mode' to become effective
358 for fontification also in regions already fontified.
359 You may also set this on a per-file basis by adding one of the following
360 lines to the buffer:
362 #+STARTUP: odd
363 #+STARTUP: oddeven"
364 :group 'org-edit-structure
365 :group 'org-font-lock
366 :type 'boolean)
368 (defcustom org-adapt-indentation t
369 "Non-nil means, adapt indentation when promoting and demoting.
370 When this is set and the *entire* text in an entry is indented, the
371 indentation is increased by one space in a demotion command, and
372 decreased by one in a promotion command. If any line in the entry
373 body starts at column 0, indentation is not changed at all."
374 :group 'org-edit-structure
375 :type 'boolean)
377 (defcustom org-insert-heading-hook nil
378 "Hook being run after inserting a new heading."
379 :group 'org-edit-structure
380 :type 'boolean)
382 (defcustom org-enable-fixed-width-editor t
383 "Non-nil means, lines starting with \":\" are treated as fixed-width.
384 This currently only means, they are never auto-wrapped.
385 When nil, such lines will be treated like ordinary lines.
386 See also the QUOTE keyword."
387 :group 'org-edit-structure
388 :type 'boolean)
390 (defgroup org-sparse-trees nil
391 "Options concerning sparse trees in Org-mode."
392 :tag "Org Sparse Trees"
393 :group 'org-structure)
395 (defcustom org-highlight-sparse-tree-matches t
396 "Non-nil means, highlight all matches that define a sparse tree.
397 The highlights will automatically disappear the next time the buffer is
398 changed by an edit command."
399 :group 'org-sparse-trees
400 :type 'boolean)
402 (defcustom org-show-hierarchy-above t
403 "Non-nil means, show full hierarchy when showing a spot in the tree.
404 Turning this off makes sparse trees more compact, but also less clear."
405 :group 'org-sparse-trees
406 :type 'boolean)
408 (defcustom org-show-following-heading t
409 "Non-nil means, show heading following match in `org-occur'.
410 When doing an `org-occur' it is useful to show the headline which
411 follows the match, even if they do not match the regexp. This makes it
412 easier to edit directly inside the sparse tree. However, if you use
413 `org-occur' mainly as an overview, the following headlines are
414 unnecessary clutter."
415 :group 'org-sparse-trees
416 :type 'boolean)
418 (defcustom org-occur-hook '(org-first-headline-recenter)
419 "Hook that is run after `org-occur' has constructed a sparse tree.
420 This can be used to recenter the window to show as much of the structure
421 as possible."
422 :group 'org-sparse-trees
423 :type 'hook)
425 (defgroup org-plain-lists nil
426 "Options concerning plain lists in Org-mode."
427 :tag "Org Plain lists"
428 :group 'org-structure)
430 (defcustom org-cycle-include-plain-lists t
431 "Non-nil means, include plain lists into visibility cycling.
432 This means that during cycling, plain list items will *temporarily* be
433 interpreted as outline headlines with a level given by 1000+i where i is the
434 indentation of the bullet. In all other operations, plain list items are
435 not seen as headlines. For example, you cannot assign a TODO keyword to
436 such an item."
437 :group 'org-plain-lists
438 :type 'boolean)
440 (defcustom org-plain-list-ordered-item-terminator t
441 "The character that makes a line with leading number an ordered list item.
442 Valid values are ?. and ?\). To get both terminators, use t. While
443 ?. may look nicer, it creates the danger that a line with leading
444 number may be incorrectly interpreted as an item. ?\) therefore is
445 the safe choice."
446 :group 'org-plain-lists
447 :type '(choice (const :tag "dot like in \"2.\"" ?.)
448 (const :tag "paren like in \"2)\"" ?\))
449 (const :tab "both" t)))
451 (defcustom org-auto-renumber-ordered-lists t
452 "Non-nil means, automatically renumber ordered plain lists.
453 Renumbering happens when the sequence have been changed with
454 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
455 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
456 :group 'org-plain-lists
457 :type 'boolean)
459 (defcustom org-provide-checkbox-statistics t
460 "Non-nil means, update checkbox statistics after insert and toggle.
461 When this is set, checkbox statistics is updated each time you either insert
462 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
463 with \\[org-ctrl-c-ctrl-c\\]."
464 :group 'org
465 :type 'boolean)
467 (defgroup org-archive nil
468 "Options concerning archiving in Org-mode."
469 :tag "Org Archive"
470 :group 'org-structure)
472 (defcustom org-archive-tag "ARCHIVE"
473 "The tag that marks a subtree as archived.
474 An archived subtree does not open during visibility cycling, and does
475 not contribute to the agenda listings."
476 :group 'org-archive
477 :group 'org-keywords
478 :type 'string)
480 (defcustom org-agenda-skip-archived-trees t
481 "Non-nil means, the agenda will skip any items located in archived trees.
482 An archived tree is a tree marked with the tag ARCHIVE."
483 :group 'org-archive
484 :group 'org-agenda-display
485 :type 'boolean)
487 (defcustom org-cycle-open-archived-trees nil
488 "Non-nil means, `org-cycle' will open archived trees.
489 An archived tree is a tree marked with the tag ARCHIVE.
490 When nil, archived trees will stay folded. You can still open them with
491 normal outline commands like `show-all', but not with the cycling commands."
492 :group 'org-archive
493 :group 'org-cycle
494 :type 'boolean)
496 (defcustom org-sparse-tree-open-archived-trees nil
497 "Non-nil means sparse tree construction shows matches in archived trees.
498 When nil, matches in these trees are highlighted, but the trees are kept in
499 collapsed state."
500 :group 'org-archive
501 :group 'org-sparse-trees
502 :type 'boolean)
504 (defcustom org-archive-location "%s_archive::"
505 "The location where subtrees should be archived.
506 This string consists of two parts, separated by a double-colon.
508 The first part is a file name - when omitted, archiving happens in the same
509 file. %s will be replaced by the current file name (without directory part).
510 Archiving to a different file is useful to keep archived entries from
511 contributing to the Org-mode Agenda.
513 The part after the double colon is a headline. The archived entries will be
514 filed under that headline. When omitted, the subtrees are simply filed away
515 at the end of the file, as top-level entries.
517 Here are a few examples:
518 \"%s_archive::\"
519 If the current file is Projects.org, archive in file
520 Projects.org_archive, as top-level trees. This is the default.
522 \"::* Archived Tasks\"
523 Archive in the current file, under the top-level headline
524 \"* Archived Tasks\".
526 \"~/org/archive.org::\"
527 Archive in file ~/org/archive.org (absolute path), as top-level trees.
529 \"basement::** Finished Tasks\"
530 Archive in file ./basement (relative path), as level 3 trees
531 below the level 2 heading \"** Finished Tasks\".
533 You may set this option on a per-file basis by adding to the buffer a
534 line like
536 #+ARCHIVE: basement::** Finished Tasks"
537 :group 'org-archive
538 :type 'string)
540 (defcustom org-archive-mark-done t
541 "Non-nil means, mark entries as DONE when they are moved to the archive file."
542 :group 'org-archive
543 :type 'boolean)
545 (defcustom org-archive-stamp-time t
546 "Non-nil means, add a time stamp to entries moved to an archive file.
547 The time stamp will be added directly after the TODO state keyword in the
548 first line, so it is probably best to use this in combinations with
549 `org-archive-mark-done'."
550 :group 'org-archive
551 :type 'boolean)
553 (defgroup org-table nil
554 "Options concerning tables in Org-mode."
555 :tag "Org Table"
556 :group 'org)
558 (defcustom org-enable-table-editor 'optimized
559 "Non-nil means, lines starting with \"|\" are handled by the table editor.
560 When nil, such lines will be treated like ordinary lines.
562 When equal to the symbol `optimized', the table editor will be optimized to
563 do the following:
564 - Use automatic overwrite mode in front of whitespace in table fields.
565 This make the structure of the table stay in tact as long as the edited
566 field does not exceed the column width.
567 - Minimize the number of realigns. Normally, the table is aligned each time
568 TAB or RET are pressed to move to another field. With optimization this
569 happens only if changes to a field might have changed the column width.
570 Optimization requires replacing the functions `self-insert-command',
571 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
572 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
573 very good at guessing when a re-align will be necessary, but you can always
574 force one with \\[org-ctrl-c-ctrl-c].
576 If you would like to use the optimized version in Org-mode, but the
577 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
579 This variable can be used to turn on and off the table editor during a session,
580 but in order to toggle optimization, a restart is required.
582 See also the variable `org-table-auto-blank-field'."
583 :group 'org-table
584 :type '(choice
585 (const :tag "off" nil)
586 (const :tag "on" t)
587 (const :tag "on, optimized" optimized)))
589 (defcustom orgtbl-optimized (eq org-enable-table-editor 'optimized)
590 "Non-nil means, use the optimized table editor version for `orgtbl-mode'.
591 In the optimized version, the table editor takes over all simple keys that
592 normally just insert a character. In tables, the characters are inserted
593 in a way to minimize disturbing the table structure (i.e. in overwrite mode
594 for empty fields). Outside tables, the correct binding of the keys is
595 restored.
597 The default for this option is t if the optimized version is also used in
598 Org-mode. See the variable `org-enable-table-editor' for details. Changing
599 this variable requires a restart of Emacs to become effective."
600 :group 'org-table
601 :type 'boolean)
603 (defgroup org-table-settings nil
604 "Settings for tables in Org-mode."
605 :tag "Org Table Settings"
606 :group 'org-table)
608 (defcustom org-table-default-size "5x2"
609 "The default size for newly created tables, Columns x Rows."
610 :group 'org-table-settings
611 :type 'string)
613 (defcustom org-table-number-regexp "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$"
614 "Regular expression for recognizing numbers in table columns.
615 If a table column contains mostly numbers, it will be aligned to the
616 right. If not, it will be aligned to the left.
618 The default value of this option is a regular expression which allows
619 anything which looks remotely like a number as used in scientific
620 context. For example, all of the following will be considered a
621 number:
622 12 12.2 2.4e-08 2x10^12 4.034+-0.02 2.7(10) >3.5
624 Other options offered by the customize interface are more restrictive."
625 :group 'org-table-settings
626 :type '(choice
627 (const :tag "Positive Integers"
628 "^[0-9]+$")
629 (const :tag "Integers"
630 "^[-+]?[0-9]+$")
631 (const :tag "Floating Point Numbers"
632 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.[0-9]*\\)$")
633 (const :tag "Floating Point Number or Integer"
634 "^[-+]?\\([0-9]*\\.[0-9]+\\|[0-9]+\\.?[0-9]*\\)$")
635 (const :tag "Exponential, Floating point, Integer"
636 "^[-+]?[0-9.]+\\([eEdD][-+0-9]+\\)?$")
637 (const :tag "Very General Number-Like"
638 "^[<>]?[-+^.0-9]*[0-9][-+^.0-9eEdDx()%]*$")
639 (string :tag "Regexp:")))
641 (defcustom org-table-number-fraction 0.5
642 "Fraction of numbers in a column required to make the column align right.
643 In a column all non-white fields are considered. If at least this
644 fraction of fields is matched by `org-table-number-fraction',
645 alignment to the right border applies."
646 :group 'org-table-settings
647 :type 'number)
649 (defgroup org-table-editing nil
650 "Bahavior of tables during editing in Org-mode."
651 :tag "Org Table Editing"
652 :group 'org-table)
654 (defcustom org-table-automatic-realign t
655 "Non-nil means, automatically re-align table when pressing TAB or RETURN.
656 When nil, aligning is only done with \\[org-table-align], or after column
657 removal/insertion."
658 :group 'org-table-editing
659 :type 'boolean)
661 (defcustom org-table-limit-column-width t ;kw
662 "Non-nil means, allow to limit the width of table columns with <N> fields."
663 :group 'org-table-editing
664 :type 'boolean)
666 (defcustom org-table-auto-blank-field t
667 "Non-nil means, automatically blank table field when starting to type into it.
668 This only happens when typing immediately after a field motion
669 command (TAB, S-TAB or RET).
670 Only relevant when `org-enable-table-editor' is equal to `optimized'."
671 :group 'org-table-editing
672 :type 'boolean)
674 (defcustom org-table-tab-jumps-over-hlines t
675 "Non-nil means, tab in the last column of a table with jump over a hline.
676 If a horizontal separator line is following the current line,
677 `org-table-next-field' can either create a new row before that line, or jump
678 over the line. When this option is nil, a new line will be created before
679 this line."
680 :group 'org-table-editing
681 :type 'boolean)
683 (defcustom org-table-tab-recognizes-table.el t
684 "Non-nil means, TAB will automatically notice a table.el table.
685 When it sees such a table, it moves point into it and - if necessary -
686 calls `table-recognize-table'."
687 :group 'org-table-editing
688 :type 'boolean)
690 (defgroup org-table-calculation nil
691 "Options concerning tables in Org-mode."
692 :tag "Org Table Calculation"
693 :group 'org-table)
695 (defcustom org-table-copy-increment t
696 "Non-nil means, increment when copying current field with \\[org-table-copy-down]."
697 :group 'org-table-calculation
698 :type 'boolean)
700 (defcustom org-calc-default-modes
701 '(calc-internal-prec 12
702 calc-float-format (float 5)
703 calc-angle-mode deg
704 calc-prefer-frac nil
705 calc-symbolic-mode nil
706 calc-date-format (YYYY "-" MM "-" DD " " Www (" " HH ":" mm))
707 calc-display-working-message t
709 "List with Calc mode settings for use in calc-eval for table formulas.
710 The list must contain alternating symbols (Calc modes variables and values).
711 Don't remove any of the default settings, just change the values. Org-mode
712 relies on the variables to be present in the list."
713 :group 'org-table-calculation
714 :type 'plist)
716 (defcustom org-table-formula-evaluate-inline t
717 "Non-nil means, TAB and RET evaluate a formula in current table field.
718 If the current field starts with an equal sign, it is assumed to be a formula
719 which should be evaluated as described in the manual and in the documentation
720 string of the command `org-table-eval-formula'. This feature requires the
721 Emacs calc package.
722 When this variable is nil, formula calculation is only available through
723 the command \\[org-table-eval-formula]."
724 :group 'org-table-calculation
725 :type 'boolean)
728 (defcustom org-table-formula-use-constants t
729 "Non-nil means, interpret constants in formulas in tables.
730 A constant looks like `$c' or `$Grav' and will be replaced before evaluation
731 by the value given in `org-table-formula-constants', or by a value obtained
732 from the `constants.el' package."
733 :group 'org-table-calculation
734 :type 'boolean)
736 (defcustom org-table-formula-constants nil
737 "Alist with constant names and values, for use in table formulas.
738 The car of each element is a name of a constant, without the `$' before it.
739 The cdr is the value as a string. For example, if you'd like to use the
740 speed of light in a formula, you would configure
742 (setq org-table-formula-constants '((\"c\" . \"299792458.\")))
744 and then use it in an equation like `$1*$c'."
745 :group 'org-table-calculation
746 :type '(repeat
747 (cons (string :tag "name")
748 (string :tag "value"))))
750 (defcustom org-table-formula-numbers-only nil
751 "Non-nil means, calculate only with numbers in table formulas.
752 Then all input fields will be converted to a number, and the result
753 must also be a number. When nil, calc's full potential is available
754 in table calculations, including symbolics etc."
755 :group 'org-table-calculation
756 :type 'boolean)
758 (defcustom org-table-allow-automatic-line-recalculation t
759 "Non-nil means, lines marked with |#| or |*| will be recomputed automatically.
760 Automatically means, when TAB or RET or C-c C-c are pressed in the line."
761 :group 'org-table-calculation
762 :type 'boolean)
764 (defgroup org-link nil
765 "Options concerning links in Org-mode."
766 :tag "Org Link"
767 :group 'org)
769 (defcustom org-descriptive-links t
770 "Non-nil means, hide link part and only show description of bracket links.
771 Bracket links are like [[link][descritpion]]. This variable sets the initial
772 state in new org-mode buffers. The setting can then be toggled on a
773 per-buffer basis from the Org->Hyperlinks menu."
774 :group 'org-link
775 :type 'boolean)
777 (defcustom org-link-style 'bracket
778 "The style of links to be inserted with \\[org-insert-link].
779 Possible values are:
780 bracket [[link][description]]. This is recommended
781 plain Description \\n link. The old way, no longer recommended."
782 :group 'org-link
783 :type '(choice
784 (const :tag "Bracket (recommended)" bracket)
785 (const :tag "Plain (no longer recommended)" plain)))
787 (defcustom org-link-format "%s"
788 "Default format for external, URL-like linkes in the buffer.
789 This is a format string for printf, %s will be replaced by the link text.
790 The recommended value is just \"%s\", since links will be protected by
791 enclosing them in double brackets. If you prefer plain links (see variable
792 `org-link-style'), \"<%s>\" is useful. Some people also recommend an
793 additional URL: prefix, so the format would be \"<URL:%s>\"."
794 :group 'org-link
795 :type '(choice
796 (const :tag "\"%s\" (e.g. http://www.there.com)" "%s")
797 (const :tag "\"<%s>\" (e.g. <http://www.there.com>)" "<%s>")
798 (const :tag "\"<URL:%s>\" (e.g. <URL:http://www.there.com>)" "<URL:%s>")
799 (string :tag "Other" :value "<%s>")))
801 (defcustom org-link-file-path-type 'adaptive
802 "How the path name in file links should be stored.
803 Valid values are:
805 relative relative to the current directory, i.e. the directory of the file
806 into which the link is being inserted.
807 absolute absolute path, if possible with ~ for home directory.
808 noabbrev absolute path, no abbreviation of home directory.
809 adaptive Use relative path for files in the current directory and sub-
810 directories of it. For other files, use an absolute path."
811 :group 'org-link
812 :type '(choice
813 (const relative)
814 (const absolute)
815 (const noabbrev)
816 (const adaptive)))
818 (defcustom org-activate-links '(bracket angle plain radio tag date)
819 "Types of links that should be activated in Org-mode files.
820 This is a list of symbols, each leading to the activation of a certain link
821 type. In principle, it does not hurt to turn on most link types - there may
822 be a small gain when turning off unused link types. The types are:
824 bracket The recommended [[link][description]] or [[link]] links with hiding.
825 angular Links in angular brackes that may contain whitespace like
826 <bbdb:Carsten Dominik>.
827 plain Plain links in normal text, no whitespace, like http://google.com.
828 radio Text that is matched by a radio target, see manual for details.
829 tag Tag settings in a headline (link to tag search).
830 date Time stamps (link to calendar).
831 camel CamelCase words defining text searches.
833 Changing this variable requires a restart of Emacs to become effective."
834 :group 'org-link
835 :type '(set (const :tag "Double bracket links (new style)" bracket)
836 (const :tag "Angular bracket links (old style)" angular)
837 (const :tag "plain text links" plain)
838 (const :tag "Radio target matches" radio)
839 (const :tag "Tags" tag)
840 (const :tag "Timestamps" date)
841 (const :tag "CamelCase words" camel)))
843 (defgroup org-link-store nil
844 "Options concerning storing links in Org-mode"
845 :tag "Org Store Link"
846 :group 'org-link)
848 (defcustom org-context-in-file-links t
849 "Non-nil means, file links from `org-store-link' contain context.
850 A search string will be added to the file name with :: as separator and
851 used to find the context when the link is activated by the command
852 `org-open-at-point'.
853 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
854 negates this setting for the duration of the command."
855 :group 'org-link-store
856 :type 'boolean)
858 (defcustom org-file-link-context-use-camel-case nil
859 "Non-nil means, use CamelCase to store a search context in a file link.
860 When nil, the search string simply consists of the words of the string.
861 CamelCase is deprecated, and support for it may be dropped in the future."
862 :group 'org-link-store
863 :type 'boolean)
865 (defcustom org-keep-stored-link-after-insertion nil
866 "Non-nil means, keep link in list for entire session.
868 The command `org-store-link' adds a link pointing to the current
869 location to an internal list. These links accumulate during a session.
870 The command `org-insert-link' can be used to insert links into any
871 Org-mode file (offering completion for all stored links). When this
872 option is nil, every link which has been inserted once using \\[org-insert-link]
873 will be removed from the list, to make completing the unused links
874 more efficient."
875 :group 'org-link-store
876 :type 'boolean)
878 (defcustom org-usenet-links-prefer-google nil
879 "Non-nil means, `org-store-link' will create web links to Google groups.
880 When nil, Gnus will be used for such links.
881 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
882 negates this setting for the duration of the command."
883 :group 'org-link-store
884 :type 'boolean)
886 (defgroup org-link-follow nil
887 "Options concerning following links in Org-mode"
888 :tag "Org Follow Link"
889 :group 'org-link)
891 (defcustom org-tab-follows-link nil
892 "Non-nil means, on links TAB will follow the link.
893 Needs to be set before org.el is loaded."
894 :group 'org-link-follow
895 :type 'boolean)
897 (defcustom org-return-follows-link nil
898 "Non-nil means, on links RET will follow the link.
899 Needs to be set before org.el is loaded."
900 :group 'org-link-follow
901 :type 'boolean)
903 (defcustom org-mouse-1-follows-link t
904 "Non-nil means, mouse-1 on a link will follow the link.
905 A longer mouse click will still set point. Does not wortk on XEmacs.
906 Needs to be set before org.el is loaded."
907 :group 'org-link-follow
908 :type 'boolean)
910 (defcustom org-mark-ring-length 4
911 "Number of different positions to be recorded in the ring
912 Changing this requires a restart of Emacs to work correctly."
913 :group 'org-link-follow
914 :type 'interger)
916 (defcustom org-link-frame-setup
917 '((vm . vm-visit-folder-other-frame)
918 (gnus . gnus-other-frame)
919 (file . find-file-other-window))
920 "Setup the frame configuration for following links.
921 When following a link with Emacs, it may often be useful to display
922 this link in another window or frame. This variable can be used to
923 set this up for the different types of links.
924 For VM, use any of
925 `vm-visit-folder'
926 `vm-visit-folder-other-frame'
927 For Gnus, use any of
928 `gnus'
929 `gnus-other-frame'
930 For FILE, use any of
931 `find-file'
932 `find-file-other-window'
933 `find-file-other-frame'
934 For the calendar, use the variable `calendar-setup'.
935 For BBDB, it is currently only possible to display the matches in
936 another window."
937 :group 'org-link-follow
938 :type '(list
939 (cons (const vm)
940 (choice
941 (const vm-visit-folder)
942 (const vm-visit-folder-other-window)
943 (const vm-visit-folder-other-frame)))
944 (cons (const gnus)
945 (choice
946 (const gnus)
947 (const gnus-other-frame)))
948 (cons (const file)
949 (choice
950 (const find-file)
951 (const find-file-other-window)
952 (const find-file-other-frame)))))
954 (defcustom org-open-non-existing-files nil
955 "Non-nil means, `org-open-file' will open non-existing file.
956 When nil, an error will be generated."
957 :group 'org-link-follow
958 :type 'boolean)
960 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
961 "Function and arguments to call for following mailto links.
962 This is a list with the first element being a lisp function, and the
963 remaining elements being arguments to the function. In string arguments,
964 %a will be replaced by the address, and %s will be replaced by the subject
965 if one was given like in <mailto:arthur@galaxy.org::this subject>."
966 :group 'org-link-follow
967 :type '(choice
968 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
969 (const :tag "compose-mail" (compose-mail "%a" "%s"))
970 (const :tag "message-mail" (message-mail "%a" "%s"))
971 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
973 (defcustom org-confirm-shell-link-function 'yes-or-no-p
974 "Non-nil means, ask for confirmation before executing shell links.
975 Shell links can be dangerous, just thing about a link
977 [[shell:rm -rf ~/*][Google Search]]
979 This link would show up in your Org-mode document as \"Google Search\"
980 but really it would remove your entire home directory.
981 Therefore I *definitely* advise against setting this variable to nil.
982 Just change it to `y-or-n-p' of you want to confirm with a single key press
983 rather than having to type \"yes\"."
984 :group 'org-link-follow
985 :type '(choice
986 (const :tag "with yes-or-no (safer)" yes-or-no-p)
987 (const :tag "with y-or-n (faster)" y-or-n-p)
988 (const :tag "no confirmation (dangerous)" nil)))
990 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
991 "Non-nil means, ask for confirmation before executing elisp links.
992 Elisp links can be dangerous, just thing about a link
994 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
996 This link would show up in your Org-mode document as \"Google Search\"
997 but really it would remove your entire home directory.
998 Therefore I *definitely* advise against setting this variable to nil.
999 Just change it to `y-or-n-p' of you want to confirm with a single key press
1000 rather than having to type \"yes\"."
1001 :group 'org-link-follow
1002 :type '(choice
1003 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1004 (const :tag "with y-or-n (faster)" y-or-n-p)
1005 (const :tag "no confirmation (dangerous)" nil)))
1007 (defconst org-file-apps-defaults-gnu
1008 '((remote . emacs)
1009 (t . mailcap))
1010 "Default file applications on a UNIX or GNU/Linux system.
1011 See `org-file-apps'.")
1013 (defconst org-file-apps-defaults-macosx
1014 '((remote . emacs)
1015 (t . "open %s")
1016 ("ps" . "gv %s")
1017 ("ps.gz" . "gv %s")
1018 ("eps" . "gv %s")
1019 ("eps.gz" . "gv %s")
1020 ("dvi" . "xdvi %s")
1021 ("fig" . "xfig %s"))
1022 "Default file applications on a MacOS X system.
1023 The system \"open\" is known as a default, but we use X11 applications
1024 for some files for which the OS does not have a good default.
1025 See `org-file-apps'.")
1027 (defconst org-file-apps-defaults-windowsnt
1028 (list
1029 '(remote . emacs)
1030 (cons t
1031 (list (if (featurep 'xemacs)
1032 'mswindows-shell-execute
1033 'w32-shell-execute)
1034 "open" 'file)))
1035 "Default file applications on a Windows NT system.
1036 The system \"open\" is used for most files.
1037 See `org-file-apps'.")
1039 (defcustom org-file-apps
1041 ("txt" . emacs)
1042 ("tex" . emacs)
1043 ("ltx" . emacs)
1044 ("org" . emacs)
1045 ("el" . emacs)
1046 ("bib" . emacs)
1048 "External applications for opening `file:path' items in a document.
1049 Org-mode uses system defaults for different file types, but
1050 you can use this variable to set the application for a given file
1051 extension. The entries in this list are cons cells where the car identifies
1052 files and the cdr the corresponding command. Possible values for the
1053 file identifier are
1054 \"ext\" A string identifying an extension
1055 `directory' Matches a directory
1056 `remote' Matches a remote file, accessible through tramp or efs.
1057 Remote files most likely should be visited through emacs
1058 because external applications cannot handle such paths.
1059 t Default for all remaining files
1061 Possible values for the command are:
1062 `emacs' The file will be visited by the current Emacs process.
1063 `default' Use the default application for this file type.
1064 string A command to be executed by a shell; %s will be replaced
1065 by the path to the file.
1066 sexp A Lisp form which will be evaluated. The file path will
1067 be available in the Lisp variable `file'.
1068 For more examples, see the system specific constants
1069 `org-file-apps-defaults-macosx'
1070 `org-file-apps-defaults-windowsnt'
1071 `org-file-apps-defaults-gnu'."
1072 :group 'org-link-follow
1073 :type '(repeat
1074 (cons (choice :value ""
1075 (string :tag "Extension")
1076 (const :tag "Default for unrecognized files" t)
1077 (const :tag "Remote file" remote)
1078 (const :tag "Links to a directory" directory))
1079 (choice :value ""
1080 (const :tag "Visit with Emacs" emacs)
1081 (const :tag "Use system default" default)
1082 (string :tag "Command")
1083 (sexp :tag "Lisp form")))))
1085 (defcustom org-mhe-search-all-folders nil
1086 "Non-nil means, that the search for the mh-message will be extended to
1087 all folders if the message cannot be found in the folder given in the link.
1088 Searching all folders is very effective with one of the search engines
1089 supported by MH-E, but will be slow with pick."
1090 :group 'org-link-follow
1091 :type 'boolean)
1093 (defgroup org-remember nil
1094 "Options concerning interaction with remember.el."
1095 :tag "Org Remember"
1096 :group 'org)
1098 (defcustom org-directory "~/org"
1099 "Directory with org files.
1100 This directory will be used as default to prompt for org files.
1101 Used by the hooks for remember.el."
1102 :group 'org-remember
1103 :type 'directory)
1105 (defcustom org-default-notes-file "~/.notes"
1106 "Default target for storing notes.
1107 Used by the hooks for remember.el. This can be a string, or nil to mean
1108 the value of `remember-data-file'."
1109 :group 'org-remember
1110 :type '(choice
1111 (const :tag "Default from remember-data-file" nil)
1112 file))
1114 (defcustom org-remember-templates nil
1115 "Templates for the creation of remember buffers.
1116 When nil, just let remember make the buffer.
1117 When not nil, this is a list of 3-element lists. In each entry, the first
1118 element is a character, a unique key to select this template.
1119 The second element is the template. The third element is optional and can
1120 specify a destination file for remember items created with this template.
1121 The default file is given by `org-default-notes-file'.
1123 The template specifies the structure of the remember buffer. It should have
1124 a first line starting with a star, to act as the org-mode headline.
1125 Furthermore, the following %-escapes will be replaced with content:
1126 %t time stamp, date only
1127 %T time stamp with date and time
1128 %u inactive time stamp, date only
1129 %U inactive time stamp with date and time
1130 %n user name
1131 %a annotation, normally the link created with org-store-link
1132 %i initial content, the region when remember is called with C-u.
1133 If %i is indented, the entire inserted text will be indented as well.
1134 %? This will be removed, and the cursor placed at this position."
1135 :group 'org-remember
1136 :type '(repeat :tag "enabled"
1137 (list :value (?a "\n" nil)
1138 (character :tag "Selection Key")
1139 (string :tag "Template")
1140 (file :tag "Destination file (optional)"))))
1142 (defcustom org-reverse-note-order nil
1143 "Non-nil means, store new notes at the beginning of a file or entry.
1144 When nil, new notes will be filed to the end of a file or entry."
1145 :group 'org-remember
1146 :type '(choice
1147 (const :tag "Reverse always" t)
1148 (const :tag "Reverse never" nil)
1149 (repeat :tag "By file name regexp"
1150 (cons regexp boolean))))
1152 (defgroup org-todo nil
1153 "Options concerning TODO items in Org-mode."
1154 :tag "Org TODO"
1155 :group 'org)
1157 (defcustom org-todo-keywords '("TODO" "DONE")
1158 "List of TODO entry keywords.
1159 \\<org-mode-map>By default, this is '(\"TODO\" \"DONE\"). The last entry in the list is
1160 considered to mean that the entry is \"done\". All the other mean that
1161 action is required, and will make the entry show up in todo lists, diaries
1162 etc.
1163 The command \\[org-todo] cycles an entry through these states, and an
1164 additional state where no keyword is present. For details about this
1165 cycling, see also the variable `org-todo-interpretation'
1166 Changes become only effective after restarting Emacs."
1167 :group 'org-todo
1168 :group 'org-keywords
1169 :type '(repeat (string :tag "Keyword")))
1171 (defcustom org-todo-interpretation 'sequence
1172 "Controls how TODO keywords are interpreted.
1173 This variable is only relevant if `org-todo-keywords' contains more than two
1174 states. \\<org-mode-map>Possible values are `sequence' and `type'.
1176 When `sequence', \\[org-todo] will always switch to the next state in the
1177 `org-todo-keywords' list. When `type', \\[org-todo] only cycles from state
1178 to state when executed several times in direct succession. Otherwise, it
1179 switches directly to DONE from any state.
1180 See the manual for more information."
1181 :group 'org-todo
1182 :group 'org-keywords
1183 :type '(choice (const sequence)
1184 (const type)))
1186 (defcustom org-after-todo-state-change-hook nil
1187 "Hook which is run after the state of a TODO item was changed.
1188 The new state (a string with a TODO keyword, or nil) is available in the
1189 Lisp variable `state'."
1190 :group 'org-todo
1191 :type 'hook)
1193 (defcustom org-log-done nil
1194 "When set, insert a (non-active) time stamp when TODO entry is marked DONE.
1195 When the state of an entry is changed from nothing to TODO, remove a previous
1196 closing date.
1197 This can also be configured on a per-file basis by adding one of
1198 the following lines anywhere in the buffer:
1200 #+STARTUP: logging
1201 #+STARTUP: nologging"
1202 :group 'org-todo
1203 :type 'boolean)
1205 (defgroup org-priorities nil
1206 "Priorities in Org-mode."
1207 :tag "Org Priorities"
1208 :group 'org-todo)
1210 (defcustom org-default-priority ?B
1211 "The default priority of TODO items.
1212 This is the priority an item get if no explicit priority is given."
1213 :group 'org-priorities
1214 :type 'character)
1216 (defcustom org-lowest-priority ?C
1217 "The lowest priority of TODO items. A character like ?A, ?B etc."
1218 :group 'org-priorities
1219 :type 'character)
1221 (defgroup org-time nil
1222 "Options concerning time stamps and deadlines in Org-mode."
1223 :tag "Org Time"
1224 :group 'org)
1226 (defcustom org-insert-labeled-timestamps-at-point nil
1227 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1228 When nil, these labeled time stamps are forces into the second line of an
1229 entry, just after the headline. When scheduling from the global TODO list,
1230 the time stamp will always be forced into the second line."
1231 :group 'org-time
1232 :type 'boolean)
1234 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1235 "Formats for `format-time-string' which are used for time stamps.
1236 It is not recommended to change this constant.")
1238 (defcustom org-time-stamp-rounding-minutes 0
1239 "Number of minutes to round time stamps to upon insertion.
1240 When zero, insert the time unmodified. Useful rounding numbers
1241 should be factors of 60, so for example 5, 10, 15.
1242 When this is not zero, you can still force an exact time-stamp by using
1243 a double prefix argument to a time-stamp command like `C-c .' or `C-c !'."
1244 :group 'org-time
1245 :type 'integer)
1247 (defcustom org-deadline-warning-days 30
1248 "No. of days before expiration during which a deadline becomes active.
1249 This variable governs the display in the org file."
1250 :group 'org-time
1251 :type 'number)
1253 (defcustom org-popup-calendar-for-date-prompt t
1254 "Non-nil means, pop up a calendar when prompting for a date.
1255 In the calendar, the date can be selected with mouse-1. However, the
1256 minibuffer will also be active, and you can simply enter the date as well.
1257 When nil, only the minibuffer will be available."
1258 :group 'org-time
1259 :type 'boolean)
1261 (defcustom org-calendar-follow-timestamp-change t
1262 "Non-nil means, make the calendar window follow timestamp changes.
1263 When a timestamp is modified and the calendar window is visible, it will be
1264 moved to the new date."
1265 :group 'org-time
1266 :type 'boolean)
1268 (defgroup org-tags nil
1269 "Options concerning tags in Org-mode."
1270 :tag "Org Tags"
1271 :group 'org)
1273 (defcustom org-tag-alist nil
1274 "List of tags allowed in Org-mode files.
1275 When this list is nil, Org-mode will base TAG input on what is already in the
1276 buffer.
1277 The value of this variable is an alist, the car may be (and should) be a
1278 character that is used to select that tag through the fast-tag-selection
1279 interface. See the manual for details."
1280 :group 'org-tags
1281 :type '(repeat
1282 (choice
1283 (cons (string :tag "Tag name")
1284 (character :tag "Access char"))
1285 (const :tag "Start radio group" (:startgroup))
1286 (const :tag "End radio group" (:endgroup)))))
1288 (defcustom org-use-fast-tag-selection 'auto
1289 "Non-nil means, use fast tag selection scheme.
1290 This is a special interface to select and deselect tags with single keys.
1291 When nil, fast selection is never used.
1292 When the symbol `auto', fast selection is used if and only if selection
1293 characters for tags have been configured, either through the variable
1294 `org-tag-alist' or through a #+TAGS line in the buffer.
1295 When t, fast selection is always used and selection keys are assigned
1296 automatically if necessary."
1297 :group 'org-tags
1298 :type '(choice
1299 (const :tag "Always" t)
1300 (const :tag "Never" nil)
1301 (const :tag "When selection characters are configured" 'auto)))
1303 (defcustom org-tags-column 48
1304 "The column to which tags should be indented in a headline.
1305 If this number is positive, it specifies the column. If it is negative,
1306 it means that the tags should be flushright to that column. For example,
1307 -79 works well for a normal 80 character screen."
1308 :group 'org-tags
1309 :type 'integer)
1311 (defcustom org-auto-align-tags t
1312 "Non-nil means, realign tags after pro/demotion of TODO state change.
1313 These operations change the length of a headline and therefore shift
1314 the tags around. With this options turned on, after each such operation
1315 the tags are again aligned to `org-tags-column'."
1316 :group 'org-tags
1317 :type 'boolean)
1319 (defcustom org-use-tag-inheritance t
1320 "Non-nil means, tags in levels apply also for sublevels.
1321 When nil, only the tags directly given in a specific line apply there.
1322 If you turn off this option, you very likely want to turn on the
1323 companion option `org-tags-match-list-sublevels'."
1324 :group 'org-tags
1325 :type 'boolean)
1327 (defcustom org-tags-match-list-sublevels nil
1328 "Non-nil means list also sublevels of headlines matching tag search.
1329 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1330 the sublevels of a headline matching a tag search often also match
1331 the same search. Listing all of them can create very long lists.
1332 Setting this variable to nil causes subtrees of a match to be skipped.
1333 This option is off by default, because inheritance in on. If you turn
1334 inheritance off, you very likely want to turn this option on.
1336 As a special case, if the tag search is restricted to TODO items, the
1337 value of this variable is ignored and sublevels are always checked, to
1338 make sure all corresponding TODO items find their way into the list."
1339 :group 'org-tags
1340 :type 'boolean)
1342 (defvar org-tags-history nil
1343 "History of minibuffer reads for tags.")
1344 (defvar org-last-tags-completion-table nil
1345 "The last used completion table for tags.")
1347 (defgroup org-agenda nil
1348 "Options concerning agenda display Org-mode."
1349 :tag "Org Agenda"
1350 :group 'org)
1352 (defvar org-category nil
1353 "Variable used by org files to set a category for agenda display.
1354 Such files should use a file variable to set it, for example
1356 -*- mode: org; org-category: \"ELisp\"
1358 or contain a special line
1360 #+CATEGORY: ELisp
1362 If the file does not specify a category, then file's base name
1363 is used instead.")
1364 (make-variable-buffer-local 'org-category)
1366 (defcustom org-agenda-files nil
1367 "The files to be used for agenda display.
1368 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1369 \\[org-remove-file]. You can also use customize to edit the list.
1371 If the value of the variable is not a list but a single file name, then
1372 the list of agenda files is actually stored and maintained in that file, one
1373 agenda file per line."
1374 :group 'org-agenda
1375 :type '(choice
1376 (repeat :tag "List of files" file)
1377 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1379 (defcustom org-agenda-custom-commands ;'(("w" todo "WAITING"))
1380 '(("w" todo "WAITING" ((aaa 1) (bbb 2))))
1381 "Custom commands for the agenda.
1382 These commands will be offered on the splash screen displayed by the
1383 agenda dispatcher \\[org-agenda]. Each entry is a list like this:
1385 (key type match options)
1387 key The key (a single char as a string) to be associated with the command.
1388 type The command type, any of the following symbols:
1389 todo Entries with a specific TODO keyword, in all agenda files.
1390 tags Tags match in all agenda files.
1391 tags-todo Tags match in all agenda files, TODO entries only.
1392 todo-tree Sparse tree of specific TODO keyword in *current* file.
1393 tags-tree Sparse tree with all tags matches in *current* file.
1394 occur-tree Occur sparse tree for *current* file.
1395 match What to search for:
1396 - a single keyword for TODO keyword searches
1397 - a tags match expression for tags searches
1398 - a regular expression for occur searches
1399 options A list of option setttings, similar to that in a let form, so like
1400 this: ((opt1 val1) (opt2 val2) ...)
1402 You can also define a set of commands, to create a composite agenda buffer.
1403 In this case, an entry looks like this:
1405 (key desc (cmd1 cmd2 ...) general-options)
1407 where
1409 desc A description string to be displayed in the dispatcher menu.
1410 cmd An agenda command, similar to the above. However, tree commands
1411 are no allowed, but instead you can get agenda and global todo list.
1412 So valid commands for a set are:
1413 (agenda)
1414 (alltodo)
1415 (todo \"match\" options)
1416 (tags \"match\" options )
1417 (tags-todo \"match\" options)
1419 Each command can carry a list of options, and another set of options can be
1420 given for the whole set of commands. Individual command options take
1421 precedence over the general options."
1422 :group 'org-agenda
1423 :type '(repeat
1424 (choice
1425 (list :tag "Single command"
1426 (string :tag "Key")
1427 (choice
1428 (const :tag "Tags search (all agenda files)" tags)
1429 (const :tag "Tags search of TODO entries (all agenda files)" tags-todo)
1430 (const :tag "TODO keyword search (all agenda files)" todo)
1431 (const :tag "Tags sparse tree (current buffer)" tags-tree)
1432 (const :tag "TODO keyword tree (current buffer)" todo-tree)
1433 (const :tag "Occur tree (current buffer)" occur-tree))
1434 (string :tag "Match")
1435 (repeat :tag "Local options"
1436 (list (variable :tag "Option") (sexp :tag "Value"))))
1437 (list :tag "Command series, all agenda files"
1438 (string :tag "Key")
1439 (string :tag "Description")
1440 (repeat
1441 (choice
1442 (const :tag "Agenda" (agenda))
1443 (const :tag "TODO list" (alltodo))
1444 (list :tag "Tags search"
1445 (const :format "" tags)
1446 (string :tag "Match")
1447 (repeat :tag "Local options"
1448 (list (variable :tag "Option")
1449 (sexp :tag "Value"))))
1451 (list :tag "Tags search, TODO entries only"
1452 (const :format "" tags-todo)
1453 (string :tag "Match")
1454 (repeat :tag "Local options"
1455 (list (variable :tag "Option")
1456 (sexp :tag "Value"))))
1458 (list :tag "TODO keyword search"
1459 (const :format "" todo)
1460 (string :tag "Match")
1461 (repeat :tag "Local options"
1462 (list (variable :tag "Option")
1463 (sexp :tag "Value"))))))
1464 (repeat :tag "General options"
1465 (list (variable :tag "Option")
1466 (sexp :tag "Value")))))))
1468 (defcustom org-agenda-todo-list-sublevels t
1469 "Non-nil means, check also the sublevels of a TODO entry for TODO entries.
1470 When nil, the sublevels of a TODO entry are not checked, resulting in
1471 potentially much shorter TODO lists."
1472 :group 'org-agenda
1473 :group 'org-todo
1474 :type 'boolean)
1476 (defcustom org-agenda-todo-ignore-scheduled nil
1477 "Non-nil means, don't show scheduled entries in the global todo list.
1478 The idea behind this is that by scheduling it, you have already taken care
1479 of this item."
1480 :group 'org-agenda
1481 :group 'org-todo
1482 :type 'boolean)
1484 (defcustom org-timeline-show-empty-dates 3
1485 "Non-nil means, `org-timeline' also shows dates without an entry.
1486 When nil, only the days which actually have entries are shown.
1487 When t, all days between the first and the last date are shown.
1488 When an integer, show also empty dates, but if there is a gap of more than
1489 N days, just insert a special line indicating the size of the gap."
1490 :group 'org-agenda
1491 :type '(choice
1492 (const :tag "None" nil)
1493 (const :tag "All" t)
1494 (number :tag "at most")))
1496 (defcustom org-agenda-include-all-todo nil
1497 "Set means weekly/daily agenda will always contain all TODO entries.
1498 The TODO entries will be listed at the top of the agenda, before
1499 the entries for specific days."
1500 :group 'org-agenda
1501 :type 'boolean)
1503 (defcustom org-agenda-include-diary nil
1504 "If non-nil, include in the agenda entries from the Emacs Calendar's diary."
1505 :group 'org-agenda
1506 :type 'boolean)
1508 (defcustom org-calendar-to-agenda-key [?c]
1509 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1510 The command `org-calendar-goto-agenda' will be bound to this key. The
1511 default is the character `c' because then `c' can be used to switch back and
1512 forth between agenda and calendar."
1513 :group 'org-agenda
1514 :type 'sexp)
1516 (defgroup org-agenda-setup nil
1517 "Options concerning setting up the Agenda window in Org Mode."
1518 :tag "Org Agenda Window Setup"
1519 :group 'org-agenda)
1521 (defcustom org-agenda-mouse-1-follows-link nil
1522 "Non-nil means, mouse-1 on a link will follow the link in the agenda.
1523 A longer mouse click will still set point. Does not wortk on XEmacs.
1524 Needs to be set before org.el is loaded."
1525 :group 'org-agenda-setup
1526 :type 'boolean)
1528 (defcustom org-agenda-start-with-follow-mode nil
1529 "The initial value of follwo-mode in a newly created agenda window."
1530 :group 'org-agenda-setup
1531 :type 'boolean)
1533 (defcustom org-select-agenda-window t
1534 "Non-nil means, after creating an agenda, move cursor into Agenda window.
1535 When nil, cursor will remain in the current window."
1536 :group 'org-agenda-setup
1537 :type 'boolean)
1539 (defcustom org-fit-agenda-window t
1540 "Non-nil means, change window size of agenda to fit content."
1541 :group 'org-agenda-setup
1542 :type 'boolean)
1544 (defgroup org-agenda-display nil
1545 "Options concerning what to display initially in Agenda."
1546 :tag "Org Agenda Display"
1547 :group 'org-agenda)
1549 (defcustom org-agenda-show-all-dates t
1550 "Non-nil means, `org-agenda' shows every day in the selected range.
1551 When nil, only the days which actually have entries are shown."
1552 :group 'org-agenda-display
1553 :type 'boolean)
1555 (defcustom org-agenda-start-on-weekday 1
1556 "Non-nil means, start the overview always on the specified weekday.
1557 0 denotes Sunday, 1 denotes Monday etc.
1558 When nil, always start on the current day."
1559 :group 'org-agenda-display
1560 :type '(choice (const :tag "Today" nil)
1561 (number :tag "Weekday No.")))
1563 (defcustom org-agenda-ndays 7
1564 "Number of days to include in overview display.
1565 Should be 1 or 7."
1566 :group 'org-agenda-display
1567 :type 'number)
1569 (defcustom org-agenda-use-time-grid t
1570 "Non-nil means, show a time grid in the agenda schedule.
1571 A time grid is a set of lines for specific times (like every two hours between
1572 8:00 and 20:00). The items scheduled for a day at specific times are
1573 sorted in between these lines.
1574 For details about when the grid will be shown, and what it will look like, see
1575 the variable `org-agenda-time-grid'."
1576 :group 'org-agenda-display
1577 :type 'boolean)
1579 (defcustom org-agenda-time-grid
1580 '((daily today require-timed)
1581 "----------------"
1582 (800 1000 1200 1400 1600 1800 2000))
1584 "The settings for time grid for agenda display.
1585 This is a list of three items. The first item is again a list. It contains
1586 symbols specifying conditions when the grid should be displayed:
1588 daily if the agenda shows a single day
1589 weekly if the agenda shows an entire week
1590 today show grid on current date, independent of daily/weekly display
1591 require-timed show grid only if at least one item has a time specification
1593 The second item is a string which will be places behing the grid time.
1595 The third item is a list of integers, indicating the times that should have
1596 a grid line."
1597 :group 'org-agenda-display
1598 :type
1599 '(list
1600 (set :greedy t :tag "Grid Display Options"
1601 (const :tag "Show grid in single day agenda display" daily)
1602 (const :tag "Show grid in weekly agenda display" weekly)
1603 (const :tag "Always show grid for today" today)
1604 (const :tag "Show grid only if any timed entries are present"
1605 require-timed)
1606 (const :tag "Skip grid times already present in an entry"
1607 remove-match))
1608 (string :tag "Grid String")
1609 (repeat :tag "Grid Times" (integer :tag "Time"))))
1611 (let ((sorting-choice
1612 '(choice
1613 (const time-up) (const time-down)
1614 (const category-keep) (const category-up) (const category-down)
1615 (const tag-down) (const tag-up)
1616 (const priority-up) (const priority-down))))
1618 (defcustom org-agenda-sorting-strategy
1619 '((agenda time-up category-keep priority-down)
1620 (todo category-keep priority-down)
1621 (tags category-keep))
1622 "Sorting structure for the agenda items of a single day.
1623 This is a list of symbols which will be used in sequence to determine
1624 if an entry should be listed before another entry. The following
1625 symbols are recognized:
1627 time-up Put entries with time-of-day indications first, early first
1628 time-down Put entries with time-of-day indications first, late first
1629 category-keep Keep the default order of categories, corresponding to the
1630 sequence in `org-agenda-files'.
1631 category-up Sort alphabetically by category, A-Z.
1632 category-down Sort alphabetically by category, Z-A.
1633 tag-up Sort alphabetically by last tag, A-Z.
1634 tag-down Sort alphabetically by last tag, Z-A.
1635 priority-up Sort numerically by priority, high priority last.
1636 priority-down Sort numerically by priority, high priority first.
1638 The different possibilities will be tried in sequence, and testing stops
1639 if one comparison returns a \"not-equal\". For example, the default
1640 '(time-up category-keep priority-down)
1641 means: Pull out all entries having a specified time of day and sort them,
1642 in order to make a time schedule for the current day the first thing in the
1643 agenda listing for the day. Of the entries without a time indication, keep
1644 the grouped in categories, don't sort the categories, but keep them in
1645 the sequence given in `org-agenda-files'. Within each category sort by
1646 priority.
1648 Leaving out `category-keep' would mean that items will be sorted across
1649 categories by priority."
1650 :group 'org-agenda-display
1651 :type `(choice
1652 (repeat :tag "General" ,sorting-choice)
1653 (list :tag "Individually"
1654 (cons (const :tag "Strategy for Weekly/Daily agenda" agenda)
1655 (repeat ,sorting-choice))
1656 (cons (const :tag "Strategy for TODO lists" todo)
1657 (repeat ,sorting-choice))
1658 (cons (const :tag "Strategy for Tags matches" tags)
1659 (repeat ,sorting-choice))))))
1661 (defcustom org-sort-agenda-notime-is-late t
1662 "Non-nil means, items without time are considered late.
1663 This is only relevant for sorting. When t, items which have no explicit
1664 time like 15:30 will be considered as 99:01, i.e. later than any items which
1665 do have a time. When nil, the default time is before 0:00. You can use this
1666 option to decide if the schedule for today should come before or after timeless
1667 agenda entries."
1668 :group 'org-agenda-display
1669 :type 'boolean)
1672 (defgroup org-agenda-prefix nil
1673 "Options concerning the entry prefix in the Org-mode agenda display."
1674 :tag "Org Agenda Prefix"
1675 :group 'org-agenda)
1677 (defcustom org-agenda-prefix-format
1678 '((agenda . " %-12:c%?-12t% s")
1679 (timeline . " % s")
1680 (todo . " %-12:c")
1681 (tags . " %-12:c"))
1682 "Format specifications for the prefix of items in the agenda views.
1683 An alist with four entries, for the different agenda types. The keys to the
1684 sublists are `agenda', `timeline', `todo', and `tags'. The values
1685 are format strings.
1686 This format works similar to a printf format, with the following meaning:
1688 %c the category of the item, \"Diary\" for entries from the diary, or
1689 as given by the CATEGORY keyword or derived from the file name.
1690 %T the *last* tag of the item. Last because inherited tags come
1691 first in the list.
1692 %t the time-of-day specification if one applies to the entry, in the
1693 format HH:MM
1694 %s Scheduling/Deadline information, a short string
1696 All specifiers work basically like the standard `%s' of printf, but may
1697 contain two additional characters: A question mark just after the `%' and
1698 a whitespace/punctuation character just before the final letter.
1700 If the first character after `%' is a question mark, the entire field
1701 will only be included if the corresponding value applies to the
1702 current entry. This is useful for fields which should have fixed
1703 width when present, but zero width when absent. For example,
1704 \"%?-12t\" will result in a 12 character time field if a time of the
1705 day is specified, but will completely disappear in entries which do
1706 not contain a time.
1708 If there is punctuation or whitespace character just before the final
1709 format letter, this character will be appended to the field value if
1710 the value is not empty. For example, the format \"%-12:c\" leads to
1711 \"Diary: \" if the category is \"Diary\". If the category were be
1712 empty, no additional colon would be interted.
1714 The default value of this option is \" %-12:c%?-12t% s\", meaning:
1715 - Indent the line with two space characters
1716 - Give the category in a 12 chars wide field, padded with whitespace on
1717 the right (because of `-'). Append a colon if there is a category
1718 (because of `:').
1719 - If there is a time-of-day, put it into a 12 chars wide field. If no
1720 time, don't put in an empty field, just skip it (because of '?').
1721 - Finally, put the scheduling information and append a whitespace.
1723 As another example, if you don't want the time-of-day of entries in
1724 the prefix, you could use:
1726 (setq org-agenda-prefix-format \" %-11:c% s\")
1728 See also the variables `org-agenda-remove-times-when-in-prefix' and
1729 `org-agenda-remove-tags-when-in-prefix'."
1730 :type '(choice
1731 (string :tag "General format")
1732 (list :greedy t :tag "View dependent"
1733 (cons (const agenda) (string :tag "Format"))
1734 (cons (const timeline) (string :tag "Format"))
1735 (cons (const todo) (string :tag "Format"))
1736 (cons (const tags) (string :tag "Format"))))
1737 :group 'org-agenda-prefix)
1739 (defvar org-prefix-format-compiled nil
1740 "The compiled version of the most recently used prefix format.
1741 See the variable `org-agenda-prefix-format'.")
1743 (defcustom org-agenda-remove-times-when-in-prefix t
1744 "Non-nil means, remove duplicate time specifications in agenda items.
1745 When the format `org-agenda-prefix-format' contains a `%t' specifier, a
1746 time-of-day specification in a headline or diary entry is extracted and
1747 placed into the prefix. If this option is non-nil, the original specification
1748 \(a timestamp or -range, or just a plain time(range) specification like
1749 11:30-4pm) will be removed for agenda display. This makes the agenda less
1750 cluttered.
1751 The option can be t or nil. It may also be the symbol `beg', indicating
1752 that the time should only be removed what it is located at the beginning of
1753 the headline/diary entry."
1754 :group 'org-agenda-prefix
1755 :type '(choice
1756 (const :tag "Always" t)
1757 (const :tag "Never" nil)
1758 (const :tag "When at beginning of entry" beg)))
1760 (defcustom org-agenda-remove-tags-when-in-prefix nil
1761 "Non-nil means, remove the tags from the headline copy in the agenda.
1762 When this is the symbol `prefix', only remove tags when
1763 `org-agenda-prefix-format' contains a `%T' specifier."
1764 :group 'org-agenda-prefix
1765 :type '(choice
1766 (const :tag "Always" t)
1767 (const :tag "Never" nil)
1768 (const :tag "When prefix format contains %T" prefix)))
1770 (defcustom org-agenda-align-tags-to-column 65
1771 "Shift tags in agenda items to this column."
1772 :group 'org-agenda-prefix ;; FIXME
1773 :type 'integer)
1775 (defgroup org-latex nil
1776 "Options for embedding LaTeX code into Org-mode"
1777 :tag "Org LaTeX"
1778 :group 'org)
1780 (defcustom org-format-latex-options
1781 '(:foreground "Black" :background "Transparent" :scale 1.0
1782 :matchers ("begin" "$" "$$" "\\(" "\\["))
1783 "Options for creating images from LaTeX fragments.
1784 This is a property list with the following properties:
1785 :foreground the foreground color, for example \"Black\".
1786 :background the background color, or \"Transparent\".
1787 :scale a scaling factor for the size of the images
1788 :matchers a list indicating which matchers should be used to
1789 find LaTeX fragments. Valid members of this list are:
1790 \"begin\" find environments
1791 \"$\" find math expressions surrounded by $...$
1792 \"$$\" find math expressions surrounded by $$....$$
1793 \"\\(\" find math expressions surrounded by \\(...\\)
1794 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1795 :group 'org-latex
1796 :type 'plist)
1798 (defgroup org-export nil
1799 "Options for exporting org-listings."
1800 :tag "Org Export"
1801 :group 'org)
1803 (defgroup org-export-general nil
1804 "General options for exporting Org-mode files."
1805 :tag "Org Export General"
1806 :group 'org-export)
1808 (defcustom org-export-publishing-directory "."
1809 "Path to the location where exported files should be located.
1810 This path may be relative to the directory where the Org-mode file lives.
1811 The default is to put them into the same directory as the Org-mode file.
1812 The variable may also be an alist with export types `:html', `:ascii',
1813 `:ical', or `:xoxo' and the corresponding directories. If a direcoty path
1814 is relative, it is interpreted relative to the directory where the exported
1815 Org-mode files lives."
1816 :group 'org-export-general
1817 :type '(choice
1818 (directory)
1819 (repeat
1820 (cons
1821 (choice :tag "Type"
1822 (const :html) (const :ascii) (const :ical) (const :xoxo))
1823 (directory)))))
1825 (defcustom org-export-language-setup
1826 '(("en" "Author" "Date" "Table of Contents")
1827 ("cs" "Autor" "Datum" "Obsah")
1828 ("da" "Ophavsmand" "Dato" "Indhold")
1829 ("de" "Autor" "Datum" "Inhaltsverzeichnis")
1830 ("es" "Autor" "Fecha" "\xccndice")
1831 ("fr" "Auteur" "Date" "Table des Mati\xe8res")
1832 ("it" "Autore" "Data" "Indice")
1833 ("nl" "Auteur" "Datum" "Inhoudsopgave")
1834 ("nn" "Forfattar" "Dato" "Innhold") ;; nn = Norsk (nynorsk)
1835 ("sv" "F\xf6rfattarens" "Datum" "Inneh\xe5ll"))
1836 "Terms used in export text, translated to different languages.
1837 Use the variable `org-export-default-language' to set the language,
1838 or use the +OPTION lines for a per-file setting."
1839 :group 'org-export-general
1840 :type '(repeat
1841 (list
1842 (string :tag "HTML language tag")
1843 (string :tag "Author")
1844 (string :tag "Date")
1845 (string :tag "Table of Contents"))))
1847 (defcustom org-export-default-language "en"
1848 "The default language of HTML export, as a string.
1849 This should have an association in `org-export-language-setup'."
1850 :group 'org-export-general
1851 :type 'string)
1853 (defcustom org-export-headline-levels 3
1854 "The last level which is still exported as a headline.
1855 Inferior levels will produce itemize lists when exported.
1856 Note that a numeric prefix argument to an exporter function overrides
1857 this setting.
1859 This option can also be set with the +OPTIONS line, e.g. \"H:2\"."
1860 :group 'org-export-general
1861 :type 'number)
1863 (defcustom org-export-with-section-numbers t
1864 "Non-nil means, add section numbers to headlines when exporting.
1866 This option can also be set with the +OPTIONS line, e.g. \"num:t\"."
1867 :group 'org-export-general
1868 :type 'boolean)
1870 (defcustom org-export-with-toc t
1871 "Non-nil means, create a table of contents in exported files.
1872 The TOC contains headlines with levels up to`org-export-headline-levels'.
1874 Headlines which contain any TODO items will be marked with \"(*)\" in
1875 ASCII export, and with red color in HTML output.
1877 In HTML output, the TOC will be clickable.
1879 This option can also be set with the +OPTIONS line, e.g. \"toc:nil\"."
1880 :group 'org-export-general
1881 :type 'boolean)
1883 (defcustom org-export-mark-todo-in-toc nil
1884 "Non-nil means, mark TOC lines that contain any open TODO items."
1885 :group 'org-export-general
1886 :type 'boolean)
1888 (defcustom org-export-preserve-breaks nil
1889 "Non-nil means, preserve all line breaks when exporting.
1890 Normally, in HTML output paragraphs will be reformatted. In ASCII
1891 export, line breaks will always be preserved, regardless of this variable.
1893 This option can also be set with the +OPTIONS line, e.g. \"\\n:t\"."
1894 :group 'org-export-general
1895 :type 'boolean)
1897 (defcustom org-export-with-archived-trees 'headline
1898 "Whether subtrees with the ARCHIVE tag should be exported.
1899 This can have three different values
1900 nil Do not export, pretend this tree is not present
1901 t Do export the entire tree
1902 headline Only export the headline, but skip the tree below it."
1903 :group 'org-export-general
1904 :group 'org-archive
1905 :type '(choice
1906 (const :tag "not at all" nil)
1907 (const :tag "headline only" 'headline)
1908 (const :tag "entirely" t)))
1910 (defcustom org-export-with-timestamps t
1911 "Nil means, do not export time stamps and associated keywords."
1912 :group 'org-export-general
1913 :type 'boolean)
1915 (defcustom org-export-remove-timestamps-from-toc t
1916 "Nil means, remove timestamps from the table of contents entries."
1917 :group 'org-export-general
1918 :type 'boolean)
1920 (defcustom org-export-with-tags t
1921 "Nil means, do not export tags, just remove them from headlines."
1922 :group 'org-export-general
1923 :type 'boolean)
1925 (defgroup org-export-translation nil
1926 "Options for translating special ascii sequences for the export backends."
1927 :tag "Org Export Translation"
1928 :group 'org-export)
1930 (defcustom org-export-with-emphasize t
1931 "Non-nil means, interpret *word*, /word/, and _word_ as emphasized text.
1932 If the export target supports emphasizing text, the word will be
1933 typeset in bold, italic, or underlined, respectively. Works only for
1934 single words, but you can say: I *really* *mean* *this*.
1935 Not all export backends support this.
1937 This option can also be set with the +OPTIONS line, e.g. \"*:nil\"."
1938 :group 'org-export-translation
1939 :type 'boolean)
1941 (defcustom org-export-with-sub-superscripts t
1942 "Non-nil means, interpret \"_\" and \"^\" for export.
1943 When this option is turned on, you can use TeX-like syntax for sub- and
1944 superscripts. Several characters after \"_\" or \"^\" will be
1945 considered as a single item - so grouping with {} is normally not
1946 needed. For example, the following things will be parsed as single
1947 sub- or superscripts.
1949 10^24 or 10^tau several digits will be considered 1 item.
1950 10^-12 or 10^-tau a leading sign with digits or a word
1951 x^2-y^3 will be read as x^2 - y^3, because items are
1952 terminated by almost any nonword/nondigit char.
1953 x_{i^2} or x^(2-i) braces or parenthesis do grouping.
1955 Still, ambiguity is possible - so when in doubt use {} to enclose the
1956 sub/superscript.
1957 Not all export backends support this, but HTML does.
1959 This option can also be set with the +OPTIONS line, e.g. \"^:nil\"."
1960 :group 'org-export-translation
1961 :type 'boolean)
1963 (defcustom org-export-with-TeX-macros t
1964 "Non-nil means, interpret simple TeX-like macros when exporting.
1965 For example, HTML export converts \\alpha to &alpha; and \\AA to &Aring;.
1966 No only real TeX macros will work here, but the standard HTML entities
1967 for math can be used as macro names as well. For a list of supported
1968 names in HTML export, see the constant `org-html-entities'.
1969 Not all export backends support this.
1971 This option can also be set with the +OPTIONS line, e.g. \"TeX:nil\"."
1972 :group 'org-export-translation
1973 :group 'org-latex
1974 :type 'boolean)
1976 (defcustom org-export-with-LaTeX-fragments nil
1977 "Non-nil means, convert LaTeX fragments to images when exporting to HTML.
1978 When set, the exporter will find LaTeX environments if the \\begin line is
1979 the first non-white thing on a line. It will also find the math delimiters
1980 like $a=b$ and \\( a=b \\) for inline math, $$a=b$$ and \\[ a=b \\] for
1981 display math.
1983 This option can also be set with the +OPTIONS line, e.g. \"LaTeX:t\"."
1984 :group 'org-export-translation
1985 :group 'org-latex
1986 :type 'boolean)
1988 (defcustom org-export-with-fixed-width t
1989 "Non-nil means, lines starting with \":\" will be in fixed width font.
1990 This can be used to have pre-formatted text, fragments of code etc. For
1991 example:
1992 : ;; Some Lisp examples
1993 : (while (defc cnt)
1994 : (ding))
1995 will be looking just like this in also HTML. See also the QUOTE keyword.
1996 Not all export backends support this.
1998 This option can also be set with the +OPTIONS line, e.g. \"::nil\"."
1999 :group 'org-export-translation
2000 :type 'boolean)
2002 (defcustom org-match-sexp-depth 3
2003 "Number of stacked braces for sub/superscript matching.
2004 This has to be set before loading org.el to be effective."
2005 :group 'org-export-translation
2006 :type 'integer)
2008 (defgroup org-export-tables nil
2009 "Options for exporting tables in Org-mode."
2010 :tag "Org Export Tables"
2011 :group 'org-export)
2013 (defcustom org-export-with-tables t
2014 "If non-nil, lines starting with \"|\" define a table.
2015 For example:
2017 | Name | Address | Birthday |
2018 |-------------+----------+-----------|
2019 | Arthur Dent | England | 29.2.2100 |
2021 Not all export backends support this.
2023 This option can also be set with the +OPTIONS line, e.g. \"|:nil\"."
2024 :group 'org-export-tables
2025 :type 'boolean)
2027 (defcustom org-export-highlight-first-table-line t
2028 "Non-nil means, highlight the first table line.
2029 In HTML export, this means use <th> instead of <td>.
2030 In tables created with table.el, this applies to the first table line.
2031 In Org-mode tables, all lines before the first horizontal separator
2032 line will be formatted with <th> tags."
2033 :group 'org-export-tables
2034 :type 'boolean)
2036 (defcustom org-export-table-remove-special-lines t
2037 "Remove special lines and marking characters in calculating tables.
2038 This removes the special marking character column from tables that are set
2039 up for spreadsheet calculations. It also removes the entire lines
2040 marked with `!', `_', or `^'. The lines with `$' are kept, because
2041 the values of constants may be useful to have."
2042 :group 'org-export-tables
2043 :type 'boolean)
2045 (defcustom org-export-prefer-native-exporter-for-tables nil
2046 "Non-nil means, always export tables created with table.el natively.
2047 Natively means, use the HTML code generator in table.el.
2048 When nil, Org-mode's own HTML generator is used when possible (i.e. if
2049 the table does not use row- or column-spanning). This has the
2050 advantage, that the automatic HTML conversions for math symbols and
2051 sub/superscripts can be applied. Org-mode's HTML generator is also
2052 much faster."
2053 :group 'org-export-tables
2054 :type 'boolean)
2056 (defgroup org-export-ascii nil
2057 "Options specific for ASCII export of Org-mode files."
2058 :tag "Org Export ASCII"
2059 :group 'org-export)
2061 (defcustom org-export-ascii-underline '(?\$ ?\# ?^ ?\~ ?\= ?\-)
2062 "Characters for underlining headings in ASCII export.
2063 In the given sequence, these characters will be used for level 1, 2, ..."
2064 :group 'org-export-ascii
2065 :type '(repeat character))
2067 (defcustom org-export-ascii-bullets '(?* ?+ ?-)
2068 "Bullet characters for headlines converted to lists in ASCII export.
2069 The first character is is used for the first lest level generated in this
2070 way, and so on. If there are more levels than characters given here,
2071 the list will be repeated.
2072 Note that plain lists will keep the same bullets as the have in the
2073 Org-mode file."
2074 :group 'org-export-ascii
2075 :type '(repeat character))
2077 (defcustom org-export-ascii-show-new-buffer t
2078 "Non-nil means, popup buffer containing the exported ASCII text.
2079 Otherwise the buffer will just be saved to a file and stay hidden."
2080 :group 'org-export-ascii
2081 :type 'boolean)
2083 (defgroup org-export-xml nil
2084 "Options specific for XML export of Org-mode files."
2085 :tag "Org Export XML"
2086 :group 'org-export)
2088 (defgroup org-export-html nil
2089 "Options specific for HTML export of Org-mode files."
2090 :tag "Org Export HTML"
2091 :group 'org-export)
2093 (defcustom org-export-html-style
2094 "<style type=\"text/css\">
2095 html {
2096 font-family: Times, serif;
2097 font-size: 12pt;
2099 .title { text-align: center; }
2100 .todo { color: red; }
2101 .done { color: green; }
2102 .timestamp { color: grey }
2103 .timestamp-kwd { color: CadetBlue }
2104 .tag { background-color:lightblue; font-weight:normal }
2105 .target { background-color: lavender; }
2106 pre {
2107 border: 1pt solid #AEBDCC;
2108 background-color: #F3F5F7;
2109 padding: 5pt;
2110 font-family: courier, monospace;
2112 table { border-collapse: collapse; }
2113 td, th {
2114 vertical-align: top;
2115 border: 1pt solid #ADB9CC;
2117 </style>"
2118 "The default style specification for exported HTML files.
2119 Since there are different ways of setting style information, this variable
2120 needs to contain the full HTML structure to provide a style, including the
2121 surrounding HTML tags. The style specifications should include definitions
2122 for new classes todo, done, title, and deadline. For example, legal values
2123 would be:
2125 <style type=\"text/css\">
2126 p { font-weight: normal; color: gray; }
2127 h1 { color: black; }
2128 .title { text-align: center; }
2129 .todo, .deadline { color: red; }
2130 .done { color: green; }
2131 </style>
2133 or, if you want to keep the style in a file,
2135 <link rel=\"stylesheet\" type=\"text/css\" href=\"mystyles.css\">
2137 As the value of this option simply gets inserted into the HTML <head> header,
2138 you can \"misuse\" it to add arbitrary text to the header."
2139 :group 'org-export-html
2140 :type 'string)
2142 (defcustom org-export-html-title-format "<h1 class=\"title\">%s</h1>\n"
2143 "Format for typesetting the document title in HTML export."
2144 :group 'org-export-html
2145 :type 'string)
2147 (defcustom org-export-html-toplevel-hlevel 2
2148 "The <H> level for level 1 headings in HTML export."
2149 :group 'org-export-html
2150 :type 'string)
2152 (defcustom org-export-html-link-org-files-as-html t
2153 "Non-nil means, make file links to `file.org' point to `file.html'.
2154 When org-mode is exporting an org-mode file to HTML, links to
2155 non-html files are directly put into a href tag in HTML.
2156 However, links to other Org-mode files (recognized by the
2157 extension `.org.) should become links to the corresponding html
2158 file, assuming that the linked org-mode file will also be
2159 converted to HTML.
2160 When nil, the links still point to the plain `.org' file."
2161 :group 'org-export-html
2162 :type 'boolean)
2164 (defcustom org-export-html-inline-images 'maybe
2165 "Non-nil means, inline images into exported HTML pages.
2166 This is done using an <img> tag. When nil, an anchor with href is used to
2167 link to the image. If this option is `maybe', then images in links with
2168 an empty description will be inlined, while images with a description will
2169 be linked only."
2170 :group 'org-export-html
2171 :type '(choice (const :tag "Never" nil)
2172 (const :tag "Always" t)
2173 (const :tag "When there is no description" maybe)))
2175 (defcustom org-export-html-expand t
2176 "Non-nil means, for HTML export, treat @<...> as HTML tag.
2177 When nil, these tags will be exported as plain text and therefore
2178 not be interpreted by a browser.
2180 This option can also be set with the +OPTIONS line, e.g. \"@:nil\"."
2181 :group 'org-export-html
2182 :type 'boolean)
2184 (defcustom org-export-html-table-tag
2185 "<table border=\"1\" cellspacing=\"0\" cellpadding=\"6\">"
2186 "The HTML tag used to start a table.
2187 This must be a <table> tag, but you may change the options like
2188 borders and spacing."
2189 :group 'org-export-html
2190 :type 'string)
2192 (defcustom org-export-html-with-timestamp nil
2193 "If non-nil, write `org-export-html-html-helper-timestamp'
2194 into the exported HTML text. Otherwise, the buffer will just be saved
2195 to a file."
2196 :group 'org-export-html
2197 :type 'boolean)
2199 (defcustom org-export-html-html-helper-timestamp
2200 "<br/><br/><hr><p><!-- hhmts start --> <!-- hhmts end --></p>\n"
2201 "The HTML tag used as timestamp delimiter for HTML-helper-mode."
2202 :group 'org-export-html
2203 :type 'string)
2205 (defcustom org-export-html-show-new-buffer nil
2206 "Non-nil means, popup buffer containing the exported html text.
2207 Otherwise, the buffer will just be saved to a file and stay hidden."
2208 :group 'org-export-html
2209 :type 'boolean)
2211 (defgroup org-export-icalendar nil
2212 "Options specific for iCalendar export of Org-mode files."
2213 :tag "Org Export iCalendar"
2214 :group 'org-export)
2216 (defcustom org-combined-agenda-icalendar-file "~/org.ics"
2217 "The file name for the iCalendar file covering all agenda files.
2218 This file is created with the command \\[org-export-icalendar-all-agenda-files].
2219 The file name should be absolute."
2220 :group 'org-export-icalendar
2221 :type 'file)
2223 (defcustom org-icalendar-include-todo nil
2224 "Non-nil means, export to iCalendar files should also cover TODO items."
2225 :group 'org-export-icalendar
2226 :type 'boolean)
2228 (defcustom org-icalendar-combined-name "OrgMode"
2229 "Calendar name for the combined iCalendar representing all agenda files."
2230 :group 'org-export-icalendar
2231 :type 'string)
2233 (defgroup org-font-lock nil
2234 "Font-lock settings for highlighting in Org-mode."
2235 :tag "Org Font Lock"
2236 :group 'org)
2238 (defcustom org-level-color-stars-only nil
2239 "Non-nil means fontify only the stars in each headline.
2240 When nil, the entire headline is fontified.
2241 Changing it requires restart of `font-lock-mode' to become effective
2242 also in regions already fontified."
2243 :group 'org-font-lock
2244 :type 'boolean)
2246 (defcustom org-hide-leading-stars nil
2247 "Non-nil means, hide the first N-1 stars in a headline.
2248 This works by using the face `org-hide' for these stars. This
2249 face is white for a light background, and black for a dark
2250 background. You may have to customize the face `org-hide' to
2251 make this work.
2252 Changing it requires restart of `font-lock-mode' to become effective
2253 also in regions already fontified.
2254 You may also set this on a per-file basis by adding one of the following
2255 lines to the buffer:
2257 #+STARTUP: hidestars
2258 #+STARTUP: showstars"
2259 :group 'org-font-lock
2260 :type 'boolean)
2262 (defcustom org-fontify-done-headline nil
2263 "Non-nil means, change the face of a headline if it is marked DONE.
2264 Normally, only the TODO/DONE keyword indicates the state of a headline.
2265 When this is non-nil, the headline after the keyword is set to the
2266 `org-headline-done' as an additional indication."
2267 :group 'org-font-lock
2268 :type 'boolean)
2270 (defcustom org-fontify-emphasized-text t
2271 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2272 Changing this variable requires a restart of Emacs to take effect."
2273 :group 'org-font-lock
2274 :type 'boolean)
2276 (defvar org-emph-re nil
2277 "Regular expression for matching emphasis.")
2278 (defvar org-emphasis-regexp-components) ; defined just below
2279 (defvar org-emphasis-alist) ; defined just below
2280 (defun org-set-emph-re (var val)
2281 "Set variable and compute the emphasis regular expression."
2282 (set var val)
2283 (when (and (boundp 'org-emphasis-alist)
2284 (boundp 'org-emphasis-regexp-components)
2285 org-emphasis-alist org-emphasis-regexp-components)
2286 (let* ((e org-emphasis-regexp-components)
2287 (pre (car e))
2288 (post (nth 1 e))
2289 (border (nth 2 e))
2290 (body (nth 3 e))
2291 (nl (nth 4 e))
2292 (stacked (nth 5 e))
2293 (body1 (concat body "*?"))
2294 (markers (mapconcat 'car org-emphasis-alist "")))
2295 ;; make sure special characters appear at the right position in the class
2296 (if (string-match "\\^" markers)
2297 (setq markers (concat (replace-match "" t t markers) "^")))
2298 (if (string-match "-" markers)
2299 (setq markers (concat (replace-match "" t t markers) "-")))
2300 (while (>= (setq nl (1- nl)) 0) (setq body1 (concat body1 "\n?" body "*?")))
2301 ;; Make the regexp
2302 (setq org-emph-re
2303 (concat "\\([" pre (if stacked markers) "]\\|^\\)"
2304 "\\("
2305 "\\([" markers "]\\)"
2306 "\\("
2307 "[^" border markers "]"
2308 body1
2309 "[^" border markers "]"
2310 "\\)"
2311 "\\3\\)"
2312 "\\([" post (if stacked markers) "]\\|$\\)")))))
2314 (defcustom org-emphasis-regexp-components
2315 '(" \t(" " \t.,?;:'\")" " \t\r\n,." "." 1 nil)
2316 "Components used to build the reqular expression for emphasis.
2317 This is a list with 6 entries. Terminology: In an emphasis string
2318 like \" *strong word* \", we call the initial space PREMATCH, the final
2319 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2320 and \"trong wor\" is the body. The different components in this variable
2321 specify what is allowed/forbidden in each part:
2323 pre Chars allowed as prematch. Beginning of line will be allowed too.
2324 post Chars allowed as postmatch. End of line will be allowed too.
2325 border The chars *forbidden* as border characters. In addition to the
2326 characters given here, all marker characters are forbidden too.
2327 body-regexp A regexp like \".\" to match a body character. Don't use
2328 non-shy groups here, and don't allow newline here.
2329 newline The maximum number of newlines allowed in an emphasis exp.
2330 stacked Non-nil means, allow stacked styles. This works only in HTML
2331 export. When this is set, all marker characters (as given in
2332 `org-emphasis-alist') will be allowed as pre/post, aiding
2333 inside-out matching.
2334 Use customize to modify this, or restart emacs after changing it."
2335 :group 'org-font-lock
2336 :set 'org-set-emph-re
2337 :type '(list
2338 (sexp :tag "Allowed chars in pre ")
2339 (sexp :tag "Allowed chars in post ")
2340 (sexp :tag "Forbidden chars in border ")
2341 (sexp :tag "Regexp for body ")
2342 (integer :tag "number of newlines allowed")
2343 (boolean :tag "Stacking allowed ")))
2345 (defcustom org-emphasis-alist
2346 '(("*" bold "<b>" "</b>")
2347 ("/" italic "<i>" "</i>")
2348 ("_" underline "<u>" "</u>")
2349 ("=" shadow "<code>" "</code>")
2350 ("+" (:strike-through t) "<del>" "</del>")
2352 "Special syntax for emphasised text.
2353 Text starting and ending with a special character will be emphasized, for
2354 example *bold*, _underlined_ and /italic/. This variable sets the marker
2355 characters, the face to bbe used by font-lock for highlighting in Org-mode
2356 emacs buffers, and the HTML tags to be used for this.
2357 Use customize to modify this, or restart emacs after changing it."
2358 :group 'org-font-lock
2359 :set 'org-set-emph-re
2360 :type '(repeat
2361 (list
2362 (string :tag "Marker character")
2363 (choice
2364 (face :tag "Font-lock-face")
2365 (plist :tag "Face property list"))
2366 (string :tag "HTML start tag")
2367 (string :tag "HTML end tag"))))
2369 (defgroup org-faces nil
2370 "Faces in Org-mode."
2371 :tag "Org Faces"
2372 :group 'org-font-lock)
2374 (defun org-compatible-face (specs)
2375 "Make a compatible face specification.
2376 XEmacs and Emacs 21 do not know about the `min-colors' attribute.
2377 For them we convert a (min-colors 8) entry to a `tty' entry and move it
2378 to the top of the list. The `min-colors' attribute will be removed from
2379 any other entries, and any resulting duplicates will be removed entirely."
2380 (if (or (featurep 'xemacs) (< emacs-major-version 22))
2381 (let (r e a)
2382 (while (setq e (pop specs))
2383 (cond
2384 ((memq (car e) '(t default)) (push e r))
2385 ((setq a (member '(min-colors 8) (car e)))
2386 (nconc r (list (cons (cons '(type tty) (delq (car a) (car e)))
2387 (cdr e)))))
2388 ((setq a (assq 'min-colors (car e)))
2389 (setq e (cons (delq a (car e)) (cdr e)))
2390 (or (assoc (car e) r) (push e r)))
2391 (t (or (assoc (car e) r) (push e r)))))
2392 (nreverse r))
2393 specs))
2395 (defface org-hide
2396 '((((background light)) (:foreground "white"))
2397 (((background dark)) (:foreground "black")))
2398 "Face used to hide leading stars in headlines.
2399 The forground color of this face should be equal to the background
2400 color of the frame."
2401 :group 'org-faces)
2403 (defface org-level-1 ;; font-lock-function-name-face
2404 (org-compatible-face
2405 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2406 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2407 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2408 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2409 (((class color) (min-colors 8)) (:foreground "blue" :bold t))
2410 (t (:bold t))))
2411 "Face used for level 1 headlines."
2412 :group 'org-faces)
2414 (defface org-level-2 ;; font-lock-variable-name-face
2415 (org-compatible-face
2416 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2417 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2418 (((class color) (min-colors 8) (background light)) (:foreground "yellow"))
2419 (((class color) (min-colors 8) (background dark)) (:foreground "yellow" :bold t))
2420 (t (:bold t))))
2421 "Face used for level 2 headlines."
2422 :group 'org-faces)
2424 (defface org-level-3 ;; font-lock-keyword-face
2425 (org-compatible-face
2426 '((((class color) (min-colors 88) (background light)) (:foreground "Purple"))
2427 (((class color) (min-colors 88) (background dark)) (:foreground "Cyan1"))
2428 (((class color) (min-colors 16) (background light)) (:foreground "Purple"))
2429 (((class color) (min-colors 16) (background dark)) (:foreground "Cyan"))
2430 (((class color) (min-colors 8) (background light)) (:foreground "purple" :bold t))
2431 (((class color) (min-colors 8) (background dark)) (:foreground "cyan" :bold t))
2432 (t (:bold t))))
2433 "Face used for level 3 headlines."
2434 :group 'org-faces)
2436 (defface org-level-4 ;; font-lock-comment-face
2437 (org-compatible-face
2438 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2439 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2440 (((class color) (min-colors 16) (background light)) (:foreground "red"))
2441 (((class color) (min-colors 16) (background dark)) (:foreground "red1"))
2442 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2443 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2444 (t (:bold t))))
2445 "Face used for level 4 headlines."
2446 :group 'org-faces)
2448 (defface org-level-5 ;; font-lock-type-face
2449 (org-compatible-face
2450 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen"))
2451 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen"))
2452 (((class color) (min-colors 8)) (:foreground "green"))))
2453 "Face used for level 5 headlines."
2454 :group 'org-faces)
2456 (defface org-level-6 ;; font-lock-constant-face
2457 (org-compatible-face
2458 '((((class color) (min-colors 16) (background light)) (:foreground "CadetBlue"))
2459 (((class color) (min-colors 16) (background dark)) (:foreground "Aquamarine"))
2460 (((class color) (min-colors 8)) (:foreground "magenta"))))
2461 "Face used for level 6 headlines."
2462 :group 'org-faces)
2464 (defface org-level-7 ;; font-lock-builtin-face
2465 (org-compatible-face
2466 '((((class color) (min-colors 16) (background light)) (:foreground "Orchid"))
2467 (((class color) (min-colors 16) (background dark)) (:foreground "LightSteelBlue"))
2468 (((class color) (min-colors 8)) (:foreground "blue"))))
2469 "Face used for level 7 headlines."
2470 :group 'org-faces)
2472 (defface org-level-8 ;; font-lock-string-face
2473 (org-compatible-face
2474 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2475 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2476 (((class color) (min-colors 8)) (:foreground "green"))))
2477 "Face used for level 8 headlines."
2478 :group 'org-faces)
2480 (defface org-special-keyword ;; font-lock-string-face
2481 (org-compatible-face
2482 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2483 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2484 (t (:italic t))))
2485 "Face used for special keywords."
2486 :group 'org-faces)
2488 (defface org-warning ;; font-lock-warning-face
2489 (org-compatible-face
2490 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2491 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2492 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2493 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2494 (t (:bold t))))
2495 "Face for deadlines and TODO keywords."
2496 :group 'org-faces)
2498 (defface org-headline-done ;; font-lock-string-face
2499 (org-compatible-face
2500 '((((class color) (min-colors 16) (background light)) (:foreground "RosyBrown"))
2501 (((class color) (min-colors 16) (background dark)) (:foreground "LightSalmon"))
2502 (((class color) (min-colors 8) (background light)) (:bold nil))))
2503 "Face used to indicate that a headline is DONE.
2504 This face is only used if `org-fontify-done-headline' is set."
2505 :group 'org-faces)
2507 (defface org-archived ; similar to shadow
2508 (org-compatible-face
2509 '((((class color grayscale) (min-colors 88) (background light))
2510 (:foreground "grey50"))
2511 (((class color grayscale) (min-colors 88) (background dark))
2512 (:foreground "grey70"))
2513 (((class color) (min-colors 8) (background light))
2514 (:foreground "green"))
2515 (((class color) (min-colors 8) (background dark))
2516 (:foreground "yellow"))))
2517 "Face for headline with the ARCHIVE tag."
2518 :group 'org-faces)
2520 (defface org-link
2521 '((((class color) (background light)) (:foreground "Purple" :underline t))
2522 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2523 (t (:underline t)))
2524 "Face for links."
2525 :group 'org-faces)
2527 (defface org-date
2528 '((((class color) (background light)) (:foreground "Purple" :underline t))
2529 (((class color) (background dark)) (:foreground "Cyan" :underline t))
2530 (t (:underline t)))
2531 "Face for links."
2532 :group 'org-faces)
2534 (defface org-tag
2535 '((t (:bold t)))
2536 "Face for tags."
2537 :group 'org-faces)
2539 (defface org-todo ;; font-lock-warning-face
2540 (org-compatible-face
2541 '((((class color) (min-colors 16) (background light)) (:foreground "Red1" :bold t))
2542 (((class color) (min-colors 16) (background dark)) (:foreground "Pink" :bold t))
2543 (((class color) (min-colors 8) (background light)) (:foreground "red" :bold t))
2544 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2545 (t (:inverse-video t :bold t))))
2546 "Face for TODO keywords."
2547 :group 'org-faces)
2549 (defface org-done ;; font-lock-type-face
2550 (org-compatible-face
2551 '((((class color) (min-colors 16) (background light)) (:foreground "ForestGreen" :bold t))
2552 (((class color) (min-colors 16) (background dark)) (:foreground "PaleGreen" :bold t))
2553 (((class color) (min-colors 8)) (:foreground "green"))
2554 (t (:bold t))))
2555 "Face used for DONE."
2556 :group 'org-faces)
2558 (defface org-table ;; font-lock-function-name-face
2559 (org-compatible-face
2560 '((((class color) (min-colors 88) (background light)) (:foreground "Blue1"))
2561 (((class color) (min-colors 88) (background dark)) (:foreground "LightSkyBlue"))
2562 (((class color) (min-colors 16) (background light)) (:foreground "Blue"))
2563 (((class color) (min-colors 16) (background dark)) (:foreground "LightSkyBlue"))
2564 (((class color) (min-colors 8) (background light)) (:foreground "blue"))
2565 (((class color) (min-colors 8) (background dark)))))
2566 "Face used for tables."
2567 :group 'org-faces)
2569 (defface org-formula
2570 (org-compatible-face
2571 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2572 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2573 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2574 (((class color) (min-colors 8) (background dark)) (:foreground "red"))
2575 (t (:bold t :italic t))))
2576 "Face for formulas."
2577 :group 'org-faces)
2579 (defface org-scheduled-today
2580 (org-compatible-face
2581 '((((class color) (min-colors 88) (background light)) (:foreground "DarkGreen"))
2582 (((class color) (min-colors 88) (background dark)) (:foreground "PaleGreen"))
2583 (((class color) (min-colors 8)) (:foreground "green"))
2584 (t (:bold t :italic t))))
2585 "Face for items scheduled for a certain day."
2586 :group 'org-faces)
2588 (defface org-scheduled-previously
2589 (org-compatible-face
2590 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2591 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2592 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2593 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2594 (t (:bold t))))
2595 "Face for items scheduled previously, and not yet done."
2596 :group 'org-faces)
2598 (defface org-upcoming-deadline
2599 (org-compatible-face
2600 '((((class color) (min-colors 88) (background light)) (:foreground "Firebrick"))
2601 (((class color) (min-colors 88) (background dark)) (:foreground "chocolate1"))
2602 (((class color) (min-colors 8) (background light)) (:foreground "red"))
2603 (((class color) (min-colors 8) (background dark)) (:foreground "red" :bold t))
2604 (t (:bold t))))
2605 "Face for items scheduled previously, and not yet done."
2606 :group 'org-faces)
2608 (defface org-time-grid ;; font-lock-variable-name-face
2609 (org-compatible-face
2610 '((((class color) (min-colors 16) (background light)) (:foreground "DarkGoldenrod"))
2611 (((class color) (min-colors 16) (background dark)) (:foreground "LightGoldenrod"))
2612 (((class color) (min-colors 8)) (:foreground "yellow" :weight light))))
2613 "Face used for time grids."
2614 :group 'org-faces)
2616 (defconst org-level-faces
2617 '(org-level-1 org-level-2 org-level-3 org-level-4
2618 org-level-5 org-level-6 org-level-7 org-level-8
2620 (defconst org-n-levels (length org-level-faces))
2623 ;; Variables for pre-computed regular expressions, all buffer local
2624 (defvar org-done-string nil
2625 "The last string in `org-todo-keywords', indicating an item is DONE.")
2626 (make-variable-buffer-local 'org-done-string)
2627 (defvar org-todo-regexp nil
2628 "Matches any of the TODO state keywords.")
2629 (make-variable-buffer-local 'org-todo-regexp)
2630 (defvar org-not-done-regexp nil
2631 "Matches any of the TODO state keywords except the last one.")
2632 (make-variable-buffer-local 'org-not-done-regexp)
2633 (defvar org-todo-line-regexp nil
2634 "Matches a headline and puts TODO state into group 2 if present.")
2635 (make-variable-buffer-local 'org-todo-line-regexp)
2636 (defvar org-todo-line-tags-regexp nil
2637 "Matches a headline and puts TODO state into group 2 if present.
2638 Also put tags into group 4 if tags are present.")
2639 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2640 (defvar org-nl-done-regexp nil
2641 "Matches newline followed by a headline with the DONE keyword.")
2642 (make-variable-buffer-local 'org-nl-done-regexp)
2643 (defvar org-looking-at-done-regexp nil
2644 "Matches the DONE keyword a point.")
2645 (make-variable-buffer-local 'org-looking-at-done-regexp)
2646 (defvar org-todo-kwd-priority-p nil
2647 "Do TODO items have priorities?")
2648 (make-variable-buffer-local 'org-todo-kwd-priority-p)
2649 (defvar org-todo-kwd-max-priority nil
2650 "Maximum priority of TODO items.")
2651 (make-variable-buffer-local 'org-todo-kwd-max-priority)
2652 (defvar org-ds-keyword-length 12
2653 "Maximum length of the Deadline and SCHEDULED keywords.")
2654 (make-variable-buffer-local 'org-ds-keyword-length)
2655 (defvar org-deadline-regexp nil
2656 "Matches the DEADLINE keyword.")
2657 (make-variable-buffer-local 'org-deadline-regexp)
2658 (defvar org-deadline-time-regexp nil
2659 "Matches the DEADLINE keyword together with a time stamp.")
2660 (make-variable-buffer-local 'org-deadline-time-regexp)
2661 (defvar org-deadline-line-regexp nil
2662 "Matches the DEADLINE keyword and the rest of the line.")
2663 (make-variable-buffer-local 'org-deadline-line-regexp)
2664 (defvar org-scheduled-regexp nil
2665 "Matches the SCHEDULED keyword.")
2666 (make-variable-buffer-local 'org-scheduled-regexp)
2667 (defvar org-scheduled-time-regexp nil
2668 "Matches the SCHEDULED keyword together with a time stamp.")
2669 (make-variable-buffer-local 'org-scheduled-time-regexp)
2670 (defvar org-closed-time-regexp nil
2671 "Matches the CLOSED keyword together with a time stamp.")
2672 (make-variable-buffer-local 'org-closed-time-regexp)
2674 (defvar org-keyword-time-regexp nil
2675 "Matches any of the 3 keywords, together with the time stamp.")
2676 (make-variable-buffer-local 'org-keyword-time-regexp)
2677 (defvar org-maybe-keyword-time-regexp nil
2678 "Matches a timestamp, possibly preceeded by a keyword.")
2679 (make-variable-buffer-local 'org-keyword-time-regexp)
2681 (defconst org-rm-props '(invisible t face t keymap t intangible t mouse-face t
2682 mouse-map t)
2683 "Properties to remove when a string without properties is wanted.")
2685 (defsubst org-match-string-no-properties (num &optional string)
2686 (if (featurep 'xemacs)
2687 (let ((s (match-string num string)))
2688 (remove-text-properties 0 (length s) org-rm-props s)
2690 (match-string-no-properties num string)))
2692 (defsubst org-no-properties (s)
2693 (remove-text-properties 0 (length s) org-rm-props s)
2696 (defsubst org-set-local (var value)
2697 "Make VAR local in current buffer and set it to VALUE."
2698 (set (make-variable-buffer-local var) value))
2700 (defsubst org-mode-p ()
2701 "Check if the current buffer is in Org-mode."
2702 (eq major-mode 'org-mode))
2704 (defun org-let (list &rest body)
2705 (eval (cons 'let (cons list body))))
2706 (put 'org-let 'lisp-indent-function 1)
2708 (defun org-let2 (list1 list2 &rest body)
2709 (eval (cons 'let (cons list1 (list (cons 'let (cons list2 body)))))))
2710 (put 'org-let2 'lisp-indent-function 2)
2712 (defconst org-startup-options
2713 '(("fold" org-startup-folded t)
2714 ("overview" org-startup-folded t)
2715 ("nofold" org-startup-folded nil)
2716 ("showall" org-startup-folded nil)
2717 ("content" org-startup-folded content)
2718 ("hidestars" org-hide-leading-stars t)
2719 ("showstars" org-hide-leading-stars nil)
2720 ("odd" org-odd-levels-only t)
2721 ("oddeven" org-odd-levels-only nil)
2722 ("align" org-startup-align-all-tables t)
2723 ("noalign" org-startup-align-all-tables nil)
2724 ("logging" org-log-done t)
2725 ("nologging" org-log-done nil)
2726 ("dlcheck" org-startup-with-deadline-check t)
2727 ("nodlcheck" org-startup-with-deadline-check nil)))
2729 (defun org-set-regexps-and-options ()
2730 "Precompute regular expressions for current buffer."
2731 (when (org-mode-p)
2732 (let ((re (org-make-options-regexp
2733 '("CATEGORY" "SEQ_TODO" "PRI_TODO" "TYP_TODO"
2734 "STARTUP" "ARCHIVE" "TAGS" "CALC")))
2735 (splitre "[ \t]+")
2736 kwds int key value cat arch tags)
2737 (save-excursion
2738 (save-restriction
2739 (widen)
2740 (goto-char (point-min))
2741 (while (re-search-forward re nil t)
2742 (setq key (match-string 1) value (org-match-string-no-properties 2))
2743 (cond
2744 ((equal key "CATEGORY")
2745 (if (string-match "[ \t]+$" value)
2746 (setq value (replace-match "" t t value)))
2747 (setq cat (intern value)))
2748 ((equal key "SEQ_TODO")
2749 (setq int 'sequence
2750 kwds (append kwds (org-split-string value splitre))))
2751 ((equal key "PRI_TODO")
2752 (setq int 'priority
2753 kwds (append kwds (org-split-string value splitre))))
2754 ((equal key "TYP_TODO")
2755 (setq int 'type
2756 kwds (append kwds (org-split-string value splitre))))
2757 ((equal key "TAGS")
2758 (setq tags (append tags (org-split-string value splitre))))
2759 ((equal key "STARTUP")
2760 (let ((opts (org-split-string value splitre))
2761 l var val)
2762 (while (setq l (assoc (pop opts) org-startup-options))
2763 (setq var (nth 1 l) val (nth 2 l))
2764 (set (make-local-variable var) val))))
2765 ((equal key "ARCHIVE")
2766 (string-match " *$" value)
2767 (setq arch (replace-match "" t t value))
2768 (remove-text-properties 0 (length arch)
2769 '(face t fontified t) arch)))
2771 (and cat (org-set-local 'org-category cat))
2772 (and kwds (org-set-local 'org-todo-keywords kwds))
2773 (and arch (org-set-local 'org-archive-location arch))
2774 (and int (org-set-local 'org-todo-interpretation int))
2775 (when tags
2776 (let (e tgs)
2777 (while (setq e (pop tags))
2778 (cond
2779 ((equal e "{") (push '(:startgroup) tgs))
2780 ((equal e "}") (push '(:endgroup) tgs))
2781 ((string-match "^\\([0-9a-zA-Z_@]+\\)(\\(.\\))$" e)
2782 (push (cons (match-string 1 e)
2783 (string-to-char (match-string 2 e)))
2784 tgs))
2785 (t (push (list e) tgs))))
2786 (org-set-local 'org-tag-alist nil)
2787 (while (setq e (pop tgs))
2788 (or (and (stringp (car e))
2789 (assoc (car e) org-tag-alist))
2790 (push e org-tag-alist))))))
2792 ;; Compute the regular expressions and other local variables
2793 (setq org-todo-kwd-priority-p (equal org-todo-interpretation 'priority)
2794 org-todo-kwd-max-priority (1- (length org-todo-keywords))
2795 org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2796 (length org-scheduled-string)))
2797 org-done-string
2798 (nth (1- (length org-todo-keywords)) org-todo-keywords)
2799 org-todo-regexp
2800 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords
2801 "\\|") "\\)\\>")
2802 org-not-done-regexp
2803 (concat "\\<\\("
2804 (mapconcat 'regexp-quote
2805 (nreverse (cdr (reverse org-todo-keywords)))
2806 "\\|")
2807 "\\)\\>")
2808 org-todo-line-regexp
2809 (concat "^\\(\\*+\\)[ \t]*\\("
2810 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2811 "\\)? *\\(.*\\)")
2812 org-nl-done-regexp
2813 (concat "[\r\n]\\*+[ \t]+" org-done-string "\\>")
2814 org-todo-line-tags-regexp
2815 (concat "^\\(\\*+\\)[ \t]*\\("
2816 (mapconcat 'regexp-quote org-todo-keywords "\\|")
2817 "\\)? *\\(.*?\\([ \t]:[a-zA-Z0-9:_@]+:[ \t]*\\)?$\\)")
2818 org-looking-at-done-regexp (concat "^" org-done-string "\\>")
2819 org-deadline-regexp (concat "\\<" org-deadline-string)
2820 org-deadline-time-regexp
2821 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2822 org-deadline-line-regexp
2823 (concat "\\<\\(" org-deadline-string "\\).*")
2824 org-scheduled-regexp
2825 (concat "\\<" org-scheduled-string)
2826 org-scheduled-time-regexp
2827 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2828 org-closed-time-regexp
2829 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2830 org-keyword-time-regexp
2831 (concat "\\<\\(" org-scheduled-string
2832 "\\|" org-deadline-string
2833 "\\|" org-closed-string
2834 "\\|" org-clock-string "\\)"
2835 " *[[<]\\([^]>]+\\)[]>]")
2836 org-maybe-keyword-time-regexp
2837 (concat "\\(\\<\\(" org-scheduled-string
2838 "\\|" org-deadline-string
2839 "\\|" org-closed-string
2840 "\\|" org-clock-string "\\)\\)?"
2841 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^]\r\n>]*?[]>]\\)"))
2843 (org-set-font-lock-defaults)))
2845 ;; Tell the compiler about dynamically scoped variables,
2846 ;; and variables from other packages
2847 (defvar calc-embedded-close-formula) ; defined by the calc package
2848 (defvar calc-embedded-open-formula) ; defined by the calc package
2849 (defvar font-lock-unfontify-region-function) ; defined by font-lock.el
2850 (defvar zmacs-regions) ; XEmacs regions
2851 (defvar original-date) ; dynamically scoped in calendar
2852 (defvar org-old-auto-fill-inhibit-regexp) ; local variable used by `orgtbl-mode'
2853 (defvar orgtbl-mode-menu) ; defined when orgtbl mode get initialized
2854 (defvar org-html-entities) ; defined later in this file
2855 (defvar org-goto-start-pos) ; dynamically scoped parameter
2856 (defvar org-time-was-given) ; dynamically scoped parameter
2857 (defvar org-ts-what) ; dynamically scoped parameter
2858 (defvar org-current-export-file) ; dynamically scoped parameter
2859 (defvar org-current-export-dir) ; dynamically scoped parameter
2860 (defvar mark-active) ; Emacs only, not available in XEmacs.
2861 (defvar timecnt) ; dynamically scoped parameter
2862 (defvar levels-open) ; dynamically scoped parameter
2863 (defvar entry) ; dynamically scoped parameter
2864 (defvar state) ; dynamically scoped into `org-after-todo-state-change-hook'
2865 (defvar date) ; dynamically scoped parameter
2866 (defvar description) ; dynamically scoped parameter
2867 (defvar ans1) ; dynamically scoped parameter
2868 (defvar ans2) ; dynamically scoped parameter
2869 (defvar starting-day) ; local variable
2870 (defvar include-all-loc) ; local variable
2871 (defvar vm-message-pointer) ; from vm
2872 (defvar vm-folder-directory) ; from vm
2873 (defvar gnus-other-frame-object) ; from gnus
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)
2898 ;;; Define the mode
2900 (defvar org-mode-map
2901 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2902 (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.")
2903 (copy-keymap outline-mode-map))
2904 "Keymap for Org-mode.")
2906 (defvar org-struct-menu) ; defined later in this file
2907 (defvar org-org-menu) ; defined later in this file
2908 (defvar org-tbl-menu) ; defined later in this file
2910 ;; We use a before-change function to check if a table might need
2911 ;; an update.
2912 (defvar org-table-may-need-update t
2913 "Indicates that a table might need an update.
2914 This variable is set by `org-before-change-function'.
2915 `org-table-align' sets it back to nil.")
2916 (defvar org-mode-hook nil)
2917 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
2918 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
2921 ;;;###autoload
2922 (define-derived-mode org-mode outline-mode "Org"
2923 "Outline-based notes management and organizer, alias
2924 \"Carsten's outline-mode for keeping track of everything.\"
2926 Org-mode develops organizational tasks around a NOTES file which
2927 contains information about projects as plain text. Org-mode is
2928 implemented on top of outline-mode, which is ideal to keep the content
2929 of large files well structured. It supports ToDo items, deadlines and
2930 time stamps, which magically appear in the diary listing of the Emacs
2931 calendar. Tables are easily created with a built-in table editor.
2932 Plain text URL-like links connect to websites, emails (VM), Usenet
2933 messages (Gnus), BBDB entries, and any files related to the project.
2934 For printing and sharing of notes, an Org-mode file (or a part of it)
2935 can be exported as a structured ASCII or HTML file.
2937 The following commands are available:
2939 \\{org-mode-map}"
2941 ;; Get rid of Outline menus, they are not needed
2942 ;; Need to do this here because define-derived-mode sets up
2943 ;; the keymap so late.
2944 (if (featurep 'xemacs)
2945 (progn
2946 ;; Assume this is Greg's port, it used easymenu
2947 (easy-menu-remove outline-mode-menu-heading)
2948 (easy-menu-remove outline-mode-menu-show)
2949 (easy-menu-remove outline-mode-menu-hide))
2950 (define-key org-mode-map [menu-bar headings] 'undefined)
2951 (define-key org-mode-map [menu-bar hide] 'undefined)
2952 (define-key org-mode-map [menu-bar show] 'undefined))
2954 (easy-menu-add org-org-menu)
2955 (easy-menu-add org-tbl-menu)
2956 (org-install-agenda-files-menu)
2957 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
2958 (org-add-to-invisibility-spec '(org-cwidth))
2959 (when (featurep 'xemacs)
2960 (org-set-local 'line-move-ignore-invisible t))
2961 (setq outline-regexp "\\*+")
2962 ;;(setq outline-regexp "\\(?:\\*+\\|[ \t]*\\(?:[-+*]\\|[0-9]+[.)]\\) \\)")
2963 (setq outline-level 'org-outline-level)
2964 (when (and org-ellipsis (stringp org-ellipsis))
2965 (unless org-display-table
2966 (setq org-display-table (make-display-table)))
2967 (set-display-table-slot org-display-table
2968 4 (string-to-vector org-ellipsis))
2969 (setq buffer-display-table org-display-table))
2970 (org-set-regexps-and-options)
2971 ;; Calc embedded
2972 (org-set-local 'calc-embedded-open-mode "# ")
2973 (modify-syntax-entry ?# "<")
2974 (if org-startup-truncated (setq truncate-lines t))
2975 (org-set-local 'font-lock-unfontify-region-function
2976 'org-unfontify-region)
2977 ;; Activate before-change-function
2978 (org-set-local 'org-table-may-need-update t)
2979 (org-add-hook 'before-change-functions 'org-before-change-function nil
2980 'local)
2981 ;; Check for running clock before killing a buffer
2982 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
2983 ;; Paragraphs and auto-filling
2984 (org-set-autofill-regexps)
2985 (org-update-radio-target-regexp)
2987 (if (and org-insert-mode-line-in-empty-file
2988 (interactive-p)
2989 (= (point-min) (point-max)))
2990 (insert " -*- mode: org -*-\n\n"))
2992 (unless org-inhibit-startup
2993 (when org-startup-align-all-tables
2994 (let ((bmp (buffer-modified-p)))
2995 (org-table-map-tables 'org-table-align)
2996 (set-buffer-modified-p bmp)))
2997 (if org-startup-with-deadline-check
2998 (call-interactively 'org-check-deadlines)
2999 (cond
3000 ((eq org-startup-folded t)
3001 (org-cycle '(4)))
3002 ((eq org-startup-folded 'content)
3003 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3004 (org-cycle '(4)) (org-cycle '(4))))))))
3006 (defsubst org-call-with-arg (command arg)
3007 "Call COMMAND interactively, but pretend prefix are was ARG."
3008 (let ((current-prefix-arg arg)) (call-interactively command)))
3010 (defsubst org-current-line (&optional pos)
3011 (+ (if (bolp) 1 0) (count-lines (point-min) (or pos (point)))))
3013 (defun org-current-time ()
3014 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3015 (if (> org-time-stamp-rounding-minutes 0)
3016 (let ((r org-time-stamp-rounding-minutes)
3017 (time (decode-time)))
3018 (apply 'encode-time
3019 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3020 (nthcdr 2 time))))
3021 (current-time)))
3023 (defun org-add-props (string plist &rest props)
3024 "Add text properties to entire string, from beginning to end.
3025 PLIST may be a list of properties, PROPS are individual properties and values
3026 that will be added to PLIST. Returns the string that was modified."
3027 (add-text-properties
3028 0 (length string) (if props (append plist props) plist) string)
3029 string)
3030 (put 'org-add-props 'lisp-indent-function 2)
3033 ;;; Font-Lock stuff
3035 (defvar org-mouse-map (make-sparse-keymap))
3036 (define-key org-mouse-map
3037 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3038 (define-key org-mouse-map
3039 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3040 (when org-mouse-1-follows-link
3041 (define-key org-mouse-map [follow-link] 'mouse-face))
3042 (when org-tab-follows-link
3043 (define-key org-mouse-map [(tab)] 'org-open-at-point)
3044 (define-key org-mouse-map "\C-i" 'org-open-at-point))
3045 (when org-return-follows-link
3046 (define-key org-mouse-map [(return)] 'org-open-at-point)
3047 (define-key org-mouse-map "\C-m" 'org-open-at-point))
3049 (require 'font-lock)
3051 (defconst org-non-link-chars "]\t\n\r<>")
3052 (defconst org-link-types '("https?" "ftp" "mailto" "file" "news" "bbdb" "vm"
3053 "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
3054 (defconst org-link-re-with-space
3055 (concat
3056 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3057 "\\([^" org-non-link-chars " ]"
3058 "[^" org-non-link-chars "]*"
3059 "[^" org-non-link-chars " ]\\)>?")
3060 "Matches a link with spaces, optional angular brackets around it.")
3062 (defconst org-link-re-with-space2
3063 (concat
3064 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3065 "\\([^" org-non-link-chars " ]"
3066 "[^]\t\n\r]*"
3067 "[^" org-non-link-chars " ]\\)>?")
3068 "Matches a link with spaces, optional angular brackets around it.")
3070 (defconst org-angle-link-re
3071 (concat
3072 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3073 "\\([^" org-non-link-chars " ]"
3074 "[^" org-non-link-chars "]*"
3075 "\\)>")
3076 "Matches link with angular brackets, spaces are allowed.")
3077 (defconst org-plain-link-re
3078 (concat
3079 "\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3080 "\\([^]\t\n\r<>,;() ]+\\)")
3081 "Matches plain link, without spaces.")
3083 (defconst org-bracket-link-regexp
3084 "\\[\\[\\([^]]+\\)\\]\\(\\[\\([^]]+\\)\\]\\)?\\]"
3085 "Matches a link in double brackets.")
3087 (defconst org-bracket-link-analytic-regexp
3088 (concat
3089 "\\[\\["
3090 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3091 "\\([^]]+\\)"
3092 "\\]"
3093 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3094 "\\]"))
3095 ; 1: http:
3096 ; 2: http
3097 ; 3: path
3098 ; 4: [desc]
3099 ; 5: desc
3102 (defconst org-ts-lengths
3103 (cons (length (format-time-string (car org-time-stamp-formats)))
3104 (length (format-time-string (cdr org-time-stamp-formats))))
3105 "This holds the lengths of the two different time formats.")
3106 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)>"
3107 "Regular expression for fast time stamp matching.")
3108 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}[^\r\n>]*?\\)[]>]"
3109 "Regular expression for fast time stamp matching.")
3110 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\)\\([^]0-9>\r\n]*\\)\\(\\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3111 "Regular expression matching time strings for analysis.")
3112 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 ">")
3113 "Regular expression matching time stamps, with groups.")
3114 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[]>]")
3115 "Regular expression matching time stamps (also [..]), with groups.")
3116 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3117 "Regular expression matching a time stamp range.")
3118 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3119 org-ts-regexp "\\)?")
3120 "Regular expression matching a time stamp or time stamp range.")
3122 (defvar org-�§emph-face nil)
3124 (defun org-do-emphasis-faces (limit)
3125 "Run through the buffer and add overlays to links."
3126 (if (re-search-forward org-emph-re limit t)
3127 (progn
3128 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3129 'face
3130 (nth 1 (assoc (match-string 3)
3131 org-emphasis-alist)))
3132 (add-text-properties (match-beginning 2) (match-end 2)
3133 '(font-lock-multiline t))
3134 (backward-char 1)
3135 t)))
3137 (defun org-activate-plain-links (limit)
3138 "Run through the buffer and add overlays to links."
3139 (if (re-search-forward org-plain-link-re limit t)
3140 (progn
3141 (add-text-properties (match-beginning 0) (match-end 0)
3142 (list 'mouse-face 'highlight
3143 'keymap org-mouse-map
3145 t)))
3147 (defun org-activate-angle-links (limit)
3148 "Run through the buffer and add overlays to links."
3149 (if (re-search-forward org-angle-link-re limit t)
3150 (progn
3151 (add-text-properties (match-beginning 0) (match-end 0)
3152 (list 'mouse-face 'highlight
3153 'keymap org-mouse-map
3155 t)))
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)))
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 'keymap org-mouse-map))
3192 t)))
3194 (defvar org-target-link-regexp nil
3195 "Regular expression matching radio targets in plain text.")
3196 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3197 "Regular expression matching a link target.")
3198 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3199 "Regular expression matching a link target.")
3201 (defun org-activate-target-links (limit)
3202 "Run through the buffer and add overlays to target matches."
3203 (when org-target-link-regexp
3204 (let ((case-fold-search t))
3205 (if (re-search-forward org-target-link-regexp limit t)
3206 (progn
3207 (add-text-properties (match-beginning 0) (match-end 0)
3208 (list 'mouse-face 'highlight
3209 'keymap org-mouse-map
3210 'help-echo "Radio target link"
3211 'org-linked-text t))
3212 t)))))
3214 (defun org-update-radio-target-regexp ()
3215 "Find all radio targets in this file and update the regular expression."
3216 (interactive)
3217 (when (memq 'radio org-activate-links)
3218 (setq org-target-link-regexp
3219 (org-make-target-link-regexp (org-all-targets 'radio)))
3220 (org-restart-font-lock)))
3222 (defun org-hide-wide-columns (limit)
3223 (let (s e)
3224 (setq s (text-property-any (point) (or limit (point-max))
3225 'org-cwidth t))
3226 (when s
3227 (setq e (next-single-property-change s 'org-cwidth))
3228 (add-text-properties s e '(invisible org-cwidth intangible t))
3229 (goto-char e)
3230 t)))
3232 (defun org-restart-font-lock ()
3233 "Restart font-lock-mode, to force refontification."
3234 (when (and (boundp 'font-lock-mode) font-lock-mode)
3235 (font-lock-mode -1)
3236 (font-lock-mode 1)))
3238 (defun org-all-targets (&optional radio)
3239 "Return a list of all targets in this file.
3240 With optional argument RADIO, only find radio targets."
3241 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3242 rtn)
3243 (save-excursion
3244 (goto-char (point-min))
3245 (while (re-search-forward re nil t)
3246 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3247 rtn)))
3249 (defun org-make-target-link-regexp (targets)
3250 "Make regular expression matching all strings in TARGETS.
3251 The regular expression finds the targets also if there is a line break
3252 between words."
3253 (and targets
3254 (concat
3255 "\\<\\("
3256 (mapconcat
3257 (lambda (x)
3258 (while (string-match " +" x)
3259 (setq x (replace-match "\\s-+" t t x)))
3261 targets
3262 "\\|")
3263 "\\)\\>")))
3265 (defvar org-camel-regexp "\\*?\\<[A-Z]+[a-z]+[A-Z][a-zA-Z]*\\>"
3266 "Matches CamelCase words, possibly with a star before it.")
3268 (defun org-activate-camels (limit)
3269 "Run through the buffer and add overlays to dates."
3270 (if (re-search-forward org-camel-regexp limit t)
3271 (progn
3272 (add-text-properties (match-beginning 0) (match-end 0)
3273 (list 'mouse-face 'highlight
3274 'keymap org-mouse-map))
3275 t)))
3277 (defun org-activate-tags (limit)
3278 (if (re-search-forward "[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \r\n]" limit t)
3279 (progn
3280 (add-text-properties (match-beginning 1) (match-end 1)
3281 (list 'mouse-face 'highlight
3282 'keymap org-mouse-map))
3283 t)))
3285 (defun org-font-lock-level ()
3286 (save-excursion
3287 (org-back-to-heading t)
3288 (- (match-end 0) (match-beginning 0))))
3290 (defun org-outline-level ()
3291 (save-excursion
3292 (looking-at outline-regexp)
3293 (if (match-beginning 1)
3294 (+ (org-get-string-indentation (match-string 1)) 1000)
3295 (- (match-end 0) (match-beginning 0)))))
3297 (defvar org-font-lock-keywords nil)
3299 (defun org-set-font-lock-defaults ()
3300 (let* ((em org-fontify-emphasized-text)
3301 (lk org-activate-links)
3302 (org-font-lock-extra-keywords
3303 ;; Headlines
3304 (list
3305 '("^\\(\\**\\)\\(\\*\\)\\(.*\\)" (1 (org-get-level-face 1))
3306 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3307 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3308 (1 'org-table))
3309 ;; Links
3310 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3311 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3312 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3313 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3314 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3315 (if (memq 'camel lk) '(org-activate-camels (0 'org-link t)))
3316 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3317 (if org-table-limit-column-width
3318 '(org-hide-wide-columns (0 nil append)))
3319 ;; TODO lines
3320 (list (concat "^\\*+[ \t]*" org-not-done-regexp)
3321 '(1 'org-todo t))
3322 ;; Priorities
3323 (list (concat "\\[#[A-Z]\\]") '(0 'org-special-keyword t))
3324 ;; Special keywords
3325 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3326 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3327 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3328 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3329 ;; Emphasis
3330 (if em '(org-do-emphasis-faces))
3331 ;; Checkboxes, similar to Frank Ruell's org-checklet.el
3332 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)"
3333 2 'bold prepend)
3334 (if org-provide-checkbox-statistics
3335 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3336 (0 (org-get-checkbox-statistics-face) t)))
3337 ;; COMMENT
3338 (list (concat "^\\*+[ \t]*\\<\\(" org-comment-string
3339 "\\|" org-quote-string "\\)\\>")
3340 '(1 'org-special-keyword t))
3341 '("^#.*" (0 'font-lock-comment-face t))
3342 ;; DONE
3343 (if org-fontify-done-headline
3344 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\(.*\\)\\>")
3345 '(1 'org-done t) '(2 'org-headline-done t))
3346 (list (concat "^[*]+ +\\<\\(" org-done-string "\\)\\>")
3347 '(1 'org-done t)))
3348 ;; Table stuff
3349 '("^[ \t]*\\(:.*\\)" (1 'org-table t))
3350 '("| *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3351 '("^[ \t]*| *\\([#!$*_^]\\) *|" (1 'org-formula t))
3352 (if org-format-transports-properties-p
3353 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3354 '("^\\*+ \\(.*:ARCHIVE:.*\\)" (1 'org-archived prepend))
3356 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3357 ;; Now set the full font-lock-keywords
3358 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3359 (org-set-local 'font-lock-defaults
3360 '(org-font-lock-keywords t nil nil backward-paragraph))
3361 (kill-local-variable 'font-lock-keywords) nil))
3363 (defvar org-m nil)
3364 (defvar org-l nil)
3365 (defvar org-f nil)
3366 (defun org-get-level-face (n)
3367 "Get the right face for match N in font-lock matching of healdines."
3368 (setq org-l (- (match-end 2) (match-beginning 1)))
3369 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3370 ; (setq org-f (nth (1- (% org-l org-n-levels)) org-level-faces))
3371 (setq org-f (nth (% (1- org-l) org-n-levels) org-level-faces))
3372 (cond
3373 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3374 ((eq n 2) org-f)
3375 (t (if org-level-color-stars-only nil org-f))))
3377 (defun org-unfontify-region (beg end &optional maybe_loudly)
3378 "Remove fontification and activation overlays from links."
3379 (font-lock-default-unfontify-region beg end)
3380 (let* ((buffer-undo-list t)
3381 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3382 (inhibit-modification-hooks t)
3383 deactivate-mark buffer-file-name buffer-file-truename)
3384 (remove-text-properties beg end
3385 '(mouse-face nil keymap nil org-linked-text nil
3386 invisible nil intangible nil))))
3387 ;;; Visibility cycling
3389 (defvar org-cycle-global-status nil)
3390 (make-variable-buffer-local 'org-cycle-global-status)
3391 (defvar org-cycle-subtree-status nil)
3392 (make-variable-buffer-local 'org-cycle-subtree-status)
3394 ;;;###autoload
3395 (defun org-cycle (&optional arg)
3396 "Visibility cycling for Org-mode.
3398 - When this function is called with a prefix argument, rotate the entire
3399 buffer through 3 states (global cycling)
3400 1. OVERVIEW: Show only top-level headlines.
3401 2. CONTENTS: Show all headlines of all levels, but no body text.
3402 3. SHOW ALL: Show everything.
3404 - When point is at the beginning of a headline, rotate the subtree started
3405 by this line through 3 different states (local cycling)
3406 1. FOLDED: Only the main headline is shown.
3407 2. CHILDREN: The main headline and the direct children are shown.
3408 From this state, you can move to one of the children
3409 and zoom in further.
3410 3. SUBTREE: Show the entire subtree, including body text.
3412 - When there is a numeric prefix, go up to a heading with level ARG, do
3413 a `show-subtree' and return to the previous cursor position. If ARG
3414 is negative, go up that many levels.
3416 - When point is not at the beginning of a headline, execute
3417 `indent-relative', like TAB normally does. See the option
3418 `org-cycle-emulate-tab' for details.
3420 - Special case: if point is the the beginning of the buffer and there is
3421 no headline in line 1, this function will act as if called with prefix arg."
3422 (interactive "P")
3423 (let* ((outline-regexp
3424 (if org-cycle-include-plain-lists
3425 "\\(?:\\*+\\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3426 outline-regexp))
3427 (bob-special (and org-cycle-global-at-bob (bobp)
3428 (not (looking-at outline-regexp))))
3429 (org-cycle-hook
3430 (if bob-special
3431 (delq 'org-optimize-window-after-visibility-change
3432 (copy-sequence org-cycle-hook))
3433 org-cycle-hook))
3434 (pos (point)))
3436 (if (or bob-special (equal arg '(4)))
3437 ;; special case: use global cycling
3438 (setq arg t))
3440 (cond
3442 ((org-at-table-p 'any)
3443 ;; Enter the table or move to the next field in the table
3444 (or (org-table-recognize-table.el)
3445 (progn
3446 (if arg (org-table-edit-field t)
3447 (org-table-justify-field-maybe)
3448 (call-interactively 'org-table-next-field)))))
3450 ((eq arg t) ;; Global cycling
3452 (cond
3453 ((and (eq last-command this-command)
3454 (eq org-cycle-global-status 'overview))
3455 ;; We just created the overview - now do table of contents
3456 ;; This can be slow in very large buffers, so indicate action
3457 (message "CONTENTS...")
3458 (org-content)
3459 (message "CONTENTS...done")
3460 (setq org-cycle-global-status 'contents)
3461 (run-hook-with-args 'org-cycle-hook 'contents))
3463 ((and (eq last-command this-command)
3464 (eq org-cycle-global-status 'contents))
3465 ;; We just showed the table of contents - now show everything
3466 (show-all)
3467 (message "SHOW ALL")
3468 (setq org-cycle-global-status 'all)
3469 (run-hook-with-args 'org-cycle-hook 'all))
3472 ;; Default action: go to overview
3473 (org-overview)
3474 (message "OVERVIEW")
3475 (setq org-cycle-global-status 'overview)
3476 (run-hook-with-args 'org-cycle-hook 'overview))))
3478 ((integerp arg)
3479 ;; Show-subtree, ARG levels up from here.
3480 (save-excursion
3481 (org-back-to-heading)
3482 (outline-up-heading (if (< arg 0) (- arg)
3483 (- (funcall outline-level) arg)))
3484 (org-show-subtree)))
3486 ((save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3487 ;; At a heading: rotate between three different views
3488 (org-back-to-heading)
3489 (let ((goal-column 0) eoh eol eos)
3490 ;; First, some boundaries
3491 (save-excursion
3492 (org-back-to-heading)
3493 (save-excursion
3494 (beginning-of-line 2)
3495 (while (and (not (eobp)) ;; this is like `next-line'
3496 (get-char-property (1- (point)) 'invisible))
3497 (beginning-of-line 2)) (setq eol (point)))
3498 (outline-end-of-heading) (setq eoh (point))
3499 (org-end-of-subtree t) (setq eos (point))
3500 (outline-next-heading))
3501 ;; Find out what to do next and set `this-command'
3502 (cond
3503 ((and (= eos eoh)
3504 ;; Nothing is hidden behind this heading
3505 (message "EMPTY ENTRY")
3506 (setq org-cycle-subtree-status nil)))
3507 ((>= eol eos)
3508 ;; Entire subtree is hidden in one line: open it
3509 (org-show-entry)
3510 (show-children)
3511 (message "CHILDREN")
3512 (setq org-cycle-subtree-status 'children)
3513 (run-hook-with-args 'org-cycle-hook 'children))
3514 ((and (eq last-command this-command)
3515 (eq org-cycle-subtree-status 'children))
3516 ;; We just showed the children, now show everything.
3517 (org-show-subtree)
3518 (message "SUBTREE")
3519 (setq org-cycle-subtree-status 'subtree)
3520 (run-hook-with-args 'org-cycle-hook 'subtree))
3522 ;; Default action: hide the subtree.
3523 (hide-subtree)
3524 (message "FOLDED")
3525 (setq org-cycle-subtree-status 'folded)
3526 (run-hook-with-args 'org-cycle-hook 'folded)))))
3528 ;; TAB emulation
3529 (buffer-read-only (org-back-to-heading))
3531 ((org-try-cdlatex-tab))
3533 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3534 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3535 (or (and (eq org-cycle-emulate-tab 'white)
3536 (= (match-end 0) (point-at-eol)))
3537 (and (eq org-cycle-emulate-tab 'whitestart)
3538 (>= (match-end 0) pos))))
3540 (eq org-cycle-emulate-tab t))
3541 (if (and (looking-at "[ \n\r\t]")
3542 (string-match "^[ \t]*$" (buffer-substring
3543 (point-at-bol) (point))))
3544 (progn
3545 (beginning-of-line 1)
3546 (and (looking-at "[ \t]+") (replace-match ""))))
3547 (indent-relative))
3549 (t (save-excursion
3550 (org-back-to-heading)
3551 (org-cycle))))))
3553 ;;;###autoload
3554 (defun org-global-cycle (&optional arg)
3555 "Cycle the global visibility. For details see `org-cycle'."
3556 (interactive "P")
3557 (if (integerp arg)
3558 (progn
3559 (show-all)
3560 (hide-sublevels arg)
3561 (setq org-cycle-global-status 'contents))
3562 (org-cycle '(4))))
3564 (defun org-overview ()
3565 "Switch to overview mode, shoing only top-level headlines.
3566 Really, this shows all headlines with level equal or greater than the level
3567 of the first headline in the buffer. This is important, because if the
3568 first headline is not level one, then (hide-sublevels 1) gives confusing
3569 results."
3570 (interactive)
3571 (hide-sublevels (save-excursion
3572 (goto-char (point-min))
3573 (if (re-search-forward (concat "^" outline-regexp) nil t)
3574 (progn
3575 (goto-char (match-beginning 0))
3576 (funcall outline-level))
3577 1))))
3579 ;; FIXME: allow an argument to give a limiting level for this.
3580 (defun org-content ()
3581 "Show all headlines in the buffer, like a table of contents"
3582 (interactive)
3583 (save-excursion
3584 ;; Visit all headings and show their offspring
3585 (goto-char (point-max))
3586 (catch 'exit
3587 (while (and (progn (condition-case nil
3588 (outline-previous-visible-heading 1)
3589 (error (goto-char (point-min))))
3591 (looking-at outline-regexp))
3592 (show-branches)
3593 (if (bobp) (throw 'exit nil))))))
3596 (defun org-optimize-window-after-visibility-change (state)
3597 "Adjust the window after a change in outline visibility.
3598 This function is the default value of the hook `org-cycle-hook'."
3599 (when (get-buffer-window (current-buffer))
3600 (cond
3601 ((eq state 'overview) (org-first-headline-recenter 1))
3602 ((eq state 'content) nil)
3603 ((eq state 'all) nil)
3604 ((eq state 'folded) nil)
3605 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3606 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3608 (defun org-subtree-end-visible-p ()
3609 "Is the end of the current subtree visible?"
3610 (pos-visible-in-window-p
3611 (save-excursion (org-end-of-subtree t) (point))))
3613 (defun org-first-headline-recenter (&optional N)
3614 "Move cursor to the first headline and recenter the headline.
3615 Optional argument N means, put the headline into the Nth line of the window."
3616 (goto-char (point-min))
3617 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
3618 (beginning-of-line)
3619 (recenter (prefix-numeric-value N))))
3621 (defvar org-goto-window-configuration nil)
3622 (defvar org-goto-marker nil)
3623 (defvar org-goto-map (make-sparse-keymap))
3624 (let ((cmds '(isearch-forward isearch-backward)) cmd)
3625 (while (setq cmd (pop cmds))
3626 (substitute-key-definition cmd cmd org-goto-map global-map)))
3627 (define-key org-goto-map "\C-m" 'org-goto-ret)
3628 (define-key org-goto-map [(left)] 'org-goto-left)
3629 (define-key org-goto-map [(right)] 'org-goto-right)
3630 (define-key org-goto-map [(?q)] 'org-goto-quit)
3631 (define-key org-goto-map [(control ?g)] 'org-goto-quit)
3632 (define-key org-goto-map "\C-i" 'org-cycle)
3633 (define-key org-goto-map [(tab)] 'org-cycle)
3634 (define-key org-goto-map [(down)] 'outline-next-visible-heading)
3635 (define-key org-goto-map [(up)] 'outline-previous-visible-heading)
3636 (define-key org-goto-map "n" 'outline-next-visible-heading)
3637 (define-key org-goto-map "p" 'outline-previous-visible-heading)
3638 (define-key org-goto-map "f" 'outline-forward-same-level)
3639 (define-key org-goto-map "b" 'outline-backward-same-level)
3640 (define-key org-goto-map "u" 'outline-up-heading)
3641 (define-key org-goto-map "\C-c\C-n" 'outline-next-visible-heading)
3642 (define-key org-goto-map "\C-c\C-p" 'outline-previous-visible-heading)
3643 (define-key org-goto-map "\C-c\C-f" 'outline-forward-same-level)
3644 (define-key org-goto-map "\C-c\C-b" 'outline-backward-same-level)
3645 (define-key org-goto-map "\C-c\C-u" 'outline-up-heading)
3646 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
3647 (while l (define-key org-goto-map (int-to-string (pop l)) 'digit-argument)))
3649 (defconst org-goto-help
3650 "Select a location to jump to, press RET
3651 \[Up]/[Down]=next/prev headline TAB=cycle visibility RET=select [Q]uit")
3653 (defun org-goto ()
3654 "Go to a different location of the document, keeping current visibility.
3656 When you want to go to a different location in a document, the fastest way
3657 is often to fold the entire buffer and then dive into the tree. This
3658 method has the disadvantage, that the previous location will be folded,
3659 which may not be what you want.
3661 This command works around this by showing a copy of the current buffer in
3662 overview mode. You can dive into the tree in that copy, to find the
3663 location you want to reach. When pressing RET, the command returns to the
3664 original buffer in which the visibility is still unchanged. It then jumps
3665 to the new location, making it and the headline hierarchy above it visible."
3666 (interactive)
3667 (let* ((org-goto-start-pos (point))
3668 (selected-point
3669 (org-get-location (current-buffer) org-goto-help)))
3670 (if selected-point
3671 (progn
3672 (org-mark-ring-push org-goto-start-pos)
3673 (goto-char selected-point)
3674 (if (or (org-invisible-p) (org-invisible-p2))
3675 (org-show-hierarchy-above)))
3676 (error "Quit"))))
3678 (defun org-get-location (buf help)
3679 "Let the user select a location in the Org-mode buffer BUF.
3680 This function uses a recursive edit. It returns the selected position
3681 or nil."
3682 (let (org-selected-point)
3683 (save-excursion
3684 (save-window-excursion
3685 (delete-other-windows)
3686 (switch-to-buffer (get-buffer-create "*org-goto*"))
3687 (with-output-to-temp-buffer "*Help*"
3688 (princ help))
3689 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
3690 (setq buffer-read-only nil)
3691 (erase-buffer)
3692 (insert-buffer-substring buf)
3693 (let ((org-startup-truncated t)
3694 (org-startup-folded t)
3695 (org-startup-align-all-tables nil)
3696 (org-startup-with-deadline-check nil))
3697 (org-mode))
3698 (setq buffer-read-only t)
3699 (if (boundp 'org-goto-start-pos)
3700 (goto-char org-goto-start-pos)
3701 (goto-char (point-min)))
3702 (org-beginning-of-line)
3703 (message "Select location and press RET")
3704 ;; now we make sure that during selection, ony very few keys work
3705 ;; and that it is impossible to switch to another window.
3706 (let ((gm (current-global-map))
3707 (overriding-local-map org-goto-map))
3708 (unwind-protect
3709 (progn
3710 (use-global-map org-goto-map)
3711 (recursive-edit))
3712 (use-global-map gm)))))
3713 (kill-buffer "*org-goto*")
3714 org-selected-point))
3716 (defun org-goto-ret (&optional arg)
3717 "Finish `org-goto' by going to the new location."
3718 (interactive "P")
3719 (setq org-selected-point (point)
3720 current-prefix-arg arg)
3721 (throw 'exit nil))
3723 (defun org-goto-left ()
3724 "Finish `org-goto' by going to the new location."
3725 (interactive)
3726 (if (org-on-heading-p)
3727 (progn
3728 (beginning-of-line 1)
3729 (setq org-selected-point (point)
3730 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3731 (throw 'exit nil))
3732 (error "Not on a heading")))
3734 (defun org-goto-right ()
3735 "Finish `org-goto' by going to the new location."
3736 (interactive)
3737 (if (org-on-heading-p)
3738 (progn
3739 (outline-end-of-subtree)
3740 (or (eobp) (forward-char 1))
3741 (setq org-selected-point (point)
3742 current-prefix-arg (- (match-end 0) (match-beginning 0)))
3743 (throw 'exit nil))
3744 (error "Not on a heading")))
3746 (defun org-goto-quit ()
3747 "Finish `org-goto' without cursor motion."
3748 (interactive)
3749 (setq org-selected-point nil)
3750 (throw 'exit nil))
3752 ;;; Promotion, Demotion, Inserting new headlines
3754 (defvar org-ignore-region nil
3755 "To temporarily disable the active region.")
3757 (defun org-insert-heading (&optional force-heading)
3758 "Insert a new heading or item with same depth at point.
3759 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
3760 If point is at the beginning of a headline, insert a sibling before the
3761 current headline. If point is in the middle of a headline, split the headline
3762 at that position and make the rest of the headline part of the sibling below
3763 the current headline."
3764 (interactive "P")
3765 (if (= (buffer-size) 0)
3766 (insert "\n* ")
3767 (when (or force-heading (not (org-insert-item)))
3768 (let* ((head (save-excursion
3769 (condition-case nil
3770 (progn
3771 (org-back-to-heading)
3772 (match-string 0))
3773 (error "*"))))
3774 pos)
3775 (cond
3776 ((and (org-on-heading-p) (bolp)
3777 (save-excursion (backward-char 1) (not (org-invisible-p))))
3778 (open-line 1))
3779 ((and (bolp) (save-excursion
3780 (backward-char 1) (not (org-invisible-p))))
3781 nil)
3782 (t (newline)))
3783 (insert head) (just-one-space)
3784 (setq pos (point))
3785 (end-of-line 1)
3786 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
3787 (run-hooks 'org-insert-heading-hook)))))
3789 (defun org-in-item-p ()
3790 "It the cursor inside a plain list item.
3791 Does not have to be the first line."
3792 (save-excursion
3793 (condition-case nil
3794 (progn
3795 (org-beginning-of-item)
3796 (org-at-item-p)
3798 (error nil))))
3800 (defun org-insert-item (&optional checkbox)
3801 "Insert a new item at the current level.
3802 Return t when things worked, nil when we are not in an item."
3803 (when (save-excursion
3804 (condition-case nil
3805 (progn
3806 (org-beginning-of-item)
3807 (org-at-item-p)
3809 (error nil)))
3810 (let* ((bul (match-string 0))
3811 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
3812 (match-end 0)))
3813 pos)
3814 (cond
3815 ((and (org-at-item-p) (<= (point) eow))
3816 ;; before the bullet
3817 (beginning-of-line 1)
3818 (open-line 1))
3819 ((<= (point) eow)
3820 (beginning-of-line 1))
3821 (t (newline)))
3822 (insert bul (if checkbox "[ ]" ""))
3823 (just-one-space)
3824 (setq pos (point))
3825 (end-of-line 1)
3826 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
3827 (org-maybe-renumber-ordered-list)
3828 (and checkbox (org-update-checkbox-count-maybe))
3831 (defun org-insert-todo-heading (arg)
3832 "Insert a new heading with the same level and TODO state as current heading.
3833 If the heading has no TODO state, or if the state is DONE, use the first
3834 state (TODO by default). Also with prefix arg, force first state."
3835 (interactive "P")
3836 (when (not (org-insert-item 'checkbox))
3837 (org-insert-heading)
3838 (save-excursion
3839 (org-back-to-heading)
3840 (outline-previous-heading)
3841 (looking-at org-todo-line-regexp))
3842 (if (or arg
3843 (not (match-beginning 2))
3844 (equal (match-string 2) org-done-string))
3845 (insert (car org-todo-keywords) " ")
3846 (insert (match-string 2) " "))))
3848 (defun org-promote-subtree ()
3849 "Promote the entire subtree.
3850 See also `org-promote'."
3851 (interactive)
3852 (save-excursion
3853 (org-map-tree 'org-promote))
3854 (org-fix-position-after-promote))
3856 (defun org-demote-subtree ()
3857 "Demote the entire subtree. See `org-demote'.
3858 See also `org-promote'."
3859 (interactive)
3860 (save-excursion
3861 (org-map-tree 'org-demote))
3862 (org-fix-position-after-promote))
3865 (defun org-do-promote ()
3866 "Promote the current heading higher up the tree.
3867 If the region is active in `transient-mark-mode', promote all headings
3868 in the region."
3869 (interactive)
3870 (save-excursion
3871 (if (org-region-active-p)
3872 (org-map-region 'org-promote (region-beginning) (region-end))
3873 (org-promote)))
3874 (org-fix-position-after-promote))
3876 (defun org-do-demote ()
3877 "Demote the current heading lower down the tree.
3878 If the region is active in `transient-mark-mode', demote all headings
3879 in the region."
3880 (interactive)
3881 (save-excursion
3882 (if (org-region-active-p)
3883 (org-map-region 'org-demote (region-beginning) (region-end))
3884 (org-demote)))
3885 (org-fix-position-after-promote))
3887 (defun org-fix-position-after-promote ()
3888 "Make sure that after pro/demotion cursor position is right."
3889 (if (and (equal (char-after) ?\n)
3890 (save-excursion
3891 (skip-chars-backward "a-zA-Z0-9_@")
3892 (looking-at org-todo-regexp)))
3893 (insert " "))
3894 (and (equal (char-after) ?\ )
3895 (equal (char-before) ?*)
3896 (forward-char 1)))
3898 (defun org-get-legal-level (level change)
3899 "Rectify a level change under the influence of `org-odd-levels-only'
3900 LEVEL is a current level, CHANGE is by how much the level should be
3901 modified. Even if CHANGE is nil, LEVEL may be returned modified because
3902 even level numbers will become the next higher odd number."
3903 (if org-odd-levels-only
3904 (cond ((not change) (1+ (* 2 (/ level 2))))
3905 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
3906 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
3907 (max 1 (+ level change))))
3909 (defun org-promote ()
3910 "Promote the current heading higher up the tree.
3911 If the region is active in `transient-mark-mode', promote all headings
3912 in the region."
3913 (org-back-to-heading t)
3914 (let* ((level (save-match-data (funcall outline-level)))
3915 (up-head (make-string (org-get-legal-level level -1) ?*))
3916 (diff (abs (- level (length up-head)))))
3917 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover"))
3918 (replace-match up-head nil t)
3919 ;; Fixup tag positioning
3920 (and org-auto-align-tags (org-set-tags nil t))
3921 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
3923 (defun org-demote ()
3924 "Demote the current heading lower down the tree.
3925 If the region is active in `transient-mark-mode', demote all headings
3926 in the region."
3927 (org-back-to-heading t)
3928 (let* ((level (save-match-data (funcall outline-level)))
3929 (down-head (make-string (org-get-legal-level level 1) ?*))
3930 (diff (abs (- level (length down-head)))))
3931 (replace-match down-head nil t)
3932 ;; Fixup tag positioning
3933 (and org-auto-align-tags (org-set-tags nil t))
3934 (if org-adapt-indentation (org-fixup-indentation diff))))
3936 (defun org-map-tree (fun)
3937 "Call FUN for every heading underneath the current one."
3938 (org-back-to-heading)
3939 (let ((level (funcall outline-level)))
3940 (save-excursion
3941 (funcall fun)
3942 (while (and (progn
3943 (outline-next-heading)
3944 (> (funcall outline-level) level))
3945 (not (eobp)))
3946 (funcall fun)))))
3948 (defun org-map-region (fun beg end)
3949 "Call FUN for every heading between BEG and END."
3950 (let ((org-ignore-region t))
3951 (save-excursion
3952 (setq end (copy-marker end))
3953 (goto-char beg)
3954 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
3955 (< (point) end))
3956 (funcall fun))
3957 (while (and (progn
3958 (outline-next-heading)
3959 (< (point) end))
3960 (not (eobp)))
3961 (funcall fun)))))
3963 (defun org-fixup-indentation (diff)
3964 "Change the indentation in the current entry by DIFF
3965 However, if any line in the current entry has no indentation, or if it
3966 would end up with no indentation after the change, nothing at all is done."
3967 (save-excursion
3968 (let ((end (save-excursion (outline-next-heading)
3969 (point-marker)))
3970 (prohibit (if (> diff 0)
3971 "^\\S-"
3972 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
3973 col)
3974 (unless (save-excursion (re-search-forward prohibit end t))
3975 (while (re-search-forward "^[ \t]+" end t)
3976 (goto-char (match-end 0))
3977 (setq col (current-column))
3978 (if (< diff 0) (replace-match ""))
3979 (indent-to (+ diff col))))
3980 (move-marker end nil))))
3982 ;;; Vertical tree motion, cutting and pasting of subtrees
3984 (defun org-move-subtree-up (&optional arg)
3985 "Move the current subtree up past ARG headlines of the same level."
3986 (interactive "p")
3987 (org-move-subtree-down (- (prefix-numeric-value arg))))
3989 (defun org-move-subtree-down (&optional arg)
3990 "Move the current subtree down past ARG headlines of the same level."
3991 (interactive "p")
3992 (setq arg (prefix-numeric-value arg))
3993 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
3994 'outline-get-last-sibling))
3995 (ins-point (make-marker))
3996 (cnt (abs arg))
3997 beg end txt folded)
3998 ;; Select the tree
3999 (org-back-to-heading)
4000 (setq beg (point))
4001 (save-match-data
4002 (save-excursion (outline-end-of-heading)
4003 (setq folded (org-invisible-p)))
4004 (outline-end-of-subtree))
4005 (outline-next-heading)
4006 (setq end (point))
4007 ;; Find insertion point, with error handling
4008 (goto-char beg)
4009 (while (> cnt 0)
4010 (or (and (funcall movfunc) (looking-at outline-regexp))
4011 (progn (goto-char beg)
4012 (error "Cannot move past superior level or buffer limit")))
4013 (setq cnt (1- cnt)))
4014 (if (> arg 0)
4015 ;; Moving forward - still need to move over subtree
4016 (progn (outline-end-of-subtree)
4017 (outline-next-heading)
4018 (if (not (or (looking-at (concat "^" outline-regexp))
4019 (bolp)))
4020 (newline))))
4021 (move-marker ins-point (point))
4022 (setq txt (buffer-substring beg end))
4023 (delete-region beg end)
4024 (insert txt)
4025 (goto-char ins-point)
4026 (if folded (hide-subtree))
4027 (move-marker ins-point nil)))
4029 (defvar org-subtree-clip ""
4030 "Clipboard for cut and paste of subtrees.
4031 This is actually only a copy of the kill, because we use the normal kill
4032 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4034 (defvar org-subtree-clip-folded nil
4035 "Was the last copied subtree folded?
4036 This is used to fold the tree back after pasting.")
4038 (defun org-cut-subtree ()
4039 "Cut the current subtree into the clipboard.
4040 This is a short-hand for marking the subtree and then cutting it."
4041 (interactive)
4042 (org-copy-subtree 'cut))
4044 (defun org-copy-subtree (&optional cut)
4045 "Cut the current subtree into the clipboard.
4046 This is a short-hand for marking the subtree and then copying it.
4047 If CUT is non nil, actually cut the subtree."
4048 (interactive)
4049 (let (beg end folded)
4050 (org-back-to-heading)
4051 (setq beg (point))
4052 (save-match-data
4053 (save-excursion (outline-end-of-heading)
4054 (setq folded (org-invisible-p)))
4055 (outline-end-of-subtree))
4056 (if (equal (char-after) ?\n) (forward-char 1))
4057 (setq end (point))
4058 (goto-char beg)
4059 (when (> end beg)
4060 (setq org-subtree-clip-folded folded)
4061 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4062 (setq org-subtree-clip (current-kill 0))
4063 (message "%s: Subtree with %d characters"
4064 (if cut "Cut" "Copied")
4065 (length org-subtree-clip)))))
4067 (defun org-paste-subtree (&optional level tree)
4068 "Paste the clipboard as a subtree, with modification of headline level.
4069 The entire subtree is promoted or demoted in order to match a new headline
4070 level. By default, the new level is derived from the visible headings
4071 before and after the insertion point, and taken to be the inferior headline
4072 level of the two. So if the previous visible heading is level 3 and the
4073 next is level 4 (or vice versa), level 4 will be used for insertion.
4074 This makes sure that the subtree remains an independent subtree and does
4075 not swallow low level entries.
4077 You can also force a different level, either by using a numeric prefix
4078 argument, or by inserting the heading marker by hand. For example, if the
4079 cursor is after \"*****\", then the tree will be shifted to level 5.
4081 If you want to insert the tree as is, just use \\[yank].
4083 If optional TREE is given, use this text instead of the kill ring."
4084 (interactive "P")
4085 (unless (org-kill-is-subtree-p tree)
4086 (error
4087 (substitute-command-keys
4088 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4089 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4090 (^re (concat "^\\(" outline-regexp "\\)"))
4091 (re (concat "\\(" outline-regexp "\\)"))
4092 (^re_ (concat "\\(" outline-regexp "\\)[ \t]*"))
4094 (old-level (if (string-match ^re txt)
4095 (- (match-end 0) (match-beginning 0))
4096 -1))
4097 (force-level (cond (level (prefix-numeric-value level))
4098 ((string-match
4099 ^re_ (buffer-substring (point-at-bol) (point)))
4100 (- (match-end 0) (match-beginning 0)))
4101 (t nil)))
4102 (previous-level (save-excursion
4103 (condition-case nil
4104 (progn
4105 (outline-previous-visible-heading 1)
4106 (if (looking-at re)
4107 (- (match-end 0) (match-beginning 0))
4109 (error 1))))
4110 (next-level (save-excursion
4111 (condition-case nil
4112 (progn
4113 (outline-next-visible-heading 1)
4114 (if (looking-at re)
4115 (- (match-end 0) (match-beginning 0))
4117 (error 1))))
4118 (new-level (or force-level (max previous-level next-level)))
4119 (shift (if (or (= old-level -1)
4120 (= new-level -1)
4121 (= old-level new-level))
4123 (- new-level old-level)))
4124 (shift1 shift)
4125 (delta (if (> shift 0) -1 1))
4126 (func (if (> shift 0) 'org-demote 'org-promote))
4127 (org-odd-levels-only nil)
4128 beg end)
4129 ;; Remove the forces level indicator
4130 (if force-level
4131 (delete-region (point-at-bol) (point)))
4132 ;; Make sure we start at the beginning of an empty line
4133 (if (not (bolp)) (insert "\n"))
4134 (if (not (looking-at "[ \t]*$"))
4135 (progn (insert "\n") (backward-char 1)))
4136 ;; Paste
4137 (setq beg (point))
4138 (if (string-match "[ \t\r\n]+\\'" txt)
4139 (setq txt (replace-match "\n" t t txt)))
4140 (insert txt)
4141 (setq end (point))
4142 (if (looking-at "[ \t\r\n]+")
4143 (replace-match "\n"))
4144 (goto-char beg)
4145 ;; Shift if necessary
4146 (if (= shift 0)
4147 (message "Pasted at level %d, without shift" new-level)
4148 (save-restriction
4149 (narrow-to-region beg end)
4150 (while (not (= shift 0))
4151 (org-map-region func (point-min) (point-max))
4152 (setq shift (+ delta shift)))
4153 (goto-char (point-min))
4154 (message "Pasted at level %d, with shift by %d levels"
4155 new-level shift1)))
4156 (if (and kill-ring
4157 (eq org-subtree-clip (current-kill 0))
4158 org-subtree-clip-folded)
4159 ;; The tree was folded before it was killed/copied
4160 (hide-subtree))))
4162 (defun org-kill-is-subtree-p (&optional txt)
4163 "Check if the current kill is an outline subtree, or a set of trees.
4164 Returns nil if kill does not start with a headline, or if the first
4165 headline level is not the largest headline level in the tree.
4166 So this will actually accept several entries of equal levels as well,
4167 which is OK for `org-paste-subtree'.
4168 If optional TXT is given, check this string instead of the current kill."
4169 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4170 (start-level (and kill
4171 (string-match (concat "\\`" outline-regexp) kill)
4172 (- (match-end 0) (match-beginning 0))))
4173 (re (concat "^" outline-regexp))
4174 (start 1))
4175 (if (not start-level)
4176 nil ;; does not even start with a heading
4177 (catch 'exit
4178 (while (setq start (string-match re kill (1+ start)))
4179 (if (< (- (match-end 0) (match-beginning 0)) start-level)
4180 (throw 'exit nil)))
4181 t))))
4183 (defun org-narrow-to-subtree ()
4184 "Narrow buffer to the current subtree."
4185 (interactive)
4186 (save-excursion
4187 (narrow-to-region
4188 (progn (org-back-to-heading) (point))
4189 (progn (org-end-of-subtree t) (point)))))
4191 ;;; Plain list items
4193 (defun org-at-item-p ()
4194 "Is point in a line starting a hand-formatted item?"
4195 (let ((llt org-plain-list-ordered-item-terminator))
4196 (save-excursion
4197 (goto-char (point-at-bol))
4198 (looking-at
4199 (cond
4200 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4201 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4202 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+)\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
4203 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
4205 (defun org-at-item-checkbox-p ()
4206 "Is point at a line starting a plain-list item with a checklet?"
4207 (and (org-at-item-p)
4208 (save-excursion
4209 (goto-char (match-end 0))
4210 (skip-chars-forward " \t")
4211 (looking-at "\\[[ X]\\]"))))
4213 (defun org-toggle-checkbox (&optional arg)
4214 "Toggle the checkbox in the current line."
4215 (interactive "P")
4216 (catch 'exit
4217 (let (beg end status (firstnew 'unknown))
4218 (cond
4219 ((org-region-active-p)
4220 (setq beg (region-beginning) end (region-end)))
4221 ((org-on-heading-p)
4222 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
4223 ((org-at-item-checkbox-p)
4224 (save-excursion
4225 (replace-match (if (equal (match-string 0) "[ ]") "[X]" "[ ]") t t))
4226 (throw 'exit t))
4227 (t (error "Not at a checkbox or heading, and no active region")))
4228 (save-excursion
4229 (goto-char beg)
4230 (while (< (point) end)
4231 (when (org-at-item-checkbox-p)
4232 (setq status (equal (match-string 0) "[X]"))
4233 (when (eq firstnew 'unknown)
4234 (setq firstnew (not status)))
4235 (replace-match
4236 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
4237 (beginning-of-line 2)))))
4238 (org-update-checkbox-count-maybe))
4240 (defun org-update-checkbox-count-maybe ()
4241 "Update checkbox statistics unless turned off by user."
4242 (when org-provide-checkbox-statistics
4243 (org-update-checkbox-count)))
4245 (defun org-update-checkbox-count (&optional all)
4246 "Update the checkbox statistics in the current section.
4247 This will find all statistic cookies like [57%] and [6/12] and update them
4248 with the current numbers. With optional prefix argument ALL, do this for
4249 the whole buffer."
4250 (interactive "P")
4251 (save-excursion
4252 (let* ((buffer-invisibility-spec nil)
4253 (beg (progn (outline-back-to-heading) (point)))
4254 (end (move-marker (make-marker)
4255 (progn (outline-next-heading) (point))))
4256 (re "\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)")
4257 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[ X]\\]\\)")
4258 b1 e1 f1 c-on c-off lim (cstat 0))
4259 (when all
4260 (goto-char (point-min))
4261 (outline-next-heading)
4262 (setq beg (point) end (point-max)))
4263 (goto-char beg)
4264 (while (re-search-forward re end t)
4265 (setq cstat (1+ cstat)
4266 b1 (match-beginning 0)
4267 e1 (match-end 0)
4268 f1 (match-beginning 1)
4269 lim (cond
4270 ((org-on-heading-p) (outline-next-heading) (point))
4271 ((org-at-item-p) (org-end-of-item) (point))
4272 (t nil))
4273 c-on 0 c-off 0)
4274 (goto-char e1)
4275 (when lim
4276 (while (re-search-forward re-box lim t)
4277 (if (equal (match-string 2) "[ ]")
4278 (setq c-off (1+ c-off))
4279 (setq c-on (1+ c-on))))
4280 (delete-region b1 e1)
4281 (goto-char b1)
4282 (insert (if f1
4283 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
4284 (format "[%d/%d]" c-on (+ c-on c-off))))))
4285 (when (interactive-p)
4286 (message "Checkbox satistics updated %s (%d places)"
4287 (if all "in entire file" "in current outline entry") cstat)))))
4289 (defun org-get-checkbox-statistics-face ()
4290 "Select the face for checkbox statistics.
4291 The face will be `org-done' when all relevant boxes are checked. Otherwise
4292 it will be `org-todo'."
4293 (if (match-end 1)
4294 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
4295 (if (and (> (match-end 2) (match-beginning 2))
4296 (equal (match-string 2) (match-string 3)))
4297 'org-done
4298 'org-todo)))
4300 (defun org-get-indentation (&optional line)
4301 "Get the indentation of the current line, interpreting tabs.
4302 When LINE is given, assume it represents a line and compute its indentation."
4303 (if line
4304 (if (string-match "^ *" (org-remove-tabs line))
4305 (match-end 0))
4306 (save-excursion
4307 (beginning-of-line 1)
4308 (skip-chars-forward " \t")
4309 (current-column))))
4311 (defun org-remove-tabs (s &optional width)
4312 "Replace tabulators in S with spaces.
4313 Assumes that s is a single line, starting in column 0."
4314 (setq width (or width tab-width))
4315 (while (string-match "\t" s)
4316 (setq s (replace-match
4317 (make-string
4318 (- (* width (/ (+ (match-beginning 0) width) width))
4319 (match-beginning 0)) ?\ )
4320 t t s)))
4323 ;; FIXME: document properly.
4324 (defun org-fix-indentation (line ind)
4325 "If the current indenation is smaller than ind1, leave it alone.
4326 If it is larger than ind, reduce it by ind."
4327 (let* ((l (org-remove-tabs line))
4328 (i (org-get-indentation l))
4329 (i1 (car ind)) (i2 (cdr ind)))
4330 (if (>= i i2) (setq l (substring line i2)))
4331 (if (> i1 0)
4332 (concat (make-string i1 ?\ ) l)
4333 l)))
4335 (defun org-beginning-of-item ()
4336 "Go to the beginning of the current hand-formatted item.
4337 If the cursor is not in an item, throw an error."
4338 (interactive)
4339 (let ((pos (point))
4340 (limit (save-excursion (org-back-to-heading)
4341 (beginning-of-line 2) (point)))
4342 ind ind1)
4343 (if (org-at-item-p)
4344 (beginning-of-line 1)
4345 (beginning-of-line 1)
4346 (skip-chars-forward " \t")
4347 (setq ind (current-column))
4348 (if (catch 'exit
4349 (while t
4350 (beginning-of-line 0)
4351 (if (< (point) limit) (throw 'exit nil))
4352 (unless (looking-at "[ \t]*$")
4353 (skip-chars-forward " \t")
4354 (setq ind1 (current-column))
4355 (if (< ind1 ind)
4356 (throw 'exit (org-at-item-p))))))
4358 (goto-char pos)
4359 (error "Not in an item")))))
4361 (defun org-end-of-item ()
4362 "Go to the end of the current hand-formatted item.
4363 If the cursor is not in an item, throw an error."
4364 (interactive)
4365 (let ((pos (point))
4366 (limit (save-excursion (outline-next-heading) (point)))
4367 (ind (save-excursion
4368 (org-beginning-of-item)
4369 (skip-chars-forward " \t")
4370 (current-column)))
4371 ind1)
4372 (if (catch 'exit
4373 (while t
4374 (beginning-of-line 2)
4375 (if (>= (point) limit) (throw 'exit t))
4376 (unless (looking-at "[ \t]*$")
4377 (skip-chars-forward " \t")
4378 (setq ind1 (current-column))
4379 (if (<= ind1 ind) (throw 'exit t)))))
4380 (beginning-of-line 1)
4381 (goto-char pos)
4382 (error "Not in an item"))))
4384 (defun org-next-item ()
4385 "Move to the beginning of the next item in the current plain list.
4386 Error if not at a plain list, or if this is the last item in the list."
4387 (interactive)
4388 (let (ind ind1 (pos (point)))
4389 (org-beginning-of-item)
4390 (setq ind (org-get-indentation))
4391 (org-end-of-item)
4392 (setq ind1 (org-get-indentation))
4393 (unless (and (org-at-item-p) (= ind ind1))
4394 (goto-char pos)
4395 (error "On last item"))))
4397 (defun org-previous-item ()
4398 "Move to the beginning of the previous item in the current plain list.
4399 Error if not at a plain list, or if this is the last item in the list."
4400 (interactive)
4401 (let (beg ind (pos (point)))
4402 (org-beginning-of-item)
4403 (setq beg (point))
4404 (setq ind (org-get-indentation))
4405 (goto-char beg)
4406 (catch 'exit
4407 (while t
4408 (beginning-of-line 0)
4409 (if (looking-at "[ \t]*$")
4411 (if (<= (org-get-indentation) ind)
4412 (throw 'exit t)))))
4413 (condition-case nil
4414 (org-beginning-of-item)
4415 (error (goto-char pos)
4416 (error "On first item")))))
4418 (defun org-move-item-down ()
4419 "Move the plain list item at point down, i.e. swap with following item.
4420 Subitems (items with larger indentation) are considered part of the item,
4421 so this really moves item trees."
4422 (interactive)
4423 (let (beg end ind ind1 (pos (point)) txt)
4424 (org-beginning-of-item)
4425 (setq beg (point))
4426 (setq ind (org-get-indentation))
4427 (org-end-of-item)
4428 (setq end (point))
4429 (setq ind1 (org-get-indentation))
4430 (if (and (org-at-item-p) (= ind ind1))
4431 (progn
4432 (org-end-of-item)
4433 (setq txt (buffer-substring beg end))
4434 (save-excursion
4435 (delete-region beg end))
4436 (setq pos (point))
4437 (insert txt)
4438 (goto-char pos)
4439 (org-maybe-renumber-ordered-list))
4440 (goto-char pos)
4441 (error "Cannot move this item further down"))))
4443 (defun org-move-item-up (arg)
4444 "Move the plain list item at point up, i.e. swap with previous item.
4445 Subitems (items with larger indentation) are considered part of the item,
4446 so this really moves item trees."
4447 (interactive "p")
4448 (let (beg end ind ind1 (pos (point)) txt)
4449 (org-beginning-of-item)
4450 (setq beg (point))
4451 (setq ind (org-get-indentation))
4452 (org-end-of-item)
4453 (setq end (point))
4454 (goto-char beg)
4455 (catch 'exit
4456 (while t
4457 (beginning-of-line 0)
4458 (if (looking-at "[ \t]*$")
4460 (if (<= (setq ind1 (org-get-indentation)) ind)
4461 (throw 'exit t)))))
4462 (condition-case nil
4463 (org-beginning-of-item)
4464 (error (goto-char beg)
4465 (error "Cannot move this item further up")))
4466 (setq ind1 (org-get-indentation))
4467 (if (and (org-at-item-p) (= ind ind1))
4468 (progn
4469 (setq txt (buffer-substring beg end))
4470 (save-excursion
4471 (delete-region beg end))
4472 (setq pos (point))
4473 (insert txt)
4474 (goto-char pos)
4475 (org-maybe-renumber-ordered-list))
4476 (goto-char pos)
4477 (error "Cannot move this item further up"))))
4479 (defun org-maybe-renumber-ordered-list ()
4480 "Renumber the ordered list at point if setup allows it.
4481 This tests the user option `org-auto-renumber-ordered-lists' before
4482 doing the renumbering."
4483 (and org-auto-renumber-ordered-lists
4484 (org-at-item-p)
4485 (match-beginning 3)
4486 (org-renumber-ordered-list 1)))
4488 (defun org-get-string-indentation (s)
4489 "What indentation has S due to SPACE and TAB at the beginning of the string?"
4490 (let ((n -1) (i 0) (w tab-width) c)
4491 (catch 'exit
4492 (while (< (setq n (1+ n)) (length s))
4493 (setq c (aref s n))
4494 (cond ((= c ?\ ) (setq i (1+ i)))
4495 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
4496 (t (throw 'exit t)))))
4499 (defun org-renumber-ordered-list (arg)
4500 "Renumber an ordered plain list.
4501 Cursor needs to be in the first line of an item, the line that starts
4502 with something like \"1.\" or \"2)\"."
4503 (interactive "p")
4504 (unless (and (org-at-item-p)
4505 (match-beginning 3))
4506 (error "This is not an ordered list"))
4507 (let ((line (org-current-line))
4508 (col (current-column))
4509 (ind (org-get-string-indentation
4510 (buffer-substring (point-at-bol) (match-beginning 3))))
4511 ;; (term (substring (match-string 3) -1))
4512 ind1 (n (1- arg)))
4513 ;; find where this list begins
4514 (catch 'exit
4515 (while t
4516 (catch 'next
4517 (beginning-of-line 0)
4518 (if (looking-at "[ \t]*$") (throw 'next t))
4519 (skip-chars-forward " \t") (setq ind1 (current-column))
4520 (if (or (< ind1 ind)
4521 (and (= ind1 ind)
4522 (not (org-at-item-p))))
4523 (throw 'exit t)))))
4524 ;; Walk forward and replace these numbers
4525 (catch 'exit
4526 (while t
4527 (catch 'next
4528 (beginning-of-line 2)
4529 (if (eobp) (throw 'exit nil))
4530 (if (looking-at "[ \t]*$") (throw 'next nil))
4531 (skip-chars-forward " \t") (setq ind1 (current-column))
4532 (if (> ind1 ind) (throw 'next t))
4533 (if (< ind1 ind) (throw 'exit t))
4534 (if (not (org-at-item-p)) (throw 'exit nil))
4535 (if (not (match-beginning 3))
4536 (error "unordered bullet in ordered list. Press \\[undo] to recover"))
4537 (delete-region (match-beginning 3) (1- (match-end 3)))
4538 (goto-char (match-beginning 3))
4539 (insert (format "%d" (setq n (1+ n)))))))
4540 (goto-line line)
4541 (move-to-column col)))
4543 (defvar org-last-indent-begin-marker (make-marker))
4544 (defvar org-last-indent-end-marker (make-marker))
4546 (defun org-outdent-item (arg)
4547 "Outdent a local list item."
4548 (interactive "p")
4549 (org-indent-item (- arg)))
4551 (defun org-indent-item (arg)
4552 "Indent a local list item."
4553 (interactive "p")
4554 (unless (org-at-item-p)
4555 (error "Not on an item"))
4556 (save-excursion
4557 (let (beg end ind ind1)
4558 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
4559 (setq beg org-last-indent-begin-marker
4560 end org-last-indent-end-marker)
4561 (org-beginning-of-item)
4562 (setq beg (move-marker org-last-indent-begin-marker (point)))
4563 (org-end-of-item)
4564 (setq end (move-marker org-last-indent-end-marker (point))))
4565 (goto-char beg)
4566 (skip-chars-forward " \t") (setq ind (current-column))
4567 (if (< (+ arg ind) 0) (error "Cannot outdent beyond margin"))
4568 (while (< (point) end)
4569 (beginning-of-line 1)
4570 (skip-chars-forward " \t") (setq ind1 (current-column))
4571 (delete-region (point-at-bol) (point))
4572 (indent-to-column (+ ind1 arg))
4573 (beginning-of-line 2)))))
4575 ;;; Archiving
4577 (defun org-archive-subtree (&optional find-done)
4578 "Move the current subtree to the archive.
4579 The archive can be a certain top-level heading in the current file, or in
4580 a different file. The tree will be moved to that location, the subtree
4581 heading be marked DONE, and the current time will be added.
4583 When called with prefix argument FIND-DONE, find whole trees without any
4584 open TODO items and archive them (after getting confirmation from the user).
4585 If the cursor is not at a headline when this comand is called, try all level
4586 1 trees. If the cursor is on a headline, only try the direct children of
4587 this heading. "
4588 (interactive "P")
4589 (if find-done
4590 (org-archive-all-done)
4591 ;; Save all relevant TODO keyword-relatex variables
4593 (let ((tr-org-todo-line-regexp org-todo-line-regexp) ; keep despite compiler
4594 (tr-org-todo-keywords org-todo-keywords)
4595 (tr-org-todo-interpretation org-todo-interpretation)
4596 (tr-org-done-string org-done-string)
4597 (tr-org-todo-regexp org-todo-regexp)
4598 (tr-org-todo-line-regexp org-todo-line-regexp)
4599 (this-buffer (current-buffer))
4600 file heading buffer level newfile-p)
4601 (if (string-match "\\(.*\\)::\\(.*\\)" org-archive-location)
4602 (progn
4603 (setq file (format (match-string 1 org-archive-location)
4604 (file-name-nondirectory buffer-file-name))
4605 heading (match-string 2 org-archive-location)))
4606 (error "Invalid `org-archive-location'"))
4607 (if (> (length file) 0)
4608 (setq newfile-p (not (file-exists-p file))
4609 buffer (find-file-noselect file))
4610 (setq buffer (current-buffer)))
4611 (unless buffer
4612 (error "Cannot access file \"%s\"" file))
4613 (if (and (> (length heading) 0)
4614 (string-match "^\\*+" heading))
4615 (setq level (match-end 0))
4616 (setq heading nil level 0))
4617 (save-excursion
4618 ;; We first only copy, in case something goes wrong
4619 ;; we need to protect this-command, to avoid kill-region sets it,
4620 ;; which would lead to duplication of subtrees
4621 (let (this-command) (org-copy-subtree))
4622 (set-buffer buffer)
4623 ;; Enforce org-mode for the archive buffer
4624 (if (not (org-mode-p))
4625 ;; Force the mode for future visits.
4626 (let ((org-insert-mode-line-in-empty-file t))
4627 (call-interactively 'org-mode)))
4628 (when newfile-p
4629 (goto-char (point-max))
4630 (insert (format "\nArchived entries from file %s\n\n"
4631 (buffer-file-name this-buffer))))
4632 ;; Force the TODO keywords of the original buffer
4633 (let ((org-todo-line-regexp tr-org-todo-line-regexp)
4634 (org-todo-keywords tr-org-todo-keywords)
4635 (org-todo-interpretation tr-org-todo-interpretation)
4636 (org-done-string tr-org-done-string)
4637 (org-todo-regexp tr-org-todo-regexp)
4638 (org-todo-line-regexp tr-org-todo-line-regexp))
4639 (goto-char (point-min))
4640 (if heading
4641 (progn
4642 (if (re-search-forward
4643 (concat "\\(^\\|\r\\)"
4644 (regexp-quote heading) "[ \t]*\\($\\|\r\\)")
4645 nil t)
4646 (goto-char (match-end 0))
4647 ;; Heading not found, just insert it at the end
4648 (goto-char (point-max))
4649 (or (bolp) (insert "\n"))
4650 (insert "\n" heading "\n")
4651 (end-of-line 0))
4652 ;; Make the subtree visible
4653 (show-subtree)
4654 (org-end-of-subtree t)
4655 (skip-chars-backward " \t\r\n]")
4656 (and (looking-at "[ \t\r\n]*")
4657 (replace-match "\n\n")))
4658 ;; No specific heading, just go to end of file.
4659 (goto-char (point-max)) (insert "\n"))
4660 ;; Paste
4661 (org-paste-subtree (1+ level))
4662 ;; Mark the entry as done, i.e. set to last work in org-todo-keywords
4663 (if org-archive-mark-done
4664 (org-todo (length org-todo-keywords)))
4665 ;; Move cursor to right after the TODO keyword
4666 (when org-archive-stamp-time
4667 (beginning-of-line 1)
4668 (looking-at org-todo-line-regexp)
4669 (goto-char (or (match-end 2) (match-beginning 3)))
4670 (insert "(" (format-time-string (cdr org-time-stamp-formats)
4671 (org-current-time))
4672 ")"))
4673 ;; Save the buffer, if it is not the same buffer.
4674 (if (not (eq this-buffer buffer)) (save-buffer))))
4675 ;; Here we are back in the original buffer. Everything seems to have
4676 ;; worked. So now cut the tree and finish up.
4677 (let (this-command) (org-cut-subtree))
4678 (if (and (not (eobp)) (looking-at "[ \t]*$")) (kill-line))
4679 (message "Subtree archived %s"
4680 (if (eq this-buffer buffer)
4681 (concat "under heading: " heading)
4682 (concat "in file: " (abbreviate-file-name file)))))))
4684 (defun org-archive-all-done (&optional tag)
4685 "Archive sublevels of the current tree without open TODO items.
4686 If the cursor is not on a headline, try all level 1 trees. If
4687 it is on a headline, try all direct children.
4688 When TAG is non-nil, don't move trees, but mark them with the ARCHIVE tag."
4689 (let ((re (concat "^\\*+ +" org-not-done-regexp)) re1
4690 (rea (concat ".*:" org-archive-tag ":"))
4691 (begm (make-marker))
4692 (endm (make-marker))
4693 (question (if tag "Set ARCHIVE tag (no open TODO items)? "
4694 "Move subtree to archive (no open TODO items)? "))
4695 beg end (cntarch 0))
4696 (if (org-on-heading-p)
4697 (progn
4698 (setq re1 (concat "^" (regexp-quote
4699 (make-string
4700 (1+ (- (match-end 0) (match-beginning 0)))
4701 ?*))
4702 " "))
4703 (move-marker begm (point))
4704 (move-marker endm (org-end-of-subtree)))
4705 (setq re1 "^* ")
4706 (move-marker begm (point-min))
4707 (move-marker endm (point-max)))
4708 (save-excursion
4709 (goto-char begm)
4710 (while (re-search-forward re1 endm t)
4711 (setq beg (match-beginning 0)
4712 end (save-excursion (org-end-of-subtree t) (point)))
4713 (goto-char beg)
4714 (if (re-search-forward re end t)
4715 (goto-char end)
4716 (goto-char beg)
4717 (if (and (or (not tag) (not (looking-at rea)))
4718 (y-or-n-p question))
4719 (progn
4720 (if tag
4721 (org-toggle-tag org-archive-tag 'on)
4722 (org-archive-subtree))
4723 (setq cntarch (1+ cntarch)))
4724 (goto-char end)))))
4725 (message "%d trees archived" cntarch)))
4727 (defun org-cycle-hide-archived-subtrees (state)
4728 "Re-hide all archived subtrees after a visibility state change."
4729 (when (and (not org-cycle-open-archived-trees)
4730 (not (memq state '(overview folded))))
4731 (save-excursion
4732 (let* ((globalp (memq state '(contents all)))
4733 (beg (if globalp (point-min) (point)))
4734 (end (if globalp (point-max) (org-end-of-subtree))))
4735 (org-hide-archived-subtrees beg end)
4736 (goto-char beg)
4737 (if (looking-at (concat ".*:" org-archive-tag ":"))
4738 (message (substitute-command-keys
4739 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
4741 (defun org-force-cycle-archived ()
4742 "Cycle subtree even if it is archived."
4743 (interactive)
4744 (setq this-command 'org-cycle)
4745 (let ((org-cycle-open-archived-trees t))
4746 (call-interactively 'org-cycle)))
4748 (defun org-hide-archived-subtrees (beg end)
4749 "Re-hide all archived subtrees after a visibility state change."
4750 (save-excursion
4751 (let* ((re (concat ":" org-archive-tag ":")))
4752 (goto-char beg)
4753 (while (re-search-forward re end t)
4754 (and (org-on-heading-p) (hide-subtree))
4755 (org-end-of-subtree)))))
4757 (defun org-toggle-tag (tag &optional onoff)
4758 "Toggle the tag TAG for the current line.
4759 If ONOFF is `on' or `off', don't toggle but set to this state."
4760 (unless (org-on-heading-p) (error "Not on headling"))
4761 (let (res current)
4762 (save-excursion
4763 (beginning-of-line)
4764 (if (re-search-forward "[ \t]:\\([a-zA-Z0-9_@:]+\\):[ \t]*$"
4765 (point-at-eol) t)
4766 (progn
4767 (setq current (match-string 1))
4768 (replace-match ""))
4769 (setq current ""))
4770 (setq current (nreverse (org-split-string current ":")))
4771 (cond
4772 ((eq onoff 'on)
4773 (setq res t)
4774 (or (member tag current) (push tag current)))
4775 ((eq onoff 'off)
4776 (or (not (member tag current)) (setq current (delete tag current))))
4777 (t (if (member tag current)
4778 (setq current (delete tag current))
4779 (setq res t)
4780 (push tag current))))
4781 (end-of-line 1)
4782 (when current
4783 (insert " :" (mapconcat 'identity (nreverse current) ":") ":"))
4784 (org-set-tags nil t))
4785 res))
4787 (defun org-toggle-archive-tag (&optional arg)
4788 "Toggle the archive tag for the current headline.
4789 With prefix ARG, check all children of current headline and offer tagging
4790 the children that do not contain any open TODO items."
4791 (interactive "P")
4792 (if arg
4793 (org-archive-all-done 'tag)
4794 (let (set)
4795 (save-excursion
4796 (org-back-to-heading t)
4797 (setq set (org-toggle-tag org-archive-tag))
4798 (when set (hide-subtree)))
4799 (and set (beginning-of-line 1))
4800 (message "Subtree %s" (if set "archived" "unarchived")))))
4802 (defvar org-agenda-multi nil) ; dynammically scoped
4803 (defvar org-agenda-buffer-name "*Org Agenda*")
4804 (defun org-prepare-agenda ()
4805 (if org-agenda-multi
4806 (progn
4807 (setq buffer-read-only nil)
4808 (goto-char (point-max))
4809 (unless (= (point) 1)
4810 (insert "\n" (make-string (window-width) ?=) "\n"))
4811 (narrow-to-region (point) (point-max)))
4812 (org-agenda-maybe-reset-markers 'force)
4813 (org-prepare-agenda-buffers (org-agenda-files))
4814 (unless (equal (current-buffer) (get-buffer org-agenda-buffer-name))
4815 (delete-other-windows)
4816 (switch-to-buffer-other-window
4817 (get-buffer-create org-agenda-buffer-name)))
4818 (setq buffer-read-only nil)
4819 (erase-buffer)
4820 (org-agenda-mode))
4821 (setq buffer-read-only nil)) ;;; FIXME: do we need all these occasions????
4823 (defun org-prepare-agenda-buffers (files)
4824 "Create buffers for all agenda files, protect archived trees and comments."
4825 (interactive)
4826 (let ((pa '(:org-archived t))
4827 (pc '(:org-comment t))
4828 (pall '(:org-archived t :org-comment t))
4829 (rea (concat ":" org-archive-tag ":"))
4830 bmp file re)
4831 (save-excursion
4832 (while (setq file (pop files))
4833 (org-check-agenda-file file)
4834 (set-buffer (org-get-agenda-file-buffer file))
4835 (widen)
4836 (setq bmp (buffer-modified-p))
4837 (save-excursion
4838 (remove-text-properties (point-min) (point-max) pall)
4839 (when org-agenda-skip-archived-trees
4840 (goto-char (point-min))
4841 (while (re-search-forward rea nil t)
4842 (if (org-on-heading-p)
4843 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
4844 (goto-char (point-min))
4845 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
4846 (while (re-search-forward re nil t)
4847 (add-text-properties
4848 (match-beginning 0) (org-end-of-subtree t) pc)))
4849 (set-buffer-modified-p bmp)))))
4851 (defun org-agenda-skip ()
4852 "Throw to `:skip' in places that should be skipped."
4853 (let ((p (point-at-bol)))
4854 (and org-agenda-skip-archived-trees
4855 (get-text-property p :org-archived)
4856 (org-end-of-subtree)
4857 (throw :skip t))
4858 (and (get-text-property p :org-comment)
4859 (org-end-of-subtree)
4860 (throw :skip t))
4861 (if (equal (char-after p) ?#) (throw :skip t))))
4863 (defun org-agenda-toggle-archive-tag ()
4864 "Toggle the archive tag for the current entry."
4865 (interactive)
4866 (org-agenda-check-no-diary)
4867 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
4868 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
4869 (org-agenda-error)))
4870 (buffer (marker-buffer hdmarker))
4871 (pos (marker-position hdmarker))
4872 (buffer-read-only nil)
4873 newhead)
4874 (with-current-buffer buffer
4875 (widen)
4876 (goto-char pos)
4877 (org-show-hidden-entry)
4878 (save-excursion
4879 (and (outline-next-heading)
4880 (org-flag-heading nil))) ; show the next heading
4881 (call-interactively 'org-toggle-archive-tag)
4882 (end-of-line 1)
4883 (setq newhead (org-get-heading)))
4884 (org-agenda-change-all-lines newhead hdmarker)
4885 (beginning-of-line 1)))
4887 ;;; Dynamic blocks
4889 (defun org-find-dblock (name)
4890 "Find the first dynamic block with name NAME in the buffer.
4891 If not found, stay at current position and return nil."
4892 (let (pos)
4893 (save-excursion
4894 (goto-char (point-min))
4895 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
4896 nil t)
4897 (match-beginning 0))))
4898 (if pos (goto-char pos))
4899 pos))
4901 (defconst org-dblock-start-re
4902 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
4903 "Matches the startline of a dynamic block, with parameters.")
4905 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
4906 "Matches the end of a dyhamic block.")
4908 (defun org-create-dblock (plist)
4909 "Create a dynamic block section, with parameters taken from PLIST.
4910 PLIST must containe a :name entry which is used as name of the block."
4911 (unless (bolp) (newline))
4912 (let ((name (plist-get plist :name)))
4913 (insert "#+BEGIN: " name)
4914 (while plist
4915 (if (eq (car plist) :name)
4916 (setq plist (cddr plist))
4917 (insert " " (prin1-to-string (pop plist)))))
4918 (insert "\n\n#+END:\n")
4919 (beginning-of-line -2)))
4921 (defun org-prepare-dblock ()
4922 "Prepare dynamic block for refresh.
4923 This empties the block, puts the cursor at the insert position and returns
4924 the property list including an extra property :name with the block name."
4925 (unless (looking-at org-dblock-start-re)
4926 (error "Not at a dynamic block"))
4927 (let* ((begdel (1+ (match-end 0)))
4928 (name (match-string 1))
4929 (params (append (list :name name)
4930 (read (concat "(" (match-string 3) ")")))))
4931 (unless (re-search-forward org-dblock-end-re nil t)
4932 (error "Dynamic block not terminated"))
4933 (delete-region begdel (match-beginning 0))
4934 (goto-char begdel)
4935 (open-line 1)
4936 params))
4938 (defun org-map-dblocks (&optional command)
4939 "Apply COMMAND to all dynamic blocks in the current buffer.
4940 If COMMAND is not given, use `org-update-dblock'."
4941 (let ((cmd (or command 'org-update-dblock))
4942 pos)
4943 (save-excursion
4944 (goto-char (point-min))
4945 (while (re-search-forward org-dblock-start-re nil t)
4946 (goto-char (setq pos (match-beginning 0)))
4947 (condition-case nil
4948 (funcall cmd)
4949 (error (message "Error during update of dynamic block")))
4950 (goto-char pos)
4951 (unless (re-search-forward org-dblock-end-re nil t)
4952 (error "Dynamic block not terminated"))))))
4954 (defun org-dblock-update (&optional arg)
4955 "User command for updating dynamic blocks.
4956 Update the dynamic block at point. With prefix ARG, update all dynamic
4957 blocks in the buffer."
4958 (interactive "P")
4959 (if arg
4960 (org-update-all-dblocks)
4961 (or (looking-at org-dblock-start-re)
4962 (org-beginning-of-dblock))
4963 (org-update-dblock)))
4965 (defun org-update-dblock ()
4966 "Update the dynamic block at point
4967 This means to empty the block, parse for parameters and then call
4968 the correct writing function."
4969 (let* ((pos (point))
4970 (params (org-prepare-dblock))
4971 (name (plist-get params :name))
4972 (cmd (intern (concat "org-dblock-write:" name))))
4973 (funcall cmd params)
4974 (goto-char pos)))
4976 (defun org-beginning-of-dblock ()
4977 "Find the beginning of the dynamic block at point.
4978 Error if there is no scuh block at point."
4979 (let ((pos (point))
4980 beg)
4981 (end-of-line 1)
4982 (if (and (re-search-backward org-dblock-start-re nil t)
4983 (setq beg (match-beginning 0))
4984 (re-search-forward org-dblock-end-re nil t)
4985 (> (match-end 0) pos))
4986 (goto-char beg)
4987 (goto-char pos)
4988 (error "Not in a dynamic block"))))
4990 (defun org-update-all-dblocks ()
4991 "Update all dynamic blocks in the buffer.
4992 This function can be used in a hook."
4993 (when (org-mode-p)
4994 (org-map-dblocks 'org-update-dblock)))
4997 ;;; Completion
4999 (defun org-complete (&optional arg)
5000 "Perform completion on word at point.
5001 At the beginning of a headline, this completes TODO keywords as given in
5002 `org-todo-keywords'.
5003 If the current word is preceded by a backslash, completes the TeX symbols
5004 that are supported for HTML support.
5005 If the current word is preceded by \"#+\", completes special words for
5006 setting file options.
5007 In the line after \"#+STARTUP:, complete valid keywords.\"
5008 At all other locations, this simply calls `ispell-complete-word'."
5009 (interactive "P")
5010 (catch 'exit
5011 (let* ((end (point))
5012 (beg1 (save-excursion
5013 ;FIXME??? (if (equal (char-before (point)) ?\ ) (backward-char 1))
5014 (skip-chars-backward "a-zA-Z_@0-9")
5015 (point)))
5016 (beg (save-excursion
5017 ;FIXME??? (if (equal (char-before (point)) ?\ ) (backward-char 1))
5018 (skip-chars-backward "a-zA-Z0-9_:$")
5019 (point)))
5020 (confirm (lambda (x) (stringp (car x))))
5021 (camel (equal (char-before beg) ?*))
5022 (tag (equal (char-before beg1) ?:))
5023 (texp (equal (char-before beg) ?\\))
5024 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
5025 beg)
5026 "#+"))
5027 (startup (string-match "^#\\+STARTUP:.*"
5028 (buffer-substring (point-at-bol) (point))))
5029 (completion-ignore-case opt)
5030 (type nil)
5031 (tbl nil)
5032 (table (cond
5033 (opt
5034 (setq type :opt)
5035 (mapcar (lambda (x)
5036 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
5037 (cons (match-string 2 x) (match-string 1 x)))
5038 (org-split-string (org-get-current-options) "\n")))
5039 (startup
5040 (setq type :startup)
5041 org-startup-options)
5042 (texp
5043 (setq type :tex)
5044 org-html-entities)
5045 ((string-match "\\`\\*+[ \t]*\\'"
5046 (buffer-substring (point-at-bol) beg))
5047 (setq type :todo)
5048 (mapcar 'list org-todo-keywords))
5049 (camel
5050 (setq type :camel)
5051 (save-excursion
5052 (goto-char (point-min))
5053 (while (re-search-forward org-todo-line-regexp nil t)
5054 (push (list
5055 (if org-file-link-context-use-camel-case
5056 (org-make-org-heading-camel (match-string 3) t)
5057 (org-make-org-heading-search-string
5058 (match-string 3) t)))
5059 tbl)))
5060 tbl)
5061 (tag (setq type :tag beg beg1)
5062 (or org-tag-alist (org-get-buffer-tags)))
5063 (t (progn (ispell-complete-word arg) (throw 'exit nil)))))
5064 (pattern (buffer-substring-no-properties beg end))
5065 (completion (try-completion pattern table confirm)))
5066 (cond ((eq completion t)
5067 (if (equal type :opt)
5068 (insert (substring (cdr (assoc (upcase pattern) table))
5069 (length pattern)))))
5070 ((null completion)
5071 (message "Can't find completion for \"%s\"" pattern)
5072 (ding))
5073 ((not (string= pattern completion))
5074 (delete-region beg end)
5075 (if (string-match " +$" completion)
5076 (setq completion (replace-match "" t t completion)))
5077 (insert completion)
5078 (if (get-buffer-window "*Completions*")
5079 (delete-window (get-buffer-window "*Completions*")))
5080 (if (assoc completion table)
5081 (if (eq type :todo) (insert " ")
5082 (if (eq type :tag) (insert ":"))))
5083 (if (and (equal type :opt) (assoc completion table))
5084 (message "%s" (substitute-command-keys
5085 "Press \\[org-complete] again to insert example settings"))))
5087 (message "Making completion list...")
5088 (let ((list (sort (all-completions pattern table confirm)
5089 'string<)))
5090 (with-output-to-temp-buffer "*Completions*"
5091 (condition-case nil
5092 ;; Protection needed for XEmacs and emacs 21
5093 (display-completion-list list pattern)
5094 (error (display-completion-list list)))))
5095 (message "Making completion list...%s" "done"))))))
5097 ;;; Comments, TODO and DEADLINE
5099 (defun org-toggle-comment ()
5100 "Change the COMMENT state of an entry."
5101 (interactive)
5102 (save-excursion
5103 (org-back-to-heading)
5104 (if (looking-at (concat outline-regexp
5105 "\\( +\\<" org-comment-string "\\>\\)"))
5106 (replace-match "" t t nil 1)
5107 (if (looking-at outline-regexp)
5108 (progn
5109 (goto-char (match-end 0))
5110 (insert " " org-comment-string))))))
5112 (defvar org-last-todo-state-is-todo nil
5113 "This is non-nil when the last TODO state change led to a TODO state.
5114 If the last change removed the TODO tag or switched to DONE, then
5115 this is nil.")
5117 (defun org-todo (&optional arg)
5118 "Change the TODO state of an item.
5119 The state of an item is given by a keyword at the start of the heading,
5120 like
5121 *** TODO Write paper
5122 *** DONE Call mom
5124 The different keywords are specified in the variable `org-todo-keywords'.
5125 By default the available states are \"TODO\" and \"DONE\".
5126 So for this example: when the item starts with TODO, it is changed to DONE.
5127 When it starts with DONE, the DONE is removed. And when neither TODO nor
5128 DONE are present, add TODO at the beginning of the heading.
5130 With prefix arg, use completion to determine the new state. With numeric
5131 prefix arg, switch to that state."
5132 (interactive "P")
5133 (save-excursion
5134 (org-back-to-heading)
5135 (if (looking-at outline-regexp) (goto-char (match-end 0)))
5136 (or (looking-at (concat " +" org-todo-regexp " *"))
5137 (looking-at " *"))
5138 (let* ((this (match-string 1))
5139 (completion-ignore-case t)
5140 (member (member this org-todo-keywords))
5141 (tail (cdr member))
5142 (state (cond
5143 ((equal arg '(4))
5144 ;; Read a state with completion
5145 (completing-read "State: " (mapcar (lambda(x) (list x))
5146 org-todo-keywords)
5147 nil t))
5148 ((eq arg 'right)
5149 (if this
5150 (if tail (car tail) nil)
5151 (car org-todo-keywords)))
5152 ((eq arg 'left)
5153 (if (equal member org-todo-keywords)
5155 (if this
5156 (nth (- (length org-todo-keywords) (length tail) 2)
5157 org-todo-keywords)
5158 org-done-string)))
5159 (arg
5160 ;; user requests a specific state
5161 (nth (1- (prefix-numeric-value arg))
5162 org-todo-keywords))
5163 ((null member) (car org-todo-keywords))
5164 ((null tail) nil) ;; -> first entry
5165 ((eq org-todo-interpretation 'sequence)
5166 (car tail))
5167 ((memq org-todo-interpretation '(type priority))
5168 (if (eq this-command last-command)
5169 (car tail)
5170 (if (> (length tail) 0) org-done-string nil)))
5171 (t nil)))
5172 (next (if state (concat " " state " ") " ")))
5173 (replace-match next t t)
5174 (setq org-last-todo-state-is-todo
5175 (not (equal state org-done-string)))
5176 (when org-log-done
5177 (if (equal state org-done-string)
5178 (org-add-planning-info 'closed (current-time) 'scheduled)
5179 (if (not this)
5180 (org-add-planning-info nil nil 'closed))))
5181 ;; Fixup tag positioning
5182 (and org-auto-align-tags (org-set-tags nil t))
5183 (run-hooks 'org-after-todo-state-change-hook)))
5184 ;; Fixup cursor location if close to the keyword
5185 (if (and (outline-on-heading-p)
5186 (not (bolp))
5187 (save-excursion (beginning-of-line 1)
5188 (looking-at org-todo-line-regexp))
5189 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
5190 (progn
5191 (goto-char (or (match-end 2) (match-end 1)))
5192 (just-one-space))))
5194 (defun org-log-done (&optional undone)
5195 "Add a time stamp logging that a TODO entry has been closed.
5196 When UNDONE is non-nil, remove such a time stamp again."
5197 (interactive)
5198 (let (beg end col)
5199 (save-excursion
5200 (org-back-to-heading t)
5201 (setq beg (point))
5202 (looking-at (concat outline-regexp " *"))
5203 (goto-char (match-end 0))
5204 (setq col (current-column))
5205 (outline-next-heading)
5206 (setq end (point))
5207 (goto-char beg)
5208 (when (re-search-forward (concat
5209 "[\r\n]\\([ \t]*"
5210 (regexp-quote org-closed-string)
5211 " *\\[.*?\\][^\n\r]*[\n\r]?\\)") end t)
5212 (delete-region (match-beginning 1) (match-end 1)))
5213 (unless undone
5214 (org-back-to-heading t)
5215 (skip-chars-forward "^\n\r")
5216 (goto-char (min (1+ (point)) (point-max)))
5217 (when (not (member (char-before) '(?\r ?\n)))
5218 (insert "\n"))
5219 (indent-to col)
5220 (insert org-closed-string " "
5221 (format-time-string
5222 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5223 (org-current-time))
5224 "\n")))))
5226 (defun org-show-todo-tree (arg)
5227 "Make a compact tree which shows all headlines marked with TODO.
5228 The tree will show the lines where the regexp matches, and all higher
5229 headlines above the match.
5230 With \\[universal-argument] prefix, also show the DONE entries.
5231 With a numeric prefix N, construct a sparse tree for the Nth element
5232 of `org-todo-keywords'."
5233 (interactive "P")
5234 (let ((case-fold-search nil)
5235 (kwd-re
5236 (cond ((null arg) org-not-done-regexp)
5237 ((equal arg '(4)) org-todo-regexp)
5238 ((<= (prefix-numeric-value arg) (length org-todo-keywords))
5239 (regexp-quote (nth (1- (prefix-numeric-value arg))
5240 org-todo-keywords)))
5241 (t (error "Invalid prefix argument: %s" arg)))))
5242 (message "%d TODO entries found"
5243 (org-occur (concat "^" outline-regexp " +" kwd-re )))))
5245 (defun org-deadline ()
5246 "Insert the DEADLINE: string to make a deadline.
5247 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5248 to modify it to the correct date."
5249 (interactive)
5250 (org-add-planning-info 'deadline nil 'closed))
5252 (defun org-schedule ()
5253 "Insert the SCHEDULED: string to schedule a TODO item.
5254 A timestamp is also inserted - use \\[org-timestamp-up] and \\[org-timestamp-down]
5255 to modify it to the correct date."
5256 (interactive)
5257 (org-add-planning-info 'scheduled nil 'closed))
5259 (defun org-add-planning-info (what &optional time &rest remove)
5260 "Insert new timestamp with keyword in the line directly after the headline.
5261 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
5262 If non is given, the user is prompted for a date.
5263 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
5264 be removed."
5265 (interactive)
5266 (when what (setq time (or time (org-read-date nil 'to-time))))
5267 (when (and org-insert-labeled-timestamps-at-point
5268 (member what '(scheduled deadline)))
5269 (insert
5270 (if (eq what 'scheduled) org-scheduled-string org-deadline-string)
5272 (format-time-string (car org-time-stamp-formats) time))
5273 (setq what nil))
5274 (save-excursion
5275 (let (col list elt (buffer-invisibility-spec nil) ts)
5276 (org-back-to-heading t)
5277 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
5278 (goto-char (match-end 1))
5279 (setq col (current-column))
5280 (goto-char (1+ (match-end 0)))
5281 (if (and (not (looking-at outline-regexp))
5282 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
5283 "[^\r\n]*"))
5284 (not (equal (match-string 1) org-clock-string)))
5285 (narrow-to-region (match-beginning 0) (match-end 0))
5286 (insert "\n")
5287 (backward-char 1)
5288 (narrow-to-region (point) (point))
5289 (indent-to-column col))
5290 ;; Check if we have to remove something.
5291 (setq list (cons what remove))
5292 (while list
5293 (setq elt (pop list))
5294 (goto-char (point-min))
5295 (when (or (and (eq elt 'scheduled)
5296 (re-search-forward org-scheduled-time-regexp nil t))
5297 (and (eq elt 'deadline)
5298 (re-search-forward org-deadline-time-regexp nil t))
5299 (and (eq elt 'closed)
5300 (re-search-forward org-closed-time-regexp nil t)))
5301 (replace-match "")
5302 (if (looking-at " +") (replace-match ""))))
5303 (goto-char (point-max))
5304 (when what
5305 (insert
5306 (if (not (equal (char-before) ?\ )) " " "")
5307 (cond ((eq what 'scheduled) org-scheduled-string)
5308 ((eq what 'deadline) org-deadline-string)
5309 ((eq what 'closed) org-closed-string))
5310 " ")
5311 (insert
5312 (setq ts
5313 (format-time-string
5314 (if (eq what 'closed)
5315 (concat "[" (substring (cdr org-time-stamp-formats) 1 -1) "]")
5316 (car org-time-stamp-formats))
5317 time))))
5318 (goto-char (point-min))
5319 (widen)
5320 (if (looking-at "[ \t]+\r?\n")
5321 (replace-match ""))
5322 ts)))
5324 (defun org-occur (regexp &optional callback)
5325 "Make a compact tree which shows all matches of REGEXP.
5326 The tree will show the lines where the regexp matches, and all higher
5327 headlines above the match. It will also show the heading after the match,
5328 to make sure editing the matching entry is easy.
5329 If CALLBACK is non-nil, it is a function which is called to confirm
5330 that the match should indeed be shown."
5331 (interactive "sRegexp: ")
5332 (org-remove-occur-highlights nil nil t)
5333 (let ((cnt 0))
5334 (save-excursion
5335 (goto-char (point-min))
5336 (org-overview)
5337 (while (re-search-forward regexp nil t)
5338 (when (or (not callback)
5339 (save-match-data (funcall callback)))
5340 (setq cnt (1+ cnt))
5341 (org-highlight-new-match (match-beginning 0) (match-end 0))
5342 (org-show-hierarchy-above))))
5343 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
5344 nil 'local)
5345 (unless org-sparse-tree-open-archived-trees
5346 (org-hide-archived-subtrees (point-min) (point-max)))
5347 (run-hooks 'org-occur-hook)
5348 (if (interactive-p)
5349 (message "%d match(es) for regexp %s" cnt regexp))
5350 cnt))
5352 (defun org-show-hierarchy-above ()
5353 "Make sure point and the headings hierarchy above is visible."
5354 (catch 'exit
5355 (if (org-on-heading-p t)
5356 (org-flag-heading nil) ; only show the heading
5357 (and (or (org-invisible-p) (org-invisible-p2))
5358 (org-show-hidden-entry))) ; show entire entry
5359 (save-excursion
5360 (and org-show-following-heading
5361 (outline-next-heading)
5362 (org-flag-heading nil))) ; show the next heading
5363 (when org-show-hierarchy-above
5364 (save-excursion ; show all higher headings
5365 (while (and (condition-case nil
5366 (progn (org-up-heading-all 1) t)
5367 (error nil))
5368 (not (bobp)))
5369 (org-flag-heading nil))))))
5371 ;; Overlay compatibility functions
5372 (defun org-make-overlay (beg end &optional buffer)
5373 (if (featurep 'xemacs)
5374 (make-extent beg end buffer)
5375 (make-overlay beg end buffer)))
5376 (defun org-delete-overlay (ovl)
5377 (if (featurep 'xemacs) (delete-extent ovl) (delete-overlay ovl)))
5378 (defun org-detatch-overlay (ovl)
5379 (if (featurep 'xemacs) (detach-extent ovl) (delete-overlay ovl)))
5380 (defun org-move-overlay (ovl beg end &optional buffer)
5381 (if (featurep 'xemacs)
5382 (set-extent-endpoints ovl beg end buffer)
5383 (move-overlay ovl beg end buffer)))
5384 (defun org-overlay-put (ovl prop value)
5385 (if (featurep 'xemacs)
5386 (set-extent-property ovl prop value)
5387 (overlay-put ovl prop value)))
5388 (defun org-overlays-at (pos)
5389 (if (featurep 'xemacs) (extents-at pos) (overlays-at pos)))
5390 (defun org-overlay-start (o)
5391 (if (featurep 'xemacs) (extent-start-position o) (overlay-start o)))
5392 (defun org-overlay-end (o)
5393 (if (featurep 'xemacs) (extent-end-position o) (overlay-end o)))
5395 (defvar org-occur-highlights nil)
5396 (make-variable-buffer-local 'org-occur-highlights)
5397 (defun org-highlight-new-match (beg end)
5398 "Highlight from BEG to END and mark the highlight is an occur headline."
5399 (let ((ov (org-make-overlay beg end)))
5400 (org-overlay-put ov 'face 'secondary-selection)
5401 (push ov org-occur-highlights)))
5403 (defvar org-inhibit-highlight-removal nil)
5404 (defun org-remove-occur-highlights (&optional beg end noremove)
5405 "Remove the occur highlights from the buffer.
5406 BEG and END are ignored. If NOREMOVE is nil, remove this function
5407 from the `before-change-functions' in the current buffer."
5408 (interactive)
5409 (unless org-inhibit-highlight-removal
5410 (mapc 'org-delete-overlay org-occur-highlights)
5411 (setq org-occur-highlights nil)
5412 (unless noremove
5413 (remove-hook 'before-change-functions
5414 'org-remove-occur-highlights 'local))))
5416 ;;; Priorities
5418 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z]\\)\\] ?\\)"
5419 "Regular expression matching the priority indicator.")
5421 (defvar org-remove-priority-next-time nil)
5423 (defun org-priority-up ()
5424 "Increase the priority of the current item."
5425 (interactive)
5426 (org-priority 'up))
5428 (defun org-priority-down ()
5429 "Decrease the priority of the current item."
5430 (interactive)
5431 (org-priority 'down))
5433 (defun org-priority (&optional action)
5434 "Change the priority of an item by ARG.
5435 ACTION can be set, up, or down."
5436 (interactive)
5437 (setq action (or action 'set))
5438 (let (current new news have remove)
5439 (save-excursion
5440 (org-back-to-heading)
5441 (if (looking-at org-priority-regexp)
5442 (setq current (string-to-char (match-string 2))
5443 have t)
5444 (setq current org-default-priority))
5445 (cond
5446 ((eq action 'set)
5447 (message "Priority A-%c, SPC to remove: " org-lowest-priority)
5448 (setq new (read-char-exclusive))
5449 (cond ((equal new ?\ ) (setq remove t))
5450 ((or (< (upcase new) ?A) (> (upcase new) org-lowest-priority))
5451 (error "Priority must be between `%c' and `%c'"
5452 ?A org-lowest-priority))))
5453 ((eq action 'up)
5454 (setq new (1- current)))
5455 ((eq action 'down)
5456 (setq new (1+ current)))
5457 (t (error "Invalid action")))
5458 (setq new (min (max ?A (upcase new)) org-lowest-priority))
5459 (setq news (format "%c" new))
5460 (if have
5461 (if remove
5462 (replace-match "" t t nil 1)
5463 (replace-match news t t nil 2))
5464 (if remove
5465 (error "No priority cookie found in line")
5466 (looking-at org-todo-line-regexp)
5467 (if (match-end 2)
5468 (progn
5469 (goto-char (match-end 2))
5470 (insert " [#" news "]"))
5471 (goto-char (match-beginning 3))
5472 (insert "[#" news "] ")))))
5473 (if remove
5474 (message "Priority removed")
5475 (message "Priority of current item set to %s" news))))
5478 (defun org-get-priority (s)
5479 "Find priority cookie and return priority."
5480 (save-match-data
5481 (if (not (string-match org-priority-regexp s))
5482 (* 1000 (- org-lowest-priority org-default-priority))
5483 (* 1000 (- org-lowest-priority
5484 (string-to-char (match-string 2 s)))))))
5486 ;;; Timestamps
5488 (defvar org-last-changed-timestamp nil)
5490 (defun org-time-stamp (arg)
5491 "Prompt for a date/time and insert a time stamp.
5492 If the user specifies a time like HH:MM, or if this command is called
5493 with a prefix argument, the time stamp will contain date and time.
5494 Otherwise, only the date will be included. All parts of a date not
5495 specified by the user will be filled in from the current date/time.
5496 So if you press just return without typing anything, the time stamp
5497 will represent the current date/time. If there is already a timestamp
5498 at the cursor, it will be modified."
5499 (interactive "P")
5500 (let ((fmt (if arg (cdr org-time-stamp-formats)
5501 (car org-time-stamp-formats)))
5502 (org-time-was-given nil)
5503 time)
5504 (cond
5505 ((and (org-at-timestamp-p)
5506 (eq last-command 'org-time-stamp)
5507 (eq this-command 'org-time-stamp))
5508 (insert "--")
5509 (setq time (let ((this-command this-command))
5510 (org-read-date arg 'totime)))
5511 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5512 (insert (format-time-string fmt time)))
5513 ((org-at-timestamp-p)
5514 (setq time (let ((this-command this-command))
5515 (org-read-date arg 'totime)))
5516 (and (org-at-timestamp-p) (replace-match
5517 (setq org-last-changed-timestamp
5518 (format-time-string fmt time))
5519 t t))
5520 (message "Timestamp updated"))
5522 (setq time (let ((this-command this-command))
5523 (org-read-date arg 'totime)))
5524 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5525 (insert (format-time-string fmt time))))))
5527 (defun org-time-stamp-inactive (&optional arg)
5528 "Insert an inactive time stamp.
5529 An inactive time stamp is enclosed in square brackets instead of angle
5530 brackets. It is inactive in the sense that it does not trigger agenda entries,
5531 does not link to the calendar and cannot be changed with the S-cursor keys.
5532 So these are more for recording a certain time/date."
5533 (interactive "P")
5534 (let ((fmt (if arg (cdr org-time-stamp-formats)
5535 (car org-time-stamp-formats)))
5536 (org-time-was-given nil)
5537 time)
5538 (setq time (org-read-date arg 'totime))
5539 (if org-time-was-given (setq fmt (cdr org-time-stamp-formats)))
5540 (setq fmt (concat "[" (substring fmt 1 -1) "]"))
5541 (insert (format-time-string fmt time))))
5543 (defvar org-date-ovl (org-make-overlay 1 1))
5544 (org-overlay-put org-date-ovl 'face 'org-warning)
5545 (org-detatch-overlay org-date-ovl)
5547 (defun org-read-date (&optional with-time to-time)
5548 "Read a date and make things smooth for the user.
5549 The prompt will suggest to enter an ISO date, but you can also enter anything
5550 which will at least partially be understood by `parse-time-string'.
5551 Unrecognized parts of the date will default to the current day, month, year,
5552 hour and minute. For example,
5553 3-2-5 --> 2003-02-05
5554 feb 15 --> currentyear-02-15
5555 sep 12 9 --> 2009-09-12
5556 12:45 --> today 12:45
5557 22 sept 0:34 --> currentyear-09-22 0:34
5558 12 --> currentyear-currentmonth-12
5559 Fri --> nearest Friday (today or later)
5560 etc.
5561 The function understands only English month and weekday abbreviations,
5562 but this can be configured with the variables `parse-time-months' and
5563 `parse-time-weekdays'.
5565 While prompting, a calendar is popped up - you can also select the
5566 date with the mouse (button 1). The calendar shows a period of three
5567 months. To scroll it to other months, use the keys `>' and `<'.
5568 If you don't like the calendar, turn it off with
5569 \(setq org-popup-calendar-for-date-prompt nil)
5571 With optional argument TO-TIME, the date will immediately be converted
5572 to an internal time.
5573 With an optional argument WITH-TIME, the prompt will suggest to also
5574 insert a time. Note that when WITH-TIME is not set, you can still
5575 enter a time, and this function will inform the calling routine about
5576 this change. The calling routine may then choose to change the format
5577 used to insert the time stamp into the buffer to include the time."
5578 (require 'parse-time)
5579 (let* ((org-time-stamp-rounding-minutes
5580 (if (equal with-time '(16)) 0 org-time-stamp-rounding-minutes))
5581 (ct (org-current-time))
5582 (default-time
5583 ;; Default time is either today, or, when entering a range,
5584 ;; the range start.
5585 (if (save-excursion
5586 (re-search-backward
5587 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
5588 (- (point) 20) t))
5589 (apply
5590 'encode-time
5591 (mapcar (lambda(x) (or x 0))
5592 (parse-time-string (match-string 1))))
5593 ct))
5594 (calendar-move-hook nil)
5595 (view-diary-entries-initially nil)
5596 (view-calendar-holidays-initially nil)
5597 (timestr (format-time-string
5598 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") default-time))
5599 (prompt (format "YYYY-MM-DD [%s]: " timestr))
5600 ans ans1 ans2
5601 second minute hour day month year tl wday wday1)
5603 (if org-popup-calendar-for-date-prompt
5604 (save-excursion
5605 (save-window-excursion
5606 (calendar)
5607 (calendar-forward-day (- (time-to-days default-time)
5608 (calendar-absolute-from-gregorian
5609 (calendar-current-date))))
5610 (org-eval-in-calendar nil)
5611 (let* ((old-map (current-local-map))
5612 (map (copy-keymap calendar-mode-map))
5613 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
5614 (define-key map (kbd "RET") 'org-calendar-select)
5615 (define-key map (if (featurep 'xemacs) [button1] [mouse-1])
5616 'org-calendar-select-mouse)
5617 (define-key map (if (featurep 'xemacs) [button2] [mouse-2])
5618 'org-calendar-select-mouse)
5619 (define-key minibuffer-local-map [(meta shift left)]
5620 (lambda () (interactive)
5621 (org-eval-in-calendar '(calendar-backward-month 1))))
5622 (define-key minibuffer-local-map [(meta shift right)]
5623 (lambda () (interactive)
5624 (org-eval-in-calendar '(calendar-forward-month 1))))
5625 (define-key minibuffer-local-map [(shift up)]
5626 (lambda () (interactive)
5627 (org-eval-in-calendar '(calendar-backward-week 1))))
5628 (define-key minibuffer-local-map [(shift down)]
5629 (lambda () (interactive)
5630 (org-eval-in-calendar '(calendar-forward-week 1))))
5631 (define-key minibuffer-local-map [(shift left)]
5632 (lambda () (interactive)
5633 (org-eval-in-calendar '(calendar-backward-day 1))))
5634 (define-key minibuffer-local-map [(shift right)]
5635 (lambda () (interactive)
5636 (org-eval-in-calendar '(calendar-forward-day 1))))
5637 (define-key minibuffer-local-map ">"
5638 (lambda () (interactive)
5639 (org-eval-in-calendar '(scroll-calendar-left 1))))
5640 (define-key minibuffer-local-map "<"
5641 (lambda () (interactive)
5642 (org-eval-in-calendar '(scroll-calendar-right 1))))
5643 (unwind-protect
5644 (progn
5645 (use-local-map map)
5646 (setq ans (read-string prompt "" nil nil))
5647 (if (not (string-match "\\S-" ans)) (setq ans nil))
5648 (setq ans (or ans1 ans ans2)))
5649 (use-local-map old-map)))))
5650 ;; Naked prompt only
5651 (setq ans (read-string prompt "" nil timestr)))
5652 (org-detatch-overlay org-date-ovl)
5654 (if (string-match
5655 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
5656 (progn
5657 (setq year (if (match-end 2)
5658 (string-to-number (match-string 2 ans))
5659 (string-to-number (format-time-string "%Y")))
5660 month (string-to-number (match-string 3 ans))
5661 day (string-to-number (match-string 4 ans)))
5662 (if (< year 100) (setq year (+ 2000 year)))
5663 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
5664 t nil ans))))
5665 (setq tl (parse-time-string ans)
5666 year (or (nth 5 tl) (string-to-number (format-time-string "%Y" ct)))
5667 month (or (nth 4 tl) (string-to-number (format-time-string "%m" ct)))
5668 day (or (nth 3 tl) (string-to-number (format-time-string "%d" ct)))
5669 hour (or (nth 2 tl) (string-to-number (format-time-string "%H" ct)))
5670 minute (or (nth 1 tl) (string-to-number (format-time-string "%M" ct)))
5671 second (or (nth 0 tl) 0)
5672 wday (nth 6 tl))
5673 (when (and wday (not (nth 3 tl)))
5674 ;; Weekday was given, but no day, so pick that day in the week
5675 ;; on or after the derived date.
5676 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
5677 (unless (equal wday wday1)
5678 (setq day (+ day (% (- wday wday1 -7) 7)))))
5679 (if (and (boundp 'org-time-was-given)
5680 (nth 2 tl))
5681 (setq org-time-was-given t))
5682 (if (< year 100) (setq year (+ 2000 year)))
5683 (if to-time
5684 (encode-time second minute hour day month year)
5685 (if (or (nth 1 tl) (nth 2 tl))
5686 (format "%04d-%02d-%02d %02d:%02d" year month day hour minute)
5687 (format "%04d-%02d-%02d" year month day)))))
5689 (defun org-eval-in-calendar (form)
5690 "Eval FORM in the calendar window and return to current window.
5691 Also, store the cursor date in variable ans2."
5692 (let ((sw (selected-window)))
5693 (select-window (get-buffer-window "*Calendar*"))
5694 (eval form)
5695 (when (calendar-cursor-to-date)
5696 (let* ((date (calendar-cursor-to-date))
5697 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5698 (setq ans2 (format-time-string "%Y-%m-%d" time))))
5699 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
5700 (select-window sw)))
5702 (defun org-calendar-select ()
5703 "Return to `org-read-date' with the date currently selected.
5704 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5705 (interactive)
5706 (when (calendar-cursor-to-date)
5707 (let* ((date (calendar-cursor-to-date))
5708 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5709 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5710 (if (active-minibuffer-window) (exit-minibuffer))))
5712 (defun org-calendar-select-mouse (ev)
5713 "Return to `org-read-date' with the date currently selected.
5714 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
5715 (interactive "e")
5716 (mouse-set-point ev)
5717 (when (calendar-cursor-to-date)
5718 (let* ((date (calendar-cursor-to-date))
5719 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
5720 (setq ans1 (format-time-string "%Y-%m-%d" time)))
5721 (if (active-minibuffer-window) (exit-minibuffer))))
5723 (defun org-check-deadlines (ndays)
5724 "Check if there are any deadlines due or past due.
5725 A deadline is considered due if it happens within `org-deadline-warning-days'
5726 days from today's date. If the deadline appears in an entry marked DONE,
5727 it is not shown. The prefix arg NDAYS can be used to test that many
5728 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
5729 (interactive "P")
5730 (let* ((org-warn-days
5731 (cond
5732 ((equal ndays '(4)) 100000)
5733 (ndays (prefix-numeric-value ndays))
5734 (t org-deadline-warning-days)))
5735 (case-fold-search nil)
5736 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
5737 (callback
5738 (lambda ()
5739 (and (let ((d1 (time-to-days (current-time)))
5740 (d2 (time-to-days
5741 (org-time-string-to-time (match-string 1)))))
5742 (< (- d2 d1) org-warn-days))
5743 (not (org-entry-is-done-p))))))
5744 (message "%d deadlines past-due or due within %d days"
5745 (org-occur regexp callback)
5746 org-warn-days)))
5748 (defun org-evaluate-time-range (&optional to-buffer)
5749 "Evaluate a time range by computing the difference between start and end.
5750 Normally the result is just printed in the echo area, but with prefix arg
5751 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
5752 If the time range is actually in a table, the result is inserted into the
5753 next column.
5754 For time difference computation, a year is assumed to be exactly 365
5755 days in order to avoid rounding problems."
5756 (interactive "P")
5758 (org-clock-update-time-maybe)
5759 (save-excursion
5760 (unless (org-at-date-range-p)
5761 (goto-char (point-at-bol))
5762 (re-search-forward org-tr-regexp (point-at-eol) t))
5763 (if (not (org-at-date-range-p))
5764 (error "Not at a time-stamp range, and none found in current line")))
5765 (let* ((ts1 (match-string 1))
5766 (ts2 (match-string 2))
5767 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
5768 (match-end (match-end 0))
5769 (time1 (org-time-string-to-time ts1))
5770 (time2 (org-time-string-to-time ts2))
5771 (t1 (time-to-seconds time1))
5772 (t2 (time-to-seconds time2))
5773 (diff (abs (- t2 t1)))
5774 (negative (< (- t2 t1) 0))
5775 ;; (ys (floor (* 365 24 60 60)))
5776 (ds (* 24 60 60))
5777 (hs (* 60 60))
5778 (fy "%dy %dd %02d:%02d")
5779 (fy1 "%dy %dd")
5780 (fd "%dd %02d:%02d")
5781 (fd1 "%dd")
5782 (fh "%02d:%02d")
5783 y d h m align)
5784 (if havetime
5785 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5787 d (floor (/ diff ds)) diff (mod diff ds)
5788 h (floor (/ diff hs)) diff (mod diff hs)
5789 m (floor (/ diff 60)))
5790 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
5792 d (floor (+ (/ diff ds) 0.5))
5793 h 0 m 0))
5794 (if (not to-buffer)
5795 (message (org-make-tdiff-string y d h m))
5796 (when (org-at-table-p)
5797 (goto-char match-end)
5798 (setq align t)
5799 (and (looking-at " *|") (goto-char (match-end 0))))
5800 (if (looking-at
5801 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
5802 (replace-match ""))
5803 (if negative (insert " -"))
5804 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
5805 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
5806 (insert " " (format fh h m))))
5807 (if align (org-table-align))
5808 (message "Time difference inserted")))))
5810 (defun org-make-tdiff-string (y d h m)
5811 (let ((fmt "")
5812 (l nil))
5813 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
5814 l (push y l)))
5815 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
5816 l (push d l)))
5817 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
5818 l (push h l)))
5819 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
5820 l (push m l)))
5821 (apply 'format fmt (nreverse l))))
5823 (defun org-time-string-to-time (s)
5824 (apply 'encode-time (org-parse-time-string s)))
5826 (defun org-parse-time-string (s &optional nodefault)
5827 "Parse the standard Org-mode time string.
5828 This should be a lot faster than the normal `parse-time-string'.
5829 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
5830 hour and minute fields will be nil if not given."
5831 (if (string-match org-ts-regexp1 s)
5832 (list 0
5833 (if (or (match-beginning 8) (not nodefault))
5834 (string-to-number (or (match-string 8 s) "0")))
5835 (if (or (match-beginning 7) (not nodefault))
5836 (string-to-number (or (match-string 7 s) "0")))
5837 (string-to-number (match-string 4 s))
5838 (string-to-number (match-string 3 s))
5839 (string-to-number (match-string 2 s))
5840 nil nil nil)
5841 (make-list 9 0)))
5843 (defun org-timestamp-up (&optional arg)
5844 "Increase the date item at the cursor by one.
5845 If the cursor is on the year, change the year. If it is on the month or
5846 the day, change that.
5847 With prefix ARG, change by that many units."
5848 (interactive "p")
5849 (org-timestamp-change (prefix-numeric-value arg)))
5851 (defun org-timestamp-down (&optional arg)
5852 "Decrease the date item at the cursor by one.
5853 If the cursor is on the year, change the year. If it is on the month or
5854 the day, change that.
5855 With prefix ARG, change by that many units."
5856 (interactive "p")
5857 (org-timestamp-change (- (prefix-numeric-value arg))))
5859 (defun org-timestamp-up-day (&optional arg)
5860 "Increase the date in the time stamp by one day.
5861 With prefix ARG, change that many days."
5862 (interactive "p")
5863 (if (and (not (org-at-timestamp-p t))
5864 (org-on-heading-p))
5865 (org-todo 'up)
5866 (org-timestamp-change (prefix-numeric-value arg) 'day)))
5868 (defun org-timestamp-down-day (&optional arg)
5869 "Decrease the date in the time stamp by one day.
5870 With prefix ARG, change that many days."
5871 (interactive "p")
5872 (if (and (not (org-at-timestamp-p t))
5873 (org-on-heading-p))
5874 (org-todo 'down)
5875 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
5877 (defsubst org-pos-in-match-range (pos n)
5878 (and (match-beginning n)
5879 (<= (match-beginning n) pos)
5880 (>= (match-end n) pos)))
5882 (defun org-at-timestamp-p (&optional also-inactive)
5883 "Determine if the cursor is in or at a timestamp."
5884 (interactive)
5885 (let* ((tsr (if also-inactive org-ts-regexp3 org-ts-regexp2))
5886 (pos (point))
5887 (ans (or (looking-at tsr)
5888 (save-excursion
5889 (skip-chars-backward "^[<\n\r\t")
5890 (if (> (point) 1) (backward-char 1))
5891 (and (looking-at tsr)
5892 (> (- (match-end 0) pos) -1))))))
5893 (and (boundp 'org-ts-what)
5894 (setq org-ts-what
5895 (cond
5896 ((org-pos-in-match-range pos 2) 'year)
5897 ((org-pos-in-match-range pos 3) 'month)
5898 ((org-pos-in-match-range pos 7) 'hour)
5899 ((org-pos-in-match-range pos 8) 'minute)
5900 ((or (org-pos-in-match-range pos 4)
5901 (org-pos-in-match-range pos 5)) 'day)
5902 (t 'day))))
5903 ans))
5905 (defun org-timestamp-change (n &optional what)
5906 "Change the date in the time stamp at point.
5907 The date will be changed by N times WHAT. WHAT can be `day', `month',
5908 `year', `minute', `second'. If WHAT is not given, the cursor position
5909 in the timestamp determines what will be changed."
5910 (let ((fmt (car org-time-stamp-formats))
5911 org-ts-what
5912 (pos (point))
5913 ts time time0)
5914 (if (not (org-at-timestamp-p t))
5915 (error "Not at a timestamp"))
5916 (setq org-ts-what (or what org-ts-what))
5917 (setq fmt (if (<= (abs (- (cdr org-ts-lengths)
5918 (- (match-end 0) (match-beginning 0))))
5920 (cdr org-time-stamp-formats)
5921 (car org-time-stamp-formats)))
5922 (if (= (char-after (match-beginning 0)) ?\[)
5923 (setq fmt (concat "[" (substring fmt 1 -1) "]")))
5924 (setq ts (match-string 0))
5925 (replace-match "")
5926 (setq time0 (org-parse-time-string ts))
5927 (setq time
5928 (apply 'encode-time
5929 (append
5930 (list (or (car time0) 0))
5931 (list (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0)))
5932 (list (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0)))
5933 (list (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0)))
5934 (list (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0)))
5935 (list (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0)))
5936 (nthcdr 6 time0))))
5937 (if (eq what 'calendar)
5938 (let ((cal-date
5939 (save-excursion
5940 (save-match-data
5941 (set-buffer "*Calendar*")
5942 (calendar-cursor-to-date)))))
5943 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
5944 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
5945 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
5946 (setcar time0 (or (car time0) 0))
5947 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
5948 (setcar (nthcdr 2 time0) (or (nth 1 time0) 0))
5949 (setq time (apply 'encode-time time0))))
5950 (insert (setq org-last-changed-timestamp (format-time-string fmt time)))
5951 (org-clock-update-time-maybe)
5952 (goto-char pos)
5953 ;; Try to recenter the calendar window, if any
5954 (if (and org-calendar-follow-timestamp-change
5955 (get-buffer-window "*Calendar*" t)
5956 (memq org-ts-what '(day month year)))
5957 (org-recenter-calendar (time-to-days time)))))
5959 (defun org-recenter-calendar (date)
5960 "If the calendar is visible, recenter it to DATE."
5961 (let* ((win (selected-window))
5962 (cwin (get-buffer-window "*Calendar*" t))
5963 (calendar-move-hook nil))
5964 (when cwin
5965 (select-window cwin)
5966 (calendar-goto-date (if (listp date) date
5967 (calendar-gregorian-from-absolute date)))
5968 (select-window win))))
5970 (defun org-goto-calendar (&optional arg)
5971 "Go to the Emacs calendar at the current date.
5972 If there is a time stamp in the current line, go to that date.
5973 A prefix ARG can be used to force the current date."
5974 (interactive "P")
5975 (let ((tsr org-ts-regexp) diff
5976 (calendar-move-hook nil)
5977 (view-calendar-holidays-initially nil)
5978 (view-diary-entries-initially nil))
5979 (if (or (org-at-timestamp-p)
5980 (save-excursion
5981 (beginning-of-line 1)
5982 (looking-at (concat ".*" tsr))))
5983 (let ((d1 (time-to-days (current-time)))
5984 (d2 (time-to-days
5985 (org-time-string-to-time (match-string 1)))))
5986 (setq diff (- d2 d1))))
5987 (calendar)
5988 (calendar-goto-today)
5989 (if (and diff (not arg)) (calendar-forward-day diff))))
5991 (defun org-date-from-calendar ()
5992 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
5993 If there is already a time stamp at the cursor position, update it."
5994 (interactive)
5995 (org-timestamp-change 0 'calendar))
5997 ;;; The clock for measuring work time.
5999 (defvar org-clock-marker (make-marker)
6000 "Marker recording the last clock-in.")
6002 (defun org-clock-in ()
6003 "Start the clock on the current item.
6004 If necessary, clock-out of the currently active clock."
6005 (interactive)
6006 (org-clock-out t)
6007 (let (ts)
6008 (save-excursion
6009 (org-back-to-heading t)
6010 (beginning-of-line 2)
6011 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
6012 (not (equal (match-string 1) org-clock-string)))
6013 (beginning-of-line 1))
6014 (insert "\n") (backward-char 1)
6015 (indent-relative)
6016 (insert org-clock-string " "
6017 (setq ts (concat "[" (format-time-string
6018 (substring
6019 (cdr org-time-stamp-formats) 1 -1)
6020 (current-time))
6021 "]")))
6022 (move-marker org-clock-marker (point))
6023 (message "Clock started at %s" ts))))
6025 (defun org-clock-out (&optional fail-quietly)
6026 "Stop the currently running clock.
6027 If there is no running clock, throw an error, unless FAIL-QUIETLY is set."
6028 (interactive)
6029 (catch 'exit
6030 (if (not (marker-buffer org-clock-marker))
6031 (if fail-quietly (throw 'exit t) (error "No active clock")))
6032 (let (ts te s h m)
6033 (save-excursion
6034 (set-buffer (marker-buffer org-clock-marker))
6035 (goto-char org-clock-marker)
6036 (beginning-of-line 1)
6037 (if (and (looking-at (concat "[ \t]*" org-keyword-time-regexp))
6038 (equal (match-string 1) org-clock-string))
6039 (setq ts (match-string 2))
6040 (if fail-quietly (throw 'exit nil) (error "Clock start time is gone")))
6041 (goto-char org-clock-marker)
6042 (setq te (concat "[" (format-time-string
6043 (substring
6044 (cdr org-time-stamp-formats) 1 -1)
6045 (current-time))
6046 "]"))
6047 (setq s (- (time-to-seconds (apply 'encode-time (org-parse-time-string te)))
6048 (time-to-seconds (apply 'encode-time (org-parse-time-string ts))))
6049 h (floor (/ s 3600))
6050 s (- s (* 3600 h))
6051 m (floor (/ s 60))
6052 s (- s (* 60 s)))
6053 (insert "--" te " => " (format "%2d:%02d" h m))
6054 (move-marker org-clock-marker nil)
6055 (message "Clock stopped at %s after HH:MM = %d:%02d" te h m)))))
6057 (defun org-clock-cancel ()
6058 "Cancel the running clock be removing the start timestamp."
6059 (interactive)
6060 (if (not (marker-buffer org-clock-marker))
6061 (error "No active clock"))
6062 (save-excursion
6063 (set-buffer (marker-buffer org-clock-marker))
6064 (goto-char org-clock-marker)
6065 (delete-region (1- (point-at-bol)) (point-at-eol)))
6066 (message "Clock canceled"))
6068 (defvar org-clock-file-total-minutes nil
6069 "Holds the file total time in minutes, after a call to `org-clock-sum'.")
6070 (make-variable-buffer-local 'org-clock-file-total-minutes)
6072 (defun org-clock-sum (&optional tstart tend)
6073 "Sum the times for each subtree.
6074 Puts the resulting times in minutes as a text property on each headline."
6075 (interactive)
6076 (let* ((bmp (buffer-modified-p))
6077 (re (concat "^\\(\\*+\\)[ \t]\\|^[ \t]*"
6078 org-clock-string
6079 "[ \t]*\\(\\[.*?\\]\\)-+\\(\\[.*?\\]\\)"))
6080 (lmax 30)
6081 (ltimes (make-vector lmax 0))
6082 (t1 0)
6083 (level 0)
6084 ts te dt
6085 time)
6086 (remove-text-properties (point-min) (point-max) '(:org-clock-minutes t))
6087 (save-excursion
6088 (goto-char (point-max))
6089 (while (re-search-backward re nil t)
6090 (if (match-end 2)
6091 ;; A time
6092 (setq ts (match-string 2)
6093 te (match-string 3)
6094 ts (time-to-seconds
6095 (apply 'encode-time (org-parse-time-string ts)))
6096 te (time-to-seconds
6097 (apply 'encode-time (org-parse-time-string te)))
6098 ts (if tstart (max ts tstart) ts)
6099 te (if tend (min te tend) te)
6100 dt (- te ts)
6101 t1 (if (> dt 0) (+ t1 (floor (/ dt 60))) t1))
6102 ;; A headline
6103 (setq level (- (match-end 1) (match-beginning 1)))
6104 (when (or (> t1 0) (> (aref ltimes level) 0))
6105 (loop for l from 0 to level do
6106 (aset ltimes l (+ (aref ltimes l) t1)))
6107 (setq t1 0 time (aref ltimes level))
6108 (loop for l from level to (1- lmax) do
6109 (aset ltimes l 0))
6110 (goto-char (match-beginning 0))
6111 (put-text-property (point) (point-at-eol) :org-clock-minutes time))))
6112 (setq org-clock-file-total-minutes (aref ltimes 0)))
6113 (set-buffer-modified-p bmp)))
6115 (defun org-clock-display (&optional total-only)
6116 "Show subtree times in the entire buffer.
6117 If TOTAL-ONLY is non-nil, only show the total time for the entire file
6118 in the echo area."
6119 (interactive)
6120 (org-remove-clock-overlays)
6121 (let (time h m p)
6122 (org-clock-sum)
6123 (unless total-only
6124 (save-excursion
6125 (goto-char (point-min))
6126 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6127 (goto-char p)
6128 (when (setq time (get-text-property p :org-clock-minutes))
6129 (org-put-clock-overlay time (funcall outline-level))))
6130 (setq h (/ org-clock-file-total-minutes 60)
6131 m (- org-clock-file-total-minutes (* 60 h)))
6132 ;; Arrange to remove the overlays upon next change.
6133 (org-add-hook 'before-change-functions 'org-remove-clock-overlays
6134 nil 'local)))
6135 (message "Total file time: %d:%02d (%d hours and %d minutes)" h m h m)))
6137 (defvar org-clock-overlays nil)
6138 (make-variable-buffer-local 'org-clock-overlays)
6140 (defun org-put-clock-overlay (time &optional level)
6141 "Put an overlays on the current line, displaying TIME.
6142 If LEVEL is given, prefix time with a corresponding number of stars.
6143 This creates a new overlay and stores it in `org-clock-overlays', so that it
6144 will be easy to remove."
6145 (let* ((c 60) (h (floor (/ time 60))) (m (- time (* 60 h)))
6146 (l (if level (org-get-legal-level level 0) 0))
6147 (off 0)
6148 ov tx)
6149 (move-to-column c)
6150 (unless (eolp) (skip-chars-backward "^ \t"))
6151 (skip-chars-backward " \t")
6152 (setq ov (org-make-overlay (1- (point)) (point-at-eol))
6153 tx (concat (buffer-substring (1- (point)) (point))
6154 (make-string (+ off (max 0 (- c (current-column)))) ?.)
6155 (org-add-props (format "%s %2d:%02d%s"
6156 (make-string l ?*) h m
6157 (make-string (- 10 l) ?\ ))
6158 '(face secondary-selection))
6159 ""))
6160 (org-overlay-put ov 'display tx)
6161 (push ov org-clock-overlays)))
6163 (defun org-remove-clock-overlays (&optional beg end noremove)
6164 "Remove the occur highlights from the buffer.
6165 BEG and END are ignored. If NOREMOVE is nil, remove this function
6166 from the `before-change-functions' in the current buffer."
6167 (interactive)
6168 (unless org-inhibit-highlight-removal
6169 (mapc 'org-delete-overlay org-clock-overlays)
6170 (setq org-clock-overlays nil)
6171 (unless noremove
6172 (remove-hook 'before-change-functions
6173 'org-remove-clock-overlays 'local))))
6175 (defun org-clock-out-if-current ()
6176 "Clock out if the current entry contains the running clock.
6177 This is used to stop the clock after a TODO entry is marked DONE."
6178 (when (and (equal state org-done-string)
6179 (equal (marker-buffer org-clock-marker) (current-buffer))
6180 (< (point) org-clock-marker)
6181 (> (save-excursion (outline-next-heading) (point))
6182 org-clock-marker))
6183 (org-clock-out)))
6185 (add-hook 'org-after-todo-state-change-hook
6186 'org-clock-out-if-current)
6188 (defun org-check-running-clock ()
6189 "Check if the current buffer contains the running clock.
6190 If yes, offer to stop it and to save the buffer with the changes."
6191 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
6192 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
6193 (buffer-name))))
6194 (org-clock-out)
6195 (when (y-or-n-p "Save changed buffer?")
6196 (save-buffer))))
6198 (defun org-clock-report ()
6199 "Create a table containing a report about clocked time.
6200 If the buffer contains lines
6201 #+BEGIN: clocktable :maxlevel 3 :emphasize nil
6203 #+END: clocktable
6204 then the table will be inserted between these lines, replacing whatever
6205 is was there before. If these lines are not in the buffer, the table
6206 is inserted at point, surrounded by the special lines.
6207 The BEGIN line can contain parameters. Allowed are:
6208 :maxlevel The maximum level to be included in the table. Default is 3.
6209 :emphasize t/nil, if levell 1 and level 2 should be bold/italic in the table."
6210 (interactive)
6211 (org-remove-clock-overlays)
6212 (unless (org-find-dblock "clocktable")
6213 (org-create-dblock (list :name "clocktable"
6214 :maxlevel 2 :emphasize nil)))
6215 (org-update-dblock))
6217 (defun org-clock-update-time-maybe ()
6218 "If this is a CLOCK line, update it and return t.
6219 Otherwise, return nil."
6220 (interactive)
6221 (save-excursion
6222 (beginning-of-line 1)
6223 (skip-chars-forward " \t")
6224 (when (looking-at org-clock-string)
6225 (let ((re (concat "[ \t]*" org-clock-string
6226 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
6227 "\\([ \t]*=>.*\\)?"))
6228 ts te h m s)
6229 (if (not (looking-at re))
6231 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
6232 (end-of-line 1)
6233 (setq ts (match-string 1)
6234 te (match-string 2))
6235 (setq s (- (time-to-seconds
6236 (apply 'encode-time (org-parse-time-string te)))
6237 (time-to-seconds
6238 (apply 'encode-time (org-parse-time-string ts))))
6239 h (floor (/ s 3600))
6240 s (- s (* 3600 h))
6241 m (floor (/ s 60))
6242 s (- s (* 60 s)))
6243 (insert " => " (format "%2d:%02d" h m))
6244 t)))))
6246 (defun org-clock-special-range (key &optional time as-strings)
6247 "Return two times bordering a special time range.
6248 Key is a symbol specifying the range and can be one of `today', `yesterday',
6249 `thisweek', `lastweek', `thismonth', `lastmonth', `thisyear', `lastyear'.
6250 A week starts Monday 0:00 and ends Sunday 24:00.
6251 The range is determined relative to TIME. TIME defaults to the current time.
6252 The return value is a cons cell with two internal times like the ones
6253 returned by `current time' or `encode-time'. if AS-STRINGS is non-nil,
6254 the returned times will be formatted strings."
6255 (let* ((tm (decode-time (or time (current-time))))
6256 (s 0) (m (nth 1 tm)) (h (nth 2 tm))
6257 (d (nth 3 tm)) (month (nth 4 tm)) (y (nth 5 tm))
6258 (dow (nth 6 tm))
6259 s1 m1 h1 d1 month1 y1 diff ts te fm)
6260 (cond
6261 ((eq key 'today)
6262 (setq h 0 m 0 h1 24 m1 0))
6263 ((eq key 'yesterday)
6264 (setq d (1- d) h 0 m 0 h1 24 m1 0))
6265 ((eq key 'thisweek)
6266 (setq diff (if (= dow 0) 6 (1- dow))
6267 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6268 ((eq key 'lastweek)
6269 (setq diff (+ 7 (if (= dow 0) 6 (1- dow)))
6270 m 0 h 0 d (- d diff) d1 (+ 7 d)))
6271 ((eq key 'thismonth)
6272 (setq d 1 h 0 m 0 d1 1 month1 (1+ month) h1 0 m1 0))
6273 ((eq key 'lastmonth)
6274 (setq d 1 h 0 m 0 d1 1 month (1- month) month1 (1+ month) h1 0 m1 0))
6275 ((eq key 'thisyear)
6276 (setq m 0 h 0 d 1 month 1 y1 (1+ y)))
6277 ((eq key 'lastyear)
6278 (setq m 0 h 0 d 1 month 1 y (1- y) y1 (1+ y)))
6279 (t (error "No such time block %s" key)))
6280 (setq ts (encode-time s m h d month y)
6281 te (encode-time (or s1 s) (or m1 m) (or h1 h)
6282 (or d1 d) (or month1 month) (or y1 y)))
6283 (setq fm (cdr org-time-stamp-formats))
6284 (if as-strings
6285 (cons (format-time-string fm ts) (format-time-string fm te))
6286 (cons ts te))))
6288 (defun org-dblock-write:clocktable (params)
6289 "Write the standard clocktable."
6290 (let ((hlchars '((1 . "*") (2 . ?/)))
6291 (emph nil)
6292 (ins (make-marker))
6293 ipos time h m p level hlc hdl maxlevel
6294 ts te cc block)
6295 (setq maxlevel (or (plist-get params :maxlevel) 3)
6296 emph (plist-get params :emphasize)
6297 ts (plist-get params :tstart)
6298 te (plist-get params :tend)
6299 block (plist-get params :block))
6300 (when block
6301 (setq cc (org-clock-special-range block nil t)
6302 ts (car cc) te (cdr cc)))
6303 (if ts (setq ts (time-to-seconds
6304 (apply 'encode-time (org-parse-time-string ts)))))
6305 (if te (setq te (time-to-seconds
6306 (apply 'encode-time (org-parse-time-string te)))))
6307 (move-marker ins (point))
6308 (setq ipos (point))
6309 (insert-before-markers "Clock summary at ["
6310 (substring
6311 (format-time-string (cdr org-time-stamp-formats))
6312 1 -1)
6313 "]."
6314 (if block
6315 (format " Considered range is /%s/." block)
6317 "\n\n|L|Headline|Time|\n")
6318 (org-clock-sum ts te)
6319 (setq h (/ org-clock-file-total-minutes 60)
6320 m (- org-clock-file-total-minutes (* 60 h)))
6321 (insert-before-markers "|-\n|0|" "*Total file time*| "
6322 (format "*%d:%02d*" h m)
6323 "|\n")
6324 (goto-char (point-min))
6325 (while (setq p (next-single-property-change (point) :org-clock-minutes))
6326 (goto-char p)
6327 (when (setq time (get-text-property p :org-clock-minutes))
6328 (beginning-of-line 1)
6329 (when (and (looking-at "\\(\\*+\\)[ \t]+\\(.*?\\)\\([ \t]+:[0-9a-zA-Z_@:]+:\\)?[ \t]*$")
6330 (setq level (- (match-end 1) (match-beginning 1)))
6331 (<= level maxlevel))
6332 (setq hlc (if emph (or (cdr (assoc level hlchars)) "") "")
6333 hdl (match-string 2)
6334 h (/ time 60)
6335 m (- time (* 60 h)))
6336 (save-excursion
6337 (goto-char ins)
6338 (if (= level 1) (insert-before-markers "|-\n"))
6339 (insert-before-markers
6340 "| " (int-to-string level) "|" hlc hdl hlc " |"
6341 (make-string (1- level) ?|)
6343 (format "%d:%02d" h m)
6345 " |\n")))))
6346 (goto-char ins)
6347 (backward-delete-char 1)
6348 (goto-char ipos)
6349 (skip-chars-forward "^|")
6350 (org-table-align)))
6352 (defun org-collect-clock-time-entries ()
6353 "Return an internal list with clocking information.
6354 This list has one entry for each CLOCK interval.
6355 FIXME: describe the elements."
6356 (interactive)
6357 (let ((re (concat "^[ \t]*" org-clock-string
6358 " *\\[\\(.*?\\)\\]--\\[\\(.*?\\)\\]"))
6359 rtn beg end next cont level title total closedp leafp
6360 clockpos titlepos h m donep)
6361 (save-excursion
6362 (org-clock-sum)
6363 (goto-char (point-min))
6364 (while (re-search-forward re nil t)
6365 (setq clockpos (match-beginning 0)
6366 beg (match-string 1) end (match-string 2)
6367 cont (match-end 0))
6368 (setq beg (apply 'encode-time (org-parse-time-string beg))
6369 end (apply 'encode-time (org-parse-time-string end)))
6370 (org-back-to-heading t)
6371 (setq donep (org-entry-is-done-p))
6372 (setq titlepos (point)
6373 total (or (get-text-property (1+ (point)) :org-clock-minutes) 0)
6374 h (/ total 60) m (- total (* 60 h))
6375 total (cons h m))
6376 (looking-at "\\(\\*+\\) +\\(.*\\)")
6377 (setq level (- (match-end 1) (match-beginning 1))
6378 title (org-match-string-no-properties 2))
6379 (save-excursion (outline-next-heading) (setq next (point)))
6380 (setq closedp (re-search-forward org-closed-time-regexp next t))
6381 (goto-char next)
6382 (setq leafp (and (looking-at "^\\*+ ")
6383 (<= (- (match-end 0) (point)) level)))
6384 (push (list beg end clockpos closedp donep
6385 total title titlepos level leafp)
6386 rtn)
6387 (goto-char cont)))
6388 (nreverse rtn)))
6390 ;;; Agenda, and Diary Integration
6392 ;;; Define the mode
6394 (defvar org-agenda-mode-map (make-sparse-keymap)
6395 "Keymap for `org-agenda-mode'.")
6397 (defvar org-agenda-menu) ; defined later in this file.
6398 (defvar org-agenda-follow-mode nil)
6399 (defvar org-agenda-show-log nil)
6400 (defvar org-agenda-redo-command nil)
6401 (defvar org-agenda-mode-hook nil)
6402 (defvar org-agenda-type nil)
6403 (defvar org-agenda-force-single-file nil)
6405 (defun org-agenda-mode ()
6406 "Mode for time-sorted view on action items in Org-mode files.
6408 The following commands are available:
6410 \\{org-agenda-mode-map}"
6411 (interactive)
6412 (kill-all-local-variables)
6413 (setq major-mode 'org-agenda-mode)
6414 (setq mode-name "Org-Agenda")
6415 (use-local-map org-agenda-mode-map)
6416 (easy-menu-add org-agenda-menu)
6417 (if org-startup-truncated (setq truncate-lines t))
6418 (org-add-hook 'post-command-hook 'org-agenda-post-command-hook nil 'local)
6419 (org-add-hook 'pre-command-hook 'org-unhighlight nil 'local)
6420 (unless org-agenda-keep-modes
6421 (setq org-agenda-follow-mode org-agenda-start-with-follow-mode
6422 org-agenda-show-log nil))
6423 (easy-menu-change
6424 '("Agenda") "Agenda Files"
6425 (append
6426 (list
6427 (vector
6428 (if (get 'org-agenda-files 'org-restrict)
6429 "Restricted to single file"
6430 "Edit File List")
6431 '(org-edit-agenda-file-list)
6432 (not (get 'org-agenda-files 'org-restrict)))
6433 "--")
6434 (mapcar 'org-file-menu-entry (org-agenda-files))))
6435 (org-agenda-set-mode-name)
6436 (apply
6437 (if (fboundp 'run-mode-hooks) 'run-mode-hooks 'run-hooks)
6438 (list 'org-agenda-mode-hook)))
6440 (define-key org-agenda-mode-map "\C-i" 'org-agenda-goto)
6441 (define-key org-agenda-mode-map [(tab)] 'org-agenda-goto)
6442 (define-key org-agenda-mode-map "\C-m" 'org-agenda-switch-to)
6443 (define-key org-agenda-mode-map " " 'org-agenda-show)
6444 (define-key org-agenda-mode-map "\C-c\C-t" 'org-agenda-todo)
6445 (define-key org-agenda-mode-map "o" 'delete-other-windows)
6446 (define-key org-agenda-mode-map "L" 'org-agenda-recenter)
6447 (define-key org-agenda-mode-map "t" 'org-agenda-todo)
6448 (define-key org-agenda-mode-map "a" 'org-agenda-toggle-archive-tag)
6449 (define-key org-agenda-mode-map ":" 'org-agenda-set-tags)
6450 (define-key org-agenda-mode-map "." 'org-agenda-goto-today)
6451 (define-key org-agenda-mode-map "d" 'org-agenda-day-view)
6452 (define-key org-agenda-mode-map "w" 'org-agenda-week-view)
6453 (define-key org-agenda-mode-map (org-key 'S-right) 'org-agenda-date-later)
6454 (define-key org-agenda-mode-map (org-key 'S-left) 'org-agenda-date-earlier)
6455 (define-key org-agenda-mode-map [?\C-c ?\C-x (right)] 'org-agenda-date-later)
6456 (define-key org-agenda-mode-map [?\C-c ?\C-x (left)] 'org-agenda-date-earlier)
6458 (define-key org-agenda-mode-map ">" 'org-agenda-date-prompt)
6459 (define-key org-agenda-mode-map "\C-c\C-s" 'org-agenda-schedule)
6460 (define-key org-agenda-mode-map "\C-c\C-d" 'org-agenda-deadline)
6461 (let ((l '(1 2 3 4 5 6 7 8 9 0)))
6462 (while l (define-key org-agenda-mode-map
6463 (int-to-string (pop l)) 'digit-argument)))
6465 (define-key org-agenda-mode-map "f" 'org-agenda-follow-mode)
6466 (define-key org-agenda-mode-map "l" 'org-agenda-log-mode)
6467 (define-key org-agenda-mode-map "D" 'org-agenda-toggle-diary)
6468 (define-key org-agenda-mode-map "g" 'org-agenda-toggle-time-grid)
6469 (define-key org-agenda-mode-map "r" 'org-agenda-redo)
6470 (define-key org-agenda-mode-map "q" 'org-agenda-quit)
6471 (define-key org-agenda-mode-map "x" 'org-agenda-exit)
6472 (define-key org-agenda-mode-map "s" 'org-save-all-org-buffers)
6473 (define-key org-agenda-mode-map "P" 'org-agenda-show-priority)
6474 (define-key org-agenda-mode-map "T" 'org-agenda-show-tags)
6475 (define-key org-agenda-mode-map "n" 'next-line)
6476 (define-key org-agenda-mode-map "p" 'previous-line)
6477 (define-key org-agenda-mode-map "\C-n" 'org-agenda-next-date-line)
6478 (define-key org-agenda-mode-map "\C-p" 'org-agenda-previous-date-line)
6479 (define-key org-agenda-mode-map "," 'org-agenda-priority)
6480 (define-key org-agenda-mode-map "\C-c," 'org-agenda-priority)
6481 (define-key org-agenda-mode-map "i" 'org-agenda-diary-entry)
6482 (define-key org-agenda-mode-map "c" 'org-agenda-goto-calendar)
6483 (eval-after-load "calendar"
6484 '(define-key calendar-mode-map org-calendar-to-agenda-key
6485 'org-calendar-goto-agenda))
6486 (define-key org-agenda-mode-map "C" 'org-agenda-convert-date)
6487 (define-key org-agenda-mode-map "m" 'org-agenda-phases-of-moon)
6488 (define-key org-agenda-mode-map "M" 'org-agenda-phases-of-moon)
6489 (define-key org-agenda-mode-map "S" 'org-agenda-sunrise-sunset)
6490 (define-key org-agenda-mode-map "h" 'org-agenda-holidays)
6491 (define-key org-agenda-mode-map "H" 'org-agenda-holidays)
6492 (define-key org-agenda-mode-map "+" 'org-agenda-priority-up)
6493 (define-key org-agenda-mode-map "I" 'org-agenda-clock-in)
6494 (define-key org-agenda-mode-map "O" 'org-clock-out)
6495 (define-key org-agenda-mode-map "X" 'org-clock-cancel)
6496 (define-key org-agenda-mode-map "-" 'org-agenda-priority-down)
6497 (define-key org-agenda-mode-map (org-key 'S-up) 'org-agenda-priority-up)
6498 (define-key org-agenda-mode-map (org-key 'S-down) 'org-agenda-priority-down)
6499 (define-key org-agenda-mode-map [?\C-c ?\C-x (up)] 'org-agenda-priority-up)
6500 (define-key org-agenda-mode-map [?\C-c ?\C-x (down)] 'org-agenda-priority-down)
6501 (define-key org-agenda-mode-map [(right)] 'org-agenda-later)
6502 (define-key org-agenda-mode-map [(left)] 'org-agenda-earlier)
6503 (define-key org-agenda-mode-map "\C-c\C-x\C-c" 'org-export-icalendar-combine-agenda-files)
6504 (defvar org-agenda-keymap (copy-keymap org-agenda-mode-map)
6505 "Local keymap for agenda entries from Org-mode.")
6507 (define-key org-agenda-keymap
6508 (if (featurep 'xemacs) [(button2)] [(mouse-2)]) 'org-agenda-goto-mouse)
6509 (define-key org-agenda-keymap
6510 (if (featurep 'xemacs) [(button3)] [(mouse-3)]) 'org-agenda-show-mouse)
6511 (when org-agenda-mouse-1-follows-link
6512 (define-key org-agenda-keymap [follow-link] 'mouse-face))
6513 (easy-menu-define org-agenda-menu org-agenda-mode-map "Agenda menu"
6514 '("Agenda"
6515 ("Agenda Files")
6516 "--"
6517 ["Show" org-agenda-show t]
6518 ["Go To (other window)" org-agenda-goto t]
6519 ["Go To (one window)" org-agenda-switch-to t]
6520 ["Follow Mode" org-agenda-follow-mode
6521 :style toggle :selected org-agenda-follow-mode :active t]
6522 "--"
6523 ["Cycle TODO" org-agenda-todo t]
6524 ("Tags"
6525 ["Show all Tags" org-agenda-show-tags t]
6526 ["Set Tags" org-agenda-set-tags t])
6527 ("Schedule"
6528 ["Schedule" org-agenda-schedule t]
6529 ["Set Deadline" org-agenda-deadline t]
6530 "--"
6531 ["Reschedule +1 day" org-agenda-date-later (org-agenda-check-type nil 'agenda 'timeline)]
6532 ["Reschedule -1 day" org-agenda-date-earlier (org-agenda-check-type nil 'agenda 'timeline)]
6533 ["Reschedule to ..." org-agenda-date-prompt (org-agenda-check-type nil 'agenda 'timeline)])
6534 ("Priority"
6535 ["Set Priority" org-agenda-priority t]
6536 ["Increase Priority" org-agenda-priority-up t]
6537 ["Decrease Priority" org-agenda-priority-down t]
6538 ["Show Priority" org-agenda-show-priority t])
6539 "--"
6540 ;; ["New agenda command" org-agenda t]
6541 ["Rebuild buffer" org-agenda-redo t]
6542 ["Save all Org-mode Buffers" org-save-all-org-buffers t]
6543 "--"
6544 ["Goto Today" org-agenda-goto-today (org-agenda-check-type nil 'agenda 'timeline)]
6545 ["Next Dates" org-agenda-later (org-agenda-check-type nil 'agenda)]
6546 ["Previous Dates" org-agenda-earlier (org-agenda-check-type nil 'agenda)]
6547 "--"
6548 ["Day View" org-agenda-day-view :active (org-agenda-check-type nil 'agenda)
6549 :style radio :selected (equal org-agenda-ndays 1)]
6550 ["Week View" org-agenda-week-view :active (org-agenda-check-type nil 'agenda)
6551 :style radio :selected (equal org-agenda-ndays 7)]
6552 "--"
6553 ["Show Logbook entries" org-agenda-log-mode
6554 :style toggle :selected org-agenda-show-log :active (org-agenda-check-type nil 'agenda 'timeline)]
6555 ["Include Diary" org-agenda-toggle-diary
6556 :style toggle :selected org-agenda-include-diary :active (org-agenda-check-type nil 'agenda)]
6557 ["Use Time Grid" org-agenda-toggle-time-grid
6558 :style toggle :selected org-agenda-use-time-grid :active (org-agenda-check-type nil 'agenda)]
6559 "--"
6560 ["New Diary Entry" org-agenda-diary-entry (org-agenda-check-type nil 'agenda 'timeline)]
6561 ("Calendar Commands"
6562 ["Goto Calendar" org-agenda-goto-calendar (org-agenda-check-type nil 'agenda 'timeline)]
6563 ["Phases of the Moon" org-agenda-phases-of-moon (org-agenda-check-type nil 'agenda 'timeline)]
6564 ["Sunrise/Sunset" org-agenda-sunrise-sunset (org-agenda-check-type nil 'agenda 'timeline)]
6565 ["Holidays" org-agenda-holidays (org-agenda-check-type nil 'agenda 'timeline)]
6566 ["Convert" org-agenda-convert-date (org-agenda-check-type nil 'agenda 'timeline)])
6567 ["Create iCalendar file" org-export-icalendar-combine-agenda-files t]
6568 "--"
6569 ["Quit" org-agenda-quit t]
6570 ["Exit and Release Buffers" org-agenda-exit t]
6573 (defvar org-agenda-restrict nil)
6574 (defvar org-agenda-restrict-begin (make-marker))
6575 (defvar org-agenda-restrict-end (make-marker))
6576 (defvar org-agenda-last-dispatch-buffer nil)
6578 ;;;###autoload
6579 (defun org-agenda (arg)
6580 "Dispatch agenda commands to collect entries to the agenda buffer.
6581 Prompts for a character to select a command. Any prefix arg will be passed
6582 on to the selected command. The default selections are:
6584 a Call `org-agenda-list' to display the agenda for current day or week.
6585 t Call `org-todo-list' to display the global todo list.
6586 T Call `org-todo-list' to display the global todo list, select only
6587 entries with a specific TODO keyword (the user gets a prompt).
6588 m Call `org-tags-view' to display headlines with tags matching
6589 a condition (the user is prompted for the condition).
6590 M Like `m', but select only TODO entries, no ordinary headlines.
6591 l Create a timeeline for the current buffer.
6593 More commands can be added by configuring the variable
6594 `org-agenda-custom-commands'. In particular, specific tags and TODO keyword
6595 searches can be pre-defined in this way.
6597 If the current buffer is in Org-mode and visiting a file, you can also
6598 first press `1' to indicate that the agenda should be temporarily (until the
6599 next use of \\[org-agenda]) restricted to the current file."
6600 (interactive "P")
6601 (catch 'exit
6602 (let ((restrict-ok (and buffer-file-name (org-mode-p)))
6603 (buf (current-buffer))
6604 (bfn buffer-file-name)
6605 (custom org-agenda-custom-commands)
6606 c entry key type match lprops)
6607 ;; Turn off restriction
6608 (put 'org-agenda-files 'org-restrict nil)
6609 (setq org-agenda-restrict nil)
6610 (move-marker org-agenda-restrict-begin nil)
6611 (move-marker org-agenda-restrict-end nil)
6612 ;; Remember where this call originated
6613 (setq org-agenda-last-dispatch-buffer (current-buffer))
6614 (save-window-excursion
6615 (delete-other-windows)
6616 (switch-to-buffer-other-window " *Agenda Commands*")
6617 (erase-buffer)
6618 (insert
6619 "Press key for an agenda command:
6620 --------------------------------
6621 a Agenda for current week or day
6622 t List of all TODO entries T Entries with special TODO kwd
6623 m Match a TAGS query M Like m, but only TODO entries
6624 L Timeline for current buffer C Configure custom agenda commands")
6625 (while (setq entry (pop custom))
6626 (setq key (car entry) type (nth 1 entry) match (nth 2 entry))
6627 (insert (format "\n%-4s%-14s: %s"
6629 (cond
6630 ((stringp type) type)
6631 ((eq type 'tags) "Tags query")
6632 ((eq type 'todo) "TODO keyword")
6633 ((eq type 'tags-tree) "Tags tree")
6634 ((eq type 'todo-tree) "TODO kwd tree")
6635 ((eq type 'occur-tree) "Occur tree")
6636 (t "???"))
6637 (if (stringp match)
6638 (org-add-props match nil 'face 'org-warning)
6639 (format "set of %d commands" (+ -2 (length entry)))))))
6640 (if restrict-ok
6641 (insert "\n"
6642 (org-add-props "1 Restrict call to current buffer 0 Restrict call to region or subtree" nil 'face 'org-table)))
6644 (goto-char (point-min))
6645 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
6646 (message "Press key for agenda command%s"
6647 (if restrict-ok ", or [1] or [0] to restrict" ""))
6648 (setq c (read-char-exclusive))
6649 (message "")
6650 (when (memq c '(?L ?1 ?0))
6651 (if restrict-ok
6652 (put 'org-agenda-files 'org-restrict (list bfn))
6653 (error "Cannot restrict agenda to current buffer"))
6654 (with-current-buffer " *Agenda Commands*"
6655 (goto-char (point-max))
6656 (delete-region (point-at-bol) (point))
6657 (goto-char (point-min)))
6658 (when (eq c ?0)
6659 (setq org-agenda-restrict t)
6660 (with-current-buffer buf
6661 (if (org-region-active-p)
6662 (progn
6663 (move-marker org-agenda-restrict-begin (region-beginning))
6664 (move-marker org-agenda-restrict-end (region-end)))
6665 (save-excursion
6666 (org-back-to-heading t)
6667 (move-marker org-agenda-restrict-begin (point))
6668 (move-marker org-agenda-restrict-end
6669 (progn (org-end-of-subtree t)))))))
6670 (unless (eq c ?L)
6671 (message "Press key for agenda command%s"
6672 (if restrict-ok " (restricted to current file)" ""))
6673 (setq c (read-char-exclusive)))
6674 (message "")))
6675 (require 'calendar) ; FIXME: can we avoid this for some commands?
6676 ;; For example the todo list should not need it (but does...)
6677 (cond
6678 ((equal c ?C) (customize-variable 'org-agenda-custom-commands))
6679 ((equal c ?a) (call-interactively 'org-agenda-list))
6680 ((equal c ?t) (call-interactively 'org-todo-list))
6681 ((equal c ?T) (org-call-with-arg 'org-todo-list (or arg '(4))))
6682 ((equal c ?m) (call-interactively 'org-tags-view))
6683 ((equal c ?M) (org-call-with-arg 'org-tags-view (or arg '(4))))
6684 ((equal c ?L)
6685 (unless restrict-ok
6686 (error "This is not an Org-mode file"))
6687 (org-call-with-arg 'org-timeline arg))
6688 ((setq entry (assoc (char-to-string c) org-agenda-custom-commands))
6689 (if (symbolp (nth 1 entry))
6690 (progn
6691 (setq type (nth 1 entry) match (nth 2 entry) lprops (nth 3 entry)
6692 lprops (nth 3 entry))
6693 (cond
6694 ((eq type 'tags)
6695 (org-let lprops '(org-tags-view current-prefix-arg match)))
6696 ((eq type 'tags-todo)
6697 (org-let lprops '(org-tags-view '(4) match)))
6698 ((eq type 'todo)
6699 (org-let lprops '(org-todo-list match)))
6700 ((eq type 'tags-tree)
6701 (org-check-for-org-mode)
6702 (org-let lprops '(org-tags-sparse-tree current-prefix-arg match)))
6703 ((eq type 'todo-tree)
6704 (org-check-for-org-mode)
6705 (org-let lprops
6706 '(org-occur (concat "^" outline-regexp "[ \t]*"
6707 (regexp-quote match) "\\>"))))
6708 ((eq type 'occur-tree)
6709 (org-check-for-org-mode)
6710 (org-let lprops '(org-occur match)))
6711 (t (error "Invalid custom agenda command type %s" type))))
6712 (org-run-agenda-series (cddr entry))))
6713 (t (error "Invalid key"))))))
6715 (defun org-run-agenda-series (series &optional window)
6716 (org-prepare-agenda)
6717 (let* ((org-agenda-multi t)
6718 (redo (list 'org-run-agenda-series (list 'quote series)))
6719 (org-select-agenda-window t)
6720 (cmds (car series))
6721 (gprops (nth 1 series))
6722 cmd type match lprops)
6723 (while (setq cmd (pop cmds))
6724 (setq type (car cmd) match (nth 1 cmd) lprops (nth 2 cmd))
6725 (cond
6726 ((eq type 'agenda)
6727 (call-interactively 'org-agenda-list))
6728 ((eq type 'alltodo)
6729 (call-interactively 'org-todo-list))
6730 ((eq type 'tags)
6731 (org-let2 gprops lprops
6732 '(org-tags-view current-prefix-arg match)))
6733 ((eq type 'tags-todo)
6734 (org-let2 gprops lprops
6735 '(org-tags-view '(4) match)))
6736 ((eq type 'todo)
6737 (org-let2 gprops lprops
6738 '(org-todo-list match)))
6739 (t (error "Invalid type in command series"))))
6740 (widen)
6741 (setq org-agenda-redo-command redo)
6742 (goto-char (point-min))))
6744 (defun org-check-for-org-mode ()
6745 "Make sure current buffer is in org-mode. Error if not."
6746 (or (org-mode-p)
6747 (error "Cannot execute org-mode agenda command on buffer in %s."
6748 major-mode)))
6750 (defun org-fit-agenda-window ()
6751 "Fit the window to the buffer size."
6752 (and org-fit-agenda-window
6753 (fboundp 'fit-window-to-buffer)
6754 (fit-window-to-buffer nil (/ (* (frame-height) 3) 4)
6755 (/ (frame-height) 2))))
6757 (defun org-agenda-files (&optional unrestricted)
6758 "Get the list of agenda files.
6759 Optional UNRESTRICTED means return the full list even if a restriction
6760 is currently in place."
6761 (cond
6762 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
6763 ((stringp org-agenda-files) (org-read-agenda-file-list))
6764 ((listp org-agenda-files) org-agenda-files)
6765 (t (error "Invalid value of `org-agenda-files'"))))
6767 (defvar org-window-configuration)
6769 (defun org-edit-agenda-file-list ()
6770 "Edit the list of agenda files.
6771 Depending on setup, this either uses customize to edit the variable
6772 `org-agenda-files', or it visits the file that is holding the list. In the
6773 latter case, the buffer is set up in a way that saving it automatically kills
6774 the buffer and restores the previous window configuration."
6775 (interactive)
6776 (if (stringp org-agenda-files)
6777 (let ((cw (current-window-configuration)))
6778 (find-file org-agenda-files)
6779 (org-set-local 'org-window-configuration cw)
6780 (org-add-hook 'after-save-hook
6781 (lambda ()
6782 (set-window-configuration
6783 (prog1 org-window-configuration
6784 (kill-buffer (current-buffer))))
6785 (org-install-agenda-files-menu)
6786 (message "New agenda file list installed"))
6787 nil 'local)
6788 (message (substitute-command-keys
6789 "Edit list and finish with \\[save-buffer]")))
6790 (customize-variable 'org-agenda-files)))
6792 (defun org-store-new-agenda-file-list (list)
6793 "Set new value for the agenda file list and save it correcly."
6794 (if (stringp org-agenda-files)
6795 (let ((f org-agenda-files) b)
6796 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
6797 (with-temp-file f
6798 (insert (mapconcat 'identity list "\n") "\n")))
6799 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
6800 (setq org-agenda-files list)
6801 (customize-save-variable 'org-agenda-files org-agenda-files))))
6803 (defun org-read-agenda-file-list ()
6804 "Read the list of agenda files from a file."
6805 (when (stringp org-agenda-files)
6806 (with-temp-buffer
6807 (insert-file-contents org-agenda-files)
6808 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
6810 (defvar org-agenda-markers nil
6811 "List of all currently active markers created by `org-agenda'.")
6812 (defvar org-agenda-last-marker-time (time-to-seconds (current-time))
6813 "Creation time of the last agenda marker.")
6815 (defun org-agenda-new-marker (&optional pos)
6816 "Return a new agenda marker.
6817 Org-mode keeps a list of these markers and resets them when they are
6818 no longer in use."
6819 (let ((m (copy-marker (or pos (point)))))
6820 (setq org-agenda-last-marker-time (time-to-seconds (current-time)))
6821 (push m org-agenda-markers)
6824 (defun org-agenda-maybe-reset-markers (&optional force)
6825 "Reset markers created by `org-agenda'. But only if they are old enough."
6826 (if (or (and force (not org-agenda-multi))
6827 (> (- (time-to-seconds (current-time))
6828 org-agenda-last-marker-time)
6830 (while org-agenda-markers
6831 (move-marker (pop org-agenda-markers) nil))))
6833 (defvar org-agenda-new-buffers nil
6834 "Buffers created to visit agenda files.")
6836 (defun org-get-agenda-file-buffer (file)
6837 "Get a buffer visiting FILE. If the buffer needs to be created, add
6838 it to the list of buffers which might be released later."
6839 (let ((buf (find-buffer-visiting file)))
6840 (if buf
6841 buf ; just return it
6842 ;; Make a new buffer and remember it
6843 (setq buf (find-file-noselect file))
6844 (if buf (push buf org-agenda-new-buffers))
6845 buf)))
6847 (defun org-release-buffers (blist)
6848 "Release all buffers in list, asking the user for confirmation when needed.
6849 When a buffer is unmodified, it is just killed. When modified, it is saved
6850 \(if the user agrees) and then killed."
6851 (let (buf file)
6852 (while (setq buf (pop blist))
6853 (setq file (buffer-file-name buf))
6854 (when (and (buffer-modified-p buf)
6855 file
6856 (y-or-n-p (format "Save file %s? " file)))
6857 (with-current-buffer buf (save-buffer)))
6858 (kill-buffer buf))))
6860 (defun org-timeline (&optional include-all keep-modes)
6861 "Show a time-sorted view of the entries in the current org file.
6862 Only entries with a time stamp of today or later will be listed. With
6863 \\[universal-argument] prefix, all unfinished TODO items will also be shown,
6864 under the current date.
6865 If the buffer contains an active region, only check the region for
6866 dates."
6867 (interactive "P")
6868 (require 'calendar)
6869 (org-compile-prefix-format 'timeline)
6870 (org-set-sorting-strategy 'timeline)
6871 (let* ((dopast t)
6872 (dotodo include-all)
6873 (doclosed org-agenda-show-log)
6874 (org-agenda-keep-modes keep-modes)
6875 (entry buffer-file-name)
6876 (date (calendar-current-date))
6877 (win (selected-window))
6878 (pos1 (point))
6879 (beg (if (org-region-active-p) (region-beginning) (point-min)))
6880 (end (if (org-region-active-p) (region-end) (point-max)))
6881 (day-numbers (org-get-all-dates beg end 'no-ranges
6882 t doclosed ; always include today
6883 org-timeline-show-empty-dates))
6884 (today (time-to-days (current-time)))
6885 (past t)
6886 args
6887 s e rtn d emptyp)
6888 (setq org-agenda-redo-command
6889 (list 'progn
6890 (list 'switch-to-buffer-other-window (current-buffer))
6891 (list 'org-timeline (list 'quote include-all) t)))
6892 (if (not dopast)
6893 ;; Remove past dates from the list of dates.
6894 (setq day-numbers (delq nil (mapcar (lambda(x)
6895 (if (>= x today) x nil))
6896 day-numbers))))
6897 (org-prepare-agenda)
6898 (if doclosed (push :closed args))
6899 (push :timestamp args)
6900 (if dotodo (push :todo args))
6901 (while (setq d (pop day-numbers))
6902 (if (and (listp d) (eq (car d) :omitted))
6903 (progn
6904 (setq s (point))
6905 (insert (format "\n[... %d empty days omitted]\n\n" (cdr d)))
6906 (put-text-property s (1- (point)) 'face 'org-level-3))
6907 (if (listp d) (setq d (car d) emptyp t) (setq emptyp nil))
6908 (if (and (>= d today)
6909 dopast
6910 past)
6911 (progn
6912 (setq past nil)
6913 (insert (make-string 79 ?-) "\n")))
6914 (setq date (calendar-gregorian-from-absolute d))
6915 (setq s (point))
6916 (setq rtn (and (not emptyp)
6917 (apply 'org-agenda-get-day-entries
6918 entry date args)))
6919 (if (or rtn (equal d today) org-timeline-show-empty-dates)
6920 (progn
6921 (insert (calendar-day-name date) " "
6922 (number-to-string (extract-calendar-day date)) " "
6923 (calendar-month-name (extract-calendar-month date)) " "
6924 (number-to-string (extract-calendar-year date)) "\n")
6925 (put-text-property s (1- (point)) 'face
6926 'org-level-3)
6927 (if (equal d today)
6928 (put-text-property s (1- (point)) 'org-today t))
6929 (and rtn (insert (org-finalize-agenda-entries rtn) "\n"))
6930 (put-text-property s (1- (point)) 'day d)))))
6931 (goto-char (point-min))
6932 (goto-char (or (text-property-any (point-min) (point-max) 'org-today t)
6933 (point-min)))
6934 (add-text-properties (point-min) (point-max) '(org-agenda-type timeline))
6935 (org-agenda-align-tags)
6936 (setq buffer-read-only t)
6937 (when (not org-select-agenda-window)
6938 (select-window win)
6939 (goto-char pos1))))
6941 (defvar org-agenda-overriding-arguments nil) ; dynamically scoped parameter
6942 (defvar org-agenda-last-arguments nil
6943 "The arguments of the previous call to org-agenda")
6945 ;;;###autoload
6946 (defun org-agenda-list (&optional include-all start-day ndays keep-modes)
6947 "Produce a weekly view from all files in variable `org-agenda-files'.
6948 The view will be for the current week, but from the overview buffer you
6949 will be able to go to other weeks.
6950 With one \\[universal-argument] prefix argument INCLUDE-ALL, all unfinished TODO items will
6951 also be shown, under the current date.
6952 With two \\[universal-argument] prefix argument INCLUDE-ALL, all TODO entries marked DONE
6953 on the days are also shown. See the variable `org-log-done' for how
6954 to turn on logging.
6955 START-DAY defaults to TODAY, or to the most recent match for the weekday
6956 given in `org-agenda-start-on-weekday'.
6957 NDAYS defaults to `org-agenda-ndays'."
6958 (interactive "P")
6959 (if org-agenda-overriding-arguments
6960 (setq include-all (car org-agenda-overriding-arguments)
6961 start-day (nth 1 org-agenda-overriding-arguments)
6962 ndays (nth 2 org-agenda-overriding-arguments)
6963 keep-modes (nth 3 org-agenda-overriding-arguments)))
6964 (setq org-agenda-last-arguments (list include-all start-day ndays keep-modes))
6965 (org-compile-prefix-format 'agenda)
6966 (org-set-sorting-strategy 'agenda)
6967 (require 'calendar)
6968 (let* ((org-agenda-start-on-weekday
6969 (if (or (equal ndays 1)
6970 (and (null ndays) (equal 1 org-agenda-ndays)))
6971 nil org-agenda-start-on-weekday))
6972 (org-agenda-keep-modes keep-modes)
6973 (thefiles (org-agenda-files))
6974 (files thefiles)
6975 (win (selected-window))
6976 (today (time-to-days (current-time)))
6977 (sd (or start-day today))
6978 (start (if (or (null org-agenda-start-on-weekday)
6979 (< org-agenda-ndays 7))
6981 (let* ((nt (calendar-day-of-week
6982 (calendar-gregorian-from-absolute sd)))
6983 (n1 org-agenda-start-on-weekday)
6984 (d (- nt n1)))
6985 (- sd (+ (if (< d 0) 7 0) d)))))
6986 (day-numbers (list start))
6987 (inhibit-redisplay t)
6988 s e rtn rtnall file date d start-pos end-pos todayp nd)
6989 (setq org-agenda-redo-command
6990 (list 'org-agenda-list (list 'quote include-all) start-day ndays t))
6991 ;; Make the list of days
6992 (setq ndays (or ndays org-agenda-ndays)
6993 nd ndays)
6994 (while (> ndays 1)
6995 (push (1+ (car day-numbers)) day-numbers)
6996 (setq ndays (1- ndays)))
6997 (setq day-numbers (nreverse day-numbers))
6998 (org-prepare-agenda)
6999 (org-set-local 'starting-day (car day-numbers))
7000 (org-set-local 'include-all-loc include-all)
7001 (when (and (or include-all org-agenda-include-all-todo)
7002 (member today day-numbers))
7003 (setq files thefiles
7004 rtnall nil)
7005 (while (setq file (pop files))
7006 (catch 'nextfile
7007 (org-check-agenda-file file)
7008 (setq date (calendar-gregorian-from-absolute today)
7009 rtn (org-agenda-get-day-entries
7010 file date :todo))
7011 (setq rtnall (append rtnall rtn))))
7012 (when rtnall
7013 (insert "ALL CURRENTLY OPEN TODO ITEMS:\n")
7014 (add-text-properties (point-min) (1- (point))
7015 (list 'face 'org-level-3))
7016 (insert (org-finalize-agenda-entries rtnall) "\n")))
7017 (setq s (point))
7018 (insert (if (= nd 7) "Week-" "Day-") "agenda:\n")
7019 (add-text-properties s (1- (point)) (list 'face 'org-level-3))
7020 (while (setq d (pop day-numbers))
7021 (setq date (calendar-gregorian-from-absolute d)
7022 s (point))
7023 (if (or (setq todayp (= d today))
7024 (and (not start-pos) (= d sd)))
7025 (setq start-pos (point))
7026 (if (and start-pos (not end-pos))
7027 (setq end-pos (point))))
7028 (setq files thefiles
7029 rtnall nil)
7030 (while (setq file (pop files))
7031 (catch 'nextfile
7032 (org-check-agenda-file file)
7033 (if org-agenda-show-log
7034 (setq rtn (org-agenda-get-day-entries
7035 file date
7036 :deadline :scheduled :timestamp :closed))
7037 (setq rtn (org-agenda-get-day-entries
7038 file date
7039 :deadline :scheduled :timestamp)))
7040 (setq rtnall (append rtnall rtn))))
7041 (if org-agenda-include-diary
7042 (progn
7043 (require 'diary-lib)
7044 (setq rtn (org-get-entries-from-diary date))
7045 (setq rtnall (append rtnall rtn))))
7046 (if (or rtnall org-agenda-show-all-dates)
7047 (progn
7048 (insert (format "%-9s %2d %s %4d\n"
7049 (calendar-day-name date)
7050 (extract-calendar-day date)
7051 (calendar-month-name (extract-calendar-month date))
7052 (extract-calendar-year date)))
7053 (put-text-property s (1- (point)) 'face
7054 'org-level-3)
7055 (if todayp (put-text-property s (1- (point)) 'org-today t))
7057 (if rtnall (insert
7058 (org-finalize-agenda-entries
7059 (org-agenda-add-time-grid-maybe
7060 rtnall nd todayp))
7061 "\n"))
7062 (put-text-property s (1- (point)) 'day d))))
7063 (goto-char (point-min))
7064 (org-fit-agenda-window)
7065 (unless (and (pos-visible-in-window-p (point-min))
7066 (pos-visible-in-window-p (point-max)))
7067 (goto-char (1- (point-max)))
7068 (recenter -1)
7069 (if (not (pos-visible-in-window-p (or start-pos 1)))
7070 (progn
7071 (goto-char (or start-pos 1))
7072 (recenter 1))))
7073 (goto-char (or start-pos 1))
7074 (add-text-properties (point-min) (point-max) '(org-agenda-type agenda))
7075 (org-agenda-align-tags)
7076 (setq buffer-read-only t)
7077 (if (not org-select-agenda-window) (select-window win))
7078 (message "")))
7080 (defvar org-select-this-todo-keyword nil)
7082 ;;;###autoload
7083 (defun org-todo-list (arg &optional keep-modes)
7084 "Show all TODO entries from all agenda file in a single list.
7085 The prefix arg can be used to select a specific TODO keyword and limit
7086 the list to these. When using \\[universal-argument], you will be prompted
7087 for a keyword. A numeric prefix directly selects the Nth keyword in
7088 `org-todo-keywords'."
7089 (interactive "P")
7090 (org-compile-prefix-format 'todo)
7091 (org-set-sorting-strategy 'todo)
7092 (let* ((org-agenda-keep-modes keep-modes)
7093 (today (time-to-days (current-time)))
7094 (date (calendar-gregorian-from-absolute today))
7095 (win (selected-window))
7096 (kwds org-todo-keywords)
7097 (completion-ignore-case t)
7098 (org-select-this-todo-keyword
7099 (if (stringp arg) arg
7100 (and arg (integerp arg) (> arg 0)
7101 (nth (1- arg) org-todo-keywords))))
7102 rtn rtnall files file pos)
7103 (when (equal arg '(4))
7104 (setq org-select-this-todo-keyword
7105 (completing-read "Keyword: " (mapcar 'list org-todo-keywords)
7106 nil t)))
7107 (and (equal 0 arg) (setq org-select-this-todo-keyword nil))
7108 (org-prepare-agenda)
7109 (org-set-local 'last-arg arg)
7110 (org-set-local 'org-todo-keywords kwds)
7111 (setq org-agenda-redo-command
7112 '(org-todo-list (or current-prefix-arg last-arg) t))
7113 (setq files (org-agenda-files)
7114 rtnall nil)
7115 (while (setq file (pop files))
7116 (catch 'nextfile
7117 (org-check-agenda-file file)
7118 (setq rtn (org-agenda-get-day-entries file date :todo))
7119 (setq rtnall (append rtnall rtn))))
7120 (insert "Global list of TODO items of type: ")
7121 (add-text-properties (point-min) (1- (point))
7122 (list 'face 'org-level-3))
7123 (setq pos (point))
7124 (insert (or org-select-this-todo-keyword "ALL") "\n")
7125 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
7126 (setq pos (point))
7127 (unless org-agenda-multi
7128 (insert
7129 "Available with `N r': (0)ALL "
7130 (let ((n 0))
7131 (mapconcat (lambda (x)
7132 (format "(%d)%s" (setq n (1+ n)) x))
7133 org-todo-keywords " "))
7134 "\n"))
7135 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
7136 (when rtnall
7137 (insert (org-finalize-agenda-entries rtnall) "\n"))
7138 (goto-char (point-min))
7139 (org-fit-agenda-window)
7140 (add-text-properties (point-min) (point-max) '(org-agenda-type todo))
7141 (org-agenda-align-tags)
7142 (setq buffer-read-only t)
7143 (if (not org-select-agenda-window) (select-window win))))
7145 (defun org-check-agenda-file (file)
7146 "Make sure FILE exists. If not, ask user what to do."
7147 (when (not (file-exists-p file))
7148 (message "non-existent file %s. [R]emove from list or [A]bort?"
7149 (abbreviate-file-name file))
7150 (let ((r (downcase (read-char-exclusive))))
7151 (cond
7152 ((equal r ?r)
7153 (org-remove-file file)
7154 (throw 'nextfile t))
7155 (t (error "Abort"))))))
7157 (defun org-agenda-check-type (error &rest types)
7158 "Check if agenda buffer is of allowed type.
7159 If ERROR is non-nil, throw an error, otherwise just return nil."
7160 (if (memq org-agenda-type types)
7162 (if error
7163 (error "Not allowed in %s-type agenda buffers" org-agenda-type)
7164 nil)))
7166 (defun org-agenda-quit ()
7167 "Exit agenda by removing the window or the buffer."
7168 (interactive)
7169 (let ((buf (current-buffer)))
7170 (if (not (one-window-p)) (delete-window))
7171 (kill-buffer buf)
7172 (org-agenda-maybe-reset-markers 'force)))
7174 (defun org-agenda-exit ()
7175 "Exit agenda by removing the window or the buffer.
7176 Also kill all Org-mode buffers which have been loaded by `org-agenda'.
7177 Org-mode buffers visited directly by the user will not be touched."
7178 (interactive)
7179 (org-release-buffers org-agenda-new-buffers)
7180 (setq org-agenda-new-buffers nil)
7181 (org-agenda-quit))
7183 ;; FIXME: move this function.
7184 (defun org-save-all-org-buffers ()
7185 "Save all Org-mode buffers without user confirmation."
7186 (interactive)
7187 (message "Saving all Org-mode buffers...")
7188 (save-some-buffers t 'org-mode-p)
7189 (message "Saving all Org-mode buffers... done"))
7191 (defun org-agenda-redo ()
7192 "Rebuild Agenda.
7193 When this is the global TODO list, a prefix argument will be interpreted."
7194 (interactive)
7195 (let* ((line (org-current-line))
7196 (window-line (- line (org-current-line (window-start)))))
7197 (message "Rebuilding agenda buffer...")
7198 (eval org-agenda-redo-command)
7199 (message "Rebuilding agenda buffer...done")
7200 (goto-line line)
7201 (recenter window-line)))
7203 (defun org-agenda-goto-today ()
7204 "Go to today."
7205 (interactive)
7206 (org-agenda-check-type t 'timeline 'agenda)
7207 (let ((tdpos (text-property-any (point-min) (point-max) 'org-today t)))
7208 (cond
7209 (tdpos (goto-char tdpos))
7210 ((eq org-agenda-type 'agenda)
7211 (let ((org-agenda-overriding-arguments org-agenda-last-arguments))
7212 (setf (nth 1 org-agenda-overriding-arguments) nil)
7213 (org-agenda-redo)
7214 (org-agenda-find-today-or-agenda)))
7215 (t (error "Cannot find today")))))
7217 (defun org-agenda-find-today-or-agenda ()
7218 (goto-char
7219 (or (text-property-any (point-min) (point-max) 'org-today t)
7220 (text-property-any (point-min) (point-max) 'org-agenda-type 'agenda)
7221 (point-min))))
7223 (defun org-agenda-later (arg)
7224 "Go forward in time by `org-agenda-ndays' days.
7225 With prefix ARG, go forward that many times `org-agenda-ndays'."
7226 (interactive "p")
7227 (org-agenda-check-type t 'agenda)
7228 (let ((org-agenda-overriding-arguments
7229 (list (car org-agenda-last-arguments)
7230 (+ starting-day (* arg org-agenda-ndays))
7231 nil t)))
7232 (org-agenda-redo)
7233 (org-agenda-find-today-or-agenda)))
7235 (defun org-agenda-earlier (arg)
7236 "Go back in time by `org-agenda-ndays' days.
7237 With prefix ARG, go back that many times `org-agenda-ndays'."
7238 (interactive "p")
7239 (org-agenda-check-type t 'agenda)
7240 (let ((org-agenda-overriding-arguments
7241 (list (car org-agenda-last-arguments)
7242 (- starting-day (* arg org-agenda-ndays))
7243 nil t)))
7244 (org-agenda-redo)
7245 (org-agenda-find-today-or-agenda)))
7247 (defun org-agenda-week-view ()
7248 "Switch to weekly view for agenda."
7249 (interactive)
7250 (org-agenda-check-type t 'agenda)
7251 (if (= org-agenda-ndays 7)
7252 (error "This is already the week view"))
7253 (setq org-agenda-ndays 7)
7254 (let ((org-agenda-overriding-arguments
7255 (list (car org-agenda-last-arguments)
7256 (or (get-text-property (point) 'day)
7257 starting-day)
7258 nil t)))
7259 (org-agenda-redo)
7260 (org-agenda-find-today-or-agenda))
7261 (org-agenda-set-mode-name)
7262 (message "Switched to week view"))
7264 (defun org-agenda-day-view ()
7265 "Switch to daily view for agenda."
7266 (interactive)
7267 (org-agenda-check-type t 'agenda)
7268 (if (= org-agenda-ndays 1)
7269 (error "This is already the day view"))
7270 (setq org-agenda-ndays 1)
7271 (let ((org-agenda-overriding-arguments
7272 (list (car org-agenda-last-arguments)
7273 (or (get-text-property (point) 'day)
7274 starting-day)
7275 nil t)))
7276 (org-agenda-redo)
7277 (org-agenda-find-today-or-agenda))
7278 (org-agenda-set-mode-name)
7279 (message "Switched to day view"))
7281 (defun org-agenda-next-date-line (&optional arg)
7282 "Jump to the next line indicating a date in agenda buffer."
7283 (interactive "p")
7284 (org-agenda-check-type t 'agenda 'timeline)
7285 (beginning-of-line 1)
7286 (if (looking-at "^\\S-") (forward-char 1))
7287 (if (not (re-search-forward "^\\S-" nil t arg))
7288 (progn
7289 (backward-char 1)
7290 (error "No next date after this line in this buffer")))
7291 (goto-char (match-beginning 0)))
7293 (defun org-agenda-previous-date-line (&optional arg)
7294 "Jump to the previous line indicating a date in agenda buffer."
7295 (interactive "p")
7296 (org-agenda-check-type t 'agenda 'timeline)
7297 (beginning-of-line 1)
7298 (if (not (re-search-backward "^\\S-" nil t arg))
7299 (error "No previous date before this line in this buffer")))
7301 ;; Initialize the highlight
7302 (defvar org-hl (org-make-overlay 1 1))
7303 (org-overlay-put org-hl 'face 'highlight)
7305 (defun org-highlight (begin end &optional buffer)
7306 "Highlight a region with overlay."
7307 (funcall (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay)
7308 org-hl begin end (or buffer (current-buffer))))
7310 (defun org-unhighlight ()
7311 "Detach overlay INDEX."
7312 (funcall (if (featurep 'xemacs) 'detach-extent 'delete-overlay) org-hl))
7315 (defun org-agenda-follow-mode ()
7316 "Toggle follow mode in an agenda buffer."
7317 (interactive)
7318 (setq org-agenda-follow-mode (not org-agenda-follow-mode))
7319 (org-agenda-set-mode-name)
7320 (message "Follow mode is %s"
7321 (if org-agenda-follow-mode "on" "off")))
7323 (defun org-agenda-log-mode ()
7324 "Toggle log mode in an agenda buffer."
7325 (interactive)
7326 (org-agenda-check-type t 'agenda 'timeline)
7327 (setq org-agenda-show-log (not org-agenda-show-log))
7328 (org-agenda-set-mode-name)
7329 (org-agenda-redo)
7330 (message "Log mode is %s"
7331 (if org-agenda-show-log "on" "off")))
7333 (defun org-agenda-toggle-diary ()
7334 "Toggle diary inclusion in an agenda buffer."
7335 (interactive)
7336 (org-agenda-check-type t 'agenda)
7337 (setq org-agenda-include-diary (not org-agenda-include-diary))
7338 (org-agenda-redo)
7339 (org-agenda-set-mode-name)
7340 (message "Diary inclusion turned %s"
7341 (if org-agenda-include-diary "on" "off")))
7343 (defun org-agenda-toggle-time-grid ()
7344 "Toggle time grid in an agenda buffer."
7345 (interactive)
7346 (org-agenda-check-type t 'agenda)
7347 (setq org-agenda-use-time-grid (not org-agenda-use-time-grid))
7348 (org-agenda-redo)
7349 (org-agenda-set-mode-name)
7350 (message "Time-grid turned %s"
7351 (if org-agenda-use-time-grid "on" "off")))
7353 (defun org-agenda-set-mode-name ()
7354 "Set the mode name to indicate all the small mode settings."
7355 (setq mode-name
7356 (concat "Org-Agenda"
7357 (if (equal org-agenda-ndays 1) " Day" "")
7358 (if (equal org-agenda-ndays 7) " Week" "")
7359 (if org-agenda-follow-mode " Follow" "")
7360 (if org-agenda-include-diary " Diary" "")
7361 (if org-agenda-use-time-grid " Grid" "")
7362 (if org-agenda-show-log " Log" "")))
7363 (force-mode-line-update))
7365 (defun org-agenda-post-command-hook ()
7366 (and (eolp) (not (bolp)) (backward-char 1))
7367 (setq org-agenda-type (get-text-property (point) 'org-agenda-type))
7368 (if (and org-agenda-follow-mode
7369 (get-text-property (point) 'org-marker))
7370 (org-agenda-show)))
7372 (defvar org-disable-agenda-to-diary nil) ;Dynamically-scoped param.
7374 (defun org-get-entries-from-diary (date)
7375 "Get the (Emacs Calendar) diary entries for DATE."
7376 (let* ((fancy-diary-buffer "*temporary-fancy-diary-buffer*")
7377 (diary-display-hook '(fancy-diary-display))
7378 (list-diary-entries-hook
7379 (cons 'org-diary-default-entry list-diary-entries-hook))
7380 (diary-file-name-prefix-function nil) ; turn this feature off
7381 (diary-modify-entry-list-string-function 'org-modify-diary-entry-string)
7382 entries
7383 (org-disable-agenda-to-diary t))
7384 (save-excursion
7385 (save-window-excursion
7386 (list-diary-entries date 1))) ;; Keep this name for now, compatibility
7387 (if (not (get-buffer fancy-diary-buffer))
7388 (setq entries nil)
7389 (with-current-buffer fancy-diary-buffer
7390 (setq buffer-read-only nil)
7391 (if (= (point-max) 1)
7392 ;; No entries
7393 (setq entries nil)
7394 ;; Omit the date and other unnecessary stuff
7395 (org-agenda-cleanup-fancy-diary)
7396 ;; Add prefix to each line and extend the text properties
7397 (if (= (point-max) 1)
7398 (setq entries nil)
7399 (setq entries (buffer-substring (point-min) (- (point-max) 1)))))
7400 (set-buffer-modified-p nil)
7401 (kill-buffer fancy-diary-buffer)))
7402 (when entries
7403 (setq entries (org-split-string entries "\n"))
7404 (setq entries
7405 (mapcar
7406 (lambda (x)
7407 (setq x (org-format-agenda-item "" x "Diary" nil 'time))
7408 ;; Extend the text properties to the beginning of the line
7409 (org-add-props x (text-properties-at (1- (length x)) x)))
7410 entries)))))
7412 (defun org-agenda-cleanup-fancy-diary ()
7413 "Remove unwanted stuff in buffer created by `fancy-diary-display'.
7414 This gets rid of the date, the underline under the date, and
7415 the dummy entry installed by `org-mode' to ensure non-empty diary for each
7416 date. It also removes lines that contain only whitespace."
7417 (goto-char (point-min))
7418 (if (looking-at ".*?:[ \t]*")
7419 (progn
7420 (replace-match "")
7421 (re-search-forward "\n=+$" nil t)
7422 (replace-match "")
7423 (while (re-search-backward "^ +\n?" nil t) (replace-match "")))
7424 (re-search-forward "\n=+$" nil t)
7425 (delete-region (point-min) (min (point-max) (1+ (match-end 0)))))
7426 (goto-char (point-min))
7427 (while (re-search-forward "^ +\n" nil t)
7428 (replace-match ""))
7429 (goto-char (point-min))
7430 (if (re-search-forward "^Org-mode dummy\n?" nil t)
7431 (replace-match "")))
7433 ;; Make sure entries from the diary have the right text properties.
7434 (eval-after-load "diary-lib"
7435 '(if (boundp 'diary-modify-entry-list-string-function)
7436 ;; We can rely on the hook, nothing to do
7438 ;; Hook not avaiable, must use advice to make this work
7439 (defadvice add-to-diary-list (before org-mark-diary-entry activate)
7440 "Make the position visible."
7441 (if (and org-disable-agenda-to-diary ;; called from org-agenda
7442 (stringp string)
7443 buffer-file-name)
7444 (setq string (org-modify-diary-entry-string string))))))
7446 (defun org-modify-diary-entry-string (string)
7447 "Add text properties to string, allowing org-mode to act on it."
7448 (org-add-props string nil
7449 'mouse-face 'highlight
7450 'keymap org-agenda-keymap
7451 'help-echo (format "mouse-2 or RET jump to diary file %s"
7452 (abbreviate-file-name buffer-file-name))
7453 'org-agenda-diary-link t
7454 'org-marker (org-agenda-new-marker (point-at-bol))))
7456 (defun org-diary-default-entry ()
7457 "Add a dummy entry to the diary.
7458 Needed to avoid empty dates which mess up holiday display."
7459 ;; Catch the error if dealing with the new add-to-diary-alist
7460 (when org-disable-agenda-to-diary
7461 (condition-case nil
7462 (add-to-diary-list original-date "Org-mode dummy" "")
7463 (error
7464 (add-to-diary-list original-date "Org-mode dummy" "" nil)))))
7466 (defun org-cycle-agenda-files ()
7467 "Cycle through the files in `org-agenda-files'.
7468 If the current buffer visits an agenda file, find the next one in the list.
7469 If the current buffer does not, find the first agenda file."
7470 (interactive)
7471 (let* ((fs (org-agenda-files t))
7472 (files (append fs (list (car fs))))
7473 (tcf (if buffer-file-name (file-truename buffer-file-name)))
7474 file)
7475 (unless files (error "No agenda files"))
7476 (catch 'exit
7477 (while (setq file (pop files))
7478 (if (equal (file-truename file) tcf)
7479 (when (car files)
7480 (find-file (car files))
7481 (throw 'exit t))))
7482 (find-file (car fs)))))
7484 (defun org-agenda-file-to-end ()
7485 "Move/add the current file to the end of the agenda file list.
7486 If the file is not present in the list, it is appended to the list. If it is
7487 present, it is moved there."
7488 (interactive)
7489 (org-agenda-file-to-front 'to-end))
7491 (defun org-agenda-file-to-front (&optional to-end)
7492 "Move/add the current file to the top of the agenda file list.
7493 If the file is not present in the list, it is added to the front. If it is
7494 present, it is moved there. With optional argument TO-END, add/move to the
7495 end of the list."
7496 (interactive "P")
7497 (let ((file-alist (mapcar (lambda (x)
7498 (cons (file-truename x) x))
7499 (org-agenda-files t)))
7500 (ctf (file-truename buffer-file-name))
7501 x had)
7502 (setq x (assoc ctf file-alist) had x)
7504 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
7505 (if to-end
7506 (setq file-alist (append (delq x file-alist) (list x)))
7507 (setq file-alist (cons x (delq x file-alist))))
7508 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
7509 (org-install-agenda-files-menu)
7510 (message "File %s to %s of agenda file list"
7511 (if had "moved" "added") (if to-end "end" "front"))))
7513 (defun org-remove-file (&optional file)
7514 "Remove current file from the list of files in variable `org-agenda-files'.
7515 These are the files which are being checked for agenda entries.
7516 Optional argument FILE means, use this file instead of the current."
7517 (interactive)
7518 (let* ((file (or file buffer-file-name))
7519 (true-file (file-truename file))
7520 (afile (abbreviate-file-name file))
7521 (files (delq nil (mapcar
7522 (lambda (x)
7523 (if (equal true-file
7524 (file-truename x))
7525 nil x))
7526 (org-agenda-files t)))))
7527 (if (not (= (length files) (length (org-agenda-files t))))
7528 (progn
7529 (org-store-new-agenda-file-list files)
7530 (org-install-agenda-files-menu)
7531 (message "Removed file: %s" afile))
7532 (message "File was not in list: %s" afile))))
7534 (defun org-file-menu-entry (file)
7535 (vector file (list 'find-file file) t))
7537 (defun org-get-all-dates (beg end &optional no-ranges force-today inactive empty)
7538 "Return a list of all relevant day numbers from BEG to END buffer positions.
7539 If NO-RANGES is non-nil, include only the start and end dates of a range,
7540 not every single day in the range. If FORCE-TODAY is non-nil, make
7541 sure that TODAY is included in the list. If INACTIVE is non-nil, also
7542 inactive time stamps (those in square brackets) are included.
7543 When EMPTY is non-nil, also include days without any entries."
7544 (let ((re (if inactive org-ts-regexp-both org-ts-regexp))
7545 dates dates1 date day day1 day2 ts1 ts2)
7546 (if force-today
7547 (setq dates (list (time-to-days (current-time)))))
7548 (save-excursion
7549 (goto-char beg)
7550 (while (re-search-forward re end t)
7551 (setq day (time-to-days (org-time-string-to-time
7552 (substring (match-string 1) 0 10))))
7553 (or (memq day dates) (push day dates)))
7554 (unless no-ranges
7555 (goto-char beg)
7556 (while (re-search-forward org-tr-regexp end t)
7557 (setq ts1 (substring (match-string 1) 0 10)
7558 ts2 (substring (match-string 2) 0 10)
7559 day1 (time-to-days (org-time-string-to-time ts1))
7560 day2 (time-to-days (org-time-string-to-time ts2)))
7561 (while (< (setq day1 (1+ day1)) day2)
7562 (or (memq day1 dates) (push day1 dates)))))
7563 (setq dates (sort dates '<))
7564 (when empty
7565 (while (setq day (pop dates))
7566 (setq day2 (car dates))
7567 (push day dates1)
7568 (when (and day2 empty)
7569 (if (or (eq empty t)
7570 (and (numberp empty) (<= (- day2 day) empty)))
7571 (while (< (setq day (1+ day)) day2)
7572 (push (list day) dates1))
7573 (push (cons :omitted (- day2 day)) dates1))))
7574 (setq dates (nreverse dates1)))
7575 dates)))
7577 ;;;###autoload
7578 (defun org-diary (&rest args)
7579 "Return diary information from org-files.
7580 This function can be used in a \"sexp\" diary entry in the Emacs calendar.
7581 It accesses org files and extracts information from those files to be
7582 listed in the diary. The function accepts arguments specifying what
7583 items should be listed. The following arguments are allowed:
7585 :timestamp List the headlines of items containing a date stamp or
7586 date range matching the selected date. Deadlines will
7587 also be listed, on the expiration day.
7589 :deadline List any deadlines past due, or due within
7590 `org-deadline-warning-days'. The listing occurs only
7591 in the diary for *today*, not at any other date. If
7592 an entry is marked DONE, it is no longer listed.
7594 :scheduled List all items which are scheduled for the given date.
7595 The diary for *today* also contains items which were
7596 scheduled earlier and are not yet marked DONE.
7598 :todo List all TODO items from the org-file. This may be a
7599 long list - so this is not turned on by default.
7600 Like deadlines, these entries only show up in the
7601 diary for *today*, not at any other date.
7603 The call in the diary file should look like this:
7605 &%%(org-diary) ~/path/to/some/orgfile.org
7607 Use a separate line for each org file to check. Or, if you omit the file name,
7608 all files listed in `org-agenda-files' will be checked automatically:
7610 &%%(org-diary)
7612 If you don't give any arguments (as in the example above), the default
7613 arguments (:deadline :scheduled :timestamp) are used. So the example above may
7614 also be written as
7616 &%%(org-diary :deadline :timestamp :scheduled)
7618 The function expects the lisp variables `entry' and `date' to be provided
7619 by the caller, because this is how the calendar works. Don't use this
7620 function from a program - use `org-agenda-get-day-entries' instead."
7621 (org-agenda-maybe-reset-markers) ;; FIXME: does this still do the right thing?
7622 (org-compile-prefix-format 'agenda)
7623 (org-set-sorting-strategy 'agenda)
7624 (setq args (or args '(:deadline :scheduled :timestamp)))
7625 (let* ((files (if (and entry (stringp entry) (string-match "\\S-" entry))
7626 (list entry)
7627 (org-agenda-files t)))
7628 file rtn results)
7629 ;; If this is called during org-agenda, don't return any entries to
7630 ;; the calendar. Org Agenda will list these entries itself.
7631 (if org-disable-agenda-to-diary (setq files nil))
7632 (while (setq file (pop files))
7633 (setq rtn (apply 'org-agenda-get-day-entries file date args))
7634 (setq results (append results rtn)))
7635 (if results
7636 (concat (org-finalize-agenda-entries results) "\n"))))
7637 (defvar org-category-table nil)
7638 (defun org-get-category-table ()
7639 "Get the table of categories and positions in current buffer."
7640 (let (tbl)
7641 (save-excursion
7642 (goto-char (point-min))
7643 (while (re-search-forward "\\(^\\|\r\\)#\\+CATEGORY:[ \t]*\\(.*\\)" nil t)
7644 (push (cons (point) (org-trim (match-string 2))) tbl)))
7645 tbl))
7646 (defun org-get-category (&optional pos)
7647 "Get the category applying to position POS."
7648 (if (not org-category-table)
7649 (cond
7650 ((null org-category)
7651 (setq org-category
7652 (if buffer-file-name
7653 (file-name-sans-extension
7654 (file-name-nondirectory buffer-file-name))
7655 "???")))
7656 ((symbolp org-category) (symbol-name org-category))
7657 (t org-category))
7658 (let ((tbl org-category-table)
7659 (pos (or pos (point))))
7660 (while (and tbl (> (caar tbl) pos))
7661 (pop tbl))
7662 (or (cdar tbl) (cdr (nth (1- (length org-category-table))
7663 org-category-table))))))
7665 (defun org-agenda-get-day-entries (file date &rest args)
7666 "Does the work for `org-diary' and `org-agenda'.
7667 FILE is the path to a file to be checked for entries. DATE is date like
7668 the one returned by `calendar-current-date'. ARGS are symbols indicating
7669 which kind of entries should be extracted. For details about these, see
7670 the documentation of `org-diary'."
7671 (setq args (or args '(:deadline :scheduled :timestamp)))
7672 (let* ((org-startup-with-deadline-check nil)
7673 (org-startup-folded nil)
7674 (org-startup-align-all-tables nil)
7675 (buffer (if (file-exists-p file)
7676 (org-get-agenda-file-buffer file)
7677 (error "No such file %s" file)))
7678 arg results rtn)
7679 (if (not buffer)
7680 ;; If file does not exist, make sure an error message ends up in diary
7681 (list (format "ORG-AGENDA-ERROR: No such org-file %s" file))
7682 (with-current-buffer buffer
7683 (unless (org-mode-p)
7684 (error "Agenda file %s is not in `org-mode'" file))
7685 (setq org-category-table (org-get-category-table))
7686 (let ((case-fold-search nil))
7687 (save-excursion
7688 (save-restriction
7689 (if org-agenda-restrict
7690 (narrow-to-region org-agenda-restrict-begin
7691 org-agenda-restrict-end)
7692 (widen))
7693 ;; The way we repeatedly append to `results' makes it O(n^2) :-(
7694 (while (setq arg (pop args))
7695 (cond
7696 ((and (eq arg :todo)
7697 (equal date (calendar-current-date)))
7698 (setq rtn (org-agenda-get-todos))
7699 (setq results (append results rtn)))
7700 ((eq arg :timestamp)
7701 (setq rtn (org-agenda-get-blocks))
7702 (setq results (append results rtn))
7703 (setq rtn (org-agenda-get-timestamps))
7704 (setq results (append results rtn)))
7705 ((eq arg :scheduled)
7706 (setq rtn (org-agenda-get-scheduled))
7707 (setq results (append results rtn)))
7708 ((eq arg :closed)
7709 (setq rtn (org-agenda-get-closed))
7710 (setq results (append results rtn)))
7711 ((and (eq arg :deadline)
7712 (equal date (calendar-current-date)))
7713 (setq rtn (org-agenda-get-deadlines))
7714 (setq results (append results rtn))))))))
7715 results))))
7717 (defun org-entry-is-done-p ()
7718 "Is the current entry marked DONE?"
7719 (save-excursion
7720 (and (re-search-backward "[\r\n]\\*" nil t)
7721 (looking-at org-nl-done-regexp))))
7723 (defun org-at-date-range-p ()
7724 "Is the cursor inside a date range?"
7725 (interactive)
7726 (save-excursion
7727 (catch 'exit
7728 (let ((pos (point)))
7729 (skip-chars-backward "^<\r\n")
7730 (skip-chars-backward "<")
7731 (and (looking-at org-tr-regexp)
7732 (>= (match-end 0) pos)
7733 (throw 'exit t))
7734 (skip-chars-backward "^<\r\n")
7735 (skip-chars-backward "<")
7736 (and (looking-at org-tr-regexp)
7737 (>= (match-end 0) pos)
7738 (throw 'exit t)))
7739 nil)))
7741 (defun org-agenda-get-todos ()
7742 "Return the TODO information for agenda display."
7743 (let* ((props (list 'face nil
7744 'done-face 'org-done
7745 'org-not-done-regexp org-not-done-regexp
7746 'mouse-face 'highlight
7747 'keymap org-agenda-keymap
7748 'help-echo
7749 (format "mouse-2 or RET jump to org file %s"
7750 (abbreviate-file-name buffer-file-name))))
7751 (regexp (concat "[\n\r]\\*+ *\\("
7752 (if org-select-this-todo-keyword
7753 (concat "\\<\\(" org-select-this-todo-keyword
7754 "\\)\\>")
7755 org-not-done-regexp)
7756 "[^\n\r]*\\)"))
7757 (sched-re (concat ".*\n?.*?" org-scheduled-time-regexp))
7758 marker priority category tags
7759 ee txt)
7760 (goto-char (point-min))
7761 (while (re-search-forward regexp nil t)
7762 (catch :skip
7763 (when (and org-agenda-todo-ignore-scheduled
7764 (looking-at sched-re))
7765 ;; FIXME: the following test also happens below, but we need it here
7766 (or org-agenda-todo-list-sublevels (org-end-of-subtree 'invisible))
7767 (throw :skip nil))
7768 (org-agenda-skip)
7769 (goto-char (match-beginning 1))
7770 (setq marker (org-agenda-new-marker (1+ (match-beginning 0)))
7771 category (org-get-category)
7772 tags (org-get-tags-at (point))
7773 txt (org-format-agenda-item "" (match-string 1) category tags)
7774 priority
7775 (+ (org-get-priority txt)
7776 (if org-todo-kwd-priority-p
7777 (- org-todo-kwd-max-priority -2
7778 (length
7779 (member (match-string 2) org-todo-keywords)))
7780 1)))
7781 (org-add-props txt props
7782 'org-marker marker 'org-hd-marker marker
7783 'priority priority 'category category)
7784 (push txt ee)
7785 (if org-agenda-todo-list-sublevels
7786 (goto-char (match-end 1))
7787 (org-end-of-subtree 'invisible))))
7788 (nreverse ee)))
7790 (defconst org-agenda-no-heading-message
7791 "No heading for this item in buffer or region.")
7793 (defun org-agenda-get-timestamps ()
7794 "Return the date stamp information for agenda display."
7795 (let* ((props (list 'face nil
7796 'org-not-done-regexp org-not-done-regexp
7797 'mouse-face 'highlight
7798 'keymap org-agenda-keymap
7799 'help-echo
7800 (format "mouse-2 or RET jump to org file %s"
7801 (abbreviate-file-name buffer-file-name))))
7802 (regexp (regexp-quote
7803 (substring
7804 (format-time-string
7805 (car org-time-stamp-formats)
7806 (apply 'encode-time ; DATE bound by calendar
7807 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7808 0 11)))
7809 marker hdmarker deadlinep scheduledp donep tmp priority category
7810 ee txt timestr tags)
7811 (goto-char (point-min))
7812 (while (re-search-forward regexp nil t)
7813 (catch :skip
7814 (and (save-match-data (org-at-date-range-p)) (throw :skip nil))
7815 (org-agenda-skip)
7816 (setq marker (org-agenda-new-marker (match-beginning 0))
7817 category (org-get-category (match-beginning 0))
7818 tmp (buffer-substring (max (point-min)
7819 (- (match-beginning 0)
7820 org-ds-keyword-length))
7821 (match-beginning 0))
7822 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7823 deadlinep (string-match org-deadline-regexp tmp)
7824 scheduledp (string-match org-scheduled-regexp tmp)
7825 donep (org-entry-is-done-p))
7826 (if (string-match ">" timestr)
7827 ;; substring should only run to end of time stamp
7828 (setq timestr (substring timestr 0 (match-end 0))))
7829 (save-excursion
7830 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7831 (progn
7832 (goto-char (match-end 1))
7833 (setq hdmarker (org-agenda-new-marker)
7834 tags (org-get-tags-at))
7835 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7836 (setq txt (org-format-agenda-item
7837 (format "%s%s"
7838 (if deadlinep "Deadline: " "")
7839 (if scheduledp "Scheduled: " ""))
7840 (match-string 1) category tags timestr)))
7841 (setq txt org-agenda-no-heading-message))
7842 (setq priority (org-get-priority txt))
7843 (org-add-props txt props
7844 'org-marker marker 'org-hd-marker hdmarker)
7845 (if deadlinep
7846 (org-add-props txt nil
7847 'face (if donep 'org-done 'org-warning)
7848 'undone-face 'org-warning 'done-face 'org-done
7849 'category category 'priority (+ 100 priority))
7850 (if scheduledp
7851 (org-add-props txt nil
7852 'face 'org-scheduled-today
7853 'undone-face 'org-scheduled-today 'done-face 'org-done
7854 'category category 'priority (+ 99 priority))
7855 (org-add-props txt nil 'priority priority 'category category)))
7856 (push txt ee))
7857 (outline-next-heading)))
7858 (nreverse ee)))
7860 (defun org-agenda-get-closed ()
7861 "Return the logged TODO entries for agenda display."
7862 (let* ((props (list 'mouse-face 'highlight
7863 'org-not-done-regexp org-not-done-regexp
7864 'keymap org-agenda-keymap
7865 'help-echo
7866 (format "mouse-2 or RET jump to org file %s"
7867 (abbreviate-file-name buffer-file-name))))
7868 (regexp (concat
7869 "\\<\\(" org-closed-string "\\|" org-clock-string "\\) *\\["
7870 (regexp-quote
7871 (substring
7872 (format-time-string
7873 (car org-time-stamp-formats)
7874 (apply 'encode-time ; DATE bound by calendar
7875 (list 0 0 0 (nth 1 date) (car date) (nth 2 date))))
7876 1 11))))
7877 marker hdmarker priority category tags closedp
7878 ee txt timestr)
7879 (goto-char (point-min))
7880 (while (re-search-forward regexp nil t)
7881 (catch :skip
7882 (org-agenda-skip)
7883 (setq marker (org-agenda-new-marker (match-beginning 0))
7884 closedp (equal (match-string 1) org-closed-string)
7885 category (org-get-category (match-beginning 0))
7886 timestr (buffer-substring (match-beginning 0) (point-at-eol))
7887 ;; donep (org-entry-is-done-p)
7889 (if (string-match "\\]" timestr)
7890 ;; substring should only run to end of time stamp
7891 (setq timestr (substring timestr 0 (match-end 0))))
7892 (save-excursion
7893 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
7894 (progn
7895 (goto-char (match-end 1))
7896 (setq hdmarker (org-agenda-new-marker)
7897 tags (org-get-tags-at))
7898 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
7899 (setq txt (org-format-agenda-item
7900 (if closedp "Closed: " "Clocked: ")
7901 (match-string 1) category tags timestr)))
7902 (setq txt org-agenda-no-heading-message))
7903 (setq priority 100000)
7904 (org-add-props txt props
7905 'org-marker marker 'org-hd-marker hdmarker 'face 'org-done
7906 'priority priority 'category category
7907 'undone-face 'org-warning 'done-face 'org-done)
7908 (push txt ee))
7909 (outline-next-heading)))
7910 (nreverse ee)))
7912 (defun org-agenda-get-deadlines ()
7913 "Return the deadline information for agenda display."
7914 (let* ((wdays org-deadline-warning-days)
7915 (props (list 'mouse-face 'highlight
7916 'org-not-done-regexp org-not-done-regexp
7917 'keymap org-agenda-keymap
7918 'help-echo
7919 (format "mouse-2 or RET jump to org file %s"
7920 (abbreviate-file-name buffer-file-name))))
7921 (regexp org-deadline-time-regexp)
7922 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7923 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7924 d2 diff pos pos1 category tags
7925 ee txt head face)
7926 (goto-char (point-min))
7927 (while (re-search-forward regexp nil t)
7928 (catch :skip
7929 (org-agenda-skip)
7930 (setq pos (1- (match-beginning 1))
7931 d2 (time-to-days
7932 (org-time-string-to-time (match-string 1)))
7933 diff (- d2 d1))
7934 ;; When to show a deadline in the calendar:
7935 ;; If the expiration is within wdays warning time.
7936 ;; Past-due deadlines are only shown on the current date
7937 (if (and (< diff wdays) todayp (not (= diff 0)))
7938 (save-excursion
7939 (setq category (org-get-category))
7940 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7941 (progn
7942 (goto-char (match-end 0))
7943 (setq pos1 (match-end 1))
7944 (setq tags (org-get-tags-at pos1))
7945 (setq head (buffer-substring-no-properties
7946 (point)
7947 (progn (skip-chars-forward "^\r\n")
7948 (point))))
7949 (if (string-match org-looking-at-done-regexp head)
7950 (setq txt nil)
7951 (setq txt (org-format-agenda-item
7952 (format "In %3d d.: " diff) head category tags))))
7953 (setq txt org-agenda-no-heading-message))
7954 (when txt
7955 (setq face (cond ((<= diff 0) 'org-warning)
7956 ((<= diff 5) 'org-upcoming-deadline)
7957 (t nil)))
7958 (org-add-props txt props
7959 'org-marker (org-agenda-new-marker pos)
7960 'org-hd-marker (org-agenda-new-marker pos1)
7961 'priority (+ (- 10 diff) (org-get-priority txt))
7962 'category category
7963 'face face 'undone-face face 'done-face 'org-done)
7964 (push txt ee))))))
7965 ee))
7967 (defun org-agenda-get-scheduled ()
7968 "Return the scheduled information for agenda display."
7969 (let* ((props (list 'face 'org-scheduled-previously
7970 'org-not-done-regexp org-not-done-regexp
7971 'undone-face 'org-scheduled-previously
7972 'done-face 'org-done
7973 'mouse-face 'highlight
7974 'keymap org-agenda-keymap
7975 'help-echo
7976 (format "mouse-2 or RET jump to org file %s"
7977 (abbreviate-file-name buffer-file-name))))
7978 (regexp org-scheduled-time-regexp)
7979 (todayp (equal date (calendar-current-date))) ; DATE bound by calendar
7980 (d1 (calendar-absolute-from-gregorian date)) ; DATE bound by calendar
7981 d2 diff pos pos1 category tags
7982 ee txt head)
7983 (goto-char (point-min))
7984 (while (re-search-forward regexp nil t)
7985 (catch :skip
7986 (org-agenda-skip)
7987 (setq pos (1- (match-beginning 1))
7988 d2 (time-to-days
7989 (org-time-string-to-time (match-string 1)))
7990 diff (- d2 d1))
7991 ;; When to show a scheduled item in the calendar:
7992 ;; If it is on or past the date.
7993 (if (and (< diff 0) todayp)
7994 (save-excursion
7995 (setq category (org-get-category))
7996 (if (re-search-backward "\\(^\\|\r\\)\\*+[ \t]*" nil t)
7997 (progn
7998 (goto-char (match-end 0))
7999 (setq pos1 (match-end 1))
8000 (setq tags (org-get-tags-at))
8001 (setq head (buffer-substring-no-properties
8002 (point)
8003 (progn (skip-chars-forward "^\r\n") (point))))
8004 (if (string-match org-looking-at-done-regexp head)
8005 (setq txt nil)
8006 (setq txt (org-format-agenda-item
8007 (format "Sched.%2dx: " (- 1 diff)) head
8008 category tags))))
8009 (setq txt org-agenda-no-heading-message))
8010 (when txt
8011 (org-add-props txt props
8012 'org-marker (org-agenda-new-marker pos)
8013 'org-hd-marker (org-agenda-new-marker pos1)
8014 'priority (+ (- 5 diff) (org-get-priority txt))
8015 'category category)
8016 (push txt ee))))))
8017 ee))
8019 (defun org-agenda-get-blocks ()
8020 "Return the date-range information for agenda display."
8021 (let* ((props (list 'face nil
8022 'org-not-done-regexp org-not-done-regexp
8023 'mouse-face 'highlight
8024 'keymap org-agenda-keymap
8025 'help-echo
8026 (format "mouse-2 or RET jump to org file %s"
8027 (abbreviate-file-name buffer-file-name))))
8028 (regexp org-tr-regexp)
8029 (d0 (calendar-absolute-from-gregorian date))
8030 marker hdmarker ee txt d1 d2 s1 s2 timestr category tags pos)
8031 (goto-char (point-min))
8032 (while (re-search-forward regexp nil t)
8033 (catch :skip
8034 (org-agenda-skip)
8035 (setq pos (point))
8036 (setq timestr (match-string 0)
8037 s1 (match-string 1)
8038 s2 (match-string 2)
8039 d1 (time-to-days (org-time-string-to-time s1))
8040 d2 (time-to-days (org-time-string-to-time s2)))
8041 (if (and (> (- d0 d1) -1) (> (- d2 d0) -1))
8042 ;; Only allow days between the limits, because the normal
8043 ;; date stamps will catch the limits.
8044 (save-excursion
8045 (setq marker (org-agenda-new-marker (point)))
8046 (setq category (org-get-category))
8047 (if (re-search-backward "\\(^\\|\r\\)\\*+" nil t)
8048 (progn
8049 (setq hdmarker (org-agenda-new-marker (match-end 1)))
8050 (goto-char (match-end 1))
8051 (setq tags (org-get-tags-at))
8052 (looking-at "\\*+[ \t]*\\([^\r\n]+\\)")
8053 (setq txt (org-format-agenda-item
8054 (format (if (= d1 d2) "" "(%d/%d): ")
8055 (1+ (- d0 d1)) (1+ (- d2 d1)))
8056 (match-string 1) category tags
8057 (if (= d0 d1) timestr))))
8058 (setq txt org-agenda-no-heading-message))
8059 (org-add-props txt props
8060 'org-marker marker 'org-hd-marker hdmarker
8061 'priority (org-get-priority txt) 'category category)
8062 (push txt ee)))
8063 (goto-char pos)))
8064 ; (outline-next-heading))) ;FIXME: correct to be removed??????
8065 ;; Sort the entries by expiration date.
8066 (nreverse ee)))
8068 (defconst org-plain-time-of-day-regexp
8069 (concat
8070 "\\(\\<[012]?[0-9]"
8071 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
8072 "\\(--?"
8073 "\\(\\<[012]?[0-9]"
8074 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
8075 "\\)?")
8076 "Regular expression to match a plain time or time range.
8077 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
8078 groups carry important information:
8079 0 the full match
8080 1 the first time, range or not
8081 8 the second time, if it is a range.")
8083 (defconst org-stamp-time-of-day-regexp
8084 (concat
8085 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
8086 "\\([012][0-9]:[0-5][0-9]\\)>"
8087 "\\(--?"
8088 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
8089 "Regular expression to match a timestamp time or time range.
8090 After a match, the following groups carry important information:
8091 0 the full match
8092 1 date plus weekday, for backreferencing to make sure both times on same day
8093 2 the first time, range or not
8094 4 the second time, if it is a range.")
8096 (defvar org-prefix-has-time nil
8097 "A flag, set by `org-compile-prefix-format'.
8098 The flag is set if the currently compiled format contains a `%t'.")
8099 (defvar org-prefix-has-tag nil
8100 "A flag, set by `org-compile-prefix-format'.
8101 The flag is set if the currently compiled format contains a `%T'.")
8103 (defun org-format-agenda-item (extra txt &optional category tags dotime
8104 noprefix)
8105 "Format TXT to be inserted into the agenda buffer.
8106 In particular, it adds the prefix and corresponding text properties. EXTRA
8107 must be a string and replaces the `%s' specifier in the prefix format.
8108 CATEGORY (string, symbol or nil) may be used to overrule the default
8109 category taken from local variable or file name. It will replace the `%c'
8110 specifier in the format. DOTIME, when non-nil, indicates that a
8111 time-of-day should be extracted from TXT for sorting of this entry, and for
8112 the `%t' specifier in the format. When DOTIME is a string, this string is
8113 searched for a time before TXT is. NOPREFIX is a flag and indicates that
8114 only the correctly processes TXT should be returned - this is used by
8115 `org-agenda-change-all-lines'. TAGS can be the tags of the headline."
8116 (save-match-data
8117 ;; Diary entries sometimes have extra whitespace at the beginning
8118 (if (string-match "^ +" txt) (setq txt (replace-match "" nil nil txt)))
8119 (let* ((category (or category
8120 org-category
8121 (if buffer-file-name
8122 (file-name-sans-extension
8123 (file-name-nondirectory buffer-file-name))
8124 "")))
8125 (tag (if tags (nth (1- (length tags)) tags) ""))
8126 time ;; needed for the eval of the prefix format
8127 (ts (if dotime (concat (if (stringp dotime) dotime "") txt)))
8128 (time-of-day (and dotime (org-get-time-of-day ts)))
8129 stamp plain s0 s1 s2 rtn)
8130 (when (and dotime time-of-day org-prefix-has-time)
8131 ;; Extract starting and ending time and move them to prefix
8132 (when (or (setq stamp (string-match org-stamp-time-of-day-regexp ts))
8133 (setq plain (string-match org-plain-time-of-day-regexp ts)))
8134 (setq s0 (match-string 0 ts)
8135 s1 (match-string (if plain 1 2) ts)
8136 s2 (match-string (if plain 8 4) ts))
8138 ;; If the times are in TXT (not in DOTIMES), and the prefix will list
8139 ;; them, we might want to remove them there to avoid duplication.
8140 ;; The user can turn this off with a variable.
8141 (if (and org-agenda-remove-times-when-in-prefix (or stamp plain)
8142 (string-match (concat (regexp-quote s0) " *") txt)
8143 (if (eq org-agenda-remove-times-when-in-prefix 'beg)
8144 (= (match-beginning 0) 0)
8146 (setq txt (replace-match "" nil nil txt))))
8147 ;; Normalize the time(s) to 24 hour
8148 (if s1 (setq s1 (org-get-time-of-day s1 'string t)))
8149 (if s2 (setq s2 (org-get-time-of-day s2 'string t))))
8151 (when (string-match "\\([ \t]+\\)\\(:[a-zA-Z_@0-9:]+:\\)[ \t]*$" txt)
8152 ;; Tags are in the string
8153 (if (or (eq org-agenda-remove-tags-when-in-prefix t)
8154 (and org-agenda-remove-tags-when-in-prefix
8155 org-prefix-has-tag))
8156 (setq txt (replace-match "" t t txt))
8157 (setq txt (replace-match
8158 (concat (make-string (max (- 50 (length txt)) 1) ?\ )
8159 (match-string 2 txt))
8160 t t txt))))
8162 ;; Create the final string
8163 (if noprefix
8164 (setq rtn txt)
8165 ;; Prepare the variables needed in the eval of the compiled format
8166 (setq time (cond (s2 (concat s1 "-" s2))
8167 (s1 (concat s1 "......"))
8168 (t ""))
8169 extra (or extra "")
8170 category (if (symbolp category) (symbol-name category) category))
8171 ;; Evaluate the compiled format
8172 (setq rtn (concat (eval org-prefix-format-compiled) txt)))
8174 ;; And finally add the text properties
8175 (org-add-props rtn nil
8176 'category (downcase category) 'tags tags
8177 'prefix-length (- (length rtn) (length txt))
8178 'time-of-day time-of-day
8179 'dotime dotime))))
8181 (defvar org-agenda-sorting-strategy)
8182 (defvar org-agenda-sorting-strategy-selected nil)
8184 (defun org-agenda-add-time-grid-maybe (list ndays todayp)
8185 (catch 'exit
8186 (cond ((not org-agenda-use-time-grid) (throw 'exit list))
8187 ((and todayp (member 'today (car org-agenda-time-grid))))
8188 ((and (= ndays 1) (member 'daily (car org-agenda-time-grid))))
8189 ((member 'weekly (car org-agenda-time-grid)))
8190 (t (throw 'exit list)))
8191 (let* ((have (delq nil (mapcar
8192 (lambda (x) (get-text-property 1 'time-of-day x))
8193 list)))
8194 (string (nth 1 org-agenda-time-grid))
8195 (gridtimes (nth 2 org-agenda-time-grid))
8196 (req (car org-agenda-time-grid))
8197 (remove (member 'remove-match req))
8198 new time)
8199 (if (and (member 'require-timed req) (not have))
8200 ;; don't show empty grid
8201 (throw 'exit list))
8202 (while (setq time (pop gridtimes))
8203 (unless (and remove (member time have))
8204 (setq time (int-to-string time))
8205 (push (org-format-agenda-item
8206 nil string "" nil
8207 (concat (substring time 0 -2) ":" (substring time -2)))
8208 new)
8209 (put-text-property
8210 1 (length (car new)) 'face 'org-time-grid (car new))))
8211 (if (member 'time-up org-agenda-sorting-strategy-selected)
8212 (append new list)
8213 (append list new)))))
8215 (defun org-compile-prefix-format (key)
8216 "Compile the prefix format into a Lisp form that can be evaluated.
8217 The resulting form is returned and stored in the variable
8218 `org-prefix-format-compiled'."
8219 (setq org-prefix-has-time nil org-prefix-has-tag nil)
8220 (let ((s (cond
8221 ((stringp org-agenda-prefix-format)
8222 org-agenda-prefix-format)
8223 ((assq key org-agenda-prefix-format)
8224 (cdr (assq key org-agenda-prefix-format)))
8225 (t " %-12:c%?-12t% s")))
8226 (start 0)
8227 varform vars var e c f opt)
8228 (while (string-match "%\\(\\?\\)?\\([-+]?[0-9.]*\\)\\([ .;,:!?=|/<>]?\\)\\([cts]\\)"
8229 s start)
8230 (setq var (cdr (assoc (match-string 4 s)
8231 '(("c" . category) ("t" . time) ("s" . extra)
8232 ("T" . tag))))
8233 c (or (match-string 3 s) "")
8234 opt (match-beginning 1)
8235 start (1+ (match-beginning 0)))
8236 (if (equal var 'time) (setq org-prefix-has-time t))
8237 (if (equal var 'tag) (setq org-prefix-has-tag t))
8238 (setq f (concat "%" (match-string 2 s) "s"))
8239 (if opt
8240 (setq varform
8241 `(if (equal "" ,var)
8243 (format ,f (if (equal "" ,var) "" (concat ,var ,c)))))
8244 (setq varform `(format ,f (if (equal ,var "") "" (concat ,var ,c)))))
8245 (setq s (replace-match "%s" t nil s))
8246 (push varform vars))
8247 (setq vars (nreverse vars))
8248 (setq org-prefix-format-compiled `(format ,s ,@vars))))
8250 (defun org-set-sorting-strategy (key)
8251 (if (symbolp (car org-agenda-sorting-strategy))
8252 ;; the old format
8253 (setq org-agenda-sorting-strategy-selected org-agenda-sorting-strategy)
8254 (setq org-agenda-sorting-strategy-selected
8255 (or (cdr (assq key org-agenda-sorting-strategy))
8256 (cdr (assq 'agenda org-agenda-sorting-strategy))
8257 '(time-up category-keep priority-down)))))
8259 (defun org-get-time-of-day (s &optional string mod24)
8260 "Check string S for a time of day.
8261 If found, return it as a military time number between 0 and 2400.
8262 If not found, return nil.
8263 The optional STRING argument forces conversion into a 5 character wide string
8264 HH:MM."
8265 (save-match-data
8266 (when
8268 (string-match
8269 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)\\([AaPp][Mm]\\)?\\> *" s)
8270 (string-match
8271 "\\<\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\([AaPp][Mm]\\)\\> *" s))
8272 (let* ((h (string-to-number (match-string 1 s)))
8273 (m (if (match-end 3) (string-to-number (match-string 3 s)) 0))
8274 (ampm (if (match-end 4) (downcase (match-string 4 s))))
8275 (am-p (equal ampm "am"))
8276 (h1 (cond ((not ampm) h)
8277 ((= h 12) (if am-p 0 12))
8278 (t (+ h (if am-p 0 12)))))
8279 (h2 (if (and string mod24 (not (and (= m 0) (= h1 24))))
8280 (mod h1 24) h1))
8281 (t0 (+ (* 100 h2) m))
8282 (t1 (concat (if (>= h1 24) "+" " ")
8283 (if (< t0 100) "0" "")
8284 (if (< t0 10) "0" "")
8285 (int-to-string t0))))
8286 (if string (concat (substring t1 -4 -2) ":" (substring t1 -2)) t0)))))
8288 (defun org-finalize-agenda-entries (list &optional nosort)
8289 "Sort and concatenate the agenda items."
8290 (setq list (mapcar 'org-agenda-highlight-todo list))
8291 (if nosort
8292 list
8293 (mapconcat 'identity (sort list 'org-entries-lessp) "\n")))
8295 (defun org-agenda-highlight-todo (x)
8296 (let (re pl)
8297 (if (eq x 'line)
8298 (save-excursion
8299 (beginning-of-line 1)
8300 (setq re (get-text-property (point) 'org-not-done-regexp))
8301 (goto-char (+ (point) (get-text-property (point) 'prefix-length)))
8302 (and (looking-at (concat "[ \t]*" re))
8303 (add-text-properties (match-beginning 0) (match-end 0)
8304 '(face org-todo))))
8305 (setq re (get-text-property 0 'org-not-done-regexp x)
8306 pl (get-text-property 0 'prefix-length x))
8307 (and re (equal (string-match re x pl) pl)
8308 (add-text-properties (match-beginning 0) (match-end 0)
8309 '(face org-todo) x))
8310 x)))
8312 (defsubst org-cmp-priority (a b)
8313 "Compare the priorities of string A and B."
8314 (let ((pa (or (get-text-property 1 'priority a) 0))
8315 (pb (or (get-text-property 1 'priority b) 0)))
8316 (cond ((> pa pb) +1)
8317 ((< pa pb) -1)
8318 (t nil))))
8320 (defsubst org-cmp-category (a b)
8321 "Compare the string values of categories of strings A and B."
8322 (let ((ca (or (get-text-property 1 'category a) ""))
8323 (cb (or (get-text-property 1 'category b) "")))
8324 (cond ((string-lessp ca cb) -1)
8325 ((string-lessp cb ca) +1)
8326 (t nil))))
8328 (defsubst org-cmp-tag (a b)
8329 "Compare the string values of categories of strings A and B."
8330 (let ((ta (car (last (get-text-property 1 'tags a))))
8331 (tb (car (last (get-text-property 1 'tags b)))))
8332 (cond ((not ta) +1)
8333 ((not tb) -1)
8334 ((string-lessp ta tb) -1)
8335 ((string-lessp tb ta) +1)
8336 (t nil))))
8338 (defsubst org-cmp-time (a b)
8339 "Compare the time-of-day values of strings A and B."
8340 (let* ((def (if org-sort-agenda-notime-is-late 9901 -1))
8341 (ta (or (get-text-property 1 'time-of-day a) def))
8342 (tb (or (get-text-property 1 'time-of-day b) def)))
8343 (cond ((< ta tb) -1)
8344 ((< tb ta) +1)
8345 (t nil))))
8347 (defun org-entries-lessp (a b)
8348 "Predicate for sorting agenda entries."
8349 ;; The following variables will be used when the form is evaluated.
8350 (let* ((time-up (org-cmp-time a b))
8351 (time-down (if time-up (- time-up) nil))
8352 (priority-up (org-cmp-priority a b))
8353 (priority-down (if priority-up (- priority-up) nil))
8354 (category-up (org-cmp-category a b))
8355 (category-down (if category-up (- category-up) nil))
8356 (category-keep (if category-up +1 nil))
8357 (tag-up (org-cmp-tag a b))
8358 (tag-down (if tag-up (- tag-up) nil)))
8359 (cdr (assoc
8360 (eval (cons 'or org-agenda-sorting-strategy-selected))
8361 '((-1 . t) (1 . nil) (nil . nil))))))
8363 (defun org-agenda-show-priority ()
8364 "Show the priority of the current item.
8365 This priority is composed of the main priority given with the [#A] cookies,
8366 and by additional input from the age of a schedules or deadline entry."
8367 (interactive)
8368 (let* ((pri (get-text-property (point-at-bol) 'priority)))
8369 (message "Priority is %d" (if pri pri -1000))))
8371 (defun org-agenda-show-tags ()
8372 "Show the tags applicable to the current item."
8373 (interactive)
8374 (let* ((tags (get-text-property (point-at-bol) 'tags)))
8375 (if tags
8376 (message "Tags are :%s:"
8377 (org-no-properties (mapconcat 'identity tags ":")))
8378 (message "No tags associated with this line"))))
8380 (defun org-agenda-goto (&optional highlight)
8381 "Go to the Org-mode file which contains the item at point."
8382 (interactive)
8383 (let* ((marker (or (get-text-property (point) 'org-marker)
8384 (org-agenda-error)))
8385 (buffer (marker-buffer marker))
8386 (pos (marker-position marker)))
8387 (switch-to-buffer-other-window buffer)
8388 (widen)
8389 (goto-char pos)
8390 (when (org-mode-p)
8391 (org-show-hidden-entry)
8392 (save-excursion
8393 (and (outline-next-heading)
8394 (org-flag-heading nil)))) ; show the next heading
8395 (and highlight (org-highlight (point-at-bol) (point-at-eol)))))
8397 (defun org-agenda-switch-to ()
8398 "Go to the Org-mode file which contains the item at point."
8399 (interactive)
8400 (let* ((marker (or (get-text-property (point) 'org-marker)
8401 (org-agenda-error)))
8402 (buffer (marker-buffer marker))
8403 (pos (marker-position marker)))
8404 (switch-to-buffer buffer)
8405 (delete-other-windows)
8406 (widen)
8407 (goto-char pos)
8408 (when (org-mode-p)
8409 (org-show-hidden-entry)
8410 (save-excursion
8411 (and (outline-next-heading)
8412 (org-flag-heading nil)))))) ; show the next heading
8414 (defun org-agenda-goto-mouse (ev)
8415 "Go to the Org-mode file which contains the item at the mouse click."
8416 (interactive "e")
8417 (mouse-set-point ev)
8418 (org-agenda-goto))
8420 (defun org-agenda-show ()
8421 "Display the Org-mode file which contains the item at point."
8422 (interactive)
8423 (let ((win (selected-window)))
8424 (org-agenda-goto t)
8425 (select-window win)))
8427 (defun org-agenda-recenter (arg)
8428 "Display the Org-mode file which contains the item at point and recenter."
8429 (interactive "P")
8430 (let ((win (selected-window)))
8431 (org-agenda-goto t)
8432 (recenter arg)
8433 (select-window win)))
8435 (defun org-agenda-show-mouse (ev)
8436 "Display the Org-mode file which contains the item at the mouse click."
8437 (interactive "e")
8438 (mouse-set-point ev)
8439 (org-agenda-show))
8441 (defun org-agenda-check-no-diary ()
8442 "Check if the entry is a diary link and abort if yes."
8443 (if (get-text-property (point) 'org-agenda-diary-link)
8444 (org-agenda-error)))
8446 (defun org-agenda-error ()
8447 (error "Command not allowed in this line"))
8449 (defvar org-last-heading-marker (make-marker)
8450 "Marker pointing to the headline that last changed its TODO state
8451 by a remote command from the agenda.")
8453 (defun org-agenda-todo (&optional arg)
8454 "Cycle TODO state of line at point, also in Org-mode file.
8455 This changes the line at point, all other lines in the agenda referring to
8456 the same tree node, and the headline of the tree node in the Org-mode file."
8457 (interactive "P")
8458 (org-agenda-check-no-diary)
8459 (let* ((col (current-column))
8460 (marker (or (get-text-property (point) 'org-marker)
8461 (org-agenda-error)))
8462 (buffer (marker-buffer marker))
8463 (pos (marker-position marker))
8464 (hdmarker (get-text-property (point) 'org-hd-marker))
8465 (buffer-read-only nil)
8466 newhead)
8467 (with-current-buffer buffer
8468 (widen)
8469 (goto-char pos)
8470 (org-show-hidden-entry)
8471 (save-excursion
8472 (and (outline-next-heading)
8473 (org-flag-heading nil))) ; show the next heading
8474 (org-todo arg)
8475 (and (bolp) (forward-char 1))
8476 (setq newhead (org-get-heading))
8477 (save-excursion
8478 (org-back-to-heading)
8479 (move-marker org-last-heading-marker (point))))
8480 (beginning-of-line 1)
8481 (save-excursion
8482 (org-agenda-change-all-lines newhead hdmarker 'fixface))
8483 (move-to-column col)))
8485 (defun org-agenda-change-all-lines (newhead hdmarker &optional fixface)
8486 "Change all lines in the agenda buffer which match HDMARKER.
8487 The new content of the line will be NEWHEAD (as modified by
8488 `org-format-agenda-item'). HDMARKER is checked with
8489 `equal' against all `org-hd-marker' text properties in the file.
8490 If FIXFACE is non-nil, the face of each item is modified acording to
8491 the new TODO state."
8492 (let* (props m pl undone-face done-face finish new dotime cat tags)
8493 ; (setq newhead (org-format-agenda-item "x" newhead "x" nil 'noprefix))
8494 (save-excursion
8495 (goto-char (point-max))
8496 (beginning-of-line 1)
8497 (while (not finish)
8498 (setq finish (bobp))
8499 (when (and (setq m (get-text-property (point) 'org-hd-marker))
8500 (equal m hdmarker))
8501 (setq props (text-properties-at (point))
8502 dotime (get-text-property (point) 'dotime)
8503 cat (get-text-property (point) 'category)
8504 tags (get-text-property (point) 'tags)
8505 new (org-format-agenda-item "x" newhead cat tags dotime 'noprefix)
8506 pl (get-text-property (point) 'prefix-length)
8507 undone-face (get-text-property (point) 'undone-face)
8508 done-face (get-text-property (point) 'done-face))
8509 (move-to-column pl)
8510 (if (looking-at ".*")
8511 (progn
8512 (replace-match new t t)
8513 (beginning-of-line 1)
8514 (add-text-properties (point-at-bol) (point-at-eol) props)
8515 (when fixface
8516 (add-text-properties
8517 (point-at-bol) (point-at-eol)
8518 (list 'face
8519 (if org-last-todo-state-is-todo
8520 undone-face done-face)))
8521 (org-agenda-highlight-todo 'line))
8522 (org-agenda-align-tags 'line)
8523 (beginning-of-line 1))
8524 (error "Line update did not work")))
8525 (beginning-of-line 0)))))
8527 (defun org-agenda-align-tags (&optional line)
8528 "Align all tags in agenda items to `org-agenda-align-tags-to-column'."
8529 (let ((buffer-read-only))
8530 (save-excursion
8531 (goto-char (if line (point-at-bol) (point-min)))
8532 (while (re-search-forward "\\([ \t]+\\):[a-zA-Z0-9_@:]+:[ \t]*$"
8533 (if line (point-at-eol) nil) t)
8534 (delete-region (match-beginning 1) (match-end 1))
8535 (goto-char (match-beginning 1))
8536 (insert (org-add-props
8537 (make-string (max 1 (- org-agenda-align-tags-to-column
8538 (current-column))) ?\ )
8539 (text-properties-at (point))))))))
8541 (defun org-agenda-priority-up ()
8542 "Increase the priority of line at point, also in Org-mode file."
8543 (interactive)
8544 (org-agenda-priority 'up))
8546 (defun org-agenda-priority-down ()
8547 "Decrease the priority of line at point, also in Org-mode file."
8548 (interactive)
8549 (org-agenda-priority 'down))
8551 (defun org-agenda-priority (&optional force-direction)
8552 "Set the priority of line at point, also in Org-mode file.
8553 This changes the line at point, all other lines in the agenda referring to
8554 the same tree node, and the headline of the tree node in the Org-mode file."
8555 (interactive)
8556 (org-agenda-check-no-diary)
8557 (let* ((marker (or (get-text-property (point) 'org-marker)
8558 (org-agenda-error)))
8559 (buffer (marker-buffer marker))
8560 (pos (marker-position marker))
8561 (hdmarker (get-text-property (point) 'org-hd-marker))
8562 (buffer-read-only nil)
8563 newhead)
8564 (with-current-buffer buffer
8565 (widen)
8566 (goto-char pos)
8567 (org-show-hidden-entry)
8568 (save-excursion
8569 (and (outline-next-heading)
8570 (org-flag-heading nil))) ; show the next heading
8571 (funcall 'org-priority force-direction)
8572 (end-of-line 1)
8573 (setq newhead (org-get-heading)))
8574 (org-agenda-change-all-lines newhead hdmarker)
8575 (beginning-of-line 1)))
8577 (defun org-get-tags-at (&optional pos)
8578 "Get a list of all headline tags applicable at POS.
8579 POS defaults to point. If tags are inherited, the list contains
8580 the targets in the same sequence as the headlines appear, i.e.
8581 the tags of the current headline come last."
8582 (interactive)
8583 (let (tags)
8584 (save-excursion
8585 (goto-char (or pos (point)))
8586 (save-match-data
8587 (org-back-to-heading t)
8588 (condition-case nil
8589 (while t
8590 (if (looking-at "[^\r\n]+?:\\([a-zA-Z_@0-9:]+\\):[ \t]*\\([\n\r]\\|\\'\\)")
8591 (setq tags (append (org-split-string
8592 (org-match-string-no-properties 1) ":")
8593 tags)))
8594 (or org-use-tag-inheritance (error ""))
8595 (org-up-heading-all 1))
8596 (error nil))))
8597 tags))
8599 (defun org-agenda-set-tags ()
8600 "Set tags for the current headline."
8601 (interactive)
8602 (org-agenda-check-no-diary)
8603 (org-agenda-show) ;;; FIXME This is a stupid hack and should not be needed
8604 (let* ((hdmarker (or (get-text-property (point) 'org-hd-marker)
8605 (org-agenda-error)))
8606 (buffer (marker-buffer hdmarker))
8607 (pos (marker-position hdmarker))
8608 (buffer-read-only nil)
8609 newhead)
8610 (with-current-buffer buffer
8611 (widen)
8612 (goto-char pos)
8613 (org-show-hidden-entry)
8614 (save-excursion
8615 (and (outline-next-heading)
8616 (org-flag-heading nil))) ; show the next heading
8617 (call-interactively 'org-set-tags)
8618 (end-of-line 1)
8619 (setq newhead (org-get-heading)))
8620 (org-agenda-change-all-lines newhead hdmarker)
8621 (beginning-of-line 1)))
8623 (defun org-agenda-date-later (arg &optional what)
8624 "Change the date of this item to one day later."
8625 (interactive "p")
8626 (org-agenda-check-type t 'agenda 'timeline)
8627 (org-agenda-check-no-diary)
8628 (let* ((marker (or (get-text-property (point) 'org-marker)
8629 (org-agenda-error)))
8630 (buffer (marker-buffer marker))
8631 (pos (marker-position marker)))
8632 (with-current-buffer buffer
8633 (widen)
8634 (goto-char pos)
8635 (if (not (org-at-timestamp-p))
8636 (error "Cannot find time stamp"))
8637 (org-timestamp-change arg (or what 'day))
8638 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8640 (defun org-agenda-date-earlier (arg &optional what)
8641 "Change the date of this item to one day earlier."
8642 (interactive "p")
8643 (org-agenda-date-later (- arg) what))
8645 (defun org-agenda-date-prompt (arg)
8646 "Change the date of this item. Date is prompted for, with default today.
8647 The prefix ARG is passed to the `org-time-stamp' command and can therefore
8648 be used to request time specification in the time stamp."
8649 (interactive "P")
8650 (org-agenda-check-type t 'agenda 'timeline)
8651 (org-agenda-check-no-diary)
8652 (let* ((marker (or (get-text-property (point) 'org-marker)
8653 (org-agenda-error)))
8654 (buffer (marker-buffer marker))
8655 (pos (marker-position marker)))
8656 (with-current-buffer buffer
8657 (widen)
8658 (goto-char pos)
8659 (if (not (org-at-timestamp-p))
8660 (error "Cannot find time stamp"))
8661 (org-time-stamp arg)
8662 (message "Time stamp changed to %s" org-last-changed-timestamp))))
8664 (defun org-agenda-schedule (arg)
8665 "Schedule the item at point."
8666 (interactive "P")
8667 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8668 (org-agenda-check-no-diary)
8669 (let* ((marker (or (get-text-property (point) 'org-marker)
8670 (org-agenda-error)))
8671 (buffer (marker-buffer marker))
8672 (pos (marker-position marker))
8673 (org-insert-labeled-timestamps-at-point nil)
8675 (with-current-buffer buffer
8676 (widen)
8677 (goto-char pos)
8678 (setq ts (org-schedule))
8679 (message "Item scheduled for %s" ts))))
8681 (defun org-agenda-deadline (arg)
8682 "Schedule the item at point."
8683 (interactive "P")
8684 (org-agenda-check-type t 'agenda 'timeline 'todo 'tags)
8685 (org-agenda-check-no-diary)
8686 (let* ((marker (or (get-text-property (point) 'org-marker)
8687 (org-agenda-error)))
8688 (buffer (marker-buffer marker))
8689 (pos (marker-position marker))
8690 (org-insert-labeled-timestamps-at-point nil)
8692 (with-current-buffer buffer
8693 (widen)
8694 (goto-char pos)
8695 (setq ts (org-deadline))
8696 (message "Deadline for this item set to %s" ts))))
8698 (defun org-get-heading ()
8699 "Return the heading of the current entry, without the stars."
8700 (save-excursion
8701 (and (memq (char-before) '(?\n ?\r)) (skip-chars-forward "^\n\r"))
8702 (if (and (re-search-backward "[\r\n]\\*" nil t)
8703 (looking-at "[\r\n]\\*+[ \t]+\\([^\r\n]*\\)"))
8704 (match-string 1)
8705 "")))
8707 (defun org-agenda-clock-in (&optional arg)
8708 "Start the clock on the currently selected item."
8709 (interactive "P")
8710 (org-agenda-check-no-diary)
8711 (let* ((marker (or (get-text-property (point) 'org-marker)
8712 (org-agenda-error)))
8713 (pos (marker-position marker)))
8714 (with-current-buffer (marker-buffer marker)
8715 (widen)
8716 (goto-char pos)
8717 (org-clock-in))))
8719 (defun org-agenda-diary-entry ()
8720 "Make a diary entry, like the `i' command from the calendar.
8721 All the standard commands work: block, weekly etc."
8722 (interactive)
8723 (org-agenda-check-type t 'agenda 'timeline)
8724 (require 'diary-lib)
8725 (let* ((char (progn
8726 (message "Diary entry: [d]ay [w]eekly [m]onthly [y]early [a]nniversary [b]lock [c]yclic")
8727 (read-char-exclusive)))
8728 (cmd (cdr (assoc char
8729 '((?d . insert-diary-entry)
8730 (?w . insert-weekly-diary-entry)
8731 (?m . insert-monthly-diary-entry)
8732 (?y . insert-yearly-diary-entry)
8733 (?a . insert-anniversary-diary-entry)
8734 (?b . insert-block-diary-entry)
8735 (?c . insert-cyclic-diary-entry)))))
8736 (oldf (symbol-function 'calendar-cursor-to-date))
8737 (point (point))
8738 (mark (or (mark t) (point))))
8739 (unless cmd
8740 (error "No command associated with <%c>" char))
8741 (unless (and (get-text-property point 'day)
8742 (or (not (equal ?b char))
8743 (get-text-property mark 'day)))
8744 (error "Don't know which date to use for diary entry"))
8745 ;; We implement this by hacking the `calendar-cursor-to-date' function
8746 ;; and the `calendar-mark-ring' variable. Saves a lot of code.
8747 (let ((calendar-mark-ring
8748 (list (calendar-gregorian-from-absolute
8749 (or (get-text-property mark 'day)
8750 (get-text-property point 'day))))))
8751 (unwind-protect
8752 (progn
8753 (fset 'calendar-cursor-to-date
8754 (lambda (&optional error)
8755 (calendar-gregorian-from-absolute
8756 (get-text-property point 'day))))
8757 (call-interactively cmd))
8758 (fset 'calendar-cursor-to-date oldf)))))
8761 (defun org-agenda-execute-calendar-command (cmd)
8762 "Execute a calendar command from the agenda, with the date associated to
8763 the cursor position."
8764 (org-agenda-check-type t 'agenda 'timeline)
8765 (require 'diary-lib)
8766 (unless (get-text-property (point) 'day)
8767 (error "Don't know which date to use for calendar command"))
8768 (let* ((oldf (symbol-function 'calendar-cursor-to-date))
8769 (point (point))
8770 (date (calendar-gregorian-from-absolute
8771 (get-text-property point 'day)))
8772 (displayed-day (extract-calendar-day date))
8773 (displayed-month (extract-calendar-month date))
8774 (displayed-year (extract-calendar-year date)))
8775 (unwind-protect
8776 (progn
8777 (fset 'calendar-cursor-to-date
8778 (lambda (&optional error)
8779 (calendar-gregorian-from-absolute
8780 (get-text-property point 'day))))
8781 (call-interactively cmd))
8782 (fset 'calendar-cursor-to-date oldf))))
8784 (defun org-agenda-phases-of-moon ()
8785 "Display the phases of the moon for the 3 months around the cursor date."
8786 (interactive)
8787 (org-agenda-execute-calendar-command 'calendar-phases-of-moon))
8789 (defun org-agenda-holidays ()
8790 "Display the holidays for the 3 months around the cursor date."
8791 (interactive)
8792 (org-agenda-execute-calendar-command 'list-calendar-holidays))
8794 (defun org-agenda-sunrise-sunset (arg)
8795 "Display sunrise and sunset for the cursor date.
8796 Latitude and longitude can be specified with the variables
8797 `calendar-latitude' and `calendar-longitude'. When called with prefix
8798 argument, latitude and longitude will be prompted for."
8799 (interactive "P")
8800 (let ((calendar-longitude (if arg nil calendar-longitude))
8801 (calendar-latitude (if arg nil calendar-latitude))
8802 (calendar-location-name
8803 (if arg "the given coordinates" calendar-location-name)))
8804 (org-agenda-execute-calendar-command 'calendar-sunrise-sunset)))
8806 (defun org-agenda-goto-calendar ()
8807 "Open the Emacs calendar with the date at the cursor."
8808 (interactive)
8809 (org-agenda-check-type t 'agenda 'timeline)
8810 (let* ((day (or (get-text-property (point) 'day)
8811 (error "Don't know which date to open in calendar")))
8812 (date (calendar-gregorian-from-absolute day))
8813 (calendar-move-hook nil)
8814 (view-calendar-holidays-initially nil)
8815 (view-diary-entries-initially nil))
8816 (calendar)
8817 (calendar-goto-date date)))
8819 (defun org-calendar-goto-agenda ()
8820 "Compute the Org-mode agenda for the calendar date displayed at the cursor.
8821 This is a command that has to be installed in `calendar-mode-map'."
8822 (interactive)
8823 (org-agenda-list nil (calendar-absolute-from-gregorian
8824 (calendar-cursor-to-date))
8825 nil t))
8827 (defun org-agenda-convert-date ()
8828 (interactive)
8829 (org-agenda-check-type t 'agenda 'timeline)
8830 (let ((day (get-text-property (point) 'day))
8831 date s)
8832 (unless day
8833 (error "Don't know which date to convert"))
8834 (setq date (calendar-gregorian-from-absolute day))
8835 (setq s (concat
8836 "Gregorian: " (calendar-date-string date) "\n"
8837 "ISO: " (calendar-iso-date-string date) "\n"
8838 "Day of Yr: " (calendar-day-of-year-string date) "\n"
8839 "Julian: " (calendar-julian-date-string date) "\n"
8840 "Astron. JD: " (calendar-astro-date-string date)
8841 " (Julian date number at noon UTC)\n"
8842 "Hebrew: " (calendar-hebrew-date-string date) " (until sunset)\n"
8843 "Islamic: " (calendar-islamic-date-string date) " (until sunset)\n"
8844 "French: " (calendar-french-date-string date) "\n"
8845 "Mayan: " (calendar-mayan-date-string date) "\n"
8846 "Coptic: " (calendar-coptic-date-string date) "\n"
8847 "Ethiopic: " (calendar-ethiopic-date-string date) "\n"
8848 "Persian: " (calendar-persian-date-string date) "\n"
8849 "Chinese: " (calendar-chinese-date-string date) "\n"))
8850 (with-output-to-temp-buffer "*Dates*"
8851 (princ s))
8852 (if (fboundp 'fit-window-to-buffer)
8853 (fit-window-to-buffer (get-buffer-window "*Dates*")))))
8855 ;;; Tags
8857 (defun org-scan-tags (action matcher &optional todo-only)
8858 "Scan headline tags with inheritance and produce output ACTION.
8859 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8860 evaluated, testing if a given set of tags qualifies a headline for
8861 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8862 are included in the output."
8863 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8864 (mapconcat 'regexp-quote
8865 (nreverse (cdr (reverse org-todo-keywords)))
8866 "\\|")
8867 "\\>\\)\\)? *\\(.*?\\)\\(:[A-Za-z_@0-9:]+:\\)?[ \t]*[\n\r]"))
8868 (props (list 'face nil
8869 'done-face 'org-done
8870 'undone-face nil
8871 'mouse-face 'highlight
8872 'org-not-done-regexp org-not-done-regexp
8873 'keymap org-agenda-keymap
8874 'help-echo
8875 (format "mouse-2 or RET jump to org file %s"
8876 (abbreviate-file-name buffer-file-name))))
8877 lspos
8878 tags tags-list tags-alist (llast 0) rtn level category i txt
8879 todo marker)
8880 (save-excursion
8881 (goto-char (point-min))
8882 (when (eq action 'sparse-tree) (org-overview))
8883 (while (re-search-forward re nil t)
8884 (catch :skip
8885 (and (eq action 'agenda) (org-agenda-skip))
8886 (setq todo (if (match-end 1) (match-string 2))
8887 tags (if (match-end 4) (match-string 4)))
8888 (goto-char (setq lspos (1+ (match-beginning 0))))
8889 (setq level (funcall outline-level)
8890 category (org-get-category))
8891 (setq i llast llast level)
8892 ;; remove tag lists from same and sublevels
8893 (while (>= i level)
8894 (when (setq entry (assoc i tags-alist))
8895 (setq tags-alist (delete entry tags-alist)))
8896 (setq i (1- i)))
8897 ;; add the nex tags
8898 (when tags
8899 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8900 tags-alist
8901 (cons (cons level tags) tags-alist)))
8902 ;; compile tags for current headline
8903 (setq tags-list
8904 (if org-use-tag-inheritance
8905 (apply 'append (mapcar 'cdr tags-alist))
8906 tags))
8907 (when (and (or (not todo-only) todo)
8908 (eval matcher)
8909 (or (not org-agenda-skip-archived-trees)
8910 (not (member org-archive-tag tags-list))))
8911 ;; list this headline
8912 (if (eq action 'sparse-tree)
8913 (progn
8914 (org-show-hierarchy-above))
8915 (setq txt (org-format-agenda-item
8917 (concat
8918 (if org-tags-match-list-sublevels
8919 (make-string (1- level) ?.) "")
8920 (org-get-heading))
8921 category tags-list))
8922 (goto-char lspos)
8923 (setq marker (org-agenda-new-marker))
8924 (org-add-props txt props
8925 'org-marker marker 'org-hd-marker marker 'category category)
8926 (push txt rtn))
8927 ;; if we are to skip sublevels, jump to end of subtree
8928 (point)
8929 (or org-tags-match-list-sublevels (org-end-of-subtree))))))
8930 (when (and (eq action 'sparse-tree)
8931 (not org-sparse-tree-open-archived-trees))
8932 (org-hide-archived-subtrees (point-min) (point-max)))
8933 (nreverse rtn)))
8935 (defun org-tags-sparse-tree (&optional arg match)
8936 "Create a sparse tree according to tags search string MATCH.
8937 MATCH can contain positive and negative selection of tags, like
8938 \"+WORK+URGENT-WITHBOSS\"."
8939 (interactive "P")
8940 (let ((org-show-following-heading nil)
8941 (org-show-hierarchy-above nil))
8942 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)))))
8944 (defun org-make-tags-matcher (match)
8945 "Create the TAGS matcher form for the tags-selecting string MATCH."
8946 (unless match
8947 ;; Get a new match request, with completion
8948 (setq org-last-tags-completion-table
8949 (or (org-get-buffer-tags)
8950 org-last-tags-completion-table))
8951 (setq match (completing-read
8952 "Tags: " 'org-tags-completion-function nil nil nil
8953 'org-tags-history)))
8954 ;; parse the string and create a lisp form
8955 (let ((match0 match) minus tag mm matcher orterms term orlist)
8956 (setq orterms (org-split-string match "|"))
8957 (while (setq term (pop orterms))
8958 (while (string-match "^&?\\([-+:]\\)?\\([A-Za-z_@0-9]+\\)" term)
8959 (setq minus (and (match-end 1)
8960 (equal (match-string 1 term) "-"))
8961 tag (match-string 2 term)
8962 term (substring term (match-end 0))
8963 mm (list 'member (downcase tag) 'tags-list)
8964 mm (if minus (list 'not mm) mm))
8965 (push mm matcher))
8966 (push (if (> (length matcher) 1) (cons 'and matcher) (car matcher))
8967 orlist)
8968 (setq matcher nil))
8969 (setq matcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8970 ;; Return the string and lisp forms of the matcher
8971 (cons match0 matcher)))
8973 ;;;###autoload
8974 (defun org-tags-view (&optional todo-only match keep-modes)
8975 "Show all headlines for all `org-agenda-files' matching a TAGS criterion.
8976 The prefix arg TODO-ONLY limits the search to TODO entries."
8977 (interactive "P")
8978 (org-compile-prefix-format 'tags)
8979 (org-set-sorting-strategy 'tags)
8980 (let* ((org-agenda-keep-modes keep-modes)
8981 (org-tags-match-list-sublevels
8982 (if todo-only t org-tags-match-list-sublevels))
8983 (win (selected-window))
8984 (completion-ignore-case t)
8985 rtn rtnall files file pos matcher
8986 buffer)
8987 (setq matcher (org-make-tags-matcher match)
8988 match (car matcher) matcher (cdr matcher))
8989 (org-prepare-agenda)
8990 (setq org-agenda-redo-command
8991 (list 'org-tags-view (list 'quote todo-only)
8992 (list 'if 'current-prefix-arg nil match) t))
8993 (setq files (org-agenda-files)
8994 rtnall nil)
8995 (while (setq file (pop files))
8996 (catch 'nextfile
8997 (org-check-agenda-file file)
8998 (setq buffer (if (file-exists-p file)
8999 (org-get-agenda-file-buffer file)
9000 (error "No such file %s" file)))
9001 (if (not buffer)
9002 ;; If file does not exist, merror message to agenda
9003 (setq rtn (list
9004 (format "ORG-AGENDA-ERROR: No such org-file %s" file))
9005 rtnall (append rtnall rtn))
9006 (with-current-buffer buffer
9007 (unless (org-mode-p)
9008 (error "Agenda file %s is not in `org-mode'" file))
9009 (setq org-category-table (org-get-category-table))
9010 (save-excursion
9011 (save-restriction
9012 (if org-agenda-restrict
9013 (narrow-to-region org-agenda-restrict-begin
9014 org-agenda-restrict-end)
9015 (widen))
9016 (setq rtn (org-scan-tags 'agenda matcher todo-only))
9017 (setq rtnall (append rtnall rtn))))))))
9018 (insert "Headlines with TAGS match: ")
9019 (add-text-properties (point-min) (1- (point))
9020 (list 'face 'org-level-3))
9021 (setq pos (point))
9022 (insert match "\n")
9023 (add-text-properties pos (1- (point)) (list 'face 'org-warning))
9024 (setq pos (point))
9025 (unless org-agenda-multi
9026 (insert "Press `C-u r' to search again with new search string\n"))
9027 (add-text-properties pos (1- (point)) (list 'face 'org-level-3))
9028 (when rtnall
9029 (insert (org-finalize-agenda-entries rtnall) "\n"))
9030 (goto-char (point-min))
9031 (org-fit-agenda-window)
9032 (add-text-properties (point-min) (point-max) '(org-agenda-type tags))
9033 (org-agenda-align-tags)
9034 (setq buffer-read-only t)
9035 (if (not org-select-agenda-window) (select-window win))))
9037 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9038 (defun org-set-tags (&optional arg just-align)
9039 "Set the tags for the current headline.
9040 With prefix ARG, realign all tags in headings in the current buffer."
9041 (interactive "P")
9042 (let* ((re (concat "^" outline-regexp))
9043 (col (current-column))
9044 (current (org-get-tags))
9045 table current-tags inherited-tags ; computed below when needed
9046 tags hd empty invis)
9047 (if arg
9048 (save-excursion
9049 (goto-char (point-min))
9050 (while (re-search-forward re nil t)
9051 (org-set-tags nil t))
9052 (message "All tags realigned to column %d" org-tags-column))
9053 (if just-align
9054 (setq tags current)
9055 (setq table (or org-tag-alist (org-get-buffer-tags))
9056 org-last-tags-completion-table table
9057 current-tags (org-split-string current ":")
9058 inherited-tags (nreverse
9059 (nthcdr (length current-tags)
9060 (nreverse (org-get-tags-at))))
9061 tags
9062 (if (or (eq t org-use-fast-tag-selection)
9063 (and org-use-fast-tag-selection
9064 (delq nil (mapcar 'cdr table))))
9065 (org-fast-tag-selection current-tags inherited-tags table)
9066 (let ((org-add-colon-after-tag-completion t))
9067 (completing-read "Tags: " 'org-tags-completion-function
9068 nil nil current 'org-tags-history))))
9069 (while (string-match "[-+&]+" tags)
9070 (setq tags (replace-match ":" t t tags))))
9072 (unless (setq empty (string-match "\\`[\t ]*\\'" tags))
9073 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9074 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9075 (if (equal current "")
9076 (progn
9077 (end-of-line 1)
9078 (or empty (insert " ")))
9079 (beginning-of-line 1)
9080 (setq invis (org-invisible-p))
9081 (looking-at (concat ".*?\\([ \t]*" (regexp-quote current) "\\)[ \t]*"))
9082 (delete-region (match-beginning 1) (match-end 1))
9083 (goto-char (match-beginning 1))
9084 (insert (if empty "" " ")))
9085 (if (equal tags "")
9086 (save-excursion
9087 (beginning-of-line 1)
9088 (skip-chars-forward "*")
9089 (if (= (char-after) ?\ ) (forward-char 1))
9090 (and (re-search-forward "[ \t]+$" (point-at-eol) t)
9091 (replace-match "")))
9092 (move-to-column (max (current-column)
9093 (if (> org-tags-column 0)
9094 org-tags-column
9095 (- (- org-tags-column) (length tags))))
9097 (insert tags)
9098 (if (and (not invis) (org-invisible-p))
9099 (outline-flag-region (point-at-bol) (point) nil)))
9100 (move-to-column col))))
9102 (defun org-tags-completion-function (string predicate &optional flag)
9103 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9104 (confirm (lambda (x) (stringp (car x)))))
9105 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9106 (setq s1 (match-string 1 string)
9107 s2 (match-string 2 string))
9108 (setq s1 "" s2 string))
9109 (cond
9110 ((eq flag nil)
9111 ;; try completion
9112 (setq rtn (try-completion s2 ctable confirm))
9113 (if (stringp rtn)
9114 (concat s1 s2 (substring rtn (length s2))
9115 (if (and org-add-colon-after-tag-completion
9116 (assoc rtn ctable))
9117 ":" "")))
9119 ((eq flag t)
9120 ;; all-completions
9121 (all-completions s2 ctable confirm)
9123 ((eq flag 'lambda)
9124 ;; exact match?
9125 (assoc s2 ctable)))
9128 (defun org-fast-tag-insert (kwd tags face &optional end)
9129 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9130 (insert (format "%-12s" (concat kwd ":"))
9131 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9132 (or end "")))
9134 (defun org-fast-tag-selection (current inherited table)
9135 "Fast tag selection with single keys.
9136 CURRENT is the current list of tags in the headline, INHERITED is the
9137 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9138 possibly with grouping information.
9139 If the keys are nil, a-z are automatically assigned.
9140 Returns the new tags string, or nil to not change the current settings."
9141 (let* ((maxlen (apply 'max (mapcar
9142 (lambda (x)
9143 (if (stringp (car x)) (string-width (car x)) 0))
9144 table)))
9145 (fwidth (+ maxlen 3 1 3))
9146 (ncol (/ (- (window-width) 4) fwidth))
9147 (i-face 'org-done)
9148 (c-face 'org-tag)
9149 tg cnt e c char c1 c2 ntable tbl rtn
9150 groups ingroup)
9151 (save-window-excursion
9152 (delete-other-windows)
9153 (split-window-vertically)
9154 (switch-to-buffer-other-window (get-buffer-create " *Org tags*"))
9155 (erase-buffer)
9156 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9157 (org-fast-tag-insert "Current" current c-face "\n\n")
9158 (setq tbl table char ?a cnt 0)
9159 (while (setq e (pop tbl))
9160 (cond
9161 ((equal e '(:startgroup))
9162 (push '() groups) (setq ingroup t)
9163 (when (not (= cnt 0))
9164 (setq cnt 0)
9165 (insert "\n"))
9166 (insert "{ "))
9167 ((equal e '(:endgroup))
9168 (setq ingroup nil cnt 0)
9169 (insert "}\n"))
9171 (setq tg (car e) c2 nil)
9172 (if (cdr e)
9173 (setq c (cdr e))
9174 ;; automatically assign a character.
9175 (setq c1 (string-to-char
9176 (downcase (substring
9177 tg (if (= (string-to-char tg) ?@) 1 0)))))
9178 (if (or (rassoc c1 ntable) (rassoc c1 table))
9179 (while (or (rassoc char ntable) (rassoc char table))
9180 (setq char (1+ char)))
9181 (setq c2 c1))
9182 (setq c (or c2 char)))
9183 (if ingroup (push tg (car groups)))
9184 (setq tg (org-add-props tg nil 'face
9185 (cond
9186 ((member tg current) c-face)
9187 ((member tg inherited) i-face)
9188 (t nil))))
9189 (if (and (= cnt 0) (not ingroup)) (insert " "))
9190 (insert "[" c "] " tg (make-string
9191 (- fwidth 4 (length tg)) ?\ ))
9192 (push (cons tg c) ntable)
9193 (when (= (setq cnt (1+ cnt)) ncol)
9194 (insert "\n")
9195 (if ingroup (insert " "))
9196 (setq cnt 0)))))
9197 (setq ntable (nreverse ntable))
9198 (insert "\n")
9199 (goto-char (point-min))
9200 (if (fboundp 'fit-window-to-buffer) (fit-window-to-buffer))
9201 (setq rtn
9202 (catch 'exit
9203 (while t
9204 (message "[key]:Toggle SPC: clear current RET accept%s"
9205 (if groups " [!] ignore goups" ""))
9206 (setq c (read-char-exclusive))
9207 (cond
9208 ((= c ?\r) (throw 'exit t))
9209 ((= c ?!)
9210 (setq groups nil)
9211 (goto-char (point-min))
9212 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9213 ((or (= c ?\C-g)
9214 (and (= c ?q) (not (rassoc c ntable))))
9215 (setq quit-flag t))
9216 ((= c ?\ ) (setq current nil))
9217 ((setq e (rassoc c ntable) tg (car e))
9218 (if (member tg current)
9219 (setq current (delete tg current))
9220 (loop for g in groups do
9221 (if (member tg g)
9222 (mapcar (lambda (x)
9223 (setq current (delete x current)))
9224 g)))
9225 (setq current (cons tg current)))))
9226 ;; Create a sorted list
9227 (setq current
9228 (sort current
9229 (lambda (a b)
9230 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9231 (goto-char (point-min))
9232 (beginning-of-line 2)
9233 (delete-region (point) (point-at-eol))
9234 (org-fast-tag-insert "Current" current c-face)
9235 (while (re-search-forward "\\[.\\] \\([a-zA-Z0-9_@]+\\)" nil t)
9236 (setq tg (match-string 1))
9237 (add-text-properties (match-beginning 1) (match-end 1)
9238 (list 'face
9239 (cond
9240 ((member tg current) c-face)
9241 ((member tg inherited) i-face)
9242 (t nil)))))
9243 (goto-char (point-min)))))
9244 (if rtn
9245 (mapconcat 'identity current ":")
9246 nil))))
9248 (defun org-get-tags ()
9249 "Get the TAGS string in the current headline."
9250 (unless (org-on-heading-p t)
9251 (error "Not on a heading"))
9252 (save-excursion
9253 (beginning-of-line 1)
9254 (if (looking-at ".*[ \t]\\(:[A-Za-z_@0-9:]+:\\)[ \t]*\\(\r\\|$\\)")
9255 (org-match-string-no-properties 1)
9256 "")))
9258 (defun org-get-buffer-tags ()
9259 "Get a table of all tags used in the buffer, for completion."
9260 (let (tags)
9261 (save-excursion
9262 (goto-char (point-min))
9263 (while (re-search-forward "[ \t]:\\([A-Za-z_@0-9:]+\\):[ \t\r\n]" nil t)
9264 (mapc (lambda (x) (add-to-list 'tags x))
9265 (org-split-string (org-match-string-no-properties 1) ":"))))
9266 (mapcar 'list tags)))
9268 ;;; Link Stuff
9270 (defvar org-create-file-search-functions nil
9271 "List of functions to construct the right search string for a file link.
9272 These functions are called in turn with point at the location to
9273 which the link should point.
9275 A function in the hook should first test if it would like to
9276 handle this file type, for example by checking the major-mode or
9277 the file extension. If it decides not to handle this file, it
9278 should just return nil to give other functions a chance. If it
9279 does handle the file, it must return the search string to be used
9280 when following the link. The search string will be part of the
9281 file link, given after a double colon, and `org-open-at-point'
9282 will automatically search for it. If special measures must be
9283 taken to make the search successful, another function should be
9284 added to the companion hook `org-execute-file-search-functions',
9285 which see.
9287 A function in this hook may also use `setq' to set the variable
9288 `description' to provide a suggestion for the descriptive text to
9289 be used for this link when it gets inserted into an Org-mode
9290 buffer with \\[org-insert-link].")
9292 (defvar org-execute-file-search-functions nil
9293 "List of functions to execute a file search triggered by a link.
9295 Functions added to this hook must accept a single argument, the
9296 search string that was part of the file link, the part after the
9297 double colon. The function must first check if it would like to
9298 handle this search, for example by checking the major-mode or the
9299 file extension. If it decides not to handle this search, it
9300 should just return nil to give other functions a chance. If it
9301 does handle the search, it must return a non-nil value to keep
9302 other functions from trying.
9304 Each function can access the current prefix argument through the
9305 variable `current-prefix-argument'. Note that a single prefix is
9306 used to force opening a link in Emacs, so it may be good to only
9307 use a numeric or double prefix to guide the search function.
9309 In case this is needed, a function in this hook can also restore
9310 the window configuration before `org-open-at-point' was called using:
9312 (set-window-configuration org-window-config-before-follow-link)")
9314 (defun org-find-file-at-mouse (ev)
9315 "Open file link or URL at mouse."
9316 (interactive "e")
9317 (mouse-set-point ev)
9318 (org-open-at-point 'in-emacs))
9320 (defun org-open-at-mouse (ev)
9321 "Open file link or URL at mouse."
9322 (interactive "e")
9323 (mouse-set-point ev)
9324 (org-open-at-point))
9326 (defvar org-window-config-before-follow-link nil
9327 "The window configuration before following a link.
9328 This is saved in case the need arises to restore it.")
9330 (defun org-open-at-point (&optional in-emacs)
9331 "Open link at or after point.
9332 If there is no link at point, this function will search forward up to
9333 the end of the current subtree.
9334 Normally, files will be opened by an appropriate application. If the
9335 optional argument IN-EMACS is non-nil, Emacs will visit the file."
9336 (interactive "P")
9337 (setq org-window-config-before-follow-link (current-window-configuration))
9338 (org-remove-occur-highlights nil nil t)
9339 (if (org-at-timestamp-p)
9340 (org-agenda-list nil (time-to-days (org-time-string-to-time
9341 (substring (match-string 1) 0 10)))
9343 (let (type path link line search (pos (point)))
9344 (catch 'match
9345 (save-excursion
9346 (skip-chars-forward "^]\n\r")
9347 (when (and (re-search-backward "\\[\\[" nil t)
9348 (looking-at org-bracket-link-regexp)
9349 (<= (match-beginning 0) pos)
9350 (>= (match-end 0) pos))
9351 (setq link (org-link-unescape (org-match-string-no-properties 1)))
9352 (while (string-match " *\n *" link)
9353 (setq link (replace-match " " t t link)))
9354 (if (string-match org-link-re-with-space2 link)
9355 (setq type (match-string 1 link)
9356 path (match-string 2 link))
9357 (setq type "thisfile"
9358 path link))
9359 (throw 'match t)))
9361 (when (get-text-property (point) 'org-linked-text)
9362 (setq type "thisfile"
9363 pos (if (get-text-property (1+ (point)) 'org-linked-text)
9364 (1+ (point)) (point))
9365 path (buffer-substring
9366 (previous-single-property-change pos 'org-linked-text)
9367 (next-single-property-change pos 'org-linked-text)))
9368 (throw 'match t))
9370 (save-excursion
9371 (skip-chars-backward (concat "^[]" org-non-link-chars " "))
9372 (if (equal (char-before) ?<) (backward-char 1))
9373 (when (or (looking-at org-angle-link-re)
9374 (looking-at org-plain-link-re)
9375 (and (or (re-search-forward org-angle-link-re (point-at-eol) t)
9376 (re-search-forward org-plain-link-re (point-at-eol) t))
9377 (<= (match-beginning 0) pos)
9378 (>= (match-end 0) pos)))
9379 (setq type (match-string 1)
9380 path (match-string 2))
9381 (throw 'match t)))
9382 (save-excursion
9383 (skip-chars-backward "^ \t\n\r")
9384 (when (looking-at "\\(:[A-Za-z_@0-9:]+\\):[ \t\r\n]")
9385 (setq type "tags"
9386 path (match-string 1))
9387 (while (string-match ":" path)
9388 (setq path (replace-match "+" t t path)))
9389 (throw 'match t)))
9390 (save-excursion
9391 (skip-chars-backward "a-zA-Z_")
9392 (when (and (memq 'camel org-activate-links)
9393 (looking-at org-camel-regexp))
9394 (setq type "camel" path (match-string 0))
9395 (if (equal (char-before) ?*)
9396 (setq path (concat "*" path))))
9397 (throw 'match t)))
9398 (unless path
9399 (error "No link found"))
9400 ;; Remove any trailing spaces in path
9401 (if (string-match " +\\'" path)
9402 (setq path (replace-match "" t t path)))
9404 (cond
9406 ((equal type "mailto")
9407 (let ((cmd (car org-link-mailto-program))
9408 (args (cdr org-link-mailto-program)) args1
9409 (address path) (subject "") a)
9410 (if (string-match "\\(.*\\)::\\(.*\\)" path)
9411 (setq address (match-string 1 path)
9412 subject (org-link-escape (match-string 2 path))))
9413 (while args
9414 (cond
9415 ((not (stringp (car args))) (push (pop args) args1))
9416 (t (setq a (pop args))
9417 (if (string-match "%a" a)
9418 (setq a (replace-match address t t a)))
9419 (if (string-match "%s" a)
9420 (setq a (replace-match subject t t a)))
9421 (push a args1))))
9422 (apply cmd (nreverse args1))))
9424 ((member type '("http" "https" "ftp" "news"))
9425 (browse-url (concat type ":" path)))
9427 ((string= type "tags")
9428 (org-tags-view in-emacs path))
9429 ((or (string= type "camel")
9430 (string= type "thisfile"))
9431 (org-mark-ring-push)
9432 (org-link-search
9433 path
9434 (cond ((equal in-emacs '(4)) 'occur)
9435 ((equal in-emacs '(16)) 'org-occur)
9436 (t nil))))
9438 ((string= type "file")
9439 (if (string-match "::\\([0-9]+\\)\\'" path)
9440 (setq line (string-to-number (match-string 1 path))
9441 path (substring path 0 (match-beginning 0)))
9442 (if (string-match "::\\(.+\\)\\'" path)
9443 (setq search (match-string 1 path)
9444 path (substring path 0 (match-beginning 0)))))
9445 (org-open-file path in-emacs line search))
9447 ((string= type "news")
9448 (org-follow-gnus-link path))
9450 ((string= type "bbdb")
9451 (org-follow-bbdb-link path))
9453 ((string= type "info")
9454 (org-follow-info-link path))
9456 ((string= type "gnus")
9457 (let (group article)
9458 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9459 (error "Error in Gnus link"))
9460 (setq group (match-string 1 path)
9461 article (match-string 3 path))
9462 (org-follow-gnus-link group article)))
9464 ((string= type "vm")
9465 (let (folder article)
9466 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9467 (error "Error in VM link"))
9468 (setq folder (match-string 1 path)
9469 article (match-string 3 path))
9470 ;; in-emacs is the prefix arg, will be interpreted as read-only
9471 (org-follow-vm-link folder article in-emacs)))
9473 ((string= type "wl")
9474 (let (folder article)
9475 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9476 (error "Error in Wanderlust link"))
9477 (setq folder (match-string 1 path)
9478 article (match-string 3 path))
9479 (org-follow-wl-link folder article)))
9481 ((string= type "mhe")
9482 (let (folder article)
9483 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9484 (error "Error in MHE link"))
9485 (setq folder (match-string 1 path)
9486 article (match-string 3 path))
9487 (org-follow-mhe-link folder article)))
9489 ((string= type "rmail")
9490 (let (folder article)
9491 (if (not (string-match "\\`\\([^#]+\\)\\(#\\(.*\\)\\)?" path))
9492 (error "Error in RMAIL link"))
9493 (setq folder (match-string 1 path)
9494 article (match-string 3 path))
9495 (org-follow-rmail-link folder article)))
9497 ((string= type "shell")
9498 (let ((cmd path))
9499 (while (string-match "@{" cmd)
9500 (setq cmd (replace-match "<" t t cmd)))
9501 (while (string-match "@}" cmd)
9502 (setq cmd (replace-match ">" t t cmd)))
9503 (if (or (not org-confirm-shell-link-function)
9504 (funcall org-confirm-shell-link-function
9505 (format "Execute \"%s\" in shell? "
9506 (org-add-props cmd nil
9507 'face 'org-warning))))
9508 (progn
9509 (message "Executing %s" cmd)
9510 (shell-command cmd))
9511 (error "Abort"))))
9513 ((string= type "elisp")
9514 (let ((cmd path))
9515 (if (or (not org-confirm-elisp-link-function)
9516 (funcall org-confirm-elisp-link-function
9517 (format "Execute \"%s\" as elisp? "
9518 (org-add-props cmd nil
9519 'face 'org-warning))))
9520 (message "%s => %s" cmd (eval (read cmd)))
9521 (error "Abort"))))
9524 (browse-url-at-point))))))
9526 (defun org-link-search (s &optional type)
9527 "Search for a link search option.
9528 When S is a CamelCaseWord, search for a target, or for a sentence containing
9529 the words. If S is surrounded by forward slashes, it is interpreted as a
9530 regular expression. In org-mode files, this will create an `org-occur'
9531 sparse tree. In ordinary files, `occur' will be used to list matches.
9532 If the current buffer is in `dired-mode', grep will be used to search
9533 in all files."
9534 (let ((case-fold-search t)
9535 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
9536 (pos (point))
9537 (pre "") (post "")
9538 words re0 re1 re2 re3 re4 re5 re2a reall camel)
9539 (cond
9540 ;; First check if there are any special
9541 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
9542 ;; Now try the builtin stuff
9543 ((save-excursion
9544 (goto-char (point-min))
9545 (and
9546 (re-search-forward
9547 (concat "<<" (regexp-quote s0) ">>") nil t)
9548 (setq pos (match-beginning 0))))
9549 ;; There is an exact target for this
9550 (goto-char pos))
9551 ((string-match "^/\\(.*\\)/$" s)
9552 ;; A regular expression
9553 (cond
9554 ((org-mode-p)
9555 (org-occur (match-string 1 s)))
9556 ;;((eq major-mode 'dired-mode)
9557 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
9558 (t (org-do-occur (match-string 1 s)))))
9559 ((or (setq camel (string-match (concat "^" org-camel-regexp "$") s))
9561 ;; A camel or a normal search string
9562 (when (equal (string-to-char s) ?*)
9563 ;; Anchor on headlines, post may include tags.
9564 (setq pre "^\\*+[ \t]*\\(?:\\sw+\\)?[ \t]*"
9565 post "[ \t]*\\(?:[ \t]+:[a-zA-Z_@0-9:+]:[ \t]*\\)?$"
9566 s (substring s 1)))
9567 (remove-text-properties
9568 0 (length s)
9569 '(face nil mouse-face nil keymap nil fontified nil) s)
9570 ;; Make a series of regular expressions to find a match
9571 (setq words
9572 (if camel
9573 (org-camel-to-words s)
9574 (org-split-string s "[ \n\r\t]+"))
9575 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
9576 re2 (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t]+") "\\)[ \t\r\n]")
9577 re2a (concat "[ \t\r\n]\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
9578 re4 (concat "[^a-zA-Z_]\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
9579 re1 (concat pre re2 post)
9580 re3 (concat pre re4 post)
9581 re5 (concat pre ".*" re4)
9582 re2 (concat pre re2)
9583 re2a (concat pre re2a)
9584 re4 (concat pre re4)
9585 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
9586 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
9587 re5 "\\)"
9589 (cond
9590 ((eq type 'org-occur) (org-occur reall))
9591 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
9592 (t (goto-char (point-min))
9593 (if (or (org-search-not-link re0 nil t)
9594 (org-search-not-link re1 nil t)
9595 (org-search-not-link re2 nil t)
9596 (org-search-not-link re2a nil t)
9597 (org-search-not-link re3 nil t)
9598 (org-search-not-link re4 nil t)
9599 (org-search-not-link re5 nil t)
9601 (goto-char (match-beginning 1))
9602 (goto-char pos)
9603 (error "No match")))))
9605 ;; Normal string-search
9606 (goto-char (point-min))
9607 (if (search-forward s nil t)
9608 (goto-char (match-beginning 0))
9609 (error "No match"))))
9610 (and (org-mode-p) (org-show-hierarchy-above))))
9612 (defun org-search-not-link (&rest args)
9613 "Execute `re-search-forward', but only accept matches that are not a link."
9614 (catch 'exit
9615 (let (p1)
9616 (while (apply 're-search-forward args)
9617 (setq p1 (point))
9618 (if (not (save-match-data
9619 (and (re-search-backward "\\[\\[" nil t)
9620 (looking-at org-bracket-link-regexp)
9621 (<= (match-beginning 0) p1)
9622 (>= (match-end 0) p1))))
9623 (progn (goto-char (match-end 0))
9624 (throw 'exit (point)))
9625 (goto-char (match-end 0)))))))
9627 (defun org-do-occur (regexp &optional cleanup)
9628 "Call the Emacs command `occur'.
9629 If CLEANUP is non-nil, remove the printout of the regular expression
9630 in the *Occur* buffer. This is useful if the regex is long and not useful
9631 to read."
9632 (occur regexp)
9633 (when cleanup
9634 (let ((cwin (selected-window)) win beg end)
9635 (when (setq win (get-buffer-window "*Occur*"))
9636 (select-window win))
9637 (goto-char (point-min))
9638 (when (re-search-forward "match[a-z]+" nil t)
9639 (setq beg (match-end 0))
9640 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9641 (setq end (1- (match-beginning 0)))))
9642 (and beg end (let ((buffer-read-only)) (delete-region beg end)))
9643 (goto-char (point-min))
9644 (select-window cwin))))
9646 (defvar org-mark-ring nil
9647 "Mark ring for positions before jumps in Org-mode.")
9648 (defvar org-mark-ring-last-goto nil
9649 "Last position in the mark ring used to go back.")
9650 ;; Fill and close the ring
9651 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9652 (loop for i from 1 to org-mark-ring-length do
9653 (push (make-marker) org-mark-ring))
9654 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9655 org-mark-ring)
9657 (defun org-mark-ring-push (&optional pos buffer)
9658 "Put the current position or POS into the mark ring and rotate it."
9659 (interactive)
9660 (setq pos (or pos (point)))
9661 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9662 (move-marker (car org-mark-ring)
9663 (or pos (point))
9664 (or buffer (current-buffer)))
9665 (message
9666 (substitute-command-keys
9667 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9669 (defun org-mark-ring-goto (&optional n)
9670 "Jump to the previous position in the mark ring.
9671 With prefix arg N, jump back that many stored positions. When
9672 called several times in succession, walk through the entire ring.
9673 Org-mode commands jumping to a different position in the current file,
9674 or to another Org-mode file, automatically push the old position
9675 onto the ring."
9676 (interactive "p")
9677 (let (p m)
9678 (if (eq last-command this-command)
9679 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9680 (setq p org-mark-ring))
9681 (setq org-mark-ring-last-goto p)
9682 (setq m (car p))
9683 (switch-to-buffer (marker-buffer m))
9684 (goto-char m)
9685 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-hierarchy-above))))
9687 (defun org-camel-to-words (s)
9688 "Split \"CamelCaseWords\" to (\"Camel\" \"Case\" \"Words\")."
9689 (let ((case-fold-search nil)
9690 words)
9691 (while (string-match "[a-z][A-Z]" s)
9692 (push (substring s 0 (1+ (match-beginning 0))) words)
9693 (setq s (substring s (1+ (match-beginning 0)))))
9694 (nreverse (cons s words))))
9696 (defun org-remove-angle-brackets (s)
9697 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9698 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9700 (defun org-add-angle-brackets (s)
9701 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9702 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9705 (defun org-follow-bbdb-link (name)
9706 "Follow a BBDB link to NAME."
9707 (require 'bbdb)
9708 (let ((inhibit-redisplay t)
9709 (bbdb-electric-p nil))
9710 (catch 'exit
9711 ;; Exact match on name
9712 (bbdb-name (concat "\\`" name "\\'") nil)
9713 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9714 ;; Exact match on name
9715 (bbdb-company (concat "\\`" name "\\'") nil)
9716 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9717 ;; Partial match on name
9718 (bbdb-name name nil)
9719 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9720 ;; Partial match on company
9721 (bbdb-company name nil)
9722 (if (< 0 (buffer-size (get-buffer "*BBDB*"))) (throw 'exit nil))
9723 ;; General match including network address and notes
9724 (bbdb name nil)
9725 (when (= 0 (buffer-size (get-buffer "*BBDB*")))
9726 (delete-window (get-buffer-window "*BBDB*"))
9727 (error "No matching BBDB record")))))
9730 (defun org-follow-info-link (name)
9731 "Follow an info file & node link to NAME."
9732 (if (or (string-match "\\(.*\\)::?\\(.*\\)" name)
9733 (string-match "\\(.*\\)" name))
9734 (progn
9735 (require 'info)
9736 (if (match-string 2 name) ; If there isn't a node, choose "Top"
9737 (Info-find-node (match-string 1 name) (match-string 2 name))
9738 (Info-find-node (match-string 1 name) "Top")))
9739 (message (concat "Could not open: " name))))
9741 (defun org-follow-gnus-link (&optional group article)
9742 "Follow a Gnus link to GROUP and ARTICLE."
9743 (require 'gnus)
9744 (funcall (cdr (assq 'gnus org-link-frame-setup)))
9745 (if gnus-other-frame-object (select-frame gnus-other-frame-object))
9746 (if group (gnus-fetch-group group))
9747 (if article
9748 (or (gnus-summary-goto-article article nil 'force)
9749 (if (fboundp 'gnus-summary-insert-cached-articles)
9750 (progn
9751 (gnus-summary-insert-cached-articles)
9752 (gnus-summary-goto-article article nil 'force))
9753 (message "Message could not be found.")))))
9755 (defun org-follow-vm-link (&optional folder article readonly)
9756 "Follow a VM link to FOLDER and ARTICLE."
9757 (require 'vm)
9758 (setq article (org-add-angle-brackets article))
9759 (if (string-match "^//\\([a-zA-Z]+@\\)?\\([^:]+\\):\\(.*\\)" folder)
9760 ;; ange-ftp or efs or tramp access
9761 (let ((user (or (match-string 1 folder) (user-login-name)))
9762 (host (match-string 2 folder))
9763 (file (match-string 3 folder)))
9764 (cond
9765 ((featurep 'tramp)
9766 ;; use tramp to access the file
9767 (if (featurep 'xemacs)
9768 (setq folder (format "[%s@%s]%s" user host file))
9769 (setq folder (format "/%s@%s:%s" user host file))))
9771 ;; use ange-ftp or efs
9772 (require (if (featurep 'xemacs) 'efs 'ange-ftp))
9773 (setq folder (format "/%s@%s:%s" user host file))))))
9774 (when folder
9775 (funcall (cdr (assq 'vm org-link-frame-setup)) folder readonly)
9776 (sit-for 0.1)
9777 (when article
9778 (vm-select-folder-buffer)
9779 (widen)
9780 (let ((case-fold-search t))
9781 (goto-char (point-min))
9782 (if (not (re-search-forward
9783 (concat "^" "message-id: *" (regexp-quote article))))
9784 (error "Could not find the specified message in this folder"))
9785 (vm-isearch-update)
9786 (vm-isearch-narrow)
9787 (vm-beginning-of-message)
9788 (vm-summarize)))))
9790 (defun org-follow-wl-link (folder article)
9791 "Follow a Wanderlust link to FOLDER and ARTICLE."
9792 (setq article (org-add-angle-brackets article))
9793 (wl-summary-goto-folder-subr folder 'no-sync t nil t)
9794 (if article (wl-summary-jump-to-msg-by-message-id article ">"))
9795 (wl-summary-redisplay))
9797 (defun org-follow-rmail-link (folder article)
9798 "Follow an RMAIL link to FOLDER and ARTICLE."
9799 (setq article (org-add-angle-brackets article))
9800 (let (message-number)
9801 (save-excursion
9802 (save-window-excursion
9803 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9804 (setq message-number
9805 (save-restriction
9806 (widen)
9807 (goto-char (point-max))
9808 (if (re-search-backward
9809 (concat "^Message-ID:\\s-+" (regexp-quote
9810 (or article "")))
9811 nil t)
9812 (rmail-what-message))))))
9813 (if message-number
9814 (progn
9815 (rmail (if (string= folder "RMAIL") rmail-file-name folder))
9816 (rmail-show-message message-number)
9817 message-number)
9818 (error "Message not found"))))
9820 ;; mh-e integration based on planner-mode
9821 (defun org-mhe-get-message-real-folder ()
9822 "Return the name of the current message real folder, so if you use
9823 sequences, it will now work."
9824 (save-excursion
9825 (let* ((folder
9826 (if (equal major-mode 'mh-folder-mode)
9827 mh-current-folder
9828 ;; Refer to the show buffer
9829 mh-show-folder-buffer))
9830 (end-index
9831 (if (boundp 'mh-index-folder)
9832 (min (length mh-index-folder) (length folder))))
9834 ;; a simple test on mh-index-data does not work, because
9835 ;; mh-index-data is always nil in a show buffer.
9836 (if (and (boundp 'mh-index-folder)
9837 (string= mh-index-folder (substring folder 0 end-index)))
9838 (if (equal major-mode 'mh-show-mode)
9839 (save-window-excursion
9840 (when (buffer-live-p (get-buffer folder))
9841 (progn
9842 (pop-to-buffer folder)
9843 (org-mhe-get-message-folder-from-index)
9846 (org-mhe-get-message-folder-from-index)
9848 folder
9852 (defun org-mhe-get-message-folder-from-index ()
9853 "Returns the name of the message folder in a index folder buffer."
9854 (save-excursion
9855 (mh-index-previous-folder)
9856 (re-search-forward "^\\(+.*\\)$" nil t)
9857 (message (match-string 1))))
9859 (defun org-mhe-get-message-folder ()
9860 "Return the name of the current message folder. Be careful if you
9861 use sequences."
9862 (save-excursion
9863 (if (equal major-mode 'mh-folder-mode)
9864 mh-current-folder
9865 ;; Refer to the show buffer
9866 mh-show-folder-buffer)))
9868 (defun org-mhe-get-message-num ()
9869 "Return the number of the current message. Be careful if you
9870 use sequences."
9871 (save-excursion
9872 (if (equal major-mode 'mh-folder-mode)
9873 (mh-get-msg-num nil)
9874 ;; Refer to the show buffer
9875 (mh-show-buffer-message-number))))
9877 (defun org-mhe-get-header (header)
9878 "Return a header of the message in folder mode. This will create a
9879 show buffer for the corresponding message. If you have a more clever
9880 idea..."
9881 (let* ((folder (org-mhe-get-message-folder))
9882 (num (org-mhe-get-message-num))
9883 (buffer (get-buffer-create (concat "show-" folder)))
9884 (header-field))
9885 (with-current-buffer buffer
9886 (mh-display-msg num folder)
9887 (if (equal major-mode 'mh-folder-mode)
9888 (mh-header-display)
9889 (mh-show-header-display))
9890 (set-buffer buffer)
9891 (setq header-field (mh-get-header-field header))
9892 (if (equal major-mode 'mh-folder-mode)
9893 (mh-show)
9894 (mh-show-show))
9895 header-field)))
9897 (defun org-follow-mhe-link (folder article)
9898 "Follow an MHE link to FOLDER and ARTICLE.
9899 If ARTICLE is nil FOLDER is shown. If the configuration variable
9900 `org-mhe-search-all-folders' is t and `mh-searcher' is pick,
9901 ARTICLE is searched in all folders. Indexed searches (swish++,
9902 namazu, and others supported by MH-E) will always search in all
9903 folders."
9904 (require 'mh-e)
9905 (require 'mh-search)
9906 (require 'mh-utils)
9907 (mh-find-path)
9908 (if (not article)
9909 (mh-visit-folder (mh-normalize-folder-name folder))
9910 (setq article (org-add-angle-brackets article))
9911 (mh-search-choose)
9912 (if (equal mh-searcher 'pick)
9913 (progn
9914 (mh-search folder (list "--message-id" article))
9915 (when (and org-mhe-search-all-folders
9916 (not (org-mhe-get-message-real-folder)))
9917 (kill-this-buffer)
9918 (mh-search "+" (list "--message-id" article))))
9919 (mh-search "+" article))
9920 (if (org-mhe-get-message-real-folder)
9921 (mh-show-msg 1)
9922 (kill-this-buffer)
9923 (error "Message not found"))))
9925 ;; BibTeX links
9927 ;; Use the custom search meachnism to construct and use search strings for
9928 ;; file links to BibTeX database entries.
9930 (defun org-create-file-search-in-bibtex ()
9931 "Create the search string and description for a BibTeX database entry."
9932 (when (eq major-mode 'bibtex-mode)
9933 ;; yes, we want to construct this search string.
9934 ;; Make a good description for this entry, using names, year and the title
9935 ;; Put it into the `description' variable which is dynamically scoped.
9936 (let ((bibtex-autokey-names 1)
9937 (bibtex-autokey-names-stretch 1)
9938 (bibtex-autokey-name-case-convert-function 'identity)
9939 (bibtex-autokey-name-separator " & ")
9940 (bibtex-autokey-additional-names " et al.")
9941 (bibtex-autokey-year-length 4)
9942 (bibtex-autokey-name-year-separator " ")
9943 (bibtex-autokey-titlewords 3)
9944 (bibtex-autokey-titleword-separator " ")
9945 (bibtex-autokey-titleword-case-convert-function 'identity)
9946 (bibtex-autokey-titleword-length 'infty)
9947 (bibtex-autokey-year-title-separator ": "))
9948 (setq description (bibtex-generate-autokey)))
9949 ;; Now parse the entry, get the key and return it.
9950 (save-excursion
9951 (bibtex-beginning-of-entry)
9952 (cdr (assoc "=key=" (bibtex-parse-entry))))))
9954 (defun org-execute-file-search-in-bibtex (s)
9955 "Find the link search string S as a key for a database entry."
9956 (when (eq major-mode 'bibtex-mode)
9957 ;; Yes, we want to do the search in this file.
9958 ;; We construct a regexp that searches for "@entrytype{" followed by the key
9959 (goto-char (point-min))
9960 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
9961 (regexp-quote s) "[ \t\n]*,") nil t)
9962 (goto-char (match-beginning 0)))
9963 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
9964 ;; Use double prefix to indicate that any web link should be browsed
9965 (let ((b (current-buffer)) (p (point)))
9966 ;; Restore the window configuration because we just use the web link
9967 (set-window-configuration org-window-config-before-follow-link)
9968 (save-excursion (set-buffer b) (goto-char p)
9969 (bibtex-url)))
9970 (recenter 0)) ; Move entry start to beginning of window
9971 ;; return t to indicate that the search is done.
9974 ;; Finally add the functions to the right hooks.
9975 (add-hook 'org-create-file-search-functions 'org-create-file-search-in-bibtex)
9976 (add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
9978 ;; end of Bibtex link setup
9980 (defun org-upgrade-old-links (&optional query-description)
9981 "Transfer old <...> style links to new [[...]] style links.
9982 With arg query-description, ask at each match for a description text to use
9983 for this link."
9984 (interactive (list (y-or-n-p "Would you like to be queried for a description at each link?")))
9985 (save-excursion
9986 (goto-char (point-min))
9987 (let ((re (concat "\\([^[]\\)<\\("
9988 "\\(" (mapconcat 'identity org-link-types "\\|")
9989 "\\):"
9990 "[^" org-non-link-chars "]+\\)>"))
9991 l1 l2 (cnt 0))
9992 (while (re-search-forward re nil t)
9993 (setq cnt (1+ cnt)
9994 l1 (org-match-string-no-properties 2)
9995 l2 (save-match-data (org-link-escape l1)))
9996 (when query-description (setq l1 (read-string "Desc: " l1)))
9997 (if (equal l1 l2)
9998 (replace-match (concat (match-string 1) "[[" l1 "]]") t t)
9999 (replace-match (concat (match-string 1) "[[" l2 "][" l1 "]]") t t)))
10000 (message "%d matches have beed treated" cnt))))
10002 (defun org-open-file (path &optional in-emacs line search)
10003 "Open the file at PATH.
10004 First, this expands any special file name abbreviations. Then the
10005 configuration variable `org-file-apps' is checked if it contains an
10006 entry for this file type, and if yes, the corresponding command is launched.
10007 If no application is found, Emacs simply visits the file.
10008 With optional argument IN-EMACS, Emacs will visit the file.
10009 Optional LINE specifies a line to go to, optional SEARCH a string to
10010 search for. If LINE or SEARCH is given, the file will always be
10011 opened in Emacs.
10012 If the file does not exist, an error is thrown."
10013 (setq in-emacs (or in-emacs line search))
10014 (let* ((file (if (equal path "")
10015 buffer-file-name
10016 path))
10017 (apps (append org-file-apps (org-default-apps)))
10018 (remp (and (assq 'remote apps) (org-file-remote-p file)))
10019 (dirp (if remp nil (file-directory-p file)))
10020 (dfile (downcase file))
10021 (old-buffer (current-buffer))
10022 (old-pos (point))
10023 (old-mode major-mode)
10024 ext cmd)
10025 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
10026 (setq ext (match-string 1 dfile))
10027 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
10028 (setq ext (match-string 1 dfile))))
10029 (if in-emacs
10030 (setq cmd 'emacs)
10031 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
10032 (and dirp (cdr (assoc 'directory apps)))
10033 (cdr (assoc ext apps))
10034 (cdr (assoc t apps)))))
10035 (when (eq cmd 'mailcap)
10036 (require 'mailcap)
10037 (mailcap-parse-mailcaps)
10038 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
10039 (command (mailcap-mime-info mime-type)))
10040 (if (stringp command)
10041 (setq cmd command)
10042 (setq cmd 'emacs))))
10043 (if (and (not (eq cmd 'emacs)) ; Emacs has not problems with non-ex files
10044 (not (file-exists-p file))
10045 (not org-open-non-existing-files))
10046 (error "No such file: %s" file))
10047 (cond
10048 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
10049 ;; Normalize use of quote, this can vary.
10050 (if (string-match "['\"]%s['\"]" cmd)
10051 (setq cmd (replace-match "'%s'" t t cmd)))
10052 (setq cmd (format cmd file))
10053 (save-window-excursion
10054 (shell-command (concat cmd " &"))))
10055 ((or (stringp cmd)
10056 (eq cmd 'emacs))
10057 ; (unless (equal (file-truename file) (file-truename (or buffer-file-name "")))
10058 ; (funcall (cdr (assq 'file org-link-frame-setup)) file))
10059 (funcall (cdr (assq 'file org-link-frame-setup)) file)
10060 (if line (goto-line line)
10061 (if search (org-link-search search))))
10062 ((consp cmd)
10063 (eval cmd))
10064 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
10065 (and (org-mode-p) (eq old-mode 'org-mode)
10066 (or (not (equal old-buffer (current-buffer)))
10067 (not (equal old-pos (point))))
10068 (org-mark-ring-push old-pos old-buffer))))
10070 (defun org-default-apps ()
10071 "Return the default applications for this operating system."
10072 (cond
10073 ((eq system-type 'darwin)
10074 org-file-apps-defaults-macosx)
10075 ((eq system-type 'windows-nt)
10076 org-file-apps-defaults-windowsnt)
10077 (t org-file-apps-defaults-gnu)))
10079 (defun org-expand-file-name (path)
10080 "Replace special path abbreviations and expand the file name."
10081 (expand-file-name path))
10083 (defun org-file-remote-p (file)
10084 "Test whether FILE specifies a location on a remote system.
10085 Return non-nil if the location is indeed remote.
10087 For example, the filename \"/user@host:/foo\" specifies a location
10088 on the system \"/user@host:\"."
10089 (cond ((fboundp 'file-remote-p)
10090 (file-remote-p file))
10091 ((fboundp 'tramp-handle-file-remote-p)
10092 (tramp-handle-file-remote-p file))
10093 ((and (boundp 'ange-ftp-name-format)
10094 (string-match ange-ftp-name-format file))
10096 (t nil)))
10098 (defvar org-insert-link-history nil
10099 "Minibuffer history for links inserted with `org-insert-link'.")
10101 (defvar org-stored-links nil
10102 "Contains the links stored with `org-store-link'.")
10104 ;;;###autoload
10105 (defun org-store-link (arg)
10106 "\\<org-mode-map>Store an org-link to the current location.
10107 This link can later be inserted into an org-buffer with
10108 \\[org-insert-link].
10109 For some link types, a prefix arg is interpreted:
10110 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
10111 For file links, arg negates `org-context-in-file-links'."
10112 (interactive "P")
10113 (let (link cpltxt desc description search txt (pos (point)))
10114 (cond
10116 ((eq major-mode 'bbdb-mode)
10117 (setq cpltxt (concat
10118 "bbdb:"
10119 (or (bbdb-record-name (bbdb-current-record))
10120 (bbdb-record-company (bbdb-current-record))))
10121 link (org-make-link cpltxt)))
10123 ((eq major-mode 'Info-mode)
10124 (setq link (org-make-link "info:"
10125 (file-name-nondirectory Info-current-file)
10126 ":" Info-current-node))
10127 (setq cpltxt (concat (file-name-nondirectory Info-current-file)
10128 ":" Info-current-node)))
10130 ((eq major-mode 'calendar-mode)
10131 (let ((cd (calendar-cursor-to-date)))
10132 (setq link
10133 (format-time-string
10134 (car org-time-stamp-formats)
10135 (apply 'encode-time
10136 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
10137 nil nil nil))))))
10139 ((or (eq major-mode 'vm-summary-mode)
10140 (eq major-mode 'vm-presentation-mode))
10141 (and (eq major-mode 'vm-presentation-mode) (vm-summarize))
10142 (vm-follow-summary-cursor)
10143 (save-excursion
10144 (vm-select-folder-buffer)
10145 (let* ((message (car vm-message-pointer))
10146 (folder buffer-file-name)
10147 (subject (vm-su-subject message))
10148 (author (vm-su-full-name message))
10149 (message-id (vm-su-message-id message)))
10150 (setq message-id (org-remove-angle-brackets message-id))
10151 (setq folder (abbreviate-file-name folder))
10152 (if (string-match (concat "^" (regexp-quote vm-folder-directory))
10153 folder)
10154 (setq folder (replace-match "" t t folder)))
10155 (setq cpltxt (concat author " on: " subject))
10156 (setq link (org-make-link "vm:" folder "#" message-id)))))
10158 ((eq major-mode 'wl-summary-mode)
10159 (let* ((msgnum (wl-summary-message-number))
10160 (message-id (elmo-message-field wl-summary-buffer-elmo-folder
10161 msgnum 'message-id))
10162 (wl-message-entity (elmo-msgdb-overview-get-entity
10163 msgnum (wl-summary-buffer-msgdb)))
10164 (author (wl-summary-line-from)) ; FIXME: correct?
10165 (subject "???")) ; FIXME:
10166 (setq message-id (org-remove-angle-brackets message-id))
10167 (setq cpltxt (concat author " on: " subject))
10168 (setq link (org-make-link "wl:" wl-summary-buffer-folder-name
10169 "#" message-id))))
10171 ((or (equal major-mode 'mh-folder-mode)
10172 (equal major-mode 'mh-show-mode))
10173 (let ((from-header (org-mhe-get-header "From:"))
10174 (to-header (org-mhe-get-header "To:"))
10175 (subject (org-mhe-get-header "Subject:")))
10176 (setq cpltxt (concat from-header " on: " subject))
10177 (setq link (org-make-link "mhe:" (org-mhe-get-message-real-folder) "#"
10178 (org-remove-angle-brackets
10179 (org-mhe-get-header "Message-Id:"))))))
10181 ((eq major-mode 'rmail-mode)
10182 (save-excursion
10183 (save-restriction
10184 (rmail-narrow-to-non-pruned-header)
10185 (let ((folder buffer-file-name)
10186 (message-id (mail-fetch-field "message-id"))
10187 (author (mail-fetch-field "from"))
10188 (subject (mail-fetch-field "subject")))
10189 (setq message-id (org-remove-angle-brackets message-id))
10190 (setq cpltxt (concat author " on: " subject))
10191 (setq link (org-make-link "rmail:" folder "#" message-id))))))
10193 ((eq major-mode 'gnus-group-mode)
10194 (let ((group (cond ((fboundp 'gnus-group-group-name) ; depending on Gnus
10195 (gnus-group-group-name)) ; version
10196 ((fboundp 'gnus-group-name)
10197 (gnus-group-name))
10198 (t "???"))))
10199 (setq cpltxt (concat
10200 (if (org-xor arg org-usenet-links-prefer-google)
10201 "http://groups.google.com/groups?group="
10202 "gnus:")
10203 group)
10204 link (org-make-link cpltxt))))
10206 ((memq major-mode '(gnus-summary-mode gnus-article-mode))
10207 (and (eq major-mode 'gnus-article-mode) (gnus-article-show-summary))
10208 (gnus-summary-beginning-of-article)
10209 (let* ((group (car gnus-article-current))
10210 (article (cdr gnus-article-current))
10211 (header (gnus-summary-article-header article))
10212 (author (mail-header-from header))
10213 (message-id (mail-header-id header))
10214 (date (mail-header-date header))
10215 (subject (gnus-summary-subject-string)))
10216 (setq cpltxt (concat author " on: " subject))
10217 (if (org-xor arg org-usenet-links-prefer-google)
10218 (setq link
10219 (concat
10220 cpltxt "\n "
10221 (format "http://groups.google.com/groups?as_umsgid=%s"
10222 (org-fixup-message-id-for-http message-id))))
10223 (setq link (org-make-link "gnus:" group
10224 "#" (number-to-string article))))))
10226 ((eq major-mode 'w3-mode)
10227 (setq cpltxt (url-view-url t)
10228 link (org-make-link cpltxt)))
10229 ((eq major-mode 'w3m-mode)
10230 (setq cpltxt (or w3m-current-title w3m-current-url)
10231 link (org-make-link w3m-current-url)))
10233 ((setq search (run-hook-with-args-until-success
10234 'org-create-file-search-functions))
10235 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
10236 "::" search))
10237 (setq cpltxt (or description link)))
10239 ((eq major-mode 'image-mode)
10240 (setq cpltxt (concat "file:"
10241 (abbreviate-file-name buffer-file-name))
10242 link (org-make-link cpltxt)))
10244 ((org-mode-p)
10245 ;; Just link to current headline
10246 (setq cpltxt (concat "file:"
10247 (abbreviate-file-name buffer-file-name)))
10248 ;; Add a context search string
10249 (when (org-xor org-context-in-file-links arg)
10250 ;; Check if we are on a target
10251 (if (save-excursion
10252 (skip-chars-forward "^>\n\r")
10253 (and (re-search-backward "<<" nil t)
10254 (looking-at "<<\\(.*?\\)>>")
10255 (<= (match-beginning 0) pos)
10256 (>= (match-end 0) pos)))
10257 (setq cpltxt (concat cpltxt "::" (match-string 1)))
10258 (setq txt (cond
10259 ((org-on-heading-p) nil)
10260 ((org-region-active-p)
10261 (buffer-substring (region-beginning) (region-end)))
10262 (t (buffer-substring (point-at-bol) (point-at-eol)))))
10263 (when (or (null txt) (string-match "\\S-" txt))
10264 (setq cpltxt
10265 (concat cpltxt "::"
10266 (if org-file-link-context-use-camel-case
10267 (org-make-org-heading-camel txt)
10268 (org-make-org-heading-search-string txt)))
10269 desc "NONE"))))
10270 (if (string-match "::\\'" cpltxt)
10271 (setq cpltxt (substring cpltxt 0 -2)))
10272 (setq link (org-make-link cpltxt)))
10274 (buffer-file-name
10275 ;; Just link to this file here.
10276 (setq cpltxt (concat "file:"
10277 (abbreviate-file-name buffer-file-name)))
10278 ;; Add a context string
10279 (when (org-xor org-context-in-file-links arg)
10280 (setq txt (if (org-region-active-p)
10281 (buffer-substring (region-beginning) (region-end))
10282 (buffer-substring (point-at-bol) (point-at-eol))))
10283 ;; Only use search option if there is some text.
10284 (when (string-match "\\S-" txt)
10285 (setq cpltxt
10286 (concat cpltxt "::"
10287 (if org-file-link-context-use-camel-case
10288 (org-make-org-heading-camel txt)
10289 (org-make-org-heading-search-string txt)))
10290 desc "NONE")))
10291 (setq link (org-make-link cpltxt)))
10293 ((interactive-p)
10294 (error "Cannot link to a buffer which is not visiting a file"))
10296 (t (setq link nil)))
10298 (if (consp link) (setq cpltxt (car link) link (cdr link)))
10299 (setq link (or link cpltxt)
10300 desc (or desc cpltxt))
10301 (if (equal desc "NONE") (setq desc nil))
10303 (if (and (interactive-p) link)
10304 (progn
10305 (setq org-stored-links
10306 (cons (list cpltxt link desc) org-stored-links))
10307 (message "Stored: %s" (or cpltxt link)))
10308 (org-make-link-string link desc))))
10310 (defun org-make-org-heading-search-string (&optional string heading)
10311 "Make search string for STRING or current headline."
10312 (interactive)
10313 (let ((s (or string (org-get-heading))))
10314 (unless (and string (not heading))
10315 ;; We are using a headline, clean up garbage in there.
10316 (if (string-match org-todo-regexp s)
10317 (setq s (replace-match "" t t s)))
10318 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10319 (setq s (replace-match "" t t s)))
10320 (setq s (org-trim s))
10321 (if (string-match (concat "^\\(" org-quote-string "\\|"
10322 org-comment-string "\\)") s)
10323 (setq s (replace-match "" t t s)))
10324 (while (string-match org-ts-regexp s)
10325 (setq s (replace-match "" t t s))))
10326 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
10327 (setq s (replace-match " " t t s)))
10328 (or string (setq s (concat "*" s))) ; Add * for headlines
10329 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
10331 (defun org-make-org-heading-camel (&optional string heading)
10332 "Make a CamelCase string for STRING or the current headline."
10333 (interactive)
10334 (let ((s (or string (org-get-heading))))
10335 (unless (and string (not heading))
10336 ;; We are using a headline, clean up garbage in there.
10337 (if (string-match org-todo-regexp s)
10338 (setq s (replace-match "" t t s)))
10339 (if (string-match ":[a-zA-Z_@0-9:]+:[ \t]*$" s)
10340 (setq s (replace-match "" t t s)))
10341 (setq s (org-trim s))
10342 (if (string-match (concat "^\\(" org-quote-string "\\|"
10343 org-comment-string "\\)") s)
10344 (setq s (replace-match "" t t s)))
10345 (while (string-match org-ts-regexp s)
10346 (setq s (replace-match "" t t s))))
10347 (while (string-match "[^a-zA-Z_ \t]+" s)
10348 (setq s (replace-match " " t t s)))
10349 (or string (setq s (concat "*" s))) ; Add * for headlines
10350 (mapconcat 'capitalize (org-split-string s "[ \t]+") "")))
10352 (defun org-make-link (&rest strings)
10353 "Concatenate STRINGS, format resulting string with `org-link-format'."
10354 (format org-link-format (apply 'concat strings)))
10356 (defun org-make-link-string (link &optional description)
10357 "Make a link with brackets, consisting of LINK and DESCRIPTION."
10358 (if (eq org-link-style 'plain)
10359 (if (equal description link)
10360 link
10361 (concat description "\n" link))
10362 (when (stringp description)
10363 ;; Remove brackets from the description, they are fatal.
10364 (while (string-match "\\[\\|\\]" description)
10365 (setq description (replace-match "" t t description))))
10366 (when (equal (org-link-escape link) description)
10367 ;; No description needed, it is identical
10368 (setq description nil))
10369 (when (and (not description)
10370 (not (equal link (org-link-escape link))))
10371 (setq description link))
10372 (concat "[[" (org-link-escape link) "]"
10373 (if description (concat "[" description "]") "")
10374 "]")))
10376 (defconst org-link-escape-chars '(("[" . "%5B") ("]" . "%5D") (" " . "%20"))
10377 "Association list of escapes for some characters problematic in links.")
10379 (defun org-link-escape (text)
10380 "Escape charaters in TEXT that are problematic for links."
10381 (when text
10382 (let ((re (mapconcat (lambda (x) (regexp-quote (car x)))
10383 org-link-escape-chars "\\|")))
10384 (while (string-match re text)
10385 (setq text
10386 (replace-match
10387 (cdr (assoc (match-string 0 text) org-link-escape-chars))
10388 t t text)))
10389 text)))
10391 (defun org-link-unescape (text)
10392 "Reverse the action of `org-link-escape'."
10393 (when text
10394 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
10395 org-link-escape-chars "\\|")))
10396 (while (string-match re text)
10397 (setq text
10398 (replace-match
10399 (car (rassoc (match-string 0 text) org-link-escape-chars))
10400 t t text)))
10401 text)))
10403 (defun org-xor (a b)
10404 "Exclusive or."
10405 (if a (not b) b))
10407 (defun org-get-header (header)
10408 "Find a header field in the current buffer."
10409 (save-excursion
10410 (goto-char (point-min))
10411 (let ((case-fold-search t) s)
10412 (cond
10413 ((eq header 'from)
10414 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
10415 (setq s (match-string 1)))
10416 (while (string-match "\"" s)
10417 (setq s (replace-match "" t t s)))
10418 (if (string-match "[<(].*" s)
10419 (setq s (replace-match "" t t s))))
10420 ((eq header 'message-id)
10421 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
10422 (setq s (match-string 1))))
10423 ((eq header 'subject)
10424 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
10425 (setq s (match-string 1)))))
10426 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
10427 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
10428 s)))
10431 (defun org-fixup-message-id-for-http (s)
10432 "Replace special characters in a message id, so it can be used in an http query."
10433 (while (string-match "<" s)
10434 (setq s (replace-match "%3C" t t s)))
10435 (while (string-match ">" s)
10436 (setq s (replace-match "%3E" t t s)))
10437 (while (string-match "@" s)
10438 (setq s (replace-match "%40" t t s)))
10441 (defun org-insert-link (&optional complete-file)
10442 "Insert a link. At the prompt, enter the link.
10444 Completion can be used to select a link previously stored with
10445 `org-store-link'. When the empty string is entered (i.e. if you just
10446 press RET at the prompt), the link defaults to the most recently
10447 stored link. As SPC triggers completion in the minibuffer, you need to
10448 use M-SPC or C-q SPC to force the insertion of a space character.
10450 You will also be prompted for a description, and if one is given, it will
10451 be displayed in the buffer instead of the link.
10453 If there is already a link at point, this command will allow you to edit link
10454 and description parts.
10456 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can be
10457 selected using completion. The path to the file will be relative to
10458 the current directory if the file is in the current directory or a
10459 subdirectory. Otherwise, the link will be the absolute path as
10460 completed in the minibuffer (i.e. normally ~/path/to/file).
10462 With two \\[universal-argument] prefixes, enforce an absolute path even if the file
10463 is in the current directory or below.
10464 With three \\[universal-argument] prefixes, negate the meaning of
10465 `org-keep-stored-link-after-insertion'."
10466 (interactive "P")
10467 (let (link desc entry remove file (pos (point)))
10468 (cond
10469 ((save-excursion
10470 (skip-chars-forward "^]\n\r")
10471 (and (re-search-backward "\\[\\[" nil t)
10472 (looking-at org-bracket-link-regexp)
10473 (<= (match-beginning 0) pos)
10474 (>= (match-end 0) pos)))
10475 ;; We do have a link at point, and we are going to edit it.
10476 (setq remove (list (match-beginning 0) (match-end 0)))
10477 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
10478 (setq link (read-string "Link: "
10479 (org-link-unescape
10480 (org-match-string-no-properties 1)))))
10481 ((equal complete-file '(4))
10482 ;; Completing read for file names.
10483 (setq file (read-file-name "File: "))
10484 (let ((pwd (file-name-as-directory (expand-file-name ".")))
10485 (pwd1 (file-name-as-directory (abbreviate-file-name
10486 (expand-file-name ".")))))
10487 (cond
10488 ((equal complete-file '(16))
10489 (setq link (org-make-link
10490 "file:"
10491 (abbreviate-file-name (expand-file-name file)))))
10492 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
10493 (setq link (org-make-link "file:" (match-string 1 file))))
10494 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
10495 (expand-file-name file))
10496 (setq link (org-make-link
10497 "file:" (match-string 1 (expand-file-name file)))))
10498 (t (setq link (org-make-link "file:" file))))))
10500 ;; Read link, with completion for stored links.
10501 (setq link (org-completing-read
10502 "Link: " org-stored-links nil nil nil
10503 org-insert-link-history
10504 (or (car (car org-stored-links)))))
10505 (setq entry (assoc link org-stored-links))
10506 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
10507 (not org-keep-stored-link-after-insertion))
10508 (setq org-stored-links (delq (assoc link org-stored-links)
10509 org-stored-links)))
10510 (setq link (if entry (nth 1 entry) link)
10511 desc (or desc (nth 2 entry)))))
10513 (if (string-match org-plain-link-re link)
10514 ;; URL-like link, normalize the use of angular brackets.
10515 (setq link (org-make-link (org-remove-angle-brackets link))))
10517 ;; Check if we are linking to the current file with a search option
10518 ;; If yes, simplify the link by using only the search option.
10519 (when (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link)
10520 (let* ((path (match-string 1 link))
10521 (case-fold-search nil)
10522 (search (match-string 2 link)))
10523 (save-match-data
10524 (if (equal (file-truename buffer-file-name) (file-truename path))
10525 ;; We are linking to this same file, with a search option
10526 (setq link search)))))
10528 ;; Check if we can/should use a relative path. If yes, simplify the link
10529 (when (string-match "\\<file:\\(.*\\)" link)
10530 (let* ((path (match-string 1 link))
10531 (case-fold-search nil))
10532 (cond
10533 ((eq org-link-file-path-type 'absolute)
10534 (setq path (abbreviate-file-name (expand-file-name path))))
10535 ((eq org-link-file-path-type 'noabbrev)
10536 (setq path (expand-file-name path)))
10537 ((eq org-link-file-path-type 'relative)
10538 (setq path (file-relative-name path)))
10540 (save-match-data
10541 (if (string-match (concat "^" (regexp-quote
10542 (file-name-as-directory
10543 (expand-file-name "."))))
10544 (expand-file-name path))
10545 ;; We are linking a file with relative path name.
10546 (setq path (substring (expand-file-name path)
10547 (match-end 0)))))))
10548 (setq link (concat "file:" path))))
10550 (setq desc (read-string "Description: " desc))
10551 (unless (string-match "\\S-" desc) (setq desc nil))
10552 (if remove (apply 'delete-region remove))
10553 (insert (org-make-link-string link desc))))
10555 (defun org-completing-read (&rest args)
10556 (let ((minibuffer-local-completion-map
10557 (copy-keymap minibuffer-local-completion-map)))
10558 (define-key minibuffer-local-completion-map " " 'self-insert-command)
10559 (apply 'completing-read args)))
10561 ;;; Hooks for remember.el
10563 (defvar org-finish-function nil)
10565 ;;;###autoload
10566 (defun org-remember-annotation ()
10567 "Return a link to the current location as an annotation for remember.el.
10568 If you are using Org-mode files as target for data storage with
10569 remember.el, then the annotations should include a link compatible with the
10570 conventions in Org-mode. This function returns such a link."
10571 (org-store-link nil))
10573 (defconst org-remember-help
10574 "Select a destination location for the note.
10575 UP/DOWN=headline TAB=cycle visibility [Q]uit RET/<left>/<right>=Store
10576 RET at beg-of-buf -> Append to file as level 2 headline
10577 RET on headline -> Store as sublevel entry to current headline
10578 <left>/<right> -> before/after current headline, same headings level")
10580 ;;;###autoload
10581 (defun org-remember-apply-template ()
10582 "Initialize *remember* buffer with template, invoke `org-mode'.
10583 This function should be placed into `remember-mode-hook' and in fact requires
10584 to be run from that hook to fucntion properly."
10585 (if org-remember-templates
10587 (let* ((entry (if (= (length org-remember-templates) 1)
10588 (cdar org-remember-templates)
10589 (message "Select template: %s"
10590 (mapconcat
10591 (lambda (x) (char-to-string (car x)))
10592 org-remember-templates " "))
10593 (cdr (assoc (read-char-exclusive) org-remember-templates))))
10594 (tpl (car entry))
10595 (file (if (consp (cdr entry)) (nth 1 entry)))
10596 (v-t (format-time-string (car org-time-stamp-formats) (org-current-time)))
10597 (v-T (format-time-string (cdr org-time-stamp-formats) (org-current-time)))
10598 (v-u (concat "[" (substring v-t 1 -1) "]"))
10599 (v-U (concat "[" (substring v-T 1 -1) "]"))
10600 (v-a annotation) ; defined in `remember-mode'
10601 (v-i initial) ; defined in `remember-mode'
10602 (v-n user-full-name)
10604 (unless tpl (setq tpl "") (message "No template") (ding))
10605 (insert tpl) (goto-char (point-min))
10606 (while (re-search-forward "%\\([tTuTai]\\)" nil t)
10607 (when (and initial (equal (match-string 0) "%i"))
10608 (save-match-data
10609 (let* ((lead (buffer-substring
10610 (point-at-bol) (match-beginning 0))))
10611 (setq v-i (mapconcat 'identity
10612 (org-split-string initial "\n")
10613 (concat "\n" lead))))))
10614 (replace-match
10615 (or (eval (intern (concat "v-" (match-string 1)))) "")
10616 t t))
10617 (let ((org-startup-folded nil)
10618 (org-startup-with-deadline-check nil))
10619 (org-mode))
10620 (if (and file (string-match "\\S-" file) (not (file-directory-p file)))
10621 (org-set-local 'org-default-notes-file file))
10622 (goto-char (point-min))
10623 (if (re-search-forward "%\\?" nil t) (replace-match "")))
10624 (let ((org-startup-folded nil)
10625 (org-startup-with-deadline-check nil))
10626 (org-mode)))
10627 (org-set-local 'org-finish-function 'remember-buffer))
10629 ;;;###autoload
10630 (defun org-remember-handler ()
10631 "Store stuff from remember.el into an org file.
10632 First prompts for an org file. If the user just presses return, the value
10633 of `org-default-notes-file' is used.
10634 Then the command offers the headings tree of the selected file in order to
10635 file the text at a specific location.
10636 You can either immediately press RET to get the note appended to the
10637 file, or you can use vertical cursor motion and visibility cycling (TAB) to
10638 find a better place. Then press RET or <left> or <right> in insert the note.
10640 Key Cursor position Note gets inserted
10641 -----------------------------------------------------------------------------
10642 RET buffer-start as level 2 heading at end of file
10643 RET on headline as sublevel of the heading at cursor
10644 RET no heading at cursor position, level taken from context.
10645 Or use prefix arg to specify level manually.
10646 <left> on headline as same level, before current heading
10647 <right> on headline as same level, after current heading
10649 So the fastest way to store the note is to press RET RET to append it to
10650 the default file. This way your current train of thought is not
10651 interrupted, in accordance with the principles of remember.el. But with
10652 little extra effort, you can push it directly to the correct location.
10654 Before being stored away, the function ensures that the text has a
10655 headline, i.e. a first line that starts with a \"*\". If not, a headline
10656 is constructed from the current date and some additional data.
10658 If the variable `org-adapt-indentation' is non-nil, the entire text is
10659 also indented so that it starts in the same column as the headline
10660 \(i.e. after the stars).
10662 See also the variable `org-reverse-note-order'."
10663 (catch 'quit
10664 (let* ((txt (buffer-substring (point-min) (point-max)))
10665 (fastp current-prefix-arg)
10666 (file (if fastp org-default-notes-file (org-get-org-file)))
10667 (visiting (find-buffer-visiting file))
10668 (org-startup-with-deadline-check nil)
10669 (org-startup-folded nil)
10670 (org-startup-align-all-tables nil)
10671 spos level indent reversed)
10672 ;; Modify text so that it becomes a nice subtree which can be inserted
10673 ;; into an org tree.
10674 (let* ((lines (split-string txt "\n"))
10675 first)
10676 ;; remove empty lines at the beginning
10677 (while (and lines (string-match "^[ \t]*\n" (car lines)))
10678 (setq lines (cdr lines)))
10679 (setq first (car lines) lines (cdr lines))
10680 (if (string-match "^\\*+" first)
10681 ;; Is already a headline
10682 (setq indent nil)
10683 ;; We need to add a headline: Use time and first buffer line
10684 (setq lines (cons first lines)
10685 first (concat "* " (current-time-string)
10686 " (" (remember-buffer-desc) ")")
10687 indent " "))
10688 (if (and org-adapt-indentation indent)
10689 (setq lines (mapcar (lambda (x) (concat indent x)) lines)))
10690 (setq txt (concat first "\n"
10691 (mapconcat 'identity lines "\n"))))
10692 ;; Find the file
10693 (if (not visiting)
10694 (find-file-noselect file))
10695 (with-current-buffer (get-file-buffer file)
10696 (save-excursion (and (goto-char (point-min))
10697 (not (re-search-forward "^\\* " nil t))
10698 (insert "\n* Notes\n")))
10699 (setq reversed (org-notes-order-reversed-p))
10700 (save-excursion
10701 (save-restriction
10702 (widen)
10703 ;; Ask the User for a location
10704 (setq spos (if fastp 1 (org-get-location
10705 (current-buffer)
10706 org-remember-help)))
10707 (if (not spos) (throw 'quit nil)) ; return nil to show we did
10708 ; not handle this note
10709 (goto-char spos)
10710 (cond ((bobp)
10711 ;; Put it at the start or end, as level 2
10712 (save-restriction
10713 (widen)
10714 (goto-char (if reversed (point-min) (point-max)))
10715 (if (not (bolp)) (newline))
10716 (org-paste-subtree 2 txt)))
10717 ((and (org-on-heading-p nil) (not current-prefix-arg))
10718 ;; Put it below this entry, at the beg/end of the subtree
10719 (org-back-to-heading)
10720 (setq level (funcall outline-level))
10721 (if reversed
10722 (outline-end-of-heading)
10723 (outline-end-of-subtree))
10724 (if (not (bolp)) (newline))
10725 (beginning-of-line 1)
10726 (org-paste-subtree (1+ level) txt))
10728 ;; Put it right there, with automatic level determined by
10729 ;; org-paste-subtree or from prefix arg
10730 (org-paste-subtree current-prefix-arg txt)))
10731 (when remember-save-after-remembering
10732 (save-buffer)
10733 (if (not visiting) (kill-buffer (current-buffer)))))))))
10734 t) ;; return t to indicate that we took care of this note.
10736 (defun org-get-org-file ()
10737 "Read a filename, with default directory `org-directory'."
10738 (let ((default (or org-default-notes-file remember-data-file)))
10739 (read-file-name (format "File name [%s]: " default)
10740 (file-name-as-directory org-directory)
10741 default)))
10743 (defun org-notes-order-reversed-p ()
10744 "Check if the current file should receive notes in reversed order."
10745 (cond
10746 ((not org-reverse-note-order) nil)
10747 ((eq t org-reverse-note-order) t)
10748 ((not (listp org-reverse-note-order)) nil)
10749 (t (catch 'exit
10750 (let ((all org-reverse-note-order)
10751 entry)
10752 (while (setq entry (pop all))
10753 (if (string-match (car entry) buffer-file-name)
10754 (throw 'exit (cdr entry))))
10755 nil)))))
10757 ;;; Tables
10759 ;; Watch out: Here we are talking about two different kind of tables.
10760 ;; Most of the code is for the tables created with the Org-mode table editor.
10761 ;; Sometimes, we talk about tables created and edited with the table.el
10762 ;; Emacs package. We call the former org-type tables, and the latter
10763 ;; table.el-type tables.
10766 (defun org-before-change-function (beg end)
10767 "Every change indicates that a table might need an update."
10768 (setq org-table-may-need-update t))
10770 (defconst org-table-line-regexp "^[ \t]*|"
10771 "Detects an org-type table line.")
10772 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
10773 "Detects an org-type table line.")
10774 (defconst org-table-auto-recalculate-regexp "^[ \t]*| *# *\\(|\\|$\\)"
10775 "Detects a table line marked for automatic recalculation.")
10776 (defconst org-table-recalculate-regexp "^[ \t]*| *[#*] *\\(|\\|$\\)"
10777 "Detects a table line marked for automatic recalculation.")
10778 (defconst org-table-calculate-mark-regexp "^[ \t]*| *[!$^_#*] *\\(|\\|$\\)"
10779 "Detects a table line marked for automatic recalculation.")
10780 (defconst org-table-hline-regexp "^[ \t]*|-"
10781 "Detects an org-type table hline.")
10782 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
10783 "Detects a table-type table hline.")
10784 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
10785 "Detects an org-type or table-type table.")
10786 (defconst org-table-border-regexp "^[ \t]*[^| \t]"
10787 "Searching from within a table (any type) this finds the first line
10788 outside the table.")
10789 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
10790 "Searching from within a table (any type) this finds the first line
10791 outside the table.")
10793 (defun org-table-create-with-table.el ()
10794 "Use the table.el package to insert a new table.
10795 If there is already a table at point, convert between Org-mode tables
10796 and table.el tables."
10797 (interactive)
10798 (require 'table)
10799 (cond
10800 ((org-at-table.el-p)
10801 (if (y-or-n-p "Convert table to Org-mode table? ")
10802 (org-table-convert)))
10803 ((org-at-table-p)
10804 (if (y-or-n-p "Convert table to table.el table? ")
10805 (org-table-convert)))
10806 (t (call-interactively 'table-insert))))
10808 (defun org-table-create-or-convert-from-region (arg)
10809 "Convert region to table, or create an empty table.
10810 If there is an active region, convert it to a table. If there is no such
10811 region, create an empty table."
10812 (interactive "P")
10813 (if (org-region-active-p)
10814 (org-table-convert-region (region-beginning) (region-end) arg)
10815 (org-table-create arg)))
10817 (defun org-table-create (&optional size)
10818 "Query for a size and insert a table skeleton.
10819 SIZE is a string Columns x Rows like for example \"3x2\"."
10820 (interactive "P")
10821 (unless size
10822 (setq size (read-string
10823 (concat "Table size Columns x Rows [e.g. "
10824 org-table-default-size "]: ")
10825 "" nil org-table-default-size)))
10827 (let* ((pos (point))
10828 (indent (make-string (current-column) ?\ ))
10829 (split (org-split-string size " *x *"))
10830 (rows (string-to-number (nth 1 split)))
10831 (columns (string-to-number (car split)))
10832 (line (concat (apply 'concat indent "|" (make-list columns " |"))
10833 "\n")))
10834 (if (string-match "^[ \t]*$" (buffer-substring-no-properties
10835 (point-at-bol) (point)))
10836 (beginning-of-line 1)
10837 (newline))
10838 ;; (mapcar (lambda (x) (insert line)) (make-list rows t))
10839 (dotimes (i rows) (insert line))
10840 (goto-char pos)
10841 (if (> rows 1)
10842 ;; Insert a hline after the first row.
10843 (progn
10844 (end-of-line 1)
10845 (insert "\n|-")
10846 (goto-char pos)))
10847 (org-table-align)))
10849 (defun org-table-convert-region (beg0 end0 &optional nspace)
10850 "Convert region to a table.
10851 The region goes from BEG0 to END0, but these borders will be moved
10852 slightly, to make sure a beginning of line in the first line is included.
10853 When NSPACE is non-nil, it indicates the minimum number of spaces that
10854 separate columns (default: just one space)."
10855 (interactive "rP")
10856 (let* ((beg (min beg0 end0))
10857 (end (max beg0 end0))
10858 (tabsep t)
10860 (goto-char beg)
10861 (beginning-of-line 1)
10862 (setq beg (move-marker (make-marker) (point)))
10863 (goto-char end)
10864 (if (bolp) (backward-char 1) (end-of-line 1))
10865 (setq end (move-marker (make-marker) (point)))
10866 ;; Lets see if this is tab-separated material. If every nonempty line
10867 ;; contains a tab, we will assume that it is tab-separated material
10868 (if nspace
10869 (setq tabsep nil)
10870 (goto-char beg)
10871 (and (re-search-forward "^[^\n\t]+$" end t) (setq tabsep nil)))
10872 (if nspace (setq tabsep nil))
10873 (if tabsep
10874 (setq re "^\\|\t")
10875 (setq re (format "^ *\\| *\t *\\| \\{%d,\\}"
10876 (max 1 (prefix-numeric-value nspace)))))
10877 (goto-char beg)
10878 (while (re-search-forward re end t)
10879 (replace-match "|" t t))
10880 (goto-char beg)
10881 (insert " ")
10882 (org-table-align)))
10884 (defun org-table-import (file arg)
10885 "Import FILE as a table.
10886 The file is assumed to be tab-separated. Such files can be produced by most
10887 spreadsheet and database applications. If no tabs (at least one per line)
10888 are found, lines will be split on whitespace into fields."
10889 (interactive "f\nP")
10890 (or (bolp) (newline))
10891 (let ((beg (point))
10892 (pm (point-max)))
10893 (insert-file-contents file)
10894 (org-table-convert-region beg (+ (point) (- (point-max) pm)) arg)))
10896 (defun org-table-export ()
10897 "Export table as a tab-separated file.
10898 Such a file can be imported into a spreadsheet program like Excel."
10899 (interactive)
10900 (let* ((beg (org-table-begin))
10901 (end (org-table-end))
10902 (table (buffer-substring beg end))
10903 (file (read-file-name "Export table to: "))
10904 buf)
10905 (unless (or (not (file-exists-p file))
10906 (y-or-n-p (format "Overwrite file %s? " file)))
10907 (error "Abort"))
10908 (with-current-buffer (find-file-noselect file)
10909 (setq buf (current-buffer))
10910 (erase-buffer)
10911 (fundamental-mode)
10912 (insert table)
10913 (goto-char (point-min))
10914 (while (re-search-forward "^[ \t]*|[ \t]*" nil t)
10915 (replace-match "" t t)
10916 (end-of-line 1))
10917 (goto-char (point-min))
10918 (while (re-search-forward "[ \t]*|[ \t]*$" nil t)
10919 (replace-match "" t t)
10920 (goto-char (min (1+ (point)) (point-max))))
10921 (goto-char (point-min))
10922 (while (re-search-forward "^-[-+]*$" nil t)
10923 (replace-match "")
10924 (if (looking-at "\n")
10925 (delete-char 1)))
10926 (goto-char (point-min))
10927 (while (re-search-forward "[ \t]*|[ \t]*" nil t)
10928 (replace-match "\t" t t))
10929 (save-buffer))
10930 (kill-buffer buf)))
10932 (defvar org-table-aligned-begin-marker (make-marker)
10933 "Marker at the beginning of the table last aligned.
10934 Used to check if cursor still is in that table, to minimize realignment.")
10935 (defvar org-table-aligned-end-marker (make-marker)
10936 "Marker at the end of the table last aligned.
10937 Used to check if cursor still is in that table, to minimize realignment.")
10938 (defvar org-table-last-alignment nil
10939 "List of flags for flushright alignment, from the last re-alignment.
10940 This is being used to correctly align a single field after TAB or RET.")
10941 (defvar org-table-last-column-widths nil
10942 "List of max width of fields in each column.
10943 This is being used to correctly align a single field after TAB or RET.")
10945 (defvar org-last-recalc-line nil)
10946 (defconst org-narrow-column-arrow "=>"
10947 "Used as display property in narrowed table columns.")
10949 (defun org-table-align ()
10950 "Align the table at point by aligning all vertical bars."
10951 (interactive)
10952 (let* (
10953 ;; Limits of table
10954 (beg (org-table-begin))
10955 (end (org-table-end))
10956 ;; Current cursor position
10957 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
10958 (colpos (org-table-current-column))
10959 (winstart (window-start))
10960 lines (new "") lengths l typenums ty fields maxfields i
10961 column
10962 (indent "") cnt frac
10963 rfmt hfmt
10964 (spaces '(1 . 1))
10965 (sp1 (car spaces))
10966 (sp2 (cdr spaces))
10967 (rfmt1 (concat
10968 (make-string sp2 ?\ ) "%%%s%ds" (make-string sp1 ?\ ) "|"))
10969 (hfmt1 (concat
10970 (make-string sp2 ?-) "%s" (make-string sp1 ?-) "+"))
10971 emptystrings links narrow fmax f1 len c e)
10972 (untabify beg end)
10973 (remove-text-properties beg end '(org-cwidth t display t))
10974 ;; Check if we have links
10975 (goto-char beg)
10976 (setq links (re-search-forward org-bracket-link-regexp end t))
10977 ;; Make sure the link properties are right
10978 (when links (goto-char beg) (while (org-activate-bracket-links end)))
10979 ;; Check if we are narrowing any columns
10980 (goto-char beg)
10981 (setq narrow (and org-format-transports-properties-p
10982 (re-search-forward "<[0-9]+>" end t)))
10983 ;; Get the rows
10984 (setq lines (org-split-string
10985 (buffer-substring beg end) "\n"))
10986 ;; Store the indentation of the first line
10987 (if (string-match "^ *" (car lines))
10988 (setq indent (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
10989 ;; Mark the hlines by setting the corresponding element to nil
10990 ;; At the same time, we remove trailing space.
10991 (setq lines (mapcar (lambda (l)
10992 (if (string-match "^ *|-" l)
10994 (if (string-match "[ \t]+$" l)
10995 (substring l 0 (match-beginning 0))
10996 l)))
10997 lines))
10998 ;; Get the data fields by splitting the lines.
10999 (setq fields (mapcar
11000 (lambda (l)
11001 (org-split-string l " *| *"))
11002 (delq nil (copy-sequence lines))))
11003 ;; How many fields in the longest line?
11004 (condition-case nil
11005 (setq maxfields (apply 'max (mapcar 'length fields)))
11006 (error
11007 (kill-region beg end)
11008 (org-table-create org-table-default-size)
11009 (error "Empty table - created default table")))
11010 ;; A list of empty string to fill any short rows on output
11011 (setq emptystrings (make-list maxfields ""))
11012 ;; Check for special formatting.
11013 (setq i -1)
11014 (while (< (setq i (1+ i)) maxfields) ;; Loop over all columns
11015 (setq column (mapcar (lambda (x) (or (nth i x) "")) fields))
11016 ;; Check if there is an explicit width specified
11017 (when (and org-table-limit-column-width narrow)
11018 (setq c column fmax nil)
11019 (while c
11020 (setq e (pop c))
11021 (if (and (stringp e) (string-match "^<\\([0-9]+\\)>$" e))
11022 (setq fmax (string-to-number (match-string 1 e)) c nil)))
11023 ;; Find fields that are wider than fmax, and shorten them
11024 (when fmax
11025 (loop for xx in column do
11026 (when (and (stringp xx)
11027 (> (org-string-width xx) fmax))
11028 (org-add-props xx nil
11029 'help-echo
11030 (concat "Clipped table field, use C-c ` to edit. Full value is:\n" (org-no-properties (copy-sequence xx))))
11031 (setq f1 (min fmax (or (string-match org-bracket-link-regexp xx) fmax)))
11032 (unless (> f1 1)
11033 (error "Cannot narrow field starting with wide link \"%s\""
11034 (match-string 0 xx)))
11035 (add-text-properties f1 (length xx) (list 'org-cwidth t) xx)
11036 (add-text-properties (- f1 2) f1
11037 (list 'display org-narrow-column-arrow)
11038 xx)))))
11039 ;; Get the maximum width for each column
11040 (push (apply 'max 1 (mapcar 'org-string-width column)) lengths)
11041 ;; Get the fraction of numbers, to decide about alignment of the column
11042 (setq cnt 0 frac 0.0)
11043 (loop for x in column do
11044 (if (equal x "")
11046 (setq frac ( / (+ (* frac cnt)
11047 (if (string-match org-table-number-regexp x) 1 0))
11048 (setq cnt (1+ cnt))))))
11049 (push (>= frac org-table-number-fraction) typenums))
11050 (setq lengths (nreverse lengths) typenums (nreverse typenums))
11052 ;; Store the alignment of this table, for later editing of single fields
11053 (setq org-table-last-alignment typenums
11054 org-table-last-column-widths lengths)
11056 ;; With invisible characters, `format' does not get the field width right
11057 ;; So we need to make these fields wide by hand.
11058 (when links
11059 (loop for i from 0 upto (1- maxfields) do
11060 (setq len (nth i lengths))
11061 (loop for j from 0 upto (1- (length fields)) do
11062 (setq c (nthcdr i (car (nthcdr j fields))))
11063 (if (and (stringp (car c))
11064 (string-match org-bracket-link-regexp (car c))
11065 (< (org-string-width (car c)) len))
11066 (setcar c (concat (car c) (make-string (- len (org-string-width (car c))) ?\ )))))))
11068 ;; Compute the formats needed for output of the table
11069 (setq rfmt (concat indent "|") hfmt (concat indent "|"))
11070 (while (setq l (pop lengths))
11071 (setq ty (if (pop typenums) "" "-")) ; number types flushright
11072 (setq rfmt (concat rfmt (format rfmt1 ty l))
11073 hfmt (concat hfmt (format hfmt1 (make-string l ?-)))))
11074 (setq rfmt (concat rfmt "\n")
11075 hfmt (concat (substring hfmt 0 -1) "|\n"))
11077 (setq new (mapconcat
11078 (lambda (l)
11079 (if l (apply 'format rfmt
11080 (append (pop fields) emptystrings))
11081 hfmt))
11082 lines ""))
11083 ;; Replace the old one
11084 (delete-region beg end)
11085 (move-marker end nil)
11086 (move-marker org-table-aligned-begin-marker (point))
11087 (insert new)
11088 (move-marker org-table-aligned-end-marker (point))
11089 (when (and orgtbl-mode (not (org-mode-p)))
11090 (goto-char org-table-aligned-begin-marker)
11091 (while (org-hide-wide-columns org-table-aligned-end-marker)))
11092 ;; Try to move to the old location (approximately)
11093 (goto-line linepos)
11094 (set-window-start (selected-window) winstart 'noforce)
11095 (org-table-goto-column colpos)
11096 (setq org-table-may-need-update nil)
11099 (defun org-string-width (s)
11100 "Compute width of string, ignoring invisible characters.
11101 This ignores character with invisibility property `org-link', and also
11102 characters with property `org-cwidth', because these will become invisible
11103 upon the next fontification round."
11104 (let (b)
11105 (when (or (eq t buffer-invisibility-spec)
11106 (assq 'org-link buffer-invisibility-spec))
11107 (while (setq b (text-property-any 0 (length s)
11108 'invisible 'org-link s))
11109 (setq s (concat (substring s 0 b)
11110 (substring s (or (next-single-property-change
11111 b 'invisible s) (length s)))))))
11112 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
11113 (setq s (concat (substring s 0 b)
11114 (substring s (or (next-single-property-change
11115 b 'org-cwidth s) (length s))))))
11116 (string-width s)))
11118 (defun org-table-begin (&optional table-type)
11119 "Find the beginning of the table and return its position.
11120 With argument TABLE-TYPE, go to the beginning of a table.el-type table."
11121 (save-excursion
11122 (if (not (re-search-backward
11123 (if table-type org-table-any-border-regexp
11124 org-table-border-regexp)
11125 nil t))
11126 (progn (goto-char (point-min)) (point))
11127 (goto-char (match-beginning 0))
11128 (beginning-of-line 2)
11129 (point))))
11131 (defun org-table-end (&optional table-type)
11132 "Find the end of the table and return its position.
11133 With argument TABLE-TYPE, go to the end of a table.el-type table."
11134 (save-excursion
11135 (if (not (re-search-forward
11136 (if table-type org-table-any-border-regexp
11137 org-table-border-regexp)
11138 nil t))
11139 (goto-char (point-max))
11140 (goto-char (match-beginning 0)))
11141 (point-marker)))
11143 (defun org-table-justify-field-maybe (&optional new)
11144 "Justify the current field, text to left, number to right.
11145 Optional argument NEW may specify text to replace the current field content."
11146 (cond
11147 ((and (not new) org-table-may-need-update)) ; Realignment will happen anyway
11148 ((org-at-table-hline-p))
11149 ((and (not new)
11150 (or (not (equal (marker-buffer org-table-aligned-begin-marker)
11151 (current-buffer)))
11152 (< (point) org-table-aligned-begin-marker)
11153 (>= (point) org-table-aligned-end-marker)))
11154 ;; This is not the same table, force a full re-align
11155 (setq org-table-may-need-update t))
11156 (t ;; realign the current field, based on previous full realign
11157 (let* ((pos (point)) s
11158 (col (org-table-current-column))
11159 (num (if (> col 0) (nth (1- col) org-table-last-alignment)))
11160 l f n o e)
11161 (when (> col 0)
11162 (skip-chars-backward "^|\n")
11163 (if (looking-at " *\\([^|\n]*?\\) *\\(|\\|$\\)")
11164 (progn
11165 (setq s (match-string 1)
11166 o (match-string 0)
11167 l (max 1 (- (match-end 0) (match-beginning 0) 3))
11168 e (not (= (match-beginning 2) (match-end 2))))
11169 (setq f (format (if num " %%%ds %s" " %%-%ds %s")
11170 l (if e "|" (setq org-table-may-need-update t) ""))
11171 n (format f s))
11172 (if new
11173 (if (<= (length new) l) ;; FIXME: length -> str-width?
11174 (setq n (format f new))
11175 (setq n (concat new "|") org-table-may-need-update t)))
11176 (or (equal n o)
11177 (let (org-table-may-need-update)
11178 (replace-match n))))
11179 (setq org-table-may-need-update t))
11180 (goto-char pos))))))
11182 (defun org-table-next-field ()
11183 "Go to the next field in the current table, creating new lines as needed.
11184 Before doing so, re-align the table if necessary."
11185 (interactive)
11186 (org-table-maybe-eval-formula)
11187 (org-table-maybe-recalculate-line)
11188 (if (and org-table-automatic-realign
11189 org-table-may-need-update)
11190 (org-table-align))
11191 (let ((end (org-table-end)))
11192 (if (org-at-table-hline-p)
11193 (end-of-line 1))
11194 (condition-case nil
11195 (progn
11196 (re-search-forward "|" end)
11197 (if (looking-at "[ \t]*$")
11198 (re-search-forward "|" end))
11199 (if (and (looking-at "-")
11200 org-table-tab-jumps-over-hlines
11201 (re-search-forward "^[ \t]*|\\([^-]\\)" end t))
11202 (goto-char (match-beginning 1)))
11203 (if (looking-at "-")
11204 (progn
11205 (beginning-of-line 0)
11206 (org-table-insert-row 'below))
11207 (if (looking-at " ") (forward-char 1))))
11208 (error
11209 (org-table-insert-row 'below)))))
11211 (defun org-table-previous-field ()
11212 "Go to the previous field in the table.
11213 Before doing so, re-align the table if necessary."
11214 (interactive)
11215 (org-table-justify-field-maybe)
11216 (org-table-maybe-recalculate-line)
11217 (if (and org-table-automatic-realign
11218 org-table-may-need-update)
11219 (org-table-align))
11220 (if (org-at-table-hline-p)
11221 (end-of-line 1))
11222 (re-search-backward "|" (org-table-begin))
11223 (re-search-backward "|" (org-table-begin))
11224 (while (looking-at "|\\(-\\|[ \t]*$\\)")
11225 (re-search-backward "|" (org-table-begin)))
11226 (if (looking-at "| ?")
11227 (goto-char (match-end 0))))
11229 (defun org-table-next-row ()
11230 "Go to the next row (same column) in the current table.
11231 Before doing so, re-align the table if necessary."
11232 (interactive)
11233 (org-table-maybe-eval-formula)
11234 (org-table-maybe-recalculate-line)
11235 (if (or (looking-at "[ \t]*$")
11236 (save-excursion (skip-chars-backward " \t") (bolp)))
11237 (newline)
11238 (if (and org-table-automatic-realign
11239 org-table-may-need-update)
11240 (org-table-align))
11241 (let ((col (org-table-current-column)))
11242 (beginning-of-line 2)
11243 (if (or (not (org-at-table-p))
11244 (org-at-table-hline-p))
11245 (progn
11246 (beginning-of-line 0)
11247 (org-table-insert-row 'below)))
11248 (org-table-goto-column col)
11249 (skip-chars-backward "^|\n\r")
11250 (if (looking-at " ") (forward-char 1)))))
11252 (defun org-table-copy-down (n)
11253 "Copy a field down in the current column.
11254 If the field at the cursor is empty, copy into it the content of the nearest
11255 non-empty field above. With argument N, use the Nth non-empty field.
11256 If the current field is not empty, it is copied down to the next row, and
11257 the cursor is moved with it. Therefore, repeating this command causes the
11258 column to be filled row-by-row.
11259 If the variable `org-table-copy-increment' is non-nil and the field is an
11260 integer, it will be incremented while copying."
11261 (interactive "p")
11262 (let* ((colpos (org-table-current-column))
11263 (field (org-table-get-field))
11264 (non-empty (string-match "[^ \t]" field))
11265 (beg (org-table-begin))
11266 txt)
11267 (org-table-check-inside-data-field)
11268 (if non-empty
11269 (progn
11270 (setq txt (org-trim field))
11271 (org-table-next-row)
11272 (org-table-blank-field))
11273 (save-excursion
11274 (setq txt
11275 (catch 'exit
11276 (while (progn (beginning-of-line 1)
11277 (re-search-backward org-table-dataline-regexp
11278 beg t))
11279 (org-table-goto-column colpos t)
11280 (if (and (looking-at
11281 "|[ \t]*\\([^| \t][^|]*?\\)[ \t]*|")
11282 (= (setq n (1- n)) 0))
11283 (throw 'exit (match-string 1))))))))
11284 (if txt
11285 (progn
11286 (if (and org-table-copy-increment
11287 (string-match "^[0-9]+$" txt))
11288 (setq txt (format "%d" (+ (string-to-number txt) 1))))
11289 (insert txt)
11290 (org-table-maybe-recalculate-line)
11291 (org-table-align))
11292 (error "No non-empty field found"))))
11294 (defun org-table-check-inside-data-field ()
11295 "Is point inside a table data field?
11296 I.e. not on a hline or before the first or after the last column?
11297 This actually throws an error, so it aborts the current command."
11298 (if (or (not (org-at-table-p))
11299 (= (org-table-current-column) 0)
11300 (org-at-table-hline-p)
11301 (looking-at "[ \t]*$"))
11302 (error "Not in table data field")))
11304 (defvar org-table-clip nil
11305 "Clipboard for table regions.")
11307 (defun org-table-blank-field ()
11308 "Blank the current table field or active region."
11309 (interactive)
11310 (org-table-check-inside-data-field)
11311 (if (and (interactive-p) (org-region-active-p))
11312 (let (org-table-clip)
11313 (org-table-cut-region (region-beginning) (region-end)))
11314 (skip-chars-backward "^|")
11315 (backward-char 1)
11316 (if (looking-at "|[^|\n]+")
11317 (let* ((pos (match-beginning 0))
11318 (match (match-string 0))
11319 (len (org-string-width match)))
11320 (replace-match (concat "|" (make-string (1- len) ?\ )))
11321 (goto-char (+ 2 pos))
11322 (substring match 1)))))
11324 (defun org-table-get-field (&optional n replace)
11325 "Return the value of the field in column N of current row.
11326 N defaults to current field.
11327 If REPLACE is a string, replace field with this value. The return value
11328 is always the old value."
11329 (and n (org-table-goto-column n))
11330 (skip-chars-backward "^|\n")
11331 (backward-char 1)
11332 (if (looking-at "|[^|\r\n]*")
11333 (let* ((pos (match-beginning 0))
11334 (val (buffer-substring (1+ pos) (match-end 0))))
11335 (if replace
11336 (replace-match (concat "|" replace)))
11337 (goto-char (min (point-at-eol) (+ 2 pos)))
11338 val)
11339 (forward-char 1) ""))
11341 (defun org-table-current-column ()
11342 "Find out which column we are in.
11343 When called interactively, column is also displayed in echo area."
11344 (interactive)
11345 (if (interactive-p) (org-table-check-inside-data-field))
11346 (save-excursion
11347 (let ((cnt 0) (pos (point)))
11348 (beginning-of-line 1)
11349 (while (search-forward "|" pos t)
11350 (setq cnt (1+ cnt)))
11351 (if (interactive-p) (message "This is table column %d" cnt))
11352 cnt)))
11354 (defun org-table-goto-column (n &optional on-delim force)
11355 "Move the cursor to the Nth column in the current table line.
11356 With optional argument ON-DELIM, stop with point before the left delimiter
11357 of the field.
11358 If there are less than N fields, just go to after the last delimiter.
11359 However, when FORCE is non-nil, create new columns if necessary."
11360 (interactive "p")
11361 (let ((pos (point-at-eol)))
11362 (beginning-of-line 1)
11363 (when (> n 0)
11364 (while (and (> (setq n (1- n)) -1)
11365 (or (search-forward "|" pos t)
11366 (and force
11367 (progn (end-of-line 1)
11368 (skip-chars-backward "^|")
11369 (insert " | "))))))
11370 ; (backward-char 2) t)))))
11371 (when (and force (not (looking-at ".*|")))
11372 (save-excursion (end-of-line 1) (insert " | ")))
11373 (if on-delim
11374 (backward-char 1)
11375 (if (looking-at " ") (forward-char 1))))))
11377 (defun org-at-table-p (&optional table-type)
11378 "Return t if the cursor is inside an org-type table.
11379 If TABLE-TYPE is non-nil, also check for table.el-type tables."
11380 (if org-enable-table-editor
11381 (save-excursion
11382 (beginning-of-line 1)
11383 (looking-at (if table-type org-table-any-line-regexp
11384 org-table-line-regexp)))
11385 nil))
11387 (defun org-at-table.el-p ()
11388 "Return t if and only if we are at a table.el table."
11389 (and (org-at-table-p 'any)
11390 (save-excursion
11391 (goto-char (org-table-begin 'any))
11392 (looking-at org-table1-hline-regexp))))
11394 (defun org-table-recognize-table.el ()
11395 "If there is a table.el table nearby, recognize it and move into it."
11396 (if org-table-tab-recognizes-table.el
11397 (if (org-at-table.el-p)
11398 (progn
11399 (beginning-of-line 1)
11400 (if (looking-at org-table-dataline-regexp)
11402 (if (looking-at org-table1-hline-regexp)
11403 (progn
11404 (beginning-of-line 2)
11405 (if (looking-at org-table-any-border-regexp)
11406 (beginning-of-line -1)))))
11407 (if (re-search-forward "|" (org-table-end t) t)
11408 (progn
11409 (require 'table)
11410 (if (table--at-cell-p (point))
11412 (message "recognizing table.el table...")
11413 (table-recognize-table)
11414 (message "recognizing table.el table...done")))
11415 (error "This should not happen..."))
11417 nil)
11418 nil))
11420 (defun org-at-table-hline-p ()
11421 "Return t if the cursor is inside a hline in a table."
11422 (if org-enable-table-editor
11423 (save-excursion
11424 (beginning-of-line 1)
11425 (looking-at org-table-hline-regexp))
11426 nil))
11428 (defun org-table-insert-column ()
11429 "Insert a new column into the table."
11430 (interactive)
11431 (if (not (org-at-table-p))
11432 (error "Not at a table"))
11433 (org-table-find-dataline)
11434 (let* ((col (max 1 (org-table-current-column)))
11435 (beg (org-table-begin))
11436 (end (org-table-end))
11437 ;; Current cursor position
11438 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11439 (colpos col))
11440 (goto-char beg)
11441 (while (< (point) end)
11442 (if (org-at-table-hline-p)
11444 (org-table-goto-column col t)
11445 (insert "| "))
11446 (beginning-of-line 2))
11447 (move-marker end nil)
11448 (goto-line linepos)
11449 (org-table-goto-column colpos)
11450 (org-table-align)
11451 (org-table-modify-formulas 'insert col)))
11453 (defun org-table-find-dataline ()
11454 "Find a dataline in the current table, which is needed for column commands."
11455 (if (and (org-at-table-p)
11456 (not (org-at-table-hline-p)))
11458 (let ((col (current-column))
11459 (end (org-table-end)))
11460 (move-to-column col)
11461 (while (and (< (point) end)
11462 (or (not (= (current-column) col))
11463 (org-at-table-hline-p)))
11464 (beginning-of-line 2)
11465 (move-to-column col))
11466 (if (and (org-at-table-p)
11467 (not (org-at-table-hline-p)))
11469 (error
11470 "Please position cursor in a data line for column operations")))))
11472 (defun org-table-delete-column ()
11473 "Delete a column from the table."
11474 (interactive)
11475 (if (not (org-at-table-p))
11476 (error "Not at a table"))
11477 (org-table-find-dataline)
11478 (org-table-check-inside-data-field)
11479 (let* ((col (org-table-current-column))
11480 (beg (org-table-begin))
11481 (end (org-table-end))
11482 ;; Current cursor position
11483 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11484 (colpos col))
11485 (goto-char beg)
11486 (while (< (point) end)
11487 (if (org-at-table-hline-p)
11489 (org-table-goto-column col t)
11490 (and (looking-at "|[^|\n]+|")
11491 (replace-match "|")))
11492 (beginning-of-line 2))
11493 (move-marker end nil)
11494 (goto-line linepos)
11495 (org-table-goto-column colpos)
11496 (org-table-align)
11497 (org-table-modify-formulas 'remove col)))
11499 (defun org-table-move-column-right ()
11500 "Move column to the right."
11501 (interactive)
11502 (org-table-move-column nil))
11503 (defun org-table-move-column-left ()
11504 "Move column to the left."
11505 (interactive)
11506 (org-table-move-column 'left))
11508 (defun org-table-move-column (&optional left)
11509 "Move the current column to the right. With arg LEFT, move to the left."
11510 (interactive "P")
11511 (if (not (org-at-table-p))
11512 (error "Not at a table"))
11513 (org-table-find-dataline)
11514 (org-table-check-inside-data-field)
11515 (let* ((col (org-table-current-column))
11516 (col1 (if left (1- col) col))
11517 (beg (org-table-begin))
11518 (end (org-table-end))
11519 ;; Current cursor position
11520 (linepos (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
11521 (colpos (if left (1- col) (1+ col))))
11522 (if (and left (= col 1))
11523 (error "Cannot move column further left"))
11524 (if (and (not left) (looking-at "[^|\n]*|[^|\n]*$"))
11525 (error "Cannot move column further right"))
11526 (goto-char beg)
11527 (while (< (point) end)
11528 (if (org-at-table-hline-p)
11530 (org-table-goto-column col1 t)
11531 (and (looking-at "|\\([^|\n]+\\)|\\([^|\n]+\\)|")
11532 (replace-match "|\\2|\\1|")))
11533 (beginning-of-line 2))
11534 (move-marker end nil)
11535 (goto-line linepos)
11536 (org-table-goto-column colpos)
11537 (org-table-align)
11538 (org-table-modify-formulas 'swap col (if left (1- col) (1+ col)))))
11540 (defun org-table-move-row-down ()
11541 "Move table row down."
11542 (interactive)
11543 (org-table-move-row nil))
11544 (defun org-table-move-row-up ()
11545 "Move table row up."
11546 (interactive)
11547 (org-table-move-row 'up))
11549 (defun org-table-move-row (&optional up)
11550 "Move the current table line down. With arg UP, move it up."
11551 (interactive "P")
11552 (let ((col (current-column))
11553 (pos (point))
11554 (tonew (if up 0 2))
11555 txt)
11556 (beginning-of-line tonew)
11557 (if (not (org-at-table-p))
11558 (progn
11559 (goto-char pos)
11560 (error "Cannot move row further")))
11561 (goto-char pos)
11562 (beginning-of-line 1)
11563 (setq pos (point))
11564 (setq txt (buffer-substring (point) (1+ (point-at-eol))))
11565 (delete-region (point) (1+ (point-at-eol)))
11566 (beginning-of-line tonew)
11567 (insert txt)
11568 (beginning-of-line 0)
11569 (move-to-column col)))
11571 (defun org-table-insert-row (&optional arg)
11572 "Insert a new row above the current line into the table.
11573 With prefix ARG, insert below the current line."
11574 (interactive "P")
11575 (if (not (org-at-table-p))
11576 (error "Not at a table"))
11577 (let* ((line (buffer-substring (point-at-bol) (point-at-eol)))
11578 (new (org-table-clean-line line)))
11579 ;; Fix the first field if necessary
11580 (if (string-match "^[ \t]*| *[#$] *|" line)
11581 (setq new (replace-match (match-string 0 line) t t new)))
11582 (beginning-of-line (if arg 2 1))
11583 (let (org-table-may-need-update) (insert-before-markers new "\n"))
11584 (beginning-of-line 0)
11585 (re-search-forward "| ?" (point-at-eol) t)
11586 (and org-table-may-need-update (org-table-align))))
11588 (defun org-table-insert-hline (&optional arg)
11589 "Insert a horizontal-line below the current line into the table.
11590 With prefix ARG, insert above the current line."
11591 (interactive "P")
11592 (if (not (org-at-table-p))
11593 (error "Not at a table"))
11594 (let ((line (org-table-clean-line
11595 (buffer-substring (point-at-bol) (point-at-eol))))
11596 (col (current-column)))
11597 (while (string-match "|\\( +\\)|" line)
11598 (setq line (replace-match
11599 (concat "+" (make-string (- (match-end 1) (match-beginning 1))
11600 ?-) "|") t t line)))
11601 (and (string-match "\\+" line) (setq line (replace-match "|" t t line)))
11602 (beginning-of-line (if arg 1 2))
11603 (insert line "\n")
11604 (beginning-of-line (if arg 1 -1))
11605 (move-to-column col)))
11607 (defun org-table-clean-line (s)
11608 "Convert a table line S into a string with only \"|\" and space.
11609 In particular, this does handle wide and invisible characters."
11610 (if (string-match "^[ \t]*|-" s)
11611 ;; It's a hline, just map the characters
11612 (setq s (mapconcat (lambda (x) (if (member x '(?| ?+)) "|" " ")) s ""))
11613 (while (string-match "|\\([ \t]*?[^ \t\r\n|][^\r\n|]*\\)|" s)
11614 (setq s (replace-match
11615 (concat "|" (make-string (org-string-width (match-string 1 s))
11616 ?\ ) "|")
11617 t t s)))
11620 (defun org-table-kill-row ()
11621 "Delete the current row or horizontal line from the table."
11622 (interactive)
11623 (if (not (org-at-table-p))
11624 (error "Not at a table"))
11625 (let ((col (current-column)))
11626 (kill-region (point-at-bol) (min (1+ (point-at-eol)) (point-max)))
11627 (if (not (org-at-table-p)) (beginning-of-line 0))
11628 (move-to-column col)))
11630 (defun org-table-sort-lines (beg end numericp)
11631 "Sort table lines in region.
11632 Point and mark define the first and last line to include. Both point and
11633 mark should be in the column that is used for sorting. For example, to
11634 sort according to column 3, put the mark in the first line to sort, in
11635 table column 3. Put point into the last line to be included in the sorting,
11636 also in table column 3. The command will prompt for the sorting method
11637 \(n for numerical, a for alphanumeric)."
11638 (interactive "r\nsSorting method: [n]=numeric [a]=alpha: ")
11639 (setq numericp (string-match "[nN]" numericp))
11640 (org-table-align) ;; Just to be safe
11641 (let* (bcol ecol cmp column lns)
11642 (goto-char beg)
11643 (org-table-check-inside-data-field)
11644 (setq column (org-table-current-column)
11645 beg (move-marker (make-marker) (point-at-bol)))
11646 (goto-char end)
11647 (org-table-check-inside-data-field)
11648 (setq end (move-marker (make-marker) (1+ (point-at-eol))))
11649 (untabify beg end)
11650 (goto-char beg)
11651 (org-table-goto-column column)
11652 (skip-chars-backward "^|")
11653 (setq bcol (current-column))
11654 (org-table-goto-column (1+ column))
11655 (skip-chars-backward "^|")
11656 (setq ecol (1- (current-column)))
11657 (setq cmp (if numericp
11658 (lambda (a b) (< (car a) (car b)))
11659 (lambda (a b) (string< (car a) (car b)))))
11660 (setq lns (mapcar (lambda(x) (cons (org-trim (substring x bcol ecol)) x))
11661 (org-split-string (buffer-substring beg end) "\n")))
11662 (if numericp
11663 (setq lns (mapcar (lambda(x)
11664 (cons (string-to-number (car x)) (cdr x)))
11665 lns)))
11666 (delete-region beg end)
11667 (move-marker beg nil)
11668 (move-marker end nil)
11669 (insert (mapconcat 'cdr (setq lns (sort lns cmp)) "\n") "\n")
11670 (message "%d lines sorted %s based on column %d"
11671 (length lns)
11672 (if numericp "numerically" "alphabetically") column)))
11674 (defun org-table-cut-region (beg end)
11675 "Copy region in table to the clipboard and blank all relevant fields."
11676 (interactive "r")
11677 (org-table-copy-region beg end 'cut))
11679 (defun org-table-copy-region (beg end &optional cut)
11680 "Copy rectangular region in table to clipboard.
11681 A special clipboard is used which can only be accessed
11682 with `org-table-paste-rectangle'."
11683 (interactive "rP")
11684 (let* (l01 c01 l02 c02 l1 c1 l2 c2 ic1 ic2
11685 region cols
11686 (rpl (if cut " " nil)))
11687 (goto-char beg)
11688 (org-table-check-inside-data-field)
11689 (setq l01 (count-lines (point-min) (point))
11690 c01 (org-table-current-column))
11691 (goto-char end)
11692 (org-table-check-inside-data-field)
11693 (setq l02 (count-lines (point-min) (point))
11694 c02 (org-table-current-column))
11695 (setq l1 (min l01 l02) l2 (max l01 l02)
11696 c1 (min c01 c02) c2 (max c01 c02))
11697 (catch 'exit
11698 (while t
11699 (catch 'nextline
11700 (if (> l1 l2) (throw 'exit t))
11701 (goto-line l1)
11702 (if (org-at-table-hline-p) (throw 'nextline (setq l1 (1+ l1))))
11703 (setq cols nil ic1 c1 ic2 c2)
11704 (while (< ic1 (1+ ic2))
11705 (push (org-table-get-field ic1 rpl) cols)
11706 (setq ic1 (1+ ic1)))
11707 (push (nreverse cols) region)
11708 (setq l1 (1+ l1)))))
11709 (setq org-table-clip (nreverse region))
11710 (if cut (org-table-align))
11711 org-table-clip))
11713 (defun org-table-paste-rectangle ()
11714 "Paste a rectangular region into a table.
11715 The upper right corner ends up in the current field. All involved fields
11716 will be overwritten. If the rectangle does not fit into the present table,
11717 the table is enlarged as needed. The process ignores horizontal separator
11718 lines."
11719 (interactive)
11720 (unless (and org-table-clip (listp org-table-clip))
11721 (error "First cut/copy a region to paste!"))
11722 (org-table-check-inside-data-field)
11723 (let* ((clip org-table-clip)
11724 (line (count-lines (point-min) (point)))
11725 (col (org-table-current-column))
11726 (org-enable-table-editor t)
11727 (org-table-automatic-realign nil)
11728 c cols field)
11729 (while (setq cols (pop clip))
11730 (while (org-at-table-hline-p) (beginning-of-line 2))
11731 (if (not (org-at-table-p))
11732 (progn (end-of-line 0) (org-table-next-field)))
11733 (setq c col)
11734 (while (setq field (pop cols))
11735 (org-table-goto-column c nil 'force)
11736 (org-table-get-field nil field)
11737 (setq c (1+ c)))
11738 (beginning-of-line 2))
11739 (goto-line line)
11740 (org-table-goto-column col)
11741 (org-table-align)))
11743 (defun org-table-convert ()
11744 "Convert from `org-mode' table to table.el and back.
11745 Obviously, this only works within limits. When an Org-mode table is
11746 converted to table.el, all horizontal separator lines get lost, because
11747 table.el uses these as cell boundaries and has no notion of horizontal lines.
11748 A table.el table can be converted to an Org-mode table only if it does not
11749 do row or column spanning. Multiline cells will become multiple cells.
11750 Beware, Org-mode does not test if the table can be successfully converted - it
11751 blindly applies a recipe that works for simple tables."
11752 (interactive)
11753 (require 'table)
11754 (if (org-at-table.el-p)
11755 ;; convert to Org-mode table
11756 (let ((beg (move-marker (make-marker) (org-table-begin t)))
11757 (end (move-marker (make-marker) (org-table-end t))))
11758 (table-unrecognize-region beg end)
11759 (goto-char beg)
11760 (while (re-search-forward "^\\([ \t]*\\)\\+-.*\n" end t)
11761 (replace-match ""))
11762 (goto-char beg))
11763 (if (org-at-table-p)
11764 ;; convert to table.el table
11765 (let ((beg (move-marker (make-marker) (org-table-begin)))
11766 (end (move-marker (make-marker) (org-table-end))))
11767 ;; first, get rid of all horizontal lines
11768 (goto-char beg)
11769 (while (re-search-forward "^\\([ \t]*\\)|-.*\n" end t)
11770 (replace-match ""))
11771 ;; insert a hline before first
11772 (goto-char beg)
11773 (org-table-insert-hline 'above)
11774 (beginning-of-line -1)
11775 ;; insert a hline after each line
11776 (while (progn (beginning-of-line 3) (< (point) end))
11777 (org-table-insert-hline))
11778 (goto-char beg)
11779 (setq end (move-marker end (org-table-end)))
11780 ;; replace "+" at beginning and ending of hlines
11781 (while (re-search-forward "^\\([ \t]*\\)|-" end t)
11782 (replace-match "\\1+-"))
11783 (goto-char beg)
11784 (while (re-search-forward "-|[ \t]*$" end t)
11785 (replace-match "-+"))
11786 (goto-char beg)))))
11788 (defun org-table-wrap-region (arg)
11789 "Wrap several fields in a column like a paragraph.
11790 This is useful if you'd like to spread the contents of a field over several
11791 lines, in order to keep the table compact.
11793 If there is an active region, and both point and mark are in the same column,
11794 the text in the column is wrapped to minimum width for the given number of
11795 lines. Generally, this makes the table more compact. A prefix ARG may be
11796 used to change the number of desired lines. For example, `C-2 \\[org-table-wrap]'
11797 formats the selected text to two lines. If the region was longer than two
11798 lines, the remaining lines remain empty. A negative prefix argument reduces
11799 the current number of lines by that amount. The wrapped text is pasted back
11800 into the table. If you formatted it to more lines than it was before, fields
11801 further down in the table get overwritten - so you might need to make space in
11802 the table first.
11804 If there is no region, the current field is split at the cursor position and
11805 the text fragment to the right of the cursor is prepended to the field one
11806 line down.
11808 If there is no region, but you specify a prefix ARG, the current field gets
11809 blank, and the content is appended to the field above."
11810 (interactive "P")
11811 (org-table-check-inside-data-field)
11812 (if (org-region-active-p)
11813 ;; There is a region: fill as a paragraph
11814 (let ((beg (region-beginning))
11815 nlines)
11816 (org-table-cut-region (region-beginning) (region-end))
11817 (if (> (length (car org-table-clip)) 1)
11818 (error "Region must be limited to single column"))
11819 (setq nlines (if arg
11820 (if (< arg 1)
11821 (+ (length org-table-clip) arg)
11822 arg)
11823 (length org-table-clip)))
11824 (setq org-table-clip
11825 (mapcar 'list (org-wrap (mapconcat 'car org-table-clip " ")
11826 nil nlines)))
11827 (goto-char beg)
11828 (org-table-paste-rectangle))
11829 ;; No region, split the current field at point
11830 (if arg
11831 ;; combine with field above
11832 (let ((s (org-table-blank-field))
11833 (col (org-table-current-column)))
11834 (beginning-of-line 0)
11835 (while (org-at-table-hline-p) (beginning-of-line 0))
11836 (org-table-goto-column col)
11837 (skip-chars-forward "^|")
11838 (skip-chars-backward " ")
11839 (insert " " (org-trim s))
11840 (org-table-align))
11841 ;; split field
11842 (when (looking-at "\\([^|]+\\)+|")
11843 (let ((s (match-string 1)))
11844 (replace-match " |")
11845 (goto-char (match-beginning 0))
11846 (org-table-next-row)
11847 (insert (org-trim s) " ")
11848 (org-table-align))))))
11850 (defvar org-field-marker nil)
11852 (defun org-table-edit-field (arg)
11853 "Edit table field in a different window.
11854 This is mainly useful for fields that contain hidden parts.
11855 When called with a \\[universal-argument] prefix, just make the full field visible so that
11856 it can be edited in place."
11857 (interactive "P")
11858 (if arg
11859 (let ((b (save-excursion (skip-chars-backward "^|") (point)))
11860 (e (save-excursion (skip-chars-forward "^|\r\n") (point))))
11861 (remove-text-properties b e '(org-cwidth t invisible t
11862 display t intangible t))
11863 (if (and (boundp 'font-lock-mode) font-lock-mode)
11864 (font-lock-fontify-block)))
11865 (let ((pos (move-marker (make-marker) (point)))
11866 (field (org-table-get-field))
11867 (cw (current-window-configuration))
11869 (switch-to-buffer-other-window "*Org tmp*")
11870 (erase-buffer)
11871 (insert "#\n# Edit field and finish with C-c C-c\n#\n")
11872 (org-mode)
11873 (goto-char (setq p (point-max)))
11874 (insert (org-trim field))
11875 (remove-text-properties p (point-max)
11876 '(invisible t org-cwidth t display t
11877 intangible t))
11878 (goto-char p)
11879 (org-set-local 'org-finish-function
11880 'org-table-finish-edit-field)
11881 (org-set-local 'org-window-configuration cw)
11882 (org-set-local 'org-field-marker pos)
11883 (message "Edit and finish with C-c C-c"))))
11885 (defun org-table-finish-edit-field ()
11886 "Finish editing a table data field.
11887 Remove all newline characters, insert the result into the table, realign
11888 the table and kill the editing buffer."
11889 (let ((pos org-field-marker)
11890 (cw org-window-configuration)
11891 (cb (current-buffer))
11892 text)
11893 (goto-char (point-min))
11894 (while (re-search-forward "^#.*\n?" nil t) (replace-match ""))
11895 (while (re-search-forward "\\([ \t]*\n[ \t]*\\)+" nil t)
11896 (replace-match " "))
11897 (setq text (org-trim (buffer-string)))
11898 (set-window-configuration cw)
11899 (kill-buffer cb)
11900 (select-window (get-buffer-window (marker-buffer pos)))
11901 (goto-char pos)
11902 (move-marker pos nil)
11903 (org-table-check-inside-data-field)
11904 (org-table-get-field nil text)
11905 (org-table-align)
11906 (message "New field value inserted")))
11908 (defun org-trim (s)
11909 "Remove whitespace at beginning and end of string."
11910 (if (string-match "^[ \t]+" s) (setq s (replace-match "" t t s)))
11911 (if (string-match "[ \t]+$" s) (setq s (replace-match "" t t s)))
11914 (defun org-wrap (string &optional width lines)
11915 "Wrap string to either a number of lines, or a width in characters.
11916 If WIDTH is non-nil, the string is wrapped to that width, however many lines
11917 that costs. If there is a word longer than WIDTH, the text is actually
11918 wrapped to the length of that word.
11919 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
11920 many lines, whatever width that takes.
11921 The return value is a list of lines, without newlines at the end."
11922 (let* ((words (org-split-string string "[ \t\n]+"))
11923 (maxword (apply 'max (mapcar 'org-string-width words)))
11924 w ll)
11925 (cond (width
11926 (org-do-wrap words (max maxword width)))
11927 (lines
11928 (setq w maxword)
11929 (setq ll (org-do-wrap words maxword))
11930 (if (<= (length ll) lines)
11932 (setq ll words)
11933 (while (> (length ll) lines)
11934 (setq w (1+ w))
11935 (setq ll (org-do-wrap words w)))
11936 ll))
11937 (t (error "Cannot wrap this")))))
11940 (defun org-do-wrap (words width)
11941 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
11942 (let (lines line)
11943 (while words
11944 (setq line (pop words))
11945 (while (and words (< (+ (length line) (length (car words))) width))
11946 (setq line (concat line " " (pop words))))
11947 (setq lines (push line lines)))
11948 (nreverse lines)))
11950 (defun org-split-string (string &optional separators)
11951 "Splits STRING into substrings at SEPARATORS.
11952 No empty strings are returned if there are matches at the beginning
11953 and end of string."
11954 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
11955 (start 0)
11956 notfirst
11957 (list nil))
11958 (while (and (string-match rexp string
11959 (if (and notfirst
11960 (= start (match-beginning 0))
11961 (< start (length string)))
11962 (1+ start) start))
11963 (< (match-beginning 0) (length string)))
11964 (setq notfirst t)
11965 (or (eq (match-beginning 0) 0)
11966 (and (eq (match-beginning 0) (match-end 0))
11967 (eq (match-beginning 0) start))
11968 (setq list
11969 (cons (substring string start (match-beginning 0))
11970 list)))
11971 (setq start (match-end 0)))
11972 (or (eq start (length string))
11973 (setq list
11974 (cons (substring string start)
11975 list)))
11976 (nreverse list)))
11978 (defun org-table-map-tables (function)
11979 "Apply FUNCTION to the start of all tables in the buffer."
11980 (save-excursion
11981 (save-restriction
11982 (widen)
11983 (goto-char (point-min))
11984 (while (re-search-forward org-table-any-line-regexp nil t)
11985 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
11986 (beginning-of-line 1)
11987 (if (looking-at org-table-line-regexp)
11988 (save-excursion (funcall function)))
11989 (re-search-forward org-table-any-border-regexp nil 1))))
11990 (message "Mapping tables: done"))
11992 (defun org-table-sum (&optional beg end nlast)
11993 "Sum numbers in region of current table column.
11994 The result will be displayed in the echo area, and will be available
11995 as kill to be inserted with \\[yank].
11997 If there is an active region, it is interpreted as a rectangle and all
11998 numbers in that rectangle will be summed. If there is no active
11999 region and point is located in a table column, sum all numbers in that
12000 column.
12002 If at least one number looks like a time HH:MM or HH:MM:SS, all other
12003 numbers are assumed to be times as well (in decimal hours) and the
12004 numbers are added as such.
12006 If NLAST is a number, only the NLAST fields will actually be summed."
12007 (interactive)
12008 (save-excursion
12009 (let (col (timecnt 0) diff h m s org-table-clip)
12010 (cond
12011 ((and beg end)) ; beg and end given explicitly
12012 ((org-region-active-p)
12013 (setq beg (region-beginning) end (region-end)))
12015 (setq col (org-table-current-column))
12016 (goto-char (org-table-begin))
12017 (unless (re-search-forward "^[ \t]*|[^-]" nil t)
12018 (error "No table data"))
12019 (org-table-goto-column col)
12020 ;not needed? (skip-chars-backward "^|")
12021 (setq beg (point))
12022 (goto-char (org-table-end))
12023 (unless (re-search-backward "^[ \t]*|[^-]" nil t)
12024 (error "No table data"))
12025 (org-table-goto-column col)
12026 ;not needed? (skip-chars-forward "^|")
12027 (setq end (point))))
12028 (let* ((items (apply 'append (org-table-copy-region beg end)))
12029 (items1 (cond ((not nlast) items)
12030 ((>= nlast (length items)) items)
12031 (t (setq items (reverse items))
12032 (setcdr (nthcdr (1- nlast) items) nil)
12033 (nreverse items))))
12034 (numbers (delq nil (mapcar 'org-table-get-number-for-summing
12035 items1)))
12036 (res (apply '+ numbers))
12037 (sres (if (= timecnt 0)
12038 (format "%g" res)
12039 (setq diff (* 3600 res)
12040 h (floor (/ diff 3600)) diff (mod diff 3600)
12041 m (floor (/ diff 60)) diff (mod diff 60)
12042 s diff)
12043 (format "%d:%02d:%02d" h m s))))
12044 (kill-new sres)
12045 (if (interactive-p)
12046 (message "%s"
12047 (substitute-command-keys
12048 (format "Sum of %d items: %-20s (\\[yank] will insert result into buffer)"
12049 (length numbers) sres))))
12050 sres))))
12052 (defun org-table-get-number-for-summing (s)
12053 (let (n)
12054 (if (string-match "^ *|? *" s)
12055 (setq s (replace-match "" nil nil s)))
12056 (if (string-match " *|? *$" s)
12057 (setq s (replace-match "" nil nil s)))
12058 (setq n (string-to-number s))
12059 (cond
12060 ((and (string-match "0" s)
12061 (string-match "\\`[-+ \t0.edED]+\\'" s)) 0)
12062 ((string-match "\\`[ \t]+\\'" s) nil)
12063 ((string-match "\\`\\([0-9]+\\):\\([0-9]+\\)\\(:\\([0-9]+\\)\\)?\\'" s)
12064 (let ((h (string-to-number (or (match-string 1 s) "0")))
12065 (m (string-to-number (or (match-string 2 s) "0")))
12066 (s (string-to-number (or (match-string 4 s) "0"))))
12067 (if (boundp 'timecnt) (setq timecnt (1+ timecnt)))
12068 (* 1.0 (+ h (/ m 60.0) (/ s 3600.0)))))
12069 ((equal n 0) nil)
12070 (t n))))
12072 (defun org-table-get-vertical-vector (desc &optional tbeg col)
12073 "Get a calc vector from a column, accorting to descriptor DESC.
12074 Optional arguments TBEG and COL can give the beginning of the table and
12075 the current column, to avoid unnecessary parsing."
12076 (save-excursion
12077 (or tbeg (setq tbeg (org-table-begin)))
12078 (or col (setq col (org-table-current-column)))
12079 (let (beg end nn n n1 n2 l (thisline (org-current-line)) hline-list)
12080 (cond
12081 ((string-match "\\(I+\\)\\(-\\(I+\\)\\)?" desc)
12082 (setq n1 (- (match-end 1) (match-beginning 1)))
12083 (if (match-beginning 3)
12084 (setq n2 (- (match-end 2) (match-beginning 3))))
12085 (setq n (if n2 (max n1 n2) n1))
12086 (setq n1 (if n2 (min n1 n2)))
12087 (setq nn n)
12088 (while (and (> nn 0)
12089 (re-search-backward org-table-hline-regexp tbeg t))
12090 (push (org-current-line) hline-list)
12091 (setq nn (1- nn)))
12092 (setq hline-list (nreverse hline-list))
12093 (goto-line (nth (1- n) hline-list))
12094 (when (re-search-forward org-table-dataline-regexp)
12095 (org-table-goto-column col)
12096 (setq beg (point)))
12097 (goto-line (if n1 (nth (1- n1) hline-list) thisline))
12098 (when (re-search-backward org-table-dataline-regexp)
12099 (org-table-goto-column col)
12100 (setq end (point)))
12101 (setq l (apply 'append (org-table-copy-region beg end)))
12102 (concat "[" (mapconcat (lambda (x) (setq x (org-trim x))
12103 (if (equal x "") "0" x))
12104 l ",") "]"))
12105 ((string-match "\\([0-9]+\\)-\\([0-9]+\\)" desc)
12106 (setq n1 (string-to-number (match-string 1 desc))
12107 n2 (string-to-number (match-string 2 desc)))
12108 (beginning-of-line 1)
12109 (save-excursion
12110 (when (re-search-backward org-table-dataline-regexp tbeg t n1)
12111 (org-table-goto-column col)
12112 (setq beg (point))))
12113 (when (re-search-backward org-table-dataline-regexp tbeg t n2)
12114 (org-table-goto-column col)
12115 (setq end (point)))
12116 (setq l (apply 'append (org-table-copy-region beg end)))
12117 (concat "[" (mapconcat
12118 (lambda (x) (setq x (org-trim x))
12119 (if (equal x "") "0" x))
12120 l ",") "]"))
12121 ((string-match "\\([0-9]+\\)" desc)
12122 (beginning-of-line 1)
12123 (when (re-search-backward org-table-dataline-regexp tbeg t
12124 (string-to-number (match-string 0 desc)))
12125 (org-table-goto-column col)
12126 (org-trim (org-table-get-field))))))))
12128 (defvar org-table-formula-history nil)
12130 (defvar org-table-column-names nil
12131 "Alist with column names, derived from the `!' line.")
12132 (defvar org-table-column-name-regexp nil
12133 "Regular expression matching the current column names.")
12134 (defvar org-table-local-parameters nil
12135 "Alist with parameter names, derived from the `$' line.")
12136 (defvar org-table-named-field-locations nil
12137 "Alist with locations of named fields.")
12139 (defun org-table-get-formula (&optional equation named)
12140 "Read a formula from the minibuffer, offer stored formula as default."
12141 (let* ((name (car (rassoc (list (org-current-line)
12142 (org-table-current-column))
12143 org-table-named-field-locations)))
12144 (scol (if named
12145 (if name name
12146 (error "Not in a named field"))
12147 (int-to-string (org-table-current-column))))
12148 (dummy (and name (not named)
12149 (not (y-or-n-p "Replace named-field formula with column equation? " ))
12150 (error "Abort")))
12151 (org-table-may-need-update nil)
12152 (stored-list (org-table-get-stored-formulas))
12153 (stored (cdr (assoc scol stored-list)))
12154 (eq (cond
12155 ((and stored equation (string-match "^ *=? *$" equation))
12156 stored)
12157 ((stringp equation)
12158 equation)
12159 (t (read-string
12160 (format "%s formula $%s=" (if named "Field" "Column") scol)
12161 (or stored "") 'org-table-formula-history
12162 ;stored
12163 ))))
12164 mustsave)
12165 (when (not (string-match "\\S-" eq))
12166 ;; remove formula
12167 (setq stored-list (delq (assoc scol stored-list) stored-list))
12168 (org-table-store-formulas stored-list)
12169 (error "Formula removed"))
12170 (if (string-match "^ *=?" eq) (setq eq (replace-match "" t t eq)))
12171 (if (string-match " *$" eq) (setq eq (replace-match "" t t eq)))
12172 (if (and name (not named))
12173 ;; We set the column equation, delete the named one.
12174 (setq stored-list (delq (assoc name stored-list) stored-list)
12175 mustsave t))
12176 (if stored
12177 (setcdr (assoc scol stored-list) eq)
12178 (setq stored-list (cons (cons scol eq) stored-list)))
12179 (if (or mustsave (not (equal stored eq)))
12180 (org-table-store-formulas stored-list))
12181 eq))
12183 (defun org-table-store-formulas (alist)
12184 "Store the list of formulas below the current table."
12185 (setq alist (sort alist (lambda (a b) (string< (car a) (car b)))))
12186 (save-excursion
12187 (goto-char (org-table-end))
12188 (if (looking-at "\\([ \t]*\n\\)*#\\+TBLFM:.*\n?")
12189 (delete-region (point) (match-end 0)))
12190 (insert "#+TBLFM: "
12191 (mapconcat (lambda (x)
12192 (concat "$" (car x) "=" (cdr x)))
12193 alist "::")
12194 "\n")))
12196 (defun org-table-get-stored-formulas ()
12197 "Return an alist with the stored formulas directly after current table."
12198 (interactive)
12199 (let (scol eq eq-alist strings string seen)
12200 (save-excursion
12201 (goto-char (org-table-end))
12202 (when (looking-at "\\([ \t]*\n\\)*#\\+TBLFM: *\\(.*\\)")
12203 (setq strings (org-split-string (match-string 2) " *:: *"))
12204 (while (setq string (pop strings))
12205 (when (string-match "\\$\\([a-zA-Z0-9]+\\) *= *\\(.*[^ \t]\\)" string)
12206 (setq scol (match-string 1 string)
12207 eq (match-string 2 string)
12208 eq-alist (cons (cons scol eq) eq-alist))
12209 (if (member scol seen)
12210 (error "Double definition `$%s=' in TBLFM line, please fix by hand" scol)
12211 (push scol seen))))))
12212 (nreverse eq-alist)))
12214 (defun org-table-modify-formulas (action &rest columns)
12215 "Modify the formulas stored below the current table.
12216 ACTION can be `remove', `insert', `swap'. For `swap', two column numbers are
12217 expected, for the other actions only a single column number is needed."
12218 (let ((list (org-table-get-stored-formulas))
12219 (nmax (length (org-split-string
12220 (buffer-substring (point-at-bol) (point-at-eol))
12221 "|")))
12222 col col1 col2 scol si sc1 sc2)
12223 (cond
12224 ((null list)) ; No action needed if there are no stored formulas
12225 ((eq action 'remove)
12226 (setq col (car columns)
12227 scol (int-to-string col))
12228 (org-table-replace-in-formulas list scol "INVALID")
12229 (if (assoc scol list) (setq list (delq (assoc scol list) list)))
12230 (loop for i from (1+ col) upto nmax by 1 do
12231 (setq si (int-to-string i))
12232 (org-table-replace-in-formulas list si (int-to-string (1- i)))
12233 (if (assoc si list) (setcar (assoc si list)
12234 (int-to-string (1- i))))))
12235 ((eq action 'insert)
12236 (setq col (car columns))
12237 (loop for i from nmax downto col by 1 do
12238 (setq si (int-to-string i))
12239 (org-table-replace-in-formulas list si (int-to-string (1+ i)))
12240 (if (assoc si list) (setcar (assoc si list)
12241 (int-to-string (1+ i))))))
12242 ((eq action 'swap)
12243 (setq col1 (car columns) col2 (nth 1 columns)
12244 sc1 (int-to-string col1) sc2 (int-to-string col2))
12245 ;; Hopefully, ZqZtZ will never be a name in a table
12246 (org-table-replace-in-formulas list sc1 "ZqZtZ")
12247 (org-table-replace-in-formulas list sc2 sc1)
12248 (org-table-replace-in-formulas list "ZqZtZ" sc2)
12249 (if (assoc sc1 list) (setcar (assoc sc1 list) "ZqZtZ"))
12250 (if (assoc sc2 list) (setcar (assoc sc2 list) sc1))
12251 (if (assoc "ZqZtZ" list) (setcar (assoc "ZqZtZ" list) sc2)))
12252 (t (error "Invalid action in `org-table-modify-formulas'")))
12253 (if list (org-table-store-formulas list))))
12255 (defun org-table-replace-in-formulas (list s1 s2)
12256 (let (elt re s)
12257 (setq s1 (concat "$" (if (integerp s1) (int-to-string s1) s1))
12258 s2 (concat "$" (if (integerp s2) (int-to-string s2) s2))
12259 re (concat (regexp-quote s1) "\\>"))
12260 (while (setq elt (pop list))
12261 (setq s (cdr elt))
12262 (while (string-match re s)
12263 (setq s (replace-match s2 t t s)))
12264 (setcdr elt s))))
12266 (defun org-table-get-specials ()
12267 "Get the column names and local parameters for this table."
12268 (save-excursion
12269 (let ((beg (org-table-begin)) (end (org-table-end))
12270 names name fields fields1 field cnt c v line col)
12271 (setq org-table-column-names nil
12272 org-table-local-parameters nil
12273 org-table-named-field-locations nil)
12274 (goto-char beg)
12275 (when (re-search-forward "^[ \t]*| *! *\\(|.*\\)" end t)
12276 (setq names (org-split-string (match-string 1) " *| *")
12277 cnt 1)
12278 (while (setq name (pop names))
12279 (setq cnt (1+ cnt))
12280 (if (string-match "^[a-zA-Z][a-zA-Z0-9]*$" name)
12281 (push (cons name (int-to-string cnt)) org-table-column-names))))
12282 (setq org-table-column-names (nreverse org-table-column-names))
12283 (setq org-table-column-name-regexp
12284 (concat "\\$\\(" (mapconcat 'car org-table-column-names "\\|") "\\)\\>"))
12285 (goto-char beg)
12286 (while (re-search-forward "^[ \t]*| *\\$ *\\(|.*\\)" end t)
12287 (setq fields (org-split-string (match-string 1) " *| *"))
12288 (while (setq field (pop fields))
12289 (if (string-match "^\\([a-zA-Z][a-zA-Z0-9]*\\|%\\) *= *\\(.*\\)" field)
12290 (push (cons (match-string 1 field) (match-string 2 field))
12291 org-table-local-parameters))))
12292 (goto-char beg)
12293 (while (re-search-forward "^[ \t]*| *\\([_^]\\) *\\(|.*\\)" end t)
12294 (setq c (match-string 1)
12295 fields (org-split-string (match-string 2) " *| *"))
12296 (save-excursion
12297 (beginning-of-line (if (equal c "_") 2 0))
12298 (setq line (org-current-line) col 1)
12299 (and (looking-at "^[ \t]*|[^|]*\\(|.*\\)")
12300 (setq fields1 (org-split-string (match-string 1) " *| *"))))
12301 (while (and fields1 (setq field (pop fields)))
12302 (setq v (pop fields1) col (1+ col))
12303 (when (and (stringp field) (stringp v)
12304 (string-match "^[a-zA-Z][a-zA-Z0-9]*$" field))
12305 (push (cons field v) org-table-local-parameters)
12306 (push (list field line col) org-table-named-field-locations)))))))
12308 (defun org-this-word ()
12309 ;; Get the current word
12310 (save-excursion
12311 (let ((beg (progn (skip-chars-backward "^ \t\n") (point)))
12312 (end (progn (skip-chars-forward "^ \t\n") (point))))
12313 (buffer-substring-no-properties beg end))))
12315 (defun org-table-maybe-eval-formula ()
12316 "Check if the current field starts with \"=\" or \":=\".
12317 If yes, store the formula and apply it."
12318 ;; We already know we are in a table. Get field will only return a formula
12319 ;; when appropriate. It might return a separator line, but no problem.
12320 (when org-table-formula-evaluate-inline
12321 (let* ((field (org-trim (or (org-table-get-field) "")))
12322 named eq)
12323 (when (string-match "^:?=\\(.*\\)" field)
12324 (setq named (equal (string-to-char field) ?:)
12325 eq (match-string 1 field))
12326 (if (fboundp 'calc-eval)
12327 (org-table-eval-formula (if named '(4) nil) eq))))))
12329 (defvar org-recalc-commands nil
12330 "List of commands triggering the recalculation of a line.
12331 Will be filled automatically during use.")
12333 (defvar org-recalc-marks
12334 '((" " . "Unmarked: no special line, no automatic recalculation")
12335 ("#" . "Automatically recalculate this line upon TAB, RET, and C-c C-c in the line")
12336 ("*" . "Recalculate only when entire table is recalculated with `C-u C-c *'")
12337 ("!" . "Column name definition line. Reference in formula as $name.")
12338 ("$" . "Parameter definition line name=value. Reference in formula as $name.")
12339 ("_" . "Names for values in row below this one.")
12340 ("^" . "Names for values in row above this one.")))
12342 (defun org-table-rotate-recalc-marks (&optional newchar)
12343 "Rotate the recalculation mark in the first column.
12344 If in any row, the first field is not consistent with a mark,
12345 insert a new column for the markers.
12346 When there is an active region, change all the lines in the region,
12347 after prompting for the marking character.
12348 After each change, a message will be displayed indicating the meaning
12349 of the new mark."
12350 (interactive)
12351 (unless (org-at-table-p) (error "Not at a table"))
12352 (let* ((marks (append (mapcar 'car org-recalc-marks) '(" ")))
12353 (beg (org-table-begin))
12354 (end (org-table-end))
12355 (l (org-current-line))
12356 (l1 (if (org-region-active-p) (org-current-line (region-beginning))))
12357 (l2 (if (org-region-active-p) (org-current-line (region-end))))
12358 (have-col
12359 (save-excursion
12360 (goto-char beg)
12361 (not (re-search-forward "^[ \t]*|[^-|][^|]*[^#!$*_^| \t][^|]*|" end t))))
12362 (col (org-table-current-column))
12363 (forcenew (car (assoc newchar org-recalc-marks)))
12364 epos new)
12365 (when l1
12366 (message "Change region to what mark? Type # * ! $ or SPC: ")
12367 (setq newchar (char-to-string (read-char-exclusive))
12368 forcenew (car (assoc newchar org-recalc-marks))))
12369 (if (and newchar (not forcenew))
12370 (error "Invalid NEWCHAR `%s' in `org-table-rotate-recalc-marks'"
12371 newchar))
12372 (if l1 (goto-line l1))
12373 (save-excursion
12374 (beginning-of-line 1)
12375 (unless (looking-at org-table-dataline-regexp)
12376 (error "Not at a table data line")))
12377 (unless have-col
12378 (org-table-goto-column 1)
12379 (org-table-insert-column)
12380 (org-table-goto-column (1+ col)))
12381 (setq epos (point-at-eol))
12382 (save-excursion
12383 (beginning-of-line 1)
12384 (org-table-get-field
12385 1 (if (looking-at "^[ \t]*| *\\([#!$*^_ ]\\) *|")
12386 (concat " "
12387 (setq new (or forcenew
12388 (cadr (member (match-string 1) marks))))
12389 " ")
12390 " # ")))
12391 (if (and l1 l2)
12392 (progn
12393 (goto-line l1)
12394 (while (progn (beginning-of-line 2) (not (= (org-current-line) l2)))
12395 (and (looking-at org-table-dataline-regexp)
12396 (org-table-get-field 1 (concat " " new " "))))
12397 (goto-line l1)))
12398 (if (not (= epos (point-at-eol))) (org-table-align))
12399 (goto-line l)
12400 (and (interactive-p) (message (cdr (assoc new org-recalc-marks))))))
12402 (defun org-table-maybe-recalculate-line ()
12403 "Recompute the current line if marked for it, and if we haven't just done it."
12404 (interactive)
12405 (and org-table-allow-automatic-line-recalculation
12406 (not (and (memq last-command org-recalc-commands)
12407 (equal org-last-recalc-line (org-current-line))))
12408 (save-excursion (beginning-of-line 1)
12409 (looking-at org-table-auto-recalculate-regexp))
12410 (fboundp 'calc-eval)
12411 (org-table-recalculate) t))
12413 (defvar org-table-formula-debug nil
12414 "Non-nil means, debug table formulas.
12415 When nil, simply write \"#ERROR\" in corrupted fields.")
12417 (defvar modes)
12418 (defsubst org-set-calc-mode (var &optional value)
12419 (if (stringp var)
12420 (setq var (assoc var '(("D" calc-angle-mode deg)
12421 ("R" calc-angle-mode rad)
12422 ("F" calc-prefer-frac t)
12423 ("S" calc-symbolic-mode t)))
12424 value (nth 2 var) var (nth 1 var)))
12425 (if (memq var modes)
12426 (setcar (cdr (memq var modes)) value)
12427 (cons var (cons value modes)))
12428 modes)
12430 (defun org-table-eval-formula (&optional arg equation
12431 suppress-align suppress-const
12432 suppress-store)
12433 "Replace the table field value at the cursor by the result of a calculation.
12435 This function makes use of Dave Gillespie's Calc package, in my view the
12436 most exciting program ever written for GNU Emacs. So you need to have Calc
12437 installed in order to use this function.
12439 In a table, this command replaces the value in the current field with the
12440 result of a formula. It also installs the formula as the \"current\" column
12441 formula, by storing it in a special line below the table. When called
12442 with a `C-u' prefix, the current field must ba a named field, and the
12443 formula is installed as valid in only this specific field.
12445 When called, the command first prompts for a formula, which is read in
12446 the minibuffer. Previously entered formulas are available through the
12447 history list, and the last used formula is offered as a default.
12448 These stored formulas are adapted correctly when moving, inserting, or
12449 deleting columns with the corresponding commands.
12451 The formula can be any algebraic expression understood by the Calc package.
12452 For details, see the Org-mode manual.
12454 This function can also be called from Lisp programs and offers
12455 additional arguments: EQUATION can be the formula to apply. If this
12456 argument is given, the user will not be prompted. SUPPRESS-ALIGN is
12457 used to speed-up recursive calls by by-passing unnecessary aligns.
12458 SUPPRESS-CONST suppresses the interpretation of constants in the
12459 formula, assuming that this has been done already outside the function.
12460 SUPPRESS-STORE means the formula should not be stored, either because
12461 it is already stored, or because it is a modified equation that should
12462 not overwrite the stored one."
12463 (interactive "P")
12464 (require 'calc)
12465 (org-table-check-inside-data-field)
12466 (org-table-get-specials)
12467 (let* (fields
12468 (ndown (if (integerp arg) arg 1))
12469 (org-table-automatic-realign nil)
12470 (case-fold-search nil)
12471 (down (> ndown 1))
12472 (formula (if (and equation suppress-store)
12473 equation
12474 (org-table-get-formula equation (equal arg '(4)))))
12475 (n0 (org-table-current-column))
12476 (modes (copy-sequence org-calc-default-modes))
12477 n form fmt x ev orig c lispp)
12478 ;; Parse the format string. Since we have a lot of modes, this is
12479 ;; a lot of work. However, I think calc still uses most of the time.
12480 (if (string-match ";" formula)
12481 (let ((tmp (org-split-string formula ";")))
12482 (setq formula (car tmp)
12483 fmt (concat (cdr (assoc "%" org-table-local-parameters))
12484 (nth 1 tmp)))
12485 (while (string-match "\\([pnfse]\\)\\(-?[0-9]+\\)" fmt)
12486 (setq c (string-to-char (match-string 1 fmt))
12487 n (string-to-number (match-string 2 fmt)))
12488 (if (= c ?p)
12489 (setq modes (org-set-calc-mode 'calc-internal-prec n))
12490 (setq modes (org-set-calc-mode
12491 'calc-float-format
12492 (list (cdr (assoc c '((?n . float) (?f . fix)
12493 (?s . sci) (?e . eng))))
12494 n))))
12495 (setq fmt (replace-match "" t t fmt)))
12496 (while (string-match "[DRFS]" fmt)
12497 (setq modes (org-set-calc-mode (match-string 0 fmt)))
12498 (setq fmt (replace-match "" t t fmt)))
12499 (unless (string-match "\\S-" fmt)
12500 (setq fmt nil))))
12501 (if (and (not suppress-const) org-table-formula-use-constants)
12502 (setq formula (org-table-formula-substitute-names formula)))
12503 (setq orig (or (get-text-property 1 :orig-formula formula) "?"))
12504 (while (> ndown 0)
12505 (setq fields (org-split-string
12506 (buffer-substring
12507 (point-at-bol) (point-at-eol)) " *| *"))
12508 (if org-table-formula-numbers-only
12509 (setq fields (mapcar
12510 (lambda (x) (number-to-string (string-to-number x)))
12511 fields)))
12512 (setq ndown (1- ndown))
12513 (setq form (copy-sequence formula)
12514 lispp (equal (substring form 0 2) "'("))
12515 ;; Insert the references to fields in same row
12516 (while (string-match "\\$\\([0-9]+\\)?" form)
12517 (setq n (if (match-beginning 1)
12518 (string-to-number (match-string 1 form))
12520 x (nth (1- n) fields))
12521 (unless x (error "Invalid field specifier \"%s\""
12522 (match-string 0 form)))
12523 (if (equal x "") (setq x "0"))
12524 (setq form (replace-match
12525 (if lispp x (concat "(" x ")"))
12526 t t form)))
12527 ;; Insert ranges in current column
12528 (while (string-match "\\&[-I0-9]+" form)
12529 (setq form (replace-match
12530 (save-match-data
12531 (org-table-get-vertical-vector (match-string 0 form)
12532 nil n0))
12533 t t form)))
12534 (if lispp
12535 (setq ev (eval (eval (read form)))
12536 ev (if (numberp ev) (number-to-string ev) ev))
12537 (setq ev (calc-eval (cons form modes)
12538 (if org-table-formula-numbers-only 'num))))
12540 (when org-table-formula-debug
12541 (with-output-to-temp-buffer "*Help*"
12542 (princ (format "Substitution history of formula
12543 Orig: %s
12544 $xyz-> %s
12545 $1-> %s\n" orig formula form))
12546 (if (listp ev)
12547 (princ (format " %s^\nError: %s"
12548 (make-string (car ev) ?\-) (nth 1 ev)))
12549 (princ (format "Result: %s\nFormat: %s\nFinal: %s"
12550 ev (or fmt "NONE")
12551 (if fmt (format fmt (string-to-number ev)) ev)))))
12552 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
12553 (unless (and (interactive-p) (not ndown))
12554 (unless (let (inhibit-redisplay)
12555 (y-or-n-p "Debugging Formula. Continue to next? "))
12556 (org-table-align)
12557 (error "Abort"))
12558 (delete-window (get-buffer-window "*Help*"))
12559 (message "")))
12560 (if (listp ev) (setq fmt nil ev "#ERROR"))
12561 (org-table-justify-field-maybe
12562 (if fmt (format fmt (string-to-number ev)) ev))
12563 (if (and down (> ndown 0) (looking-at ".*\n[ \t]*|[^-]"))
12564 (call-interactively 'org-return)
12565 (setq ndown 0)))
12566 (and down (org-table-maybe-recalculate-line))
12567 (or suppress-align (and org-table-may-need-update
12568 (org-table-align)))))
12570 (defun org-table-recalculate (&optional all noalign)
12571 "Recalculate the current table line by applying all stored formulas.
12572 With prefix arg ALL, do this for all lines in the table."
12573 (interactive "P")
12574 (or (memq this-command org-recalc-commands)
12575 (setq org-recalc-commands (cons this-command org-recalc-commands)))
12576 (unless (org-at-table-p) (error "Not at a table"))
12577 (org-table-get-specials)
12578 (let* ((eqlist (sort (org-table-get-stored-formulas)
12579 (lambda (a b) (string< (car a) (car b)))))
12580 (inhibit-redisplay t)
12581 (line-re org-table-dataline-regexp)
12582 (thisline (+ (if (bolp) 1 0) (count-lines (point-min) (point))))
12583 (thiscol (org-table-current-column))
12584 beg end entry eqlnum eqlname eql (cnt 0) eq a name)
12585 ;; Insert constants in all formulas
12586 (setq eqlist
12587 (mapcar (lambda (x)
12588 (setcdr x (org-table-formula-substitute-names (cdr x)))
12590 eqlist))
12591 ;; Split the equation list
12592 (while (setq eq (pop eqlist))
12593 (if (<= (string-to-char (car eq)) ?9)
12594 (push eq eqlnum)
12595 (push eq eqlname)))
12596 (setq eqlnum (nreverse eqlnum) eqlname (nreverse eqlname))
12597 (if all
12598 (progn
12599 (setq end (move-marker (make-marker) (1+ (org-table-end))))
12600 (goto-char (setq beg (org-table-begin)))
12601 (if (re-search-forward org-table-calculate-mark-regexp end t)
12602 ;; This is a table with marked lines, only compute selected lines
12603 (setq line-re org-table-recalculate-regexp)
12604 ;; Move forward to the first non-header line
12605 (if (and (re-search-forward org-table-dataline-regexp end t)
12606 (re-search-forward org-table-hline-regexp end t)
12607 (re-search-forward org-table-dataline-regexp end t))
12608 (setq beg (match-beginning 0))
12609 nil))) ;; just leave beg where it is
12610 (setq beg (point-at-bol)
12611 end (move-marker (make-marker) (1+ (point-at-eol)))))
12612 (goto-char beg)
12613 (and all (message "Re-applying formulas to full table..."))
12614 (while (re-search-forward line-re end t)
12615 (unless (string-match "^ *[_^!$] *$" (org-table-get-field 1))
12616 ;; Unprotected line, recalculate
12617 (and all (message "Re-applying formulas to full table...(line %d)"
12618 (setq cnt (1+ cnt))))
12619 (setq org-last-recalc-line (org-current-line))
12620 (setq eql eqlnum)
12621 (while (setq entry (pop eql))
12622 (goto-line org-last-recalc-line)
12623 (org-table-goto-column (string-to-number (car entry)) nil 'force)
12624 (org-table-eval-formula nil (cdr entry) 'noalign 'nocst 'nostore))))
12625 (goto-line thisline)
12626 (org-table-goto-column thiscol)
12627 (or noalign (and org-table-may-need-update (org-table-align))
12628 (and all (message "Re-applying formulas to %d lines...done" cnt)))
12629 ;; Now do the names fields
12630 (while (setq eq (pop eqlname))
12631 (setq name (car eq)
12632 a (assoc name org-table-named-field-locations))
12633 (when a
12634 (message "Re-applying formula to named field: %s" name)
12635 (goto-line (nth 1 a))
12636 (org-table-goto-column (nth 2 a))
12637 (org-table-eval-formula nil (cdr eq) 'noalign 'nocst 'nostore)))
12638 ;; back to initial position
12639 (goto-line thisline)
12640 (org-table-goto-column thiscol)
12641 (or noalign (and org-table-may-need-update (org-table-align))
12642 (and all (message "Re-applying formulas...done")))))
12644 (defun org-table-formula-substitute-names (f)
12645 "Replace $const with values in string F."
12646 (let ((start 0) a n1 n2 nn1 nn2 s (f1 f))
12647 ;; First, check for column names
12648 (while (setq start (string-match org-table-column-name-regexp f start))
12649 (setq start (1+ start))
12650 (setq a (assoc (match-string 1 f) org-table-column-names))
12651 (setq f (replace-match (concat "$" (cdr a)) t t f)))
12652 ;; Expand ranges to vectors
12653 (while (string-match "\\$\\([0-9]+\\)\\.\\.\\.?\\$\\([0-9]+\\)" f)
12654 (setq n1 (string-to-number (match-string 1 f))
12655 n2 (string-to-number (match-string 2 f))
12656 nn1 (1+ (min n1 n2)) nn2 (max n1 n2)
12657 s (concat "[($" (number-to-string (1- nn1)) ")"))
12658 (loop for i from nn1 upto nn2 do
12659 (setq s (concat s ",($" (int-to-string i) ")")))
12660 (setq s (concat s "]"))
12661 (if (< n2 n1) (setq s (concat "rev(" s ")")))
12662 (setq f (replace-match s t t f)))
12663 ;; Parameters and constants
12664 (setq start 0)
12665 (while (setq start (string-match "\\$\\([a-zA-Z][a-zA-Z0-9]*\\)" f start))
12666 (setq start (1+ start))
12667 (if (setq a (save-match-data
12668 (org-table-get-constant (match-string 1 f))))
12669 (setq f (replace-match (concat "(" a ")") t t f))))
12670 (if org-table-formula-debug
12671 (put-text-property 0 (length f) :orig-formula f1 f))
12674 (defun org-table-get-constant (const)
12675 "Find the value for a parameter or constant in a formula.
12676 Parameters get priority."
12677 (or (cdr (assoc const org-table-local-parameters))
12678 (cdr (assoc const org-table-formula-constants))
12679 (and (fboundp 'constants-get) (constants-get const))
12680 "#UNDEFINED_NAME"))
12682 (defvar org-edit-formulas-map (make-sparse-keymap))
12683 (define-key org-edit-formulas-map "\C-c\C-c" 'org-finish-edit-formulas)
12684 (define-key org-edit-formulas-map "\C-c\C-q" 'org-abort-edit-formulas)
12685 (define-key org-edit-formulas-map "\C-c?" 'org-show-variable)
12687 (defvar org-pos)
12689 (defun org-table-edit-formulas ()
12690 "Edit the formulas of the current table in a separate buffer."
12691 (interactive)
12692 (unless (org-at-table-p)
12693 (error "Not at a table"))
12694 (org-table-get-specials)
12695 (let ((eql (org-table-get-stored-formulas))
12696 (pos (move-marker (make-marker) (point)))
12697 (wc (current-window-configuration))
12698 entry loc s)
12699 (switch-to-buffer-other-window "*Edit Formulas*")
12700 (erase-buffer)
12701 (fundamental-mode)
12702 (org-set-local 'org-pos pos)
12703 (org-set-local 'org-window-configuration wc)
12704 (use-local-map org-edit-formulas-map)
12705 (setq s "# Edit formulas and finish with `C-c C-c'.
12706 # Use `C-u C-c C-c' to also appy them immediately to the entire table.
12707 # Use `C-c ?' to get information about $name at point.
12708 # To cancel editing, press `C-c C-q'.\n")
12709 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12710 (insert s)
12711 (while (setq entry (pop eql))
12712 (when (setq loc (assoc (car entry) org-table-named-field-locations))
12713 (setq s (format "# Named formula, referring to column %d in line %d\n"
12714 (nth 2 loc) (nth 1 loc)))
12715 (put-text-property 0 (length s) 'face 'font-lock-comment-face s)
12716 (insert s))
12717 (setq s (concat "$" (car entry) "=" (cdr entry) "\n"))
12718 (remove-text-properties 0 (length s) '(face nil) s)
12719 (insert s))
12720 (goto-char (point-min))
12721 (message "Edit formulas and finish with `C-c C-c'.")))
12723 (defun org-show-variable ()
12724 "Show the location/value of the $ expression at point."
12725 (interactive)
12726 (let (var (pos org-pos) (win (selected-window)) e)
12727 (save-excursion
12728 (or (looking-at "\\$") (skip-chars-backward "$a-zA-Z0-9"))
12729 (if (looking-at "\\$\\([a-zA-Z0-9]+\\)")
12730 (setq var (match-string 1))
12731 (error "No variable at point")))
12732 (cond
12733 ((setq e (assoc var org-table-named-field-locations))
12734 (switch-to-buffer-other-window (marker-buffer pos))
12735 (goto-line (nth 1 e))
12736 (org-table-goto-column (nth 2 e))
12737 (select-window win)
12738 (message "Named field, column %d of line %d" (nth 2 e) (nth 1 e)))
12739 ((setq e (assoc var org-table-column-names))
12740 (switch-to-buffer-other-window (marker-buffer pos))
12741 (goto-char pos)
12742 (goto-char (org-table-begin))
12743 (if (re-search-forward (concat "^[ \t]*| *! *.*?| *\\(" var "\\) *|")
12744 (org-table-end) t)
12745 (progn
12746 (goto-char (match-beginning 1))
12747 (message "Named column (column %s)" (cdr e)))
12748 (error "Column name not found"))
12749 (select-window win))
12750 ((string-match "^[0-9]$" var)
12751 ;; column number
12752 (switch-to-buffer-other-window (marker-buffer pos))
12753 (goto-char pos)
12754 (goto-char (org-table-begin))
12755 (recenter 1)
12756 (if (re-search-forward org-table-dataline-regexp
12757 (org-table-end) t)
12758 (progn
12759 (goto-char (match-beginning 0))
12760 (org-table-goto-column (string-to-number var))
12761 (message "Column %s" var))
12762 (error "Column name not found"))
12763 (select-window win))
12764 ((setq e (assoc var org-table-local-parameters))
12765 (switch-to-buffer-other-window (marker-buffer pos))
12766 (goto-char pos)
12767 (goto-char (org-table-begin))
12768 (if (re-search-forward (concat "^[ \t]*| *\\$ *.*?| *\\(" var "=\\)") nil t)
12769 (progn
12770 (goto-char (match-beginning 1))
12771 (message "Local parameter."))
12772 (error "Parameter not found"))
12773 (select-window win))
12775 (cond
12776 ((setq e (assoc var org-table-formula-constants))
12777 (message "Constant: $%s=%s in `org-table-formula-constants'." var (cdr e)))
12778 ((setq e (and (fboundp 'constants-get) (constants-get var)))
12779 (message "Constant: $%s=%s, retrieved from `constants.el'." var e))
12780 (t (error "Undefined name $%s" var)))))))
12782 (defun org-finish-edit-formulas (&optional arg)
12783 "Parse the buffer for formula definitions and install them.
12784 With prefix ARG, apply the new formulas to the table."
12785 (interactive "P")
12786 (let ((pos org-pos) eql)
12787 (goto-char (point-min))
12788 (while (re-search-forward "^\\$\\([a-zA-Z0-9]+\\) *= *\\(.*?\\) *$" nil t)
12789 (push (cons (match-string 1) (match-string 2)) eql))
12790 (set-window-configuration org-window-configuration)
12791 (select-window (get-buffer-window (marker-buffer pos)))
12792 (goto-char pos)
12793 (unless (org-at-table-p)
12794 (error "Lost table position - cannot install formulae"))
12795 (org-table-store-formulas eql)
12796 (move-marker pos nil)
12797 (kill-buffer "*Edit Formulas*")
12798 (if arg
12799 (org-table-recalculate 'all)
12800 (message "New formulas installed - press C-u C-c C-c to apply."))))
12802 (defun org-abort-edit-formulas ()
12803 "Abort editing formulas, without installing the changes."
12804 (interactive)
12805 (let ((pos org-pos))
12806 (set-window-configuration org-window-configuration)
12807 (select-window (get-buffer-window (marker-buffer pos)))
12808 (goto-char pos)
12809 (message "Formula editing aborted without installing changes")))
12811 ;;; The orgtbl minor mode
12813 ;; Define a minor mode which can be used in other modes in order to
12814 ;; integrate the org-mode table editor.
12816 ;; This is really a hack, because the org-mode table editor uses several
12817 ;; keys which normally belong to the major mode, for example the TAB and
12818 ;; RET keys. Here is how it works: The minor mode defines all the keys
12819 ;; necessary to operate the table editor, but wraps the commands into a
12820 ;; function which tests if the cursor is currently inside a table. If that
12821 ;; is the case, the table editor command is executed. However, when any of
12822 ;; those keys is used outside a table, the function uses `key-binding' to
12823 ;; look up if the key has an associated command in another currently active
12824 ;; keymap (minor modes, major mode, global), and executes that command.
12825 ;; There might be problems if any of the keys used by the table editor is
12826 ;; otherwise used as a prefix key.
12828 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
12829 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
12830 ;; addresses this by checking explicitly for both bindings.
12832 ;; The optimized version (see variable `orgtbl-optimized') takes over
12833 ;; all keys which are bound to `self-insert-command' in the *global map*.
12834 ;; Some modes bind other commands to simple characters, for example
12835 ;; AUCTeX binds the double quote to `Tex-insert-quote'. With orgtbl-mode
12836 ;; active, this binding is ignored inside tables and replaced with a
12837 ;; modified self-insert.
12839 (defvar orgtbl-mode nil
12840 "Variable controlling `orgtbl-mode', a minor mode enabling the `org-mode'
12841 table editor in arbitrary modes.")
12842 (make-variable-buffer-local 'orgtbl-mode)
12844 (defvar orgtbl-mode-map (make-keymap)
12845 "Keymap for `orgtbl-mode'.")
12847 ;;;###autoload
12848 (defun turn-on-orgtbl ()
12849 "Unconditionally turn on `orgtbl-mode'."
12850 (orgtbl-mode 1))
12852 ;;;###autoload
12853 (defun orgtbl-mode (&optional arg)
12854 "The `org-mode' table editor as a minor mode for use in other modes."
12855 (interactive)
12856 (if (org-mode-p)
12857 ;; Exit without error, in case some hook functions calls this
12858 ;; by accident in org-mode.
12859 (message "Orgtbl-mode is not useful in org-mode, command ignored")
12860 (setq orgtbl-mode
12861 (if arg (> (prefix-numeric-value arg) 0) (not orgtbl-mode)))
12862 (if orgtbl-mode
12863 (progn
12864 (and (orgtbl-setup) (defun orgtbl-setup () nil))
12865 ;; Make sure we are first in minor-mode-map-alist
12866 (let ((c (assq 'orgtbl-mode minor-mode-map-alist)))
12867 (and c (setq minor-mode-map-alist
12868 (cons c (delq c minor-mode-map-alist)))))
12869 (org-set-local (quote org-table-may-need-update) t)
12870 (org-add-hook 'before-change-functions 'org-before-change-function
12871 nil 'local)
12872 (org-set-local 'org-old-auto-fill-inhibit-regexp
12873 auto-fill-inhibit-regexp)
12874 (org-set-local 'auto-fill-inhibit-regexp
12875 (if auto-fill-inhibit-regexp
12876 (concat "\\([ \t]*|\\|" auto-fill-inhibit-regexp)
12877 "[ \t]*|"))
12878 (org-add-to-invisibility-spec '(org-cwidth))
12879 (easy-menu-add orgtbl-mode-menu)
12880 (run-hooks 'orgtbl-mode-hook))
12881 (setq auto-fill-inhibit-regexp org-old-auto-fill-inhibit-regexp)
12882 (org-cleanup-narrow-column-properties)
12883 (org-remove-from-invisibility-spec '(org-cwidth))
12884 (remove-hook 'before-change-functions 'org-before-change-function t)
12885 (easy-menu-remove orgtbl-mode-menu)
12886 (force-mode-line-update 'all))))
12888 (defun org-cleanup-narrow-column-properties ()
12889 "Remove all properties related to narrow-column invisibility."
12890 (let ((s 1))
12891 (while (setq s (text-property-any s (point-max)
12892 'display org-narrow-column-arrow))
12893 (remove-text-properties s (1+ s) '(display t)))
12894 (setq s 1)
12895 (while (setq s (text-property-any s (point-max) 'org-cwidth 1))
12896 (remove-text-properties s (1+ s) '(org-cwidth t)))
12897 (setq s 1)
12898 (while (setq s (text-property-any s (point-max) 'invisible 'org-cwidth))
12899 (remove-text-properties s (1+ s) '(invisible t)))))
12901 ;; Install it as a minor mode.
12902 (put 'orgtbl-mode :included t)
12903 (put 'orgtbl-mode :menu-tag "Org Table Mode")
12904 (add-minor-mode 'orgtbl-mode " OrgTbl" orgtbl-mode-map)
12906 (defun orgtbl-make-binding (fun n &rest keys)
12907 "Create a function for binding in the table minor mode.
12908 FUN is the command to call inside a table. N is used to create a unique
12909 command name. KEYS are keys that should be checked in for a command
12910 to execute outside of tables."
12911 (eval
12912 (list 'defun
12913 (intern (concat "orgtbl-hijacker-command-" (int-to-string n)))
12914 '(arg)
12915 (concat "In tables, run `" (symbol-name fun) "'.\n"
12916 "Outside of tables, run the binding of `"
12917 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
12918 "'.")
12919 '(interactive "p")
12920 (list 'if
12921 '(org-at-table-p)
12922 (list 'call-interactively (list 'quote fun))
12923 (list 'let '(orgtbl-mode)
12924 (list 'call-interactively
12925 (append '(or)
12926 (mapcar (lambda (k)
12927 (list 'key-binding k))
12928 keys)
12929 '('orgtbl-error))))))))
12931 (defun orgtbl-error ()
12932 "Error when there is no default binding for a table key."
12933 (interactive)
12934 (error "This key is has no function outside tables"))
12936 (defun orgtbl-setup ()
12937 "Setup orgtbl keymaps."
12938 (let ((nfunc 0)
12939 (bindings
12940 (list
12941 '([(meta shift left)] org-table-delete-column)
12942 '([(meta left)] org-table-move-column-left)
12943 '([(meta right)] org-table-move-column-right)
12944 '([(meta shift right)] org-table-insert-column)
12945 '([(meta shift up)] org-table-kill-row)
12946 '([(meta shift down)] org-table-insert-row)
12947 '([(meta up)] org-table-move-row-up)
12948 '([(meta down)] org-table-move-row-down)
12949 '("\C-c\C-w" org-table-cut-region)
12950 '("\C-c\M-w" org-table-copy-region)
12951 '("\C-c\C-y" org-table-paste-rectangle)
12952 '("\C-c-" org-table-insert-hline)
12953 ; '([(shift tab)] org-table-previous-field)
12954 '("\C-m" org-table-next-row)
12955 (list (org-key 'S-return) 'org-table-copy-down)
12956 '([(meta return)] org-table-wrap-region)
12957 '("\C-c\C-q" org-table-wrap-region)
12958 '("\C-c?" org-table-current-column)
12959 '("\C-c " org-table-blank-field)
12960 '("\C-c+" org-table-sum)
12961 '("\C-c=" org-table-eval-formula)
12962 '("\C-c'" org-table-edit-formulas)
12963 '("\C-c`" org-table-edit-field)
12964 '("\C-c*" org-table-recalculate)
12965 '("\C-c|" org-table-create-or-convert-from-region)
12966 '("\C-c^" org-table-sort-lines)
12967 '([(control ?#)] org-table-rotate-recalc-marks)))
12968 elt key fun cmd)
12969 (while (setq elt (pop bindings))
12970 (setq nfunc (1+ nfunc))
12971 (setq key (car elt)
12972 fun (nth 1 elt)
12973 cmd (orgtbl-make-binding fun nfunc key))
12974 (define-key orgtbl-mode-map key cmd))
12975 ;; Special treatment needed for TAB and RET
12976 (define-key orgtbl-mode-map [(return)]
12977 (orgtbl-make-binding 'orgtbl-ret 100 [(return)] "\C-m"))
12978 (define-key orgtbl-mode-map "\C-m"
12979 (orgtbl-make-binding 'orgtbl-ret 101 "\C-m" [(return)]))
12980 (define-key orgtbl-mode-map [(tab)]
12981 (orgtbl-make-binding 'orgtbl-tab 102 [(tab)] "\C-i"))
12982 (define-key orgtbl-mode-map "\C-i"
12983 (orgtbl-make-binding 'orgtbl-tab 103 "\C-i" [(tab)])))
12984 (define-key orgtbl-mode-map "\C-i"
12985 (orgtbl-make-binding 'orgtbl-tab 104 [(shift tab)]))
12986 (define-key orgtbl-mode-map "\C-c\C-c"
12987 (orgtbl-make-binding 'org-ctrl-c-ctrl-c 105 "\C-c\C-c"))
12988 (when orgtbl-optimized
12989 ;; If the user wants maximum table support, we need to hijack
12990 ;; some standard editing functions
12991 (org-remap orgtbl-mode-map
12992 'self-insert-command 'orgtbl-self-insert-command
12993 'delete-char 'org-delete-char
12994 'delete-backward-char 'org-delete-backward-char)
12995 (define-key orgtbl-mode-map "|" 'org-force-self-insert))
12996 (easy-menu-define orgtbl-mode-menu orgtbl-mode-map "OrgTbl menu"
12997 '("OrgTbl"
12998 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p) :keys "C-c C-c"]
12999 ["Next Field" org-cycle :active (org-at-table-p) :keys "TAB"]
13000 ["Previous Field" org-shifttab :active (org-at-table-p) :keys "S-TAB"]
13001 ["Next Row" org-return :active (org-at-table-p) :keys "RET"]
13002 "--"
13003 ["Blank Field" org-table-blank-field :active (org-at-table-p) :keys "C-c SPC"]
13004 ["Edit Field" org-table-edit-field :active (org-at-table-p) :keys "C-c ` "]
13005 ["Copy Field from Above"
13006 org-table-copy-down :active (org-at-table-p) :keys "S-RET"]
13007 "--"
13008 ("Column"
13009 ["Move Column Left" org-metaleft :active (org-at-table-p) :keys "M-<left>"]
13010 ["Move Column Right" org-metaright :active (org-at-table-p) :keys "M-<right>"]
13011 ["Delete Column" org-shiftmetaleft :active (org-at-table-p) :keys "M-S-<left>"]
13012 ["Insert Column" org-shiftmetaright :active (org-at-table-p) :keys "M-S-<right>"]
13013 "--"
13014 ["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])
13015 ("Row"
13016 ["Move Row Up" org-metaup :active (org-at-table-p) :keys "M-<up>"]
13017 ["Move Row Down" org-metadown :active (org-at-table-p) :keys "M-<down>"]
13018 ["Delete Row" org-shiftmetaup :active (org-at-table-p) :keys "M-S-<up>"]
13019 ["Insert Row" org-shiftmetadown :active (org-at-table-p) :keys "M-S-<down>"]
13020 ["Sort lines in region" org-table-sort-lines (org-at-table-p) :keys "C-c ^"]
13021 "--"
13022 ["Insert Hline" org-table-insert-hline :active (org-at-table-p) :keys "C-c -"])
13023 ("Rectangle"
13024 ["Copy Rectangle" org-copy-special :active (org-at-table-p)]
13025 ["Cut Rectangle" org-cut-special :active (org-at-table-p)]
13026 ["Paste Rectangle" org-paste-special :active (org-at-table-p)]
13027 ["Fill Rectangle" org-table-wrap-region :active (org-at-table-p)])
13028 "--"
13029 ["Set Column Formula" org-table-eval-formula :active (org-at-table-p) :keys "C-c ="]
13030 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13031 ["Edit Formulas" org-table-edit-formulas :active (org-at-table-p) :keys "C-c '"]
13032 ["Recalculate line" org-table-recalculate :active (org-at-table-p) :keys "C-c *"]
13033 ["Recalculate all" (org-table-recalculate '(4)) :active (org-at-table-p) :keys "C-u C-c *"]
13034 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks :active (org-at-table-p) :keys "C-c #"]
13035 ["Sum Column/Rectangle" org-table-sum
13036 :active (or (org-at-table-p) (org-region-active-p)) :keys "C-c +"]
13037 ["Which Column?" org-table-current-column :active (org-at-table-p) :keys "C-c ?"]
13038 ["Debug Formulas"
13039 (setq org-table-formula-debug (not org-table-formula-debug))
13040 :style toggle :selected org-table-formula-debug]
13044 (defun orgtbl-tab (arg)
13045 "Justification and field motion for `orgtbl-mode'."
13046 (interactive "P")
13047 (if arg (org-table-edit-field t)
13048 (org-table-justify-field-maybe)
13049 (org-table-next-field)))
13051 (defun orgtbl-ret ()
13052 "Justification and field motion for `orgtbl-mode'."
13053 (interactive)
13054 (org-table-justify-field-maybe)
13055 (org-table-next-row))
13057 (defun orgtbl-self-insert-command (N)
13058 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13059 If the cursor is in a table looking at whitespace, the whitespace is
13060 overwritten, and the table is not marked as requiring realignment."
13061 (interactive "p")
13062 (if (and (org-at-table-p)
13064 (and org-table-auto-blank-field
13065 (member last-command
13066 '(orgtbl-hijacker-command-100
13067 orgtbl-hijacker-command-101
13068 orgtbl-hijacker-command-102
13069 orgtbl-hijacker-command-103
13070 orgtbl-hijacker-command-104
13071 orgtbl-hijacker-command-105))
13072 (org-table-blank-field))
13074 (eq N 1)
13075 (looking-at "[^|\n]* +|"))
13076 (let (org-table-may-need-update)
13077 (goto-char (1- (match-end 0)))
13078 (delete-backward-char 1)
13079 (goto-char (match-beginning 0))
13080 (self-insert-command N))
13081 (setq org-table-may-need-update t)
13082 (let (orgtbl-mode)
13083 (call-interactively (key-binding (vector last-input-event))))))
13085 (defun org-force-self-insert (N)
13086 "Needed to enforce self-insert under remapping."
13087 (interactive "p")
13088 (self-insert-command N))
13090 ;;; Exporting
13092 (defconst org-level-max 20)
13094 (defvar org-export-html-preamble nil
13095 "Preamble, to be inserted just after <body>. Set by publishing functions.")
13096 (defvar org-export-html-postamble nil
13097 "Preamble, to be inserted just before </body>. Set by publishing functions.")
13098 (defvar org-export-html-auto-preamble t
13099 "Should default preamble be inserted? Set by publishing functions.")
13100 (defvar org-export-html-auto-postamble t
13101 "Should default postamble be inserted? Set by publishing functions.")
13103 (defconst org-export-plist-vars
13104 '((:language . org-export-default-language)
13105 (:headline-levels . org-export-headline-levels)
13106 (:section-numbers . org-export-with-section-numbers)
13107 (:table-of-contents . org-export-with-toc)
13108 (:archived-trees . org-export-with-archived-trees)
13109 (:emphasize . org-export-with-emphasize)
13110 (:sub-superscript . org-export-with-sub-superscripts)
13111 (:TeX-macros . org-export-with-TeX-macros)
13112 (:LaTeX-fragments . org-export-with-LaTeX-fragments)
13113 (:fixed-width . org-export-with-fixed-width)
13114 (:timestamps . org-export-with-timestamps)
13115 (:tables . org-export-with-tables)
13116 (:table-auto-headline . org-export-highlight-first-table-line)
13117 (:style . org-export-html-style)
13118 (:convert-org-links . org-export-html-link-org-files-as-html)
13119 (:inline-images . org-export-html-inline-images)
13120 (:expand-quoted-html . org-export-html-expand)
13121 (:timestamp . org-export-html-with-timestamp)
13122 (:publishing-directory . org-export-publishing-directory)
13123 (:preamble . org-export-html-preamble)
13124 (:postamble . org-export-html-postamble)
13125 (:auto-preamble . org-export-html-auto-preamble)
13126 (:auto-postamble . org-export-html-auto-postamble)
13127 (:author . user-full-name)
13128 (:email . user-mail-address)))
13130 (defun org-default-export-plist ()
13131 "Return the property list with default settings for the export variables."
13132 (let ((l org-export-plist-vars) rtn e)
13133 (while (setq e (pop l))
13134 (setq rtn (cons (car e) (cons (symbol-value (cdr e)) rtn))))
13135 rtn))
13137 (defun org-infile-export-plist ()
13138 "Return the property list with file-local settings for export."
13139 (save-excursion
13140 (goto-char 0)
13141 (let ((re (org-make-options-regexp
13142 '("TITLE" "AUTHOR" "EMAIL" "TEXT" "OPTIONS" "LANGUAGE")))
13143 p key val text options)
13144 (while (re-search-forward re nil t)
13145 (setq key (org-match-string-no-properties 1)
13146 val (org-match-string-no-properties 2))
13147 (cond
13148 ((string-equal key "TITLE") (setq p (plist-put p :title val)))
13149 ((string-equal key "AUTHOR")(setq p (plist-put p :author val)))
13150 ((string-equal key "EMAIL") (setq p (plist-put p :email val)))
13151 ((string-equal key "LANGUAGE") (setq p (plist-put p :language val)))
13152 ((string-equal key "TEXT")
13153 (setq text (if text (concat text "\n" val) val)))
13154 ((string-equal key "OPTIONS") (setq options val))))
13155 (setq p (plist-put p :text text))
13156 (when options
13157 (let ((op '(("H" . :headline-levels)
13158 ("num" . :section-numbers)
13159 ("toc" . :table-of-contents)
13160 ("\\n" . :preserve-breaks)
13161 ("@" . :expand-quoted-html)
13162 (":" . :fixed-width)
13163 ("|" . :tables)
13164 ("^" . :sub-superscript)
13165 ("*" . :emphasize)
13166 ("TeX" . :TeX-macros)
13167 ("LaTeX" . :LaTeX-fragments)))
13169 (while (setq o (pop op))
13170 (if (string-match (concat (regexp-quote (car o))
13171 ":\\([^ \t\n\r;,.]*\\)")
13172 options)
13173 (setq p (plist-put p (cdr o)
13174 (car (read-from-string
13175 (match-string 1 options)))))))))
13176 p)))
13178 (defun org-combine-plists (&rest plists)
13179 "Create a single property list from all plists in PLISTS.
13180 The process starts by copying the last list, and then setting properties
13181 from the other lists. Settings in the first list are the most significant
13182 ones and overrule settings in the other lists."
13183 (let ((rtn (copy-sequence (pop plists)))
13184 p v ls)
13185 (while plists
13186 (setq ls (pop plists))
13187 (while ls
13188 (setq p (pop ls) v (pop ls))
13189 (setq rtn (plist-put rtn p v))))
13190 rtn))
13192 (defun org-export-directory (type plist)
13193 (let* ((val (plist-get plist :publishing-directory))
13194 (dir (if (listp val)
13195 (or (cdr (assoc type val)) ".")
13196 val)))
13197 dir))
13199 (defun org-export-find-first-heading-line (list)
13200 "Remove all lines from LIST which are before the first headline."
13201 (let ((orig-list list)
13202 (re (concat "^" outline-regexp)))
13203 (while (and list
13204 (not (string-match re (car list))))
13205 (pop list))
13206 (or list orig-list)))
13208 (defun org-skip-comments (lines)
13209 "Skip lines starting with \"#\" and subtrees starting with COMMENT."
13210 (let ((re1 (concat "^\\(\\*+\\)[ \t]+" org-comment-string))
13211 (re2 "^\\(\\*+\\)[ \t\n\r]")
13212 rtn line level)
13213 (while (setq line (pop lines))
13214 (cond
13215 ((and (string-match re1 line)
13216 (setq level (- (match-end 1) (match-beginning 1))))
13217 ;; Beginning of a COMMENT subtree. Skip it.
13218 (while (and (setq line (pop lines))
13219 (or (not (string-match re2 line))
13220 (> (- (match-end 1) (match-beginning 1)) level))))
13221 (setq lines (cons line lines)))
13222 ((string-match "^#" line)
13223 ;; an ordinary comment line
13225 ((and org-export-table-remove-special-lines
13226 (string-match "^[ \t]*|" line)
13227 (or (string-match "^[ \t]*| *[!_^] *|" line)
13228 (and (string-match "| *<[0-9]+> *|" line)
13229 (not (string-match "| *[^ <|]" line)))))
13230 ;; a special table line that should be removed
13232 (t (setq rtn (cons line rtn)))))
13233 (nreverse rtn)))
13235 (defun org-export (&optional arg)
13236 (interactive)
13237 (let ((help "[t] insert the export option template
13238 \[v] limit export to visible part of outline tree
13240 \[a] export as ASCII
13241 \[h] export as HTML
13242 \[b] export as HTML and browse immediately
13243 \[x] export as XOXO
13245 \[i] export current file as iCalendar file
13246 \[I] export all agenda files as iCalendar files
13247 \[c] export agenda files into combined iCalendar file
13249 \[F] publish current file
13250 \[P] publish current project
13251 \[X] publish... (project will be prompted for)
13252 \[A] publish all projects")
13253 (cmds
13254 '((?t . org-insert-export-options-template)
13255 (?v . org-export-visible)
13256 (?a . org-export-as-ascii)
13257 (?h . org-export-as-html)
13258 (?b . org-export-as-html-and-open)
13259 (?x . org-export-as-xoxo)
13260 (?i . org-export-icalendar-this-file)
13261 (?I . org-export-icalendar-all-agenda-files)
13262 (?c . org-export-icalendar-combine-agenda-files)
13263 (?F . org-publish-current-file)
13264 (?P . org-publish-current-project)
13265 (?X . org-publish)
13266 (?A . org-publish-all)))
13267 r1 r2 ass)
13268 (save-window-excursion
13269 (delete-other-windows)
13270 (with-output-to-temp-buffer "*Org Export/Publishing Help*"
13271 (princ help))
13272 (message "Select command: ")
13273 (setq r1 (read-char-exclusive)))
13274 (setq r2 (if (< r1 27) (+ r1 96) r1))
13275 (if (setq ass (assq r2 cmds))
13276 (call-interactively (cdr ass))
13277 (error "No command associated with key %c" r1))))
13279 ;; ASCII
13281 (defconst org-html-entities
13282 '(("nbsp")
13283 ("iexcl")
13284 ("cent")
13285 ("pound")
13286 ("curren")
13287 ("yen")
13288 ("brvbar")
13289 ("sect")
13290 ("uml")
13291 ("copy")
13292 ("ordf")
13293 ("laquo")
13294 ("not")
13295 ("shy")
13296 ("reg")
13297 ("macr")
13298 ("deg")
13299 ("plusmn")
13300 ("sup2")
13301 ("sup3")
13302 ("acute")
13303 ("micro")
13304 ("para")
13305 ("middot")
13306 ("odot"."o")
13307 ("star"."*")
13308 ("cedil")
13309 ("sup1")
13310 ("ordm")
13311 ("raquo")
13312 ("frac14")
13313 ("frac12")
13314 ("frac34")
13315 ("iquest")
13316 ("Agrave")
13317 ("Aacute")
13318 ("Acirc")
13319 ("Atilde")
13320 ("Auml")
13321 ("Aring") ("AA"."&Aring;")
13322 ("AElig")
13323 ("Ccedil")
13324 ("Egrave")
13325 ("Eacute")
13326 ("Ecirc")
13327 ("Euml")
13328 ("Igrave")
13329 ("Iacute")
13330 ("Icirc")
13331 ("Iuml")
13332 ("ETH")
13333 ("Ntilde")
13334 ("Ograve")
13335 ("Oacute")
13336 ("Ocirc")
13337 ("Otilde")
13338 ("Ouml")
13339 ("times")
13340 ("Oslash")
13341 ("Ugrave")
13342 ("Uacute")
13343 ("Ucirc")
13344 ("Uuml")
13345 ("Yacute")
13346 ("THORN")
13347 ("szlig")
13348 ("agrave")
13349 ("aacute")
13350 ("acirc")
13351 ("atilde")
13352 ("auml")
13353 ("aring")
13354 ("aelig")
13355 ("ccedil")
13356 ("egrave")
13357 ("eacute")
13358 ("ecirc")
13359 ("euml")
13360 ("igrave")
13361 ("iacute")
13362 ("icirc")
13363 ("iuml")
13364 ("eth")
13365 ("ntilde")
13366 ("ograve")
13367 ("oacute")
13368 ("ocirc")
13369 ("otilde")
13370 ("ouml")
13371 ("divide")
13372 ("oslash")
13373 ("ugrave")
13374 ("uacute")
13375 ("ucirc")
13376 ("uuml")
13377 ("yacute")
13378 ("thorn")
13379 ("yuml")
13380 ("fnof")
13381 ("Alpha")
13382 ("Beta")
13383 ("Gamma")
13384 ("Delta")
13385 ("Epsilon")
13386 ("Zeta")
13387 ("Eta")
13388 ("Theta")
13389 ("Iota")
13390 ("Kappa")
13391 ("Lambda")
13392 ("Mu")
13393 ("Nu")
13394 ("Xi")
13395 ("Omicron")
13396 ("Pi")
13397 ("Rho")
13398 ("Sigma")
13399 ("Tau")
13400 ("Upsilon")
13401 ("Phi")
13402 ("Chi")
13403 ("Psi")
13404 ("Omega")
13405 ("alpha")
13406 ("beta")
13407 ("gamma")
13408 ("delta")
13409 ("epsilon")
13410 ("varepsilon"."&epsilon;")
13411 ("zeta")
13412 ("eta")
13413 ("theta")
13414 ("iota")
13415 ("kappa")
13416 ("lambda")
13417 ("mu")
13418 ("nu")
13419 ("xi")
13420 ("omicron")
13421 ("pi")
13422 ("rho")
13423 ("sigmaf") ("varsigma"."&sigmaf;")
13424 ("sigma")
13425 ("tau")
13426 ("upsilon")
13427 ("phi")
13428 ("chi")
13429 ("psi")
13430 ("omega")
13431 ("thetasym") ("vartheta"."&thetasym;")
13432 ("upsih")
13433 ("piv")
13434 ("bull") ("bullet"."&bull;")
13435 ("hellip") ("dots"."&hellip;")
13436 ("prime")
13437 ("Prime")
13438 ("oline")
13439 ("frasl")
13440 ("weierp")
13441 ("image")
13442 ("real")
13443 ("trade")
13444 ("alefsym")
13445 ("larr") ("leftarrow"."&larr;") ("gets"."&larr;")
13446 ("uarr") ("uparrow"."&uarr;")
13447 ("rarr") ("to"."&rarr;") ("rightarrow"."&rarr;")
13448 ("darr")("downarrow"."&darr;")
13449 ("harr") ("leftrightarrow"."&harr;")
13450 ("crarr") ("hookleftarrow"."&crarr;") ; has round hook, not quite CR
13451 ("lArr") ("Leftarrow"."&lArr;")
13452 ("uArr") ("Uparrow"."&uArr;")
13453 ("rArr") ("Rightarrow"."&rArr;")
13454 ("dArr") ("Downarrow"."&dArr;")
13455 ("hArr") ("Leftrightarrow"."&hArr;")
13456 ("forall")
13457 ("part") ("partial"."&part;")
13458 ("exist") ("exists"."&exist;")
13459 ("empty") ("emptyset"."&empty;")
13460 ("nabla")
13461 ("isin") ("in"."&isin;")
13462 ("notin")
13463 ("ni")
13464 ("prod")
13465 ("sum")
13466 ("minus")
13467 ("lowast") ("ast"."&lowast;")
13468 ("radic")
13469 ("prop") ("proptp"."&prop;")
13470 ("infin") ("infty"."&infin;")
13471 ("ang") ("angle"."&ang;")
13472 ("and") ("vee"."&and;")
13473 ("or") ("wedge"."&or;")
13474 ("cap")
13475 ("cup")
13476 ("int")
13477 ("there4")
13478 ("sim")
13479 ("cong") ("simeq"."&cong;")
13480 ("asymp")("approx"."&asymp;")
13481 ("ne") ("neq"."&ne;")
13482 ("equiv")
13483 ("le")
13484 ("ge")
13485 ("sub") ("subset"."&sub;")
13486 ("sup") ("supset"."&sup;")
13487 ("nsub")
13488 ("sube")
13489 ("supe")
13490 ("oplus")
13491 ("otimes")
13492 ("perp")
13493 ("sdot") ("cdot"."&sdot;")
13494 ("lceil")
13495 ("rceil")
13496 ("lfloor")
13497 ("rfloor")
13498 ("lang")
13499 ("rang")
13500 ("loz") ("Diamond"."&loz;")
13501 ("spades") ("spadesuit"."&spades;")
13502 ("clubs") ("clubsuit"."&clubs;")
13503 ("hearts") ("diamondsuit"."&hearts;")
13504 ("diams") ("diamondsuit"."&diams;")
13505 ("quot")
13506 ("amp")
13507 ("lt")
13508 ("gt")
13509 ("OElig")
13510 ("oelig")
13511 ("Scaron")
13512 ("scaron")
13513 ("Yuml")
13514 ("circ")
13515 ("tilde")
13516 ("ensp")
13517 ("emsp")
13518 ("thinsp")
13519 ("zwnj")
13520 ("zwj")
13521 ("lrm")
13522 ("rlm")
13523 ("ndash")
13524 ("mdash")
13525 ("lsquo")
13526 ("rsquo")
13527 ("sbquo")
13528 ("ldquo")
13529 ("rdquo")
13530 ("bdquo")
13531 ("dagger")
13532 ("Dagger")
13533 ("permil")
13534 ("lsaquo")
13535 ("rsaquo")
13536 ("euro")
13538 ("arccos"."arccos")
13539 ("arcsin"."arcsin")
13540 ("arctan"."arctan")
13541 ("arg"."arg")
13542 ("cos"."cos")
13543 ("cosh"."cosh")
13544 ("cot"."cot")
13545 ("coth"."coth")
13546 ("csc"."csc")
13547 ("deg"."deg")
13548 ("det"."det")
13549 ("dim"."dim")
13550 ("exp"."exp")
13551 ("gcd"."gcd")
13552 ("hom"."hom")
13553 ("inf"."inf")
13554 ("ker"."ker")
13555 ("lg"."lg")
13556 ("lim"."lim")
13557 ("liminf"."liminf")
13558 ("limsup"."limsup")
13559 ("ln"."ln")
13560 ("log"."log")
13561 ("max"."max")
13562 ("min"."min")
13563 ("Pr"."Pr")
13564 ("sec"."sec")
13565 ("sin"."sin")
13566 ("sinh"."sinh")
13567 ("sup"."sup")
13568 ("tan"."tan")
13569 ("tanh"."tanh")
13571 "Entities for TeX->HTML translation.
13572 Entries can be like (\"ent\"), in which case \"\\ent\" will be translated to
13573 \"&ent;\". An entry can also be a dotted pair like (\"ent\".\"&other;\").
13574 In that case, \"\\ent\" will be translated to \"&other;\".
13575 The list contains HTML entities for Latin-1, Greek and other symbols.
13576 It is supplemented by a number of commonly used TeX macros with appropriate
13577 translations. There is currently no way for users to extend this.")
13579 (defun org-cleaned-string-for-export (string &rest parameters)
13580 "Cleanup a buffer substring so that links can be created safely."
13581 (interactive)
13582 (let* ((re-radio (and org-target-link-regexp
13583 (concat "\\([^<]\\)\\(" org-target-link-regexp "\\)")))
13584 (re-plain-link (concat "\\([^[<]\\)" org-plain-link-re))
13585 (re-angle-link (concat "\\([^[]\\)" org-angle-link-re))
13586 (re-archive (concat ":" org-archive-tag ":"))
13587 rtn)
13588 (save-excursion
13589 (set-buffer (get-buffer-create " org-mode-tmp"))
13590 (erase-buffer)
13591 (insert string)
13592 (let ((org-inhibit-startup t)) (org-mode))
13594 ;; Get rid of archived trees
13595 (when (not (eq org-export-with-archived-trees t))
13596 (goto-char (point-min))
13597 (while (re-search-forward re-archive nil t)
13598 (if (not (org-on-heading-p))
13599 (org-end-of-subtree t)
13600 (beginning-of-line 1)
13601 (delete-region
13602 (if org-export-with-archived-trees (1+ (point-at-eol)) (point))
13603 (org-end-of-subtree)))))
13605 ;; Find targets in comments and move them out of comments,
13606 ;; but mark them as targets that should be invisible
13607 (goto-char (point-min))
13608 (while (re-search-forward "^#.*?\\(<<<?[^>\r\n]+>>>?\\).*" nil t)
13609 (replace-match "\\1(INVISIBLE)"))
13611 ;; Find matches for radio targets and turn them into internal links
13612 (goto-char (point-min))
13613 (when re-radio
13614 (while (re-search-forward re-radio nil t)
13615 (replace-match "\\1[[\\2]]")))
13617 ;; Find all links that contain a newline and put them into a single line
13618 (goto-char (point-min))
13619 (while (re-search-forward "\\(\\(\\[\\|\\]\\)\\[[^]]*?\\)[ \t]*\n[ \t]*\\([^]]*\\]\\(\\[\\|\\]\\)\\)" nil t)
13620 (replace-match "\\1 \\3")
13621 (goto-char (match-beginning 0)))
13623 ;; Convert LaTeX fragments to images
13624 (when (memq :LaTeX-fragments parameters)
13625 (org-format-latex
13626 (concat "ltxpng/" (file-name-sans-extension
13627 (file-name-nondirectory
13628 org-current-export-file)))
13629 org-current-export-dir nil "Creating LaTeX image %s"))
13630 (message "Exporting...")
13632 ;; Normalize links: Convert angle and plain links into bracket links
13633 (goto-char (point-min))
13634 (while (re-search-forward re-plain-link nil t)
13635 (replace-match
13636 (concat
13637 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13638 t t))
13639 (goto-char (point-min))
13640 (while (re-search-forward re-angle-link nil t)
13641 (replace-match
13642 (concat
13643 (match-string 1) "[[" (match-string 2) ":" (match-string 3) "]]")
13644 t t))
13646 ;; Find multiline emphasis and put them into single line
13647 (when (memq :emph-multiline parameters)
13648 (goto-char (point-min))
13649 (while (re-search-forward org-emph-re nil t)
13650 (subst-char-in-region (match-beginning 0) (match-end 0) ?\n ?\ t)
13651 (goto-char (1- (match-end 0)))))
13653 ;; Remove comments
13654 (goto-char (point-min))
13655 (while (re-search-forward "^#.*\n?" nil t)
13656 (replace-match ""))
13657 (setq rtn (buffer-string)))
13658 (kill-buffer " org-mode-tmp")
13659 rtn))
13661 (defun org-solidify-link-text (s &optional alist)
13662 "Take link text and make a safe target out of it."
13663 (save-match-data
13664 (let* ((rtn
13665 (mapconcat
13666 'identity
13667 (org-split-string s "[ \t\r\n]+") "--"))
13668 (a (assoc rtn alist)))
13669 (or (cdr a) rtn))))
13671 (defun org-convert-to-odd-levels ()
13672 "Convert an org-mode file with all levels allowed to one with odd levels.
13673 This will leave level 1 alone, convert level 2 to level 3, level 3 to
13674 level 5 etc."
13675 (interactive)
13676 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
13677 (let ((org-odd-levels-only nil) n)
13678 (save-excursion
13679 (goto-char (point-min))
13680 (while (re-search-forward "^\\*\\*+" nil t)
13681 (setq n (1- (length (match-string 0))))
13682 (while (>= (setq n (1- n)) 0)
13683 (org-demote))
13684 (end-of-line 1))))))
13687 (defun org-convert-to-oddeven-levels ()
13688 "Convert an org-mode file with only odd levels to one with odd and even levels.
13689 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
13690 section with an even level, conversion would destroy the structure of the file. An error
13691 is signaled in this case."
13692 (interactive)
13693 (goto-char (point-min))
13694 ;; First check if there are no even levels
13695 (when (re-search-forward "^\\(\\*\\*\\)+[^*]" nil t)
13696 (org-show-hierarchy-above)
13697 (error "Not all levels are odd in this file. Conversion not possible."))
13698 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
13699 (let ((org-odd-levels-only nil) n)
13700 (save-excursion
13701 (goto-char (point-min))
13702 (while (re-search-forward "^\\*\\*+" nil t)
13703 (setq n (/ (length (match-string 0)) 2))
13704 (while (>= (setq n (1- n)) 0)
13705 (org-promote))
13706 (end-of-line 1))))))
13708 (defun org-tr-level (n)
13709 "Make N odd if required."
13710 (if org-odd-levels-only (1+ (/ n 2)) n))
13712 (defvar org-last-level nil) ; dynamically scoped variable
13713 (defvar org-ascii-current-indentation nil) ; For communication
13715 (defun org-export-as-ascii (arg)
13716 "Export the outline as a pretty ASCII file.
13717 If there is an active region, export only the region.
13718 The prefix ARG specifies how many levels of the outline should become
13719 underlined headlines. The default is 3."
13720 (interactive "P")
13721 (setq-default org-todo-line-regexp org-todo-line-regexp)
13722 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
13723 (org-infile-export-plist)))
13724 (region
13725 (buffer-substring
13726 (if (org-region-active-p) (region-beginning) (point-min))
13727 (if (org-region-active-p) (region-end) (point-max))))
13728 (lines (org-export-find-first-heading-line
13729 (org-skip-comments
13730 (org-split-string
13731 (org-cleaned-string-for-export region)
13732 "[\r\n]"))))
13733 (org-ascii-current-indentation '(0 . 0))
13734 (org-startup-with-deadline-check nil)
13735 (level 0) line txt
13736 (umax nil)
13737 (case-fold-search nil)
13738 (filename (concat (file-name-as-directory
13739 (org-export-directory :ascii opt-plist))
13740 (file-name-sans-extension
13741 (file-name-nondirectory buffer-file-name))
13742 ".txt"))
13743 (buffer (find-file-noselect filename))
13744 (levels-open (make-vector org-level-max nil))
13745 (odd org-odd-levels-only)
13746 (date (format-time-string "%Y/%m/%d" (current-time)))
13747 (time (format-time-string "%X" (org-current-time)))
13748 (author (plist-get opt-plist :author))
13749 (title (or (plist-get opt-plist :title)
13750 (file-name-sans-extension
13751 (file-name-nondirectory buffer-file-name))))
13752 (email (plist-get opt-plist :email))
13753 (language (plist-get opt-plist :language))
13754 (text nil)
13755 (todo nil)
13756 (lang-words nil))
13758 (setq org-last-level 1)
13759 (org-init-section-numbers)
13761 (find-file-noselect filename)
13763 (setq lang-words (or (assoc language org-export-language-setup)
13764 (assoc "en" org-export-language-setup)))
13765 (if org-export-ascii-show-new-buffer
13766 (switch-to-buffer-other-window buffer)
13767 (set-buffer buffer))
13768 (erase-buffer)
13769 (fundamental-mode)
13770 ;; create local variables for all options, to make sure all called
13771 ;; functions get the correct information
13772 (mapcar (lambda (x)
13773 (set (make-local-variable (cdr x))
13774 (plist-get opt-plist (car x))))
13775 org-export-plist-vars)
13776 (org-set-local 'org-odd-levels-only odd)
13777 (setq umax (if arg (prefix-numeric-value arg)
13778 org-export-headline-levels))
13780 ;; File header
13781 (if title (org-insert-centered title ?=))
13782 (insert "\n")
13783 (if (or author email)
13784 (insert (concat (nth 1 lang-words) ": " (or author "")
13785 (if email (concat " <" email ">") "")
13786 "\n")))
13787 (if (and date time)
13788 (insert (concat (nth 2 lang-words) ": " date " " time "\n")))
13789 (if text (insert (concat (org-html-expand-for-ascii text) "\n\n")))
13791 (insert "\n\n")
13793 (if org-export-with-toc
13794 (progn
13795 (insert (nth 3 lang-words) "\n"
13796 (make-string (length (nth 3 lang-words)) ?=) "\n")
13797 (mapcar '(lambda (line)
13798 (if (string-match org-todo-line-regexp
13799 line)
13800 ;; This is a headline
13801 (progn
13802 (setq level (- (match-end 1) (match-beginning 1))
13803 level (org-tr-level level)
13804 txt (match-string 3 line)
13805 todo
13806 (or (and org-export-mark-todo-in-toc
13807 (match-beginning 2)
13808 (not (equal (match-string 2 line)
13809 org-done-string)))
13810 ; TODO, not DONE
13811 (and org-export-mark-todo-in-toc
13812 (= level umax)
13813 (org-search-todo-below
13814 line lines level))))
13815 (setq txt (org-html-expand-for-ascii txt))
13817 (if org-export-with-section-numbers
13818 (setq txt (concat (org-section-number level)
13819 " " txt)))
13820 (if (<= level umax)
13821 (progn
13822 (insert
13823 (make-string (* (1- level) 4) ?\ )
13824 (format (if todo "%s (*)\n" "%s\n") txt))
13825 (setq org-last-level level))
13826 ))))
13827 lines)))
13829 (org-init-section-numbers)
13830 (while (setq line (pop lines))
13831 ;; Remove the quoted HTML tags.
13832 (setq line (org-html-expand-for-ascii line))
13833 ;; Remove targets
13834 (while (string-match "<<<?[^<>]*>>>?[ \t]*\n?" line)
13835 (setq line (replace-match "" t t line)))
13836 ;; Replace internal links
13837 (while (string-match org-bracket-link-regexp line)
13838 (setq line (replace-match
13839 (if (match-end 3) "[\\3]" "[\\1]")
13840 t nil line)))
13841 (cond
13842 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
13843 ;; a Headline
13844 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
13845 txt (match-string 2 line))
13846 (org-ascii-level-start level txt umax lines))
13848 (insert (org-fix-indentation line org-ascii-current-indentation) "\n"))))
13849 (normal-mode)
13850 (save-buffer)
13851 ;; remove display and invisible chars
13852 (let (beg end)
13853 (goto-char (point-min))
13854 (while (setq beg (next-single-property-change (point) 'display))
13855 (setq end (next-single-property-change beg 'display))
13856 (delete-region beg end)
13857 (goto-char beg)
13858 (insert "=>"))
13859 (goto-char (point-min))
13860 (while (setq beg (next-single-property-change (point) 'org-cwidth))
13861 (setq end (next-single-property-change beg 'org-cwidth))
13862 (delete-region beg end)
13863 (goto-char beg)))
13864 (goto-char (point-min))))
13866 (defun org-search-todo-below (line lines level)
13867 "Search the subtree below LINE for any TODO entries."
13868 (let ((rest (cdr (memq line lines)))
13869 (re org-todo-line-regexp)
13870 line lv todo)
13871 (catch 'exit
13872 (while (setq line (pop rest))
13873 (if (string-match re line)
13874 (progn
13875 (setq lv (- (match-end 1) (match-beginning 1))
13876 todo (and (match-beginning 2)
13877 (not (equal (match-string 2 line)
13878 org-done-string))))
13879 ; TODO, not DONE
13880 (if (<= lv level) (throw 'exit nil))
13881 (if todo (throw 'exit t))))))))
13883 (defun org-html-expand-for-ascii (line)
13884 "Handle quoted HTML for ASCII export."
13885 (if org-export-html-expand
13886 (while (string-match "@<[^<>\n]*>" line)
13887 ;; We just remove the tags for now.
13888 (setq line (replace-match "" nil nil line))))
13889 line)
13891 (defun org-insert-centered (s &optional underline)
13892 "Insert the string S centered and underline it with character UNDERLINE."
13893 (let ((ind (max (/ (- 80 (string-width s)) 2) 0)))
13894 (insert (make-string ind ?\ ) s "\n")
13895 (if underline
13896 (insert (make-string ind ?\ )
13897 (make-string (string-width s) underline)
13898 "\n"))))
13900 (defun org-ascii-level-start (level title umax &optional lines)
13901 "Insert a new level in ASCII export."
13902 (let (char (n (- level umax 1)) (ind 0))
13903 (if (> level umax)
13904 (progn
13905 (insert (make-string (* 2 n) ?\ )
13906 (char-to-string (nth (% n (length org-export-ascii-bullets))
13907 org-export-ascii-bullets))
13908 " " title "\n")
13909 ;; find the indentation of the next non-empty line
13910 (catch 'stop
13911 (while lines
13912 (if (string-match "^\\*" (car lines)) (throw 'stop nil))
13913 (if (string-match "^\\([ \t]*\\)\\S-" (car lines))
13914 (throw 'stop (setq ind (org-get-indentation (car lines)))))
13915 (pop lines)))
13916 (setq org-ascii-current-indentation (cons (* 2 (1+ n)) ind)))
13917 (if (or (not (equal (char-before) ?\n))
13918 (not (equal (char-before (1- (point))) ?\n)))
13919 (insert "\n"))
13920 (setq char (nth (- umax level) (reverse org-export-ascii-underline)))
13921 (if org-export-with-section-numbers
13922 (setq title (concat (org-section-number level) " " title)))
13923 (insert title "\n" (make-string (string-width title) char) "\n")
13924 (setq org-ascii-current-indentation '(0 . 0)))))
13926 (defun org-export-visible (type arg)
13927 "Create a copy of the visible part of the current buffer, and export it.
13928 The copy is created in a temporary buffer and removed after use.
13929 TYPE is the final key (as a string) that also select the export command in
13930 the `C-c C-e' export dispatcher.
13931 As a special case, if the you type SPC at the prompt, the temporary
13932 org-mode file will not be removed but presented to you so that you can
13933 continue to use it. The prefix arg ARG is passed through to the exporting
13934 command."
13935 (interactive
13936 (list (progn
13937 (message "Export visible: [a]SCII [h]tml [b]rowse HTML [x]OXO [ ]keep buffer")
13938 (read-char-exclusive))
13939 current-prefix-arg))
13940 (if (not (member type '(?a ?\C-a ?b ?\C-b ?h ?x ?\ )))
13941 (error "Invalid export key"))
13942 (let* ((binding (cdr (assoc type
13943 '((?a . org-export-as-ascii)
13944 (?\C-a . org-export-as-ascii)
13945 (?b . org-export-as-html-and-open)
13946 (?\C-b . org-export-as-html-and-open)
13947 (?h . org-export-as-html)
13948 (?x . org-export-as-xoxo)))))
13949 (keepp (equal type ?\ ))
13950 (file buffer-file-name)
13951 (buffer (get-buffer-create "*Org Export Visible*"))
13952 s e)
13953 (with-current-buffer buffer (erase-buffer))
13954 (save-excursion
13955 (setq s (goto-char (point-min)))
13956 (while (not (= (point) (point-max)))
13957 (goto-char (org-find-invisible))
13958 (append-to-buffer buffer s (point))
13959 (setq s (goto-char (org-find-visible))))
13960 (goto-char (point-min))
13961 (unless keepp
13962 ;; Copy all comment lines to the end, to make sure #+ settings are
13963 ;; still available for the second export step. Kind of a hack, but
13964 ;; does do the trick.
13965 (if (looking-at "#[^\r\n]*")
13966 (append-to-buffer buffer (match-beginning 0) (1+ (match-end 0))))
13967 (while (re-search-forward "[\n\r]#[^\n\r]*" nil t)
13968 (append-to-buffer buffer (1+ (match-beginning 0))
13969 (min (point-max) (1+ (match-end 0))))))
13970 (set-buffer buffer)
13971 (let ((buffer-file-name file)
13972 (org-inhibit-startup t))
13973 (org-mode)
13974 (show-all)
13975 (unless keepp (funcall binding arg))))
13976 (if (not keepp)
13977 (kill-buffer buffer)
13978 (switch-to-buffer-other-window buffer)
13979 (goto-char (point-min)))))
13981 (defun org-find-visible ()
13982 (let ((s (point)))
13983 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13984 (get-char-property s 'invisible)))
13986 (defun org-find-invisible ()
13987 (let ((s (point)))
13988 (while (and (not (= (point-max) (setq s (next-overlay-change s))))
13989 (not (get-char-property s 'invisible))))
13992 ;; HTML
13994 (defun org-get-current-options ()
13995 "Return a string with current options as keyword options.
13996 Does include HTML export options as well as TODO and CATEGORY stuff."
13997 (format
13998 "#+TITLE: %s
13999 #+AUTHOR: %s
14000 #+EMAIL: %s
14001 #+LANGUAGE: %s
14002 #+TEXT: Some descriptive text to be emitted. Several lines OK.
14003 #+OPTIONS: H:%d num:%s toc:%s \\n:%s @:%s ::%s |:%s ^:%s *:%s TeX:%s LaTeX:%s
14004 #+CATEGORY: %s
14005 #+SEQ_TODO: %s
14006 #+TYP_TODO: %s
14007 #+STARTUP: %s %s %s %s %s %s
14008 #+TAGS: %s
14009 #+ARCHIVE: %s
14011 (buffer-name) (user-full-name) user-mail-address org-export-default-language
14012 org-export-headline-levels
14013 org-export-with-section-numbers
14014 org-export-with-toc
14015 org-export-preserve-breaks
14016 org-export-html-expand
14017 org-export-with-fixed-width
14018 org-export-with-tables
14019 org-export-with-sub-superscripts
14020 org-export-with-emphasize
14021 org-export-with-TeX-macros
14022 org-export-with-LaTeX-fragments
14023 (file-name-nondirectory buffer-file-name)
14024 (if (equal org-todo-interpretation 'sequence)
14025 (mapconcat 'identity org-todo-keywords " ")
14026 "TODO FEEDBACK VERIFY DONE")
14027 (if (equal org-todo-interpretation 'type)
14028 (mapconcat 'identity org-todo-keywords " ")
14029 "Me Jason Marie DONE")
14030 (cdr (assoc org-startup-folded
14031 '((nil . "showall") (t . "overview") (content . "content"))))
14032 (if org-startup-with-deadline-check "dlcheck" "nodlcheck")
14033 (if org-odd-levels-only "odd" "oddeven")
14034 (if org-hide-leading-stars "hidestars" "showstars")
14035 (if org-startup-align-all-tables "align" "noalign")
14036 (if org-log-done "logging" "nologging")
14037 (or (mapconcat (lambda (x)
14038 (cond
14039 ((equal '(:startgroup) x) "{")
14040 ((equal '(:endgroup) x) "}")
14041 ((cdr x) (format "%s(%c)" (car x) (cdr x)))
14042 (t (car x))))
14043 (or org-tag-alist (org-get-buffer-tags)) " ") "")
14044 org-archive-location
14047 (defun org-insert-export-options-template ()
14048 "Insert into the buffer a template with information for exporting."
14049 (interactive)
14050 (if (not (bolp)) (newline))
14051 (let ((s (org-get-current-options)))
14052 (and (string-match "#\\+CATEGORY" s)
14053 (setq s (substring s 0 (match-beginning 0))))
14054 (insert s)))
14056 (defun org-toggle-fixed-width-section (arg)
14057 "Toggle the fixed-width export.
14058 If there is no active region, the QUOTE keyword at the current headline is
14059 inserted or removed. When present, it causes the text between this headline
14060 and the next to be exported as fixed-width text, and unmodified.
14061 If there is an active region, this command adds or removes a colon as the
14062 first character of this line. If the first character of a line is a colon,
14063 this line is also exported in fixed-width font."
14064 (interactive "P")
14065 (let* ((cc 0)
14066 (regionp (org-region-active-p))
14067 (beg (if regionp (region-beginning) (point)))
14068 (end (if regionp (region-end)))
14069 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14070 (re "[ \t]*\\(:\\)")
14071 off)
14072 (if regionp
14073 (save-excursion
14074 (goto-char beg)
14075 (setq cc (current-column))
14076 (beginning-of-line 1)
14077 (setq off (looking-at re))
14078 (while (> nlines 0)
14079 (setq nlines (1- nlines))
14080 (beginning-of-line 1)
14081 (cond
14082 (arg
14083 (move-to-column cc t)
14084 (insert ":\n")
14085 (forward-line -1))
14086 ((and off (looking-at re))
14087 (replace-match "" t t nil 1))
14088 ((not off) (move-to-column cc t) (insert ":")))
14089 (forward-line 1)))
14090 (save-excursion
14091 (org-back-to-heading)
14092 (if (looking-at (concat outline-regexp
14093 "\\( +\\<" org-quote-string "\\>\\)"))
14094 (replace-match "" t t nil 1)
14095 (if (looking-at outline-regexp)
14096 (progn
14097 (goto-char (match-end 0))
14098 (insert " " org-quote-string))))))))
14100 (defun org-export-as-html-and-open (arg)
14101 "Export the outline as HTML and immediately open it with a browser.
14102 If there is an active region, export only the region.
14103 The prefix ARG specifies how many levels of the outline should become
14104 headlines. The default is 3. Lower levels will become bulleted lists."
14105 (interactive "P")
14106 (org-export-as-html arg 'hidden)
14107 (org-open-file buffer-file-name))
14109 (defun org-export-as-html-batch ()
14110 "Call `org-export-as-html', may be used in batch processing as
14111 emacs --batch
14112 --load=$HOME/lib/emacs/org.el
14113 --eval \"(setq org-export-headline-levels 2)\"
14114 --visit=MyFile --funcall org-export-as-html-batch"
14115 (org-export-as-html org-export-headline-levels 'hidden))
14117 (defun org-export-as-html (arg &optional hidden ext-plist)
14118 "Export the outline as a pretty HTML file.
14119 If there is an active region, export only the region.
14120 The prefix ARG specifies how many levels of the outline should become
14121 headlines. The default is 3. Lower levels will become bulleted lists.
14122 When HIDDEN is non-nil, don't display the HTML buffer.
14123 EXT-PLIST is a property list with external parameters overriding
14124 org-mode's default settings, but still inferior to file-local settings."
14125 (interactive "P")
14126 (message "Exporting...")
14127 (setq-default org-todo-line-regexp org-todo-line-regexp)
14128 (setq-default org-deadline-line-regexp org-deadline-line-regexp)
14129 (setq-default org-done-string org-done-string)
14130 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
14131 ext-plist
14132 (org-infile-export-plist)))
14134 (style (plist-get opt-plist :style))
14135 (link-validate (plist-get opt-plist :link-validation-function))
14136 valid
14137 (odd org-odd-levels-only)
14138 (region-p (org-region-active-p))
14139 (region
14140 (buffer-substring
14141 (if region-p (region-beginning) (point-min))
14142 (if region-p (region-end) (point-max))))
14143 ;; The following two are dynamically scoped into other
14144 ;; routines below.
14145 (org-current-export-dir (org-export-directory :html opt-plist))
14146 (org-current-export-file buffer-file-name)
14147 (all_lines
14148 (org-skip-comments (org-split-string
14149 (org-cleaned-string-for-export
14150 region :emph-multiline
14151 (if (plist-get opt-plist :LaTeX-fragments)
14152 :LaTeX-fragments))
14153 "[\r\n]")))
14154 (lines (org-export-find-first-heading-line all_lines))
14155 (level 0) (line "") (origline "") txt todo
14156 (umax nil)
14157 (filename (concat (file-name-as-directory
14158 (org-export-directory :html opt-plist))
14159 (file-name-sans-extension
14160 (file-name-nondirectory buffer-file-name))
14161 ".html"))
14162 (current-dir (file-name-directory buffer-file-name))
14163 (buffer (find-file-noselect filename))
14164 (levels-open (make-vector org-level-max nil))
14165 (date (format-time-string "%Y/%m/%d" (current-time)))
14166 (time (format-time-string "%X" (org-current-time)))
14167 (author (plist-get opt-plist :author))
14168 (title (or (plist-get opt-plist :title)
14169 (file-name-sans-extension
14170 (file-name-nondirectory buffer-file-name))))
14171 (quote-re0 (concat "^[ \t]*" org-quote-string "\\>"))
14172 (quote-re (concat "^\\(\\*+\\)\\([ \t]*" org-quote-string "\\>\\)"))
14173 (inquote nil)
14174 (infixed nil)
14175 (in-local-list nil)
14176 (local-list-num nil)
14177 (local-list-indent nil)
14178 (llt org-plain-list-ordered-item-terminator)
14179 (email (plist-get opt-plist :email))
14180 (language (plist-get opt-plist :language))
14181 (text (plist-get opt-plist :text))
14182 (lang-words nil)
14183 (target-alist nil) tg
14184 (head-count 0) cnt
14185 (start 0)
14186 (coding-system (and (boundp 'buffer-file-coding-system)
14187 buffer-file-coding-system))
14188 (coding-system-for-write coding-system)
14189 (save-buffer-coding-system coding-system)
14190 (charset (and coding-system
14191 (fboundp 'coding-system-get)
14192 (coding-system-get coding-system 'mime-charset)))
14193 table-open type
14194 table-buffer table-orig-buffer
14195 ind start-is-num starter
14196 rpl path desc descp desc1 desc2 link
14198 (message "Exporting...")
14200 (setq org-last-level 1)
14201 (org-init-section-numbers)
14203 ;; Get the language-dependent settings
14204 (setq lang-words (or (assoc language org-export-language-setup)
14205 (assoc "en" org-export-language-setup)))
14207 ;; Switch to the output buffer
14208 (if (or hidden (not org-export-html-show-new-buffer))
14209 (set-buffer buffer)
14210 (switch-to-buffer-other-window buffer))
14211 (erase-buffer)
14212 (fundamental-mode)
14213 (let ((case-fold-search nil)
14214 (org-odd-levels-only odd))
14215 ;; create local variables for all options, to make sure all called
14216 ;; functions get the correct information
14217 (mapcar (lambda (x)
14218 (set (make-local-variable (cdr x))
14219 (plist-get opt-plist (car x))))
14220 org-export-plist-vars)
14221 (setq umax (if arg (prefix-numeric-value arg)
14222 org-export-headline-levels))
14224 ;; File header
14225 (insert (format
14226 "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"
14227 \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">
14228 <html xmlns=\"http://www.w3.org/1999/xhtml\"
14229 lang=\"%s\" xml:lang=\"%s\">
14230 <head>
14231 <title>%s</title>
14232 <meta http-equiv=\"Content-Type\" content=\"text/html;charset=%s\"/>
14233 <meta name=\"generator\" content=\"Org-mode\"/>
14234 <meta name=\"generated\" content=\"%s %s\"/>
14235 <meta name=\"author\" content=\"%s\"/>
14237 </head><body>
14239 language language (org-html-expand title) (or charset "iso-8859-1")
14240 date time author style))
14243 (insert (or (plist-get opt-plist :preamble) ""))
14245 (when (plist-get opt-plist :auto-preamble)
14246 (if title (insert (format org-export-html-title-format
14247 (org-html-expand title))))
14248 (if text (insert "<p>\n" (org-html-expand text) "</p>")))
14250 (if org-export-with-toc
14251 (progn
14252 (insert (format "<h%d>%s</h%d>\n"
14253 org-export-html-toplevel-hlevel
14254 (nth 3 lang-words)
14255 org-export-html-toplevel-hlevel))
14256 (insert "<ul>\n<li>")
14257 (setq lines
14258 (mapcar '(lambda (line)
14259 (if (string-match org-todo-line-regexp line)
14260 ;; This is a headline
14261 (progn
14262 (setq level (- (match-end 1) (match-beginning 1))
14263 level (org-tr-level level)
14264 txt (save-match-data
14265 (org-html-expand
14266 (org-export-cleanup-toc-line
14267 (match-string 3 line))))
14268 todo
14269 (or (and org-export-mark-todo-in-toc
14270 (match-beginning 2)
14271 (not (equal (match-string 2 line)
14272 org-done-string)))
14273 ; TODO, not DONE
14274 (and org-export-mark-todo-in-toc
14275 (= level umax)
14276 (org-search-todo-below
14277 line lines level))))
14278 (if org-export-with-section-numbers
14279 (setq txt (concat (org-section-number level)
14280 " " txt)))
14281 (if (<= level umax)
14282 (progn
14283 (setq head-count (+ head-count 1))
14284 (if (> level org-last-level)
14285 (progn
14286 (setq cnt (- level org-last-level))
14287 (while (>= (setq cnt (1- cnt)) 0)
14288 (insert "\n<ul>\n<li>"))
14289 (insert "\n")))
14290 (if (< level org-last-level)
14291 (progn
14292 (setq cnt (- org-last-level level))
14293 (while (>= (setq cnt (1- cnt)) 0)
14294 (insert "</li>\n</ul>"))
14295 (insert "\n")))
14296 ;; Check for targets
14297 (while (string-match org-target-regexp line)
14298 (setq tg (match-string 1 line)
14299 line (replace-match
14300 (concat "@<span class=\"target\">" tg "@</span> ")
14301 t t line))
14302 (push (cons (org-solidify-link-text tg)
14303 (format "sec-%d" head-count))
14304 target-alist))
14305 (while (string-match "&lt;\\(&lt;\\)+\\|&gt;\\(&gt;\\)+" txt)
14306 (setq txt (replace-match "" t t txt)))
14307 (insert
14308 (format
14309 (if todo
14310 "</li>\n<li><a href=\"#sec-%d\"><span class=\"todo\">%s</span></a>"
14311 "</li>\n<li><a href=\"#sec-%d\">%s</a>")
14312 head-count txt))
14314 (setq org-last-level level))
14316 line)
14317 lines))
14318 (while (> org-last-level 0)
14319 (setq org-last-level (1- org-last-level))
14320 (insert "</li>\n</ul>\n"))
14322 (setq head-count 0)
14323 (org-init-section-numbers)
14325 (while (setq line (pop lines) origline line)
14326 (catch 'nextline
14328 ;; end of quote section?
14329 (when (and inquote (string-match "^\\*+" line))
14330 (insert "</pre>\n")
14331 (setq inquote nil))
14332 ;; inside a quote section?
14333 (when inquote
14334 (insert (org-html-protect line) "\n")
14335 (throw 'nextline nil))
14337 ;; verbatim lines
14338 (when (and org-export-with-fixed-width
14339 (string-match "^[ \t]*:\\(.*\\)" line))
14340 (when (not infixed)
14341 (setq infixed t)
14342 (insert "<pre>\n"))
14343 (insert (org-html-protect (match-string 1 line)) "\n")
14344 (when (and lines
14345 (not (string-match "^[ \t]*\\(:.*\\)"
14346 (car lines))))
14347 (setq infixed nil)
14348 (insert "</pre>\n"))
14349 (throw 'nextline nil))
14352 ;; make targets to anchors
14353 (while (string-match "<<<?\\([^<>]*\\)>>>?\\((INVISIBLE)\\)?[ \t]*\n?" line)
14354 (cond
14355 ((match-end 2)
14356 (setq line (replace-match
14357 (concat "@<a name=\""
14358 (org-solidify-link-text (match-string 1 line))
14359 "\">\\nbsp@</a>")
14360 t t line)))
14361 ((and org-export-with-toc (equal (string-to-char line) ?*))
14362 (setq line (replace-match
14363 (concat "@<span class=\"target\">" (match-string 1 line) "@</span> ")
14364 ; (concat "@<i>" (match-string 1 line) "@</i> ")
14365 t t line)))
14367 (setq line (replace-match
14368 (concat "@<a name=\""
14369 (org-solidify-link-text (match-string 1 line))
14370 "\" class=\"target\">" (match-string 1 line) "@</a> ")
14371 t t line)))))
14373 (setq line (org-html-handle-time-stamps line))
14375 ;; replace "&" by "&amp;", "<" and ">" by "&lt;" and "&gt;"
14376 ;; handle @<..> HTML tags (replace "@&gt;..&lt;" by "<..>")
14377 ;; Also handle sub_superscripts and checkboxes
14378 (setq line (org-html-expand line))
14380 ;; Format the links
14381 (setq start 0)
14382 (while (string-match org-bracket-link-analytic-regexp line start)
14383 (setq start (match-beginning 0))
14384 (setq type (if (match-end 2) (match-string 2 line) "internal"))
14385 (setq path (match-string 3 line))
14386 (setq desc1 (if (match-end 5) (match-string 5 line))
14387 desc2 (if (match-end 2) (concat type ":" path) path)
14388 descp (and desc1 (not (equal desc1 desc2)))
14389 desc (or desc1 desc2))
14390 ;; FIXME: do we need to unescape here somewhere?
14391 (cond
14392 ((equal type "internal")
14393 (setq rpl
14394 (concat
14395 "<a href=\"#"
14396 (org-solidify-link-text path target-alist)
14397 "\">" desc "</a>")))
14398 ((member type '("http" "https" "ftp" "mailto" "news"))
14399 ;; standard URL
14400 (setq link (concat type ":" path))
14401 (setq rpl (concat "<a href=\"" link "\">" desc "</a>")))
14402 ((string= type "file")
14403 ;; FILE link
14404 (let* ((filename path)
14405 (abs-p (file-name-absolute-p filename))
14406 thefile file-is-image-p search)
14407 (save-match-data
14408 (if (string-match "::\\(.*\\)" filename)
14409 (setq search (match-string 1 filename)
14410 filename (replace-match "" t nil filename)))
14411 (setq valid
14412 (if (functionp link-validate)
14413 (funcall link-validate filename current-dir)
14414 t))
14415 (setq file-is-image-p
14416 (string-match (org-image-file-name-regexp) filename))
14417 (setq thefile (if abs-p (expand-file-name filename) filename))
14418 (when (and org-export-html-link-org-files-as-html
14419 (string-match "\\.org$" thefile))
14420 (setq thefile (concat (substring thefile 0
14421 (match-beginning 0))
14422 ".html"))
14423 (if (and search
14424 ;; make sure this is can be used as target search
14425 (not (string-match "^[0-9]*$" search))
14426 (not (string-match "^\\*" search))
14427 (not (string-match "^/.*/$" search)))
14428 (setq thefile (concat thefile "#"
14429 (org-solidify-link-text
14430 (org-link-unescape search)))))
14431 (when (string-match "^file:" desc)
14432 (setq desc (replace-match "" t t desc))
14433 (if (string-match "\\.org$" desc)
14434 (setq desc (replace-match "" t t desc))))))
14435 (setq rpl (if (and file-is-image-p
14436 (or (eq t org-export-html-inline-images)
14437 (and org-export-html-inline-images
14438 (not descp))))
14439 (concat "<img src=\"" thefile "\"/>")
14440 (concat "<a href=\"" thefile "\">" desc "</a>")))
14441 (if (not valid) (setq rpl desc))))
14442 ((member type '("bbdb" "vm" "wl" "mhe" "rmail" "gnus" "shell" "info" "elisp"))
14443 (setq rpl (concat "<i>&lt;" type ":"
14444 (save-match-data (org-link-unescape path))
14445 "&gt;</i>"))))
14446 (setq line (replace-match rpl t t line)
14447 start (+ start (length rpl))))
14448 ;; TODO items
14449 (if (and (string-match org-todo-line-regexp line)
14450 (match-beginning 2))
14451 (if (equal (match-string 2 line) org-done-string)
14452 (setq line (replace-match
14453 "<span class=\"done\">\\2</span>"
14454 t nil line 2))
14455 (setq line (replace-match "<span class=\"todo\">\\2</span>"
14456 t nil line 2))))
14458 (cond
14459 ((string-match "^\\(\\*+\\)[ \t]*\\(.*\\)" line)
14460 ;; This is a headline
14461 (setq level (org-tr-level (- (match-end 1) (match-beginning 1)))
14462 txt (match-string 2 line))
14463 (if (string-match quote-re0 txt)
14464 (setq txt (replace-match "" t t txt)))
14465 (if (<= level umax) (setq head-count (+ head-count 1)))
14466 (when in-local-list
14467 ;; Close any local lists before inserting a new header line
14468 (while local-list-num
14469 (org-close-li)
14470 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14471 (pop local-list-num))
14472 (setq local-list-indent nil
14473 in-local-list nil))
14474 (org-html-level-start level txt umax
14475 (and org-export-with-toc (<= level umax))
14476 head-count)
14477 ;; QUOTES
14478 (when (string-match quote-re line)
14479 (insert "<pre>")
14480 (setq inquote t)))
14482 ((and org-export-with-tables
14483 (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)" line))
14484 (if (not table-open)
14485 ;; New table starts
14486 (setq table-open t table-buffer nil table-orig-buffer nil))
14487 ;; Accumulate lines
14488 (setq table-buffer (cons line table-buffer)
14489 table-orig-buffer (cons origline table-orig-buffer))
14490 (when (or (not lines)
14491 (not (string-match "^\\([ \t]*\\)\\(|\\|\\+-+\\+\\)"
14492 (car lines))))
14493 (setq table-open nil
14494 table-buffer (nreverse table-buffer)
14495 table-orig-buffer (nreverse table-orig-buffer))
14496 (org-close-par-maybe)
14497 (insert (org-format-table-html table-buffer table-orig-buffer))))
14499 ;; Normal lines
14500 (when (string-match
14501 (cond
14502 ((eq llt t) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+[.)]\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14503 ((= llt ?.) "^\\([ \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+\\.\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14504 ((= llt ?\)) "^\\( \t]*\\)\\(\\([-+*] \\)\\|\\([0-9]+)\\) \\)?\\( *[^ \t\n\r]\\|[ \t]*$\\)")
14505 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))
14506 line)
14507 (setq ind (org-get-string-indentation line)
14508 start-is-num (match-beginning 4)
14509 starter (if (match-beginning 2)
14510 (substring (match-string 2 line) 0 -1))
14511 line (substring line (match-beginning 5)))
14512 (unless (string-match "[^ \t]" line)
14513 ;; empty line. Pretend indentation is large.
14514 (setq ind (1+ (or (car local-list-indent) 1))))
14515 (while (and in-local-list
14516 (or (and (= ind (car local-list-indent))
14517 (not starter))
14518 (< ind (car local-list-indent))))
14519 (org-close-li)
14520 (insert (if (car local-list-num) "</ol>\n" "</ul>"))
14521 (pop local-list-num) (pop local-list-indent)
14522 (setq in-local-list local-list-indent))
14523 (cond
14524 ((and starter
14525 (or (not in-local-list)
14526 (> ind (car local-list-indent))))
14527 ;; Start new (level of ) list
14528 (org-close-par-maybe)
14529 (insert (if start-is-num "<ol>\n<li>\n" "<ul>\n<li>\n"))
14530 (push start-is-num local-list-num)
14531 (push ind local-list-indent)
14532 (setq in-local-list t))
14533 (starter
14534 ;; continue current list
14535 (org-close-li)
14536 (insert "<li>\n")))
14537 (if (string-match "^[ \t]*\\[\\([X ]\\)\\]" line)
14538 (setq line
14539 (replace-match
14540 (if (equal (match-string 1 line) "X")
14541 "<b>[X]</b>"
14542 "<b>[<span style=\"visibility:hidden;\">X</span>]</b>")
14543 t t line))))
14545 ;; Empty lines start a new paragraph. If hand-formatted lists
14546 ;; are not fully interpreted, lines starting with "-", "+", "*"
14547 ;; also start a new paragraph.
14548 (if (string-match "^ [-+*]-\\|^[ \t]*$" line) (org-open-par))
14550 ;; Check if the line break needs to be conserved
14551 (cond
14552 ((string-match "\\\\\\\\[ \t]*$" line)
14553 (setq line (replace-match "<br/>" t t line)))
14554 (org-export-preserve-breaks
14555 (setq line (concat line "<br/>"))))
14557 (insert line "\n")))))
14559 ;; Properly close all local lists and other lists
14560 (when inquote (insert "</pre>\n"))
14561 (when in-local-list
14562 ;; Close any local lists before inserting a new header line
14563 (while local-list-num
14564 (org-close-li)
14565 (insert (if (car local-list-num) "</ol>\n" "</ul>\n"))
14566 (pop local-list-num))
14567 (setq local-list-indent nil
14568 in-local-list nil))
14569 (org-html-level-start 1 nil umax
14570 (and org-export-with-toc (<= level umax))
14571 head-count)
14573 (when (plist-get opt-plist :auto-postamble)
14574 (when author
14575 (insert "<p class=\"author\"> "
14576 (nth 1 lang-words) ": " author "\n")
14577 (when email
14578 (insert "<a href=\"mailto:" email "\">&lt;"
14579 email "&gt;</a>\n"))
14580 (insert "</p>\n"))
14581 (when (and date time)
14582 (insert "<p class=\"date\"> "
14583 (nth 2 lang-words) ": "
14584 date " " time "</p>\n")))
14586 (if org-export-html-with-timestamp
14587 (insert org-export-html-html-helper-timestamp))
14588 (insert (or (plist-get opt-plist :postamble) ""))
14589 (insert "</body>\n</html>\n")
14590 (normal-mode)
14591 ;; remove empty paragraphs and lists
14592 (goto-char (point-min))
14593 (while (re-search-forward "<p>[ \r\n\t]*</p>" nil t)
14594 (replace-match ""))
14595 (goto-char (point-min))
14596 (while (re-search-forward "<li>[ \r\n\t]*</li>\n?" nil t)
14597 (replace-match ""))
14598 (save-buffer)
14599 (goto-char (point-min))
14600 (message "Exporting... done"))))
14603 (defun org-format-table-html (lines olines)
14604 "Find out which HTML converter to use and return the HTML code."
14605 (if (string-match "^[ \t]*|" (car lines))
14606 ;; A normal org table
14607 (org-format-org-table-html lines)
14608 ;; Table made by table.el - test for spanning
14609 (let* ((hlines (delq nil (mapcar
14610 (lambda (x)
14611 (if (string-match "^[ \t]*\\+-" x) x
14612 nil))
14613 lines)))
14614 (first (car hlines))
14615 (ll (and (string-match "\\S-+" first)
14616 (match-string 0 first)))
14617 (re (concat "^[ \t]*" (regexp-quote ll)))
14618 (spanning (delq nil (mapcar (lambda (x) (not (string-match re x)))
14619 hlines))))
14620 (if (and (not spanning)
14621 (not org-export-prefer-native-exporter-for-tables))
14622 ;; We can use my own converter with HTML conversions
14623 (org-format-table-table-html lines)
14624 ;; Need to use the code generator in table.el, with the original text.
14625 (org-format-table-table-html-using-table-generate-source olines)))))
14627 (defun org-format-org-table-html (lines)
14628 "Format a table into HTML."
14629 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14630 (setq lines (nreverse lines))
14631 (if (string-match "^[ \t]*|-" (car lines)) (setq lines (cdr lines)))
14632 (setq lines (nreverse lines))
14633 (when org-export-table-remove-special-lines
14634 ;; Check if the table has a marking column. If yes remove the
14635 ;; column and the special lines
14636 (let* ((special
14637 (not
14638 (memq nil
14639 (mapcar
14640 (lambda (x)
14641 (or (string-match "^[ \t]*|-" x)
14642 (string-match "^[ \t]*| *\\([#!$*_^ ]\\) *|" x)))
14643 lines)))))
14644 (if special
14645 (setq lines
14646 (delq nil
14647 (mapcar
14648 (lambda (x)
14649 (if (string-match "^[ \t]*| *[!_^] *|" x)
14650 nil ; ignore this line
14651 (and (or (string-match "^[ \t]*|-+\\+" x)
14652 (string-match "^[ \t]*|[^|]*|" x))
14653 (replace-match "|" t t x))))
14654 lines))))))
14656 (let ((head (and org-export-highlight-first-table-line
14657 (delq nil (mapcar
14658 (lambda (x) (string-match "^[ \t]*|-" x))
14659 (cdr lines)))))
14660 line fields html)
14661 (setq html (concat org-export-html-table-tag "\n"))
14662 (while (setq line (pop lines))
14663 (catch 'next-line
14664 (if (string-match "^[ \t]*|-" line)
14665 (progn
14666 (setq head nil) ;; head ends here, first time around
14667 ;; ignore this line
14668 (throw 'next-line t)))
14669 ;; Break the line into fields
14670 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14671 (setq html (concat
14672 html
14673 "<tr>"
14674 (mapconcat (lambda (x)
14675 (if head
14676 (concat "<th>" x "</th>")
14677 (concat "<td>" x "</td>")))
14678 fields "")
14679 "</tr>\n"))))
14680 (setq html (concat html "</table>\n"))
14681 html))
14683 (defun org-fake-empty-table-line (line)
14684 "Replace everything except \"|\" with spaces."
14685 (let ((i (length line))
14686 (newstr (copy-sequence line)))
14687 (while (> i 0)
14688 (setq i (1- i))
14689 (if (not (eq (aref newstr i) ?|))
14690 (aset newstr i ?\ )))
14691 newstr))
14693 (defun org-format-table-table-html (lines)
14694 "Format a table generated by table.el into HTML.
14695 This conversion does *not* use `table-generate-source' from table.el.
14696 This has the advantage that Org-mode's HTML conversions can be used.
14697 But it has the disadvantage, that no cell- or row-spanning is allowed."
14698 (let (line field-buffer
14699 (head org-export-highlight-first-table-line)
14700 fields html empty)
14701 (setq html (concat org-export-html-table-tag "\n"))
14702 (while (setq line (pop lines))
14703 (setq empty "&nbsp;")
14704 (catch 'next-line
14705 (if (string-match "^[ \t]*\\+-" line)
14706 (progn
14707 (if field-buffer
14708 (progn
14709 (setq html (concat
14710 html
14711 "<tr>"
14712 (mapconcat
14713 (lambda (x)
14714 (if (equal x "") (setq x empty))
14715 (if head
14716 (concat "<th>" x "</th>\n")
14717 (concat "<td>" x "</td>\n")))
14718 field-buffer "\n")
14719 "</tr>\n"))
14720 (setq head nil)
14721 (setq field-buffer nil)))
14722 ;; Ignore this line
14723 (throw 'next-line t)))
14724 ;; Break the line into fields and store the fields
14725 (setq fields (org-split-string line "[ \t]*|[ \t]*"))
14726 (if field-buffer
14727 (setq field-buffer (mapcar
14728 (lambda (x)
14729 (concat x "<br/>" (pop fields)))
14730 field-buffer))
14731 (setq field-buffer fields))))
14732 (setq html (concat html "</table>\n"))
14733 html))
14735 (defun org-format-table-table-html-using-table-generate-source (lines)
14736 "Format a table into html, using `table-generate-source' from table.el.
14737 This has the advantage that cell- or row-spanning is allowed.
14738 But it has the disadvantage, that Org-mode's HTML conversions cannot be used."
14739 (require 'table)
14740 (with-current-buffer (get-buffer-create " org-tmp1 ")
14741 (erase-buffer)
14742 (insert (mapconcat 'identity lines "\n"))
14743 (goto-char (point-min))
14744 (if (not (re-search-forward "|[^+]" nil t))
14745 (error "Error processing table"))
14746 (table-recognize-table)
14747 (with-current-buffer (get-buffer-create " org-tmp2 ") (erase-buffer))
14748 (table-generate-source 'html " org-tmp2 ")
14749 (set-buffer " org-tmp2 ")
14750 (buffer-substring (point-min) (point-max))))
14752 (defun org-html-handle-time-stamps (s)
14753 "Format time stamps in string S, or remove them."
14754 (catch 'exit
14755 (let (r b)
14756 (while (string-match org-maybe-keyword-time-regexp s)
14757 ;; FIXME: is it good to never export CLOCK, or do we need control?
14758 (if (and (match-end 1) (equal (match-string 1 s) org-clock-string))
14759 (throw 'exit ""))
14760 (or b (setq b (substring s 0 (match-beginning 0))))
14761 (if (not org-export-with-timestamps)
14762 (setq r (concat r (substring s 0 (match-beginning 0)))
14763 s (substring s (match-end 0)))
14764 (setq r (concat
14765 r (substring s 0 (match-beginning 0))
14766 (if (match-end 1)
14767 (format "@<span class=\"timestamp-kwd\">%s @</span>"
14768 (match-string 1 s)))
14769 (format " @<span class=\"timestamp\">%s@</span>"
14770 (substring (match-string 3 s) 1 -1)))
14771 s (substring s (match-end 0)))))
14772 ;; Line break if line started and ended with time stamp stuff
14773 (if (not r)
14775 (setq r (concat r s))
14776 (unless (string-match "\\S-" (concat b s))
14777 (setq r (concat r "@<br/>")))
14778 r))))
14780 (defun org-html-protect (s)
14781 ;; convert & to &amp;, < to &lt; and > to &gt;
14782 (let ((start 0))
14783 (while (string-match "&" s start)
14784 (setq s (replace-match "&amp;" t t s)
14785 start (1+ (match-beginning 0))))
14786 (while (string-match "<" s)
14787 (setq s (replace-match "&lt;" t t s)))
14788 (while (string-match ">" s)
14789 (setq s (replace-match "&gt;" t t s))))
14792 (defun org-export-cleanup-toc-line (s)
14793 "Remove tags and time staps from lines going into the toc."
14794 (if (string-match " +:[a-zA-Z0-9_@:]+: *$" s)
14795 (setq s (replace-match "" t t s)))
14796 (when org-export-remove-timestamps-from-toc
14797 (while (string-match org-maybe-keyword-time-regexp s)
14798 (setq s (replace-match "" t t s))))
14801 (defun org-html-expand (string)
14802 "Prepare STRING for HTML export. Applies all active conversions.
14803 If there are links in the string, don't modify these."
14804 (let* (m s l res)
14805 (while (setq m (string-match org-bracket-link-regexp string))
14806 (setq s (substring string 0 m)
14807 l (match-string 0 string)
14808 string (substring string (match-end 0)))
14809 (push (org-html-do-expand s) res)
14810 (push l res))
14811 (push (org-html-do-expand string) res)
14812 (apply 'concat (nreverse res))))
14814 (defun org-html-do-expand (s)
14815 "Apply all active conversions to translate special ASCII to HTML."
14816 (setq s (org-html-protect s))
14817 (if org-export-html-expand
14818 (while (string-match "@&lt;\\([^&]*\\)&gt;" s)
14819 (setq s (replace-match "<\\1>" t nil s))))
14820 (if org-export-with-emphasize
14821 (setq s (org-export-html-convert-emphasize s)))
14822 (if org-export-with-sub-superscripts
14823 (setq s (org-export-html-convert-sub-super s)))
14824 (if org-export-with-TeX-macros
14825 (let ((start 0) wd ass)
14826 (while (setq start (string-match "\\\\\\([a-zA-Z]+\\)" s start))
14827 (setq wd (match-string 1 s))
14828 (if (setq ass (assoc wd org-html-entities))
14829 (setq s (replace-match (or (cdr ass)
14830 (concat "&" (car ass) ";"))
14831 t t s))
14832 (setq start (+ start (length wd)))))))
14835 (defun org-create-multibrace-regexp (left right n)
14836 "Create a regular expression which will match a balanced sexp.
14837 Opening delimiter is LEFT, and closing delimiter is RIGHT, both given
14838 as single character strings.
14839 The regexp returned will match the entire expression including the
14840 delimiters. It will also define a single group which contains the
14841 match except for the outermost delimiters. The maximum depth of
14842 stacked delimiters is N. Escaping delimiters is not possible."
14843 (let* ((nothing (concat "[^" "\\" left "\\" right "]*?"))
14844 (or "\\|")
14845 (re nothing)
14846 (next (concat "\\(?:" nothing left nothing right "\\)+" nothing)))
14847 (while (> n 1)
14848 (setq n (1- n)
14849 re (concat re or next)
14850 next (concat "\\(?:" nothing left next right "\\)+" nothing)))
14851 (concat left "\\(" re "\\)" right)))
14853 (defvar org-match-substring-regexp
14854 (concat
14855 "\\([^\\]\\)\\([_^]\\)\\("
14856 "\\(" (org-create-multibrace-regexp "{" "}" org-match-sexp-depth) "\\)"
14857 "\\|"
14858 "\\(" (org-create-multibrace-regexp "(" ")" org-match-sexp-depth) "\\)"
14859 "\\|"
14860 "\\(\\(?:\\*\\|[-+]?[^-+*!@#$%^_ \t\r\n,:\"?<>~;./{}=()]+\\)\\)\\)")
14861 "The regular expression matching a sub- or superscript.")
14863 (defun org-export-html-convert-sub-super (string)
14864 "Convert sub- and superscripts in STRING to HTML."
14865 (let (key c)
14866 (while (string-match org-match-substring-regexp string)
14867 (setq key (if (string= (match-string 2 string) "_") "sub" "sup"))
14868 (setq c (or (match-string 8 string)
14869 (match-string 6 string)
14870 (match-string 5 string)))
14871 (setq string (replace-match
14872 (concat (match-string 1 string)
14873 "<" key ">" c "</" key ">")
14874 t t string)))
14875 (while (string-match "\\\\\\([_^]\\)" string)
14876 (setq string (replace-match (match-string 1 string) t t string))))
14877 string)
14879 (defun org-export-html-convert-emphasize (string)
14880 "Apply emphasis."
14881 (while (string-match org-emph-re string)
14882 (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)))
14883 string)
14885 (defvar org-par-open nil)
14886 (defun org-open-par ()
14887 "Insert <p>, but first close previous paragraph if any."
14888 (org-close-par-maybe)
14889 (insert "\n<p>")
14890 (setq org-par-open t))
14891 (defun org-close-par-maybe ()
14892 "Close paragraph if there is one open."
14893 (when org-par-open
14894 (insert "</p>")
14895 (setq org-par-open nil)))
14896 (defun org-close-li ()
14897 "Close <li> if necessary."
14898 (org-close-par-maybe)
14899 (insert "</li>\n"))
14900 ; (when (save-excursion
14901 ; (re-search-backward "</?\\(ul\\|ol\\|li\\|[hH][0-9]\\)>" nil t))
14902 ; (if (member (match-string 0) '("</ul>" "</ol>" "<li>"))
14903 ; (insert "</li>"))))
14905 (defun org-html-level-start (level title umax with-toc head-count)
14906 "Insert a new level in HTML export.
14907 When TITLE is nil, just close all open levels."
14908 (org-close-par-maybe)
14909 (let ((l (1+ (max level umax))))
14910 (while (<= l org-level-max)
14911 (if (aref levels-open (1- l))
14912 (progn
14913 (org-html-level-close l)
14914 (aset levels-open (1- l) nil)))
14915 (setq l (1+ l)))
14916 (when title
14917 ;; If title is nil, this means this function is called to close
14918 ;; all levels, so the rest is done only if title is given
14919 (when (string-match "\\(:[a-zA-Z0-9_@:]+:\\)[ \t]*$" title)
14920 (setq title (replace-match
14921 (if org-export-with-tags
14922 (save-match-data
14923 (concat
14924 "&nbsp;&nbsp;&nbsp;<span class=\"tag\">"
14925 (mapconcat 'identity (org-split-string
14926 (match-string 1 title) ":")
14927 "&nbsp;")
14928 "</span>"))
14930 t t title)))
14931 (if (> level umax)
14932 (progn
14933 (if (aref levels-open (1- level))
14934 (progn
14935 (org-close-li)
14936 (insert "<li>" title "<br/>\n"))
14937 (aset levels-open (1- level) t)
14938 (org-close-par-maybe)
14939 (insert "<ul>\n<li>" title "<br/>\n")))
14940 (if org-export-with-section-numbers
14941 (setq title (concat (org-section-number level) " " title)))
14942 (setq level (+ level org-export-html-toplevel-hlevel -1))
14943 (if with-toc
14944 (insert (format "\n<h%d><a name=\"sec-%d\">%s</a></h%d>\n"
14945 level head-count title level))
14946 (insert (format "\n<h%d>%s</h%d>\n" level title level)))
14947 (org-open-par)))))
14949 (defun org-html-level-close (&rest args)
14950 "Terminate one level in HTML export."
14951 (org-close-li)
14952 (insert "</ul>"))
14954 ;; Variable holding the vector with section numbers
14955 (defvar org-section-numbers (make-vector org-level-max 0))
14957 (defun org-init-section-numbers ()
14958 "Initialize the vector for the section numbers."
14959 (let* ((level -1)
14960 (numbers (nreverse (org-split-string "" "\\.")))
14961 (depth (1- (length org-section-numbers)))
14962 (i depth) number-string)
14963 (while (>= i 0)
14964 (if (> i level)
14965 (aset org-section-numbers i 0)
14966 (setq number-string (or (car numbers) "0"))
14967 (if (string-match "\\`[A-Z]\\'" number-string)
14968 (aset org-section-numbers i
14969 (- (string-to-char number-string) ?A -1))
14970 (aset org-section-numbers i (string-to-number number-string)))
14971 (pop numbers))
14972 (setq i (1- i)))))
14974 (defun org-section-number (&optional level)
14975 "Return a string with the current section number.
14976 When LEVEL is non-nil, increase section numbers on that level."
14977 (let* ((depth (1- (length org-section-numbers))) idx n (string ""))
14978 (when level
14979 (when (> level -1)
14980 (aset org-section-numbers
14981 level (1+ (aref org-section-numbers level))))
14982 (setq idx (1+ level))
14983 (while (<= idx depth)
14984 (if (not (= idx 1))
14985 (aset org-section-numbers idx 0))
14986 (setq idx (1+ idx))))
14987 (setq idx 0)
14988 (while (<= idx depth)
14989 (setq n (aref org-section-numbers idx))
14990 (setq string (concat string (if (not (string= string "")) "." "")
14991 (int-to-string n)))
14992 (setq idx (1+ idx)))
14993 (save-match-data
14994 (if (string-match "\\`\\([@0]\\.\\)+" string)
14995 (setq string (replace-match "" t nil string)))
14996 (if (string-match "\\(\\.0\\)+\\'" string)
14997 (setq string (replace-match "" t nil string))))
14998 string))
15001 ;;;###autoload
15002 (defun org-export-icalendar-this-file ()
15003 "Export current file as an iCalendar file.
15004 The iCalendar file will be located in the same directory as the Org-mode
15005 file, but with extension `.ics'."
15006 (interactive)
15007 (org-export-icalendar nil buffer-file-name))
15009 (defun org-export-as-xoxo-insert-into (buffer &rest output)
15010 (with-current-buffer buffer
15011 (apply 'insert output)))
15012 (put 'org-export-as-xoxo-insert-into 'lisp-indent-function 1)
15014 (defun org-export-as-xoxo (&optional buffer)
15015 "Export the org buffer as XOXO.
15016 The XOXO buffer is named *xoxo-<source buffer name>*"
15017 (interactive (list (current-buffer)))
15018 ;; A quickie abstraction
15020 ;; Output everything as XOXO
15021 (with-current-buffer (get-buffer buffer)
15022 (goto-char (point-min)) ;; CD: beginning-of-buffer is not allowed.
15023 (let* ((opt-plist (org-combine-plists (org-default-export-plist)
15024 (org-infile-export-plist)))
15025 (filename (concat (file-name-as-directory
15026 (org-export-directory :xoxo opt-plist))
15027 (file-name-sans-extension
15028 (file-name-nondirectory buffer-file-name))
15029 ".html"))
15030 (out (find-file-noselect filename))
15031 (last-level 1)
15032 (hanging-li nil))
15033 ;; Check the output buffer is empty.
15034 (with-current-buffer out (erase-buffer))
15035 ;; Kick off the output
15036 (org-export-as-xoxo-insert-into out "<ol class='xoxo'>\n")
15037 (while (re-search-forward "^\\(\\*+\\) \\(.+\\)" (point-max) 't)
15038 (let* ((hd (match-string-no-properties 1))
15039 (level (length hd))
15040 (text (concat
15041 (match-string-no-properties 2)
15042 (save-excursion
15043 (goto-char (match-end 0))
15044 (let ((str ""))
15045 (catch 'loop
15046 (while 't
15047 (forward-line)
15048 (if (looking-at "^[ \t]\\(.*\\)")
15049 (setq str (concat str (match-string-no-properties 1)))
15050 (throw 'loop str)))))))))
15052 ;; Handle level rendering
15053 (cond
15054 ((> level last-level)
15055 (org-export-as-xoxo-insert-into out "\n<ol>\n"))
15057 ((< level last-level)
15058 (dotimes (- (- last-level level) 1)
15059 (if hanging-li
15060 (org-export-as-xoxo-insert-into out "</li>\n"))
15061 (org-export-as-xoxo-insert-into out "</ol>\n"))
15062 (when hanging-li
15063 (org-export-as-xoxo-insert-into out "</li>\n")
15064 (setq hanging-li nil)))
15066 ((equal level last-level)
15067 (if hanging-li
15068 (org-export-as-xoxo-insert-into out "</li>\n")))
15071 (setq last-level level)
15073 ;; And output the new li
15074 (setq hanging-li 't)
15075 (if (equal ?+ (elt text 0))
15076 (org-export-as-xoxo-insert-into out "<li class='" (substring text 1) "'>")
15077 (org-export-as-xoxo-insert-into out "<li>" text))))
15079 ;; Finally finish off the ol
15080 (dotimes (- last-level 1)
15081 (if hanging-li
15082 (org-export-as-xoxo-insert-into out "</li>\n"))
15083 (org-export-as-xoxo-insert-into out "</ol>\n"))
15085 ;; Finish the buffer off and clean it up.
15086 (switch-to-buffer-other-window out)
15087 (indent-region (point-min) (point-max) nil)
15088 (save-buffer)
15089 (goto-char (point-min))
15092 ;;;###autoload
15093 (defun org-export-icalendar-all-agenda-files ()
15094 "Export all files in `org-agenda-files' to iCalendar .ics files.
15095 Each iCalendar file will be located in the same directory as the Org-mode
15096 file, but with extension `.ics'."
15097 (interactive)
15098 (apply 'org-export-icalendar nil (org-agenda-files t)))
15100 ;;;###autoload
15101 (defun org-export-icalendar-combine-agenda-files ()
15102 "Export all files in `org-agenda-files' to a single combined iCalendar file.
15103 The file is stored under the name `org-combined-agenda-icalendar-file'."
15104 (interactive)
15105 (apply 'org-export-icalendar t (org-agenda-files t)))
15107 (defun org-export-icalendar (combine &rest files)
15108 "Create iCalendar files for all elements of FILES.
15109 If COMBINE is non-nil, combine all calendar entries into a single large
15110 file and store it under the name `org-combined-agenda-icalendar-file'."
15111 (save-excursion
15112 (let* ((dir (org-export-directory
15113 :ical (list :publishing-directory
15114 org-export-publishing-directory)))
15115 file ical-file ical-buffer category started org-agenda-new-buffers)
15117 (when combine
15118 (setq ical-file
15119 (if (file-name-absolute-p org-combined-agenda-icalendar-file)
15120 org-combined-agenda-icalendar-file
15121 (expand-file-name org-combined-agenda-icalendar-file dir))
15122 ical-buffer (org-get-agenda-file-buffer ical-file))
15123 (set-buffer ical-buffer) (erase-buffer))
15124 (while (setq file (pop files))
15125 (catch 'nextfile
15126 (org-check-agenda-file file)
15127 (set-buffer (org-get-agenda-file-buffer file))
15128 (unless combine
15129 (setq ical-file (concat (file-name-as-directory dir)
15130 (file-name-sans-extension
15131 (file-name-nondirectory buffer-file-name))
15132 ".ics"))
15133 (setq ical-buffer (org-get-agenda-file-buffer ical-file))
15134 (with-current-buffer ical-buffer (erase-buffer)))
15135 (setq category (or org-category
15136 (file-name-sans-extension
15137 (file-name-nondirectory buffer-file-name))))
15138 (if (symbolp category) (setq category (symbol-name category)))
15139 (let ((standard-output ical-buffer))
15140 (if combine
15141 (and (not started) (setq started t)
15142 (org-start-icalendar-file org-icalendar-combined-name))
15143 (org-start-icalendar-file category))
15144 (org-print-icalendar-entries combine category)
15145 (when (or (and combine (not files)) (not combine))
15146 (org-finish-icalendar-file)
15147 (set-buffer ical-buffer)
15148 (save-buffer)
15149 (run-hooks 'org-after-save-iCalendar-file-hook)))))
15150 (org-release-buffers org-agenda-new-buffers))))
15152 (defvar org-after-save-iCalendar-file-hook nil
15153 "Hook run after an iCalendar file has been saved.
15154 The iCalendar buffer is still current when this hook is run.
15155 A good way to use this is to tell a desktop calenndar application to re-read
15156 the iCalendar file.")
15158 (defun org-print-icalendar-entries (&optional combine category)
15159 "Print iCalendar entries for the current Org-mode file to `standard-output'.
15160 When COMBINE is non nil, add the category to each line."
15161 (let ((re2 (concat "--?-?\\(" org-ts-regexp "\\)"))
15162 (dts (org-ical-ts-to-string
15163 (format-time-string (cdr org-time-stamp-formats) (current-time))
15164 "DTSTART"))
15165 hd ts ts2 state (inc t) pos scheduledp deadlinep tmp pri)
15166 (save-excursion
15167 (goto-char (point-min))
15168 (while (re-search-forward org-ts-regexp nil t)
15169 (setq pos (match-beginning 0)
15170 ts (match-string 0)
15171 inc t
15172 hd (org-get-heading))
15173 (if (looking-at re2)
15174 (progn
15175 (goto-char (match-end 0))
15176 (setq ts2 (match-string 1) inc nil))
15177 (setq ts2 ts
15178 tmp (buffer-substring (max (point-min)
15179 (- pos org-ds-keyword-length))
15180 pos)
15181 deadlinep (string-match org-deadline-regexp tmp)
15182 scheduledp (string-match org-scheduled-regexp tmp)
15183 ;; donep (org-entry-is-done-p)
15185 (if (or (string-match org-tr-regexp hd)
15186 (string-match org-ts-regexp hd))
15187 (setq hd (replace-match "" t t hd)))
15188 (if combine
15189 (setq hd (concat hd " (category " category ")")))
15190 (if deadlinep (setq hd (concat "DL: " hd " This is a deadline")))
15191 (if scheduledp (setq hd (concat "S: " hd " Scheduled for this date")))
15192 (princ (format "BEGIN:VEVENT
15195 SUMMARY:%s
15196 END:VEVENT\n"
15197 (org-ical-ts-to-string ts "DTSTART")
15198 (org-ical-ts-to-string ts2 "DTEND" inc)
15199 hd)))
15200 (when org-icalendar-include-todo
15201 (goto-char (point-min))
15202 (while (re-search-forward org-todo-line-regexp nil t)
15203 (setq state (match-string 1))
15204 (unless (equal state org-done-string)
15205 (setq hd (match-string 3))
15206 (if (string-match org-priority-regexp hd)
15207 (setq pri (string-to-char (match-string 2 hd))
15208 hd (concat (substring hd 0 (match-beginning 1))
15209 (substring hd (- (match-end 1)))))
15210 (setq pri org-default-priority))
15211 (setq pri (floor (1+ (* 8. (/ (float (- org-lowest-priority pri))
15212 (- org-lowest-priority ?A))))))
15214 (princ (format "BEGIN:VTODO
15216 SUMMARY:%s
15217 SEQUENCE:1
15218 PRIORITY:%d
15219 END:VTODO\n"
15220 dts hd pri))))))))
15222 (defun org-start-icalendar-file (name)
15223 "Start an iCalendar file by inserting the header."
15224 (let ((user user-full-name)
15225 (name (or name "unknown"))
15226 (timezone (cadr (current-time-zone))))
15227 (princ
15228 (format "BEGIN:VCALENDAR
15229 VERSION:2.0
15230 X-WR-CALNAME:%s
15231 PRODID:-//%s//Emacs with Org-mode//EN
15232 X-WR-TIMEZONE:%s
15233 CALSCALE:GREGORIAN\n" name user timezone))))
15235 (defun org-finish-icalendar-file ()
15236 "Finish an iCalendar file by inserting the END statement."
15237 (princ "END:VCALENDAR\n"))
15239 (defun org-ical-ts-to-string (s keyword &optional inc)
15240 "Take a time string S and convert it to iCalendar format.
15241 KEYWORD is added in front, to make a complete line like DTSTART....
15242 When INC is non-nil, increase the hour by two (if time string contains
15243 a time), or the day by one (if it does not contain a time)."
15244 (let ((t1 (org-parse-time-string s 'nodefault))
15245 t2 fmt have-time time)
15246 (if (and (car t1) (nth 1 t1) (nth 2 t1))
15247 (setq t2 t1 have-time t)
15248 (setq t2 (org-parse-time-string s)))
15249 (let ((s (car t2)) (mi (nth 1 t2)) (h (nth 2 t2))
15250 (d (nth 3 t2)) (m (nth 4 t2)) (y (nth 5 t2)))
15251 (when inc
15252 (if have-time (setq h (+ 2 h)) (setq d (1+ d))))
15253 (setq time (encode-time s mi h d m y)))
15254 (setq fmt (if have-time ":%Y%m%dT%H%M%S" ";VALUE=DATE:%Y%m%d"))
15255 (concat keyword (format-time-string fmt time))))
15257 ;;; LaTeX stuff
15259 (defvar org-cdlatex-mode-map (make-sparse-keymap)
15260 "Keymap for the minor `org-cdlatex-mode'.")
15262 (define-key org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
15263 (define-key org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
15264 (define-key org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
15265 (define-key org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
15266 (define-key org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
15268 (defvar org-cdlatex-texmathp-advice-is-done nil
15269 "Flag remembering if we have applied the advice to texmathp already.")
15271 (define-minor-mode org-cdlatex-mode
15272 "Toggle the minor `org-cdlatex-mode'.
15273 This mode supports entering LaTeX environment and math in LaTeX fragments
15274 in Org-mode.
15275 \\{org-cdlatex-mode-map}"
15276 nil " OCDL" nil
15277 (when org-cdlatex-mode (require 'cdlatex))
15278 (unless org-cdlatex-texmathp-advice-is-done
15279 (setq org-cdlatex-texmathp-advice-is-done t)
15280 (defadvice texmathp (around org-math-always-on activate)
15281 "Always return t in org-mode buffers.
15282 This is because we want to insert math symbols without dollars even outside
15283 the LaTeX math segments. If Orgmode thinks that point is actually inside
15284 en embedded LaTeX fragement, let texmathp do its job.
15285 \\[org-cdlatex-mode-map]"
15286 (interactive)
15287 (let (p)
15288 (cond
15289 ((not (org-mode-p)) ad-do-it)
15290 ((eq this-command 'cdlatex-math-symbol)
15291 (setq ad-return-value t
15292 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15294 (let ((p (org-inside-LaTeX-fragment-p)))
15295 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15296 (setq ad-return-value t
15297 texmathp-why '("Org-mode embedded math" . 0))
15298 (if p ad-do-it)))))))))
15300 (defun turn-on-org-cdlatex ()
15301 "Unconditionally turn on `org-cdlatex-mode'."
15302 (org-cdlatex-mode 1))
15304 (defun org-inside-LaTeX-fragment-p ()
15305 "Test if point is inside a LaTeX fragment.
15306 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15307 sequence appearing also before point.
15308 Even though the matchers for math are configurable, this function assumes
15309 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15310 delimiters are skipped when they have been removed by customization.
15311 The return value is nil, or a cons cell with the delimiter and
15312 and the position of this delimiter.
15314 This function does a reasonably good job, but can locally be fooled by
15315 for example currency specifications. For example it will assume being in
15316 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15317 fragments that are properly closed, but during editing, we have to live
15318 with the uncertainty caused by missing closing delimiters. This function
15319 looks only before point, not after."
15320 (catch 'exit
15321 (let ((pos (point))
15322 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15323 (lim (progn
15324 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15325 (point)))
15326 dd-on str (start 0) m re)
15327 (goto-char pos)
15328 (when dodollar
15329 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15330 re (nth 1 (assoc "$" org-latex-regexps)))
15331 (while (string-match re str start)
15332 (cond
15333 ((= (match-end 0) (length str))
15334 (throw 'exit (cons "$" (+ lim (match-beginning 0)))))
15335 ((= (match-end 0) (- (length str) 5))
15336 (throw 'exit nil))
15337 (t (setq start (match-end 0))))))
15338 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15339 (goto-char pos)
15340 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15341 (and (match-beginning 2) (throw 'exit nil))
15342 ;; count $$
15343 (while (re-search-backward "\\$\\$" lim t)
15344 (setq dd-on (not dd-on)))
15345 (goto-char pos)
15346 (if dd-on (cons "$$" m))))))
15349 (defun org-try-cdlatex-tab ()
15350 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15351 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15352 - inside a LaTeX fragment, or
15353 - after the first word in a line, where an abbreviation expansion could
15354 insert a LaTeX environment."
15355 ;; FIXME: This may still need refinement.
15356 (when org-cdlatex-mode
15357 (cond
15358 ((save-excursion
15359 (skip-chars-backward "a-zA-Z0-9*")
15360 (skip-chars-backward " \t")
15361 (bolp))
15362 (cdlatex-tab) t)
15363 ((org-inside-LaTeX-fragment-p)
15364 (cdlatex-tab) t)
15365 (t nil))))
15367 (defun org-cdlatex-underscore-caret (&optional arg)
15368 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15369 Revert to the normal definition outside of these fragments."
15370 (interactive "P")
15371 (if (org-inside-LaTeX-fragment-p)
15372 (call-interactively 'cdlatex-sub-superscript)
15373 (let (org-cdlatex-mode)
15374 (call-interactively (key-binding (vector last-input-event))))))
15376 (defun org-cdlatex-math-modify (&optional arg)
15377 "Execute `cdlatex-math-modify' in LaTeX fragments.
15378 Revert to the normal definition outside of these fragments."
15379 (interactive "P")
15380 (if (org-inside-LaTeX-fragment-p)
15381 (call-interactively 'cdlatex-math-modify)
15382 (let (org-cdlatex-mode)
15383 (call-interactively (key-binding (vector last-input-event))))))
15385 (defvar org-latex-fragment-image-overlays nil
15386 "List of overlays carrying the images of latex fragments.")
15387 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15389 (defun org-remove-latex-fragment-image-overlays ()
15390 "Remove all overlays with LaTeX fragment images in current buffer."
15391 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
15392 (setq org-latex-fragment-image-overlays nil))
15394 (defun org-preview-latex-fragment (&optional subtree)
15395 "Preview the LaTeX fragment at point, or all locally or globally.
15396 If the cursor is in a LaTeX fragment, create the image and overlay
15397 it over the source code. If there is no fragment at point, display
15398 all fragments in the current text, from one headline to the next. With
15399 prefix SUBTREE, display all fragments in the current subtree. With a
15400 double prefix `C-u C-u', or when the cursor is before the first headline,
15401 display all fragments in the buffer.
15402 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15403 (interactive "P")
15404 (org-remove-latex-fragment-image-overlays)
15405 (save-excursion
15406 (save-restriction
15407 (let (beg end at msg)
15408 (cond
15409 ((or (equal subtree '(16))
15410 (not (save-excursion
15411 (re-search-backward (concat "^" outline-regexp) nil t))))
15412 (setq beg (point-min) end (point-max)
15413 msg "Creating images for buffer...%s"))
15414 ((equal subtree '(4))
15415 (org-back-to-heading)
15416 (setq beg (point) end (org-end-of-subtree)
15417 msg "Creating images for subtree...%s"))
15419 (if (setq at (org-inside-LaTeX-fragment-p))
15420 (goto-char (max (point-min) (- (cdr at) 2)))
15421 (org-back-to-heading))
15422 (setq beg (point) end (progn (outline-next-heading) (point))
15423 msg (if at "Creating image...%s"
15424 "Creating images for entry...%s"))))
15425 (message msg "")
15426 (narrow-to-region beg end)
15427 (org-format-latex
15428 (concat "ltxpng/" (file-name-sans-extension
15429 (file-name-nondirectory
15430 buffer-file-name)))
15431 default-directory 'overlays msg at)
15432 (message msg "done. Use `C-c C-c' to remove images.")))))
15434 (defvar org-latex-regexps
15435 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15436 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15437 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15438 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
15439 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15440 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
15441 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
15442 "Regular expressions for matching embedded LaTeX.")
15444 (defun org-format-latex (prefix &optional dir overlays msg at)
15445 "Replace LaTeX fragments with links to an image, and produce images."
15446 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15447 (let* ((prefixnodir (file-name-nondirectory prefix))
15448 (absprefix (expand-file-name prefix dir))
15449 (todir (file-name-directory absprefix))
15450 (opt org-format-latex-options)
15451 (matchers (plist-get opt :matchers))
15452 (re-list org-latex-regexps)
15453 (cnt 0) txt link beg end re e oldfiles
15454 m n block linkfile movefile ov)
15455 ;; Make sure the directory exists
15456 (or (file-directory-p todir) (make-directory todir))
15457 ;; Check if there are old images files with this prefix, and remove them
15458 (setq oldfiles (directory-files
15459 todir 'full
15460 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$")))
15461 (while oldfiles (delete-file (pop oldfiles)))
15462 ;; Check the different regular expressions
15463 (while (setq e (pop re-list))
15464 (setq m (car e) re (nth 1 e) n (nth 2 e)
15465 block (if (nth 3 e) "\n\n" ""))
15466 (when (member m matchers)
15467 (goto-char (point-min))
15468 (while (re-search-forward re nil t)
15469 (when (or (not at) (equal (cdr at) (match-beginning n)))
15470 (setq txt (match-string n)
15471 beg (match-beginning n) end (match-end n)
15472 cnt (1+ cnt)
15473 linkfile (format "%s_%04d.png" prefix cnt)
15474 movefile (format "%s_%04d.png" absprefix cnt)
15475 link (concat block "[[file:" linkfile "]]" block))
15476 (if msg (message msg cnt))
15477 (goto-char beg)
15478 (org-create-formula-image
15479 txt movefile opt)
15480 (if overlays
15481 (progn
15482 (setq ov (org-make-overlay beg end))
15483 (if (featurep 'xemacs)
15484 (progn
15485 (org-overlay-put ov 'invisible t)
15486 (org-overlay-put
15487 ov 'end-glyph
15488 (make-glyph (vector 'png :file movefile))))
15489 (org-overlay-put
15490 ov 'display
15491 (list 'image :type 'png :file movefile :ascent 'center)))
15492 (push ov org-latex-fragment-image-overlays)
15493 (goto-char end))
15494 (delete-region beg end)
15495 (insert link))))))))
15497 ;; This function borrows from Ganesh Swami's latex2png.el
15498 (defun org-create-formula-image (string tofile options)
15499 (let* ((tmpdir (if (featurep 'xemacs)
15500 (temp-directory)
15501 temporary-file-directory))
15502 (texfilebase (make-temp-name
15503 (expand-file-name "orgtex" tmpdir)))
15505 ;(texfilebase (make-temp-file "orgtex"))
15506 ; (dummy (delete-file texfilebase))
15507 (texfile (concat texfilebase ".tex"))
15508 (dvifile (concat texfilebase ".dvi"))
15509 (pngfile (concat texfilebase ".png"))
15510 (scale (number-to-string (* 1000 (or (plist-get options :scale) 1.0))))
15511 (fg (or (plist-get options :foreground) "Black"))
15512 (bg (or (plist-get options :background) "Transparent")))
15513 (with-temp-file texfile
15514 (insert "\\documentclass{article}
15515 \\usepackage{fullpage}
15516 \\usepackage{amssymb}
15517 \\usepackage[usenames]{color}
15518 \\usepackage{amsmath}
15519 \\usepackage{latexsym}
15520 \\usepackage[mathscr]{eucal}
15521 \\pagestyle{empty}
15522 \\begin{document}\n" string "\n\\end{document}\n"))
15523 (let ((dir default-directory))
15524 (condition-case nil
15525 (progn
15526 (cd tmpdir)
15527 (call-process "latex" nil nil nil texfile))
15528 (error nil))
15529 (cd dir))
15530 (if (not (file-exists-p dvifile))
15531 (progn (message "Failed to create dvi file from %s" texfile) nil)
15532 (call-process "dvipng" nil nil nil
15533 "-E" "-fg" fg "-bg" bg
15534 "-x" scale "-y" scale "-T" "tight"
15535 "-o" pngfile
15536 dvifile)
15537 (if (not (file-exists-p pngfile))
15538 (progn (message "Failed to create png file from %s" texfile) nil)
15539 ;; Use the requested file name and clean up
15540 (copy-file pngfile tofile 'replace)
15541 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15542 (delete-file (concat texfilebase e)))
15543 pngfile))))
15545 ;;; Key bindings
15547 ;; - Bindings in Org-mode map are currently
15548 ;; 0123456789abcdefghijklmnopqrstuvwxyz!?@#$%^&-+*/=()_{}[]:;"|,.<>~`'\t the alphabet
15549 ;; abcd fgh j lmnopqrstuvwxyz!? #$ ^ -+*/= [] ; |,.<>~ '\t necessary bindings
15550 ;; e (?) useful from outline-mode
15551 ;; i k @ expendable from outline-mode
15552 ;; 0123456789 % & ()_{} " ` free
15554 ;; Make `C-c C-x' a prefix key
15555 (define-key org-mode-map "\C-c\C-x" (make-sparse-keymap))
15557 ;; TAB key with modifiers
15558 (define-key org-mode-map "\C-i" 'org-cycle)
15559 (define-key org-mode-map [(tab)] 'org-cycle)
15560 (define-key org-mode-map [(control tab)] 'org-force-cycle-archived)
15561 (define-key org-mode-map [(meta tab)] 'org-complete)
15562 (define-key org-mode-map "\M-\C-i" 'org-complete) ; for tty emacs
15563 ;; The following line is necessary under Suse GNU/Linux
15564 (unless (featurep 'xemacs)
15565 (define-key org-mode-map [S-iso-lefttab] 'org-shifttab))
15566 (define-key org-mode-map [(shift tab)] 'org-shifttab)
15568 (define-key org-mode-map (org-key 'S-return) 'org-table-copy-down)
15569 (define-key org-mode-map "\C-c\C-xc" 'org-table-copy-down) ; tty
15570 (define-key org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15571 (define-key org-mode-map "\C-c\C-xM" 'org-insert-todo-heading) ; tty
15572 (define-key org-mode-map [(meta return)] 'org-meta-return)
15573 (define-key org-mode-map "\C-c\C-xm" 'org-meta-return) ; tty emacs
15574 (define-key org-mode-map [?\e (return)] 'org-meta-return) ; tty emacs
15576 ;; Cursor keys with modifiers
15577 (define-key org-mode-map [(meta left)] 'org-metaleft)
15578 (define-key org-mode-map [?\e (left)] 'org-metaleft) ; for tty emacs
15579 (define-key org-mode-map "\C-c\C-xl" 'org-metaleft) ; for tty emacs
15580 (define-key org-mode-map [(meta right)] 'org-metaright)
15581 (define-key org-mode-map [?\e (right)] 'org-metaright) ; for tty emacs
15582 (define-key org-mode-map "\C-c\C-xr" 'org-metaright) ; for tty emacs
15583 (define-key org-mode-map [(meta up)] 'org-metaup)
15584 (define-key org-mode-map [?\e (up)] 'org-metaup) ; for tty emacs
15585 (define-key org-mode-map "\C-c\C-xu" 'org-metaup) ; for tty emacs
15586 (define-key org-mode-map [(meta down)] 'org-metadown)
15587 (define-key org-mode-map [?\e (down)] 'org-metadown) ; for tty emacs
15588 (define-key org-mode-map "\C-c\C-xd" 'org-metadown) ; for tty emacs
15590 (define-key org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15591 (define-key org-mode-map "\C-c\C-xL" 'org-shiftmetaleft) ; tty
15592 (define-key org-mode-map [(meta shift right)] 'org-shiftmetaright)
15593 (define-key org-mode-map "\C-c\C-xR" 'org-shiftmetaright) ; tty
15594 (define-key org-mode-map [(meta shift up)] 'org-shiftmetaup)
15595 (define-key org-mode-map "\C-c\C-xU" 'org-shiftmetaup) ; tty
15596 (define-key org-mode-map [(meta shift down)] 'org-shiftmetadown)
15597 (define-key org-mode-map "\C-c\C-xD" 'org-shiftmetadown) ; tty
15598 (define-key org-mode-map (org-key 'S-up) 'org-shiftup)
15599 (define-key org-mode-map [?\C-c ?\C-x (up)] 'org-shiftup)
15600 (define-key org-mode-map (org-key 'S-down) 'org-shiftdown)
15601 (define-key org-mode-map [?\C-c ?\C-x (down)] 'org-shiftdown)
15602 (define-key org-mode-map (org-key 'S-left) 'org-shiftleft)
15603 (define-key org-mode-map [?\C-c ?\C-x (left)] 'org-shiftleft)
15604 (define-key org-mode-map (org-key 'S-right) 'org-shiftright)
15605 (define-key org-mode-map [?\C-c ?\C-x (right)] 'org-shiftright)
15607 ;; All the other keys
15609 (define-key org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15610 (define-key org-mode-map "\C-xns" 'org-narrow-to-subtree)
15611 (define-key org-mode-map "\C-c$" 'org-archive-subtree)
15612 (define-key org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
15613 (define-key org-mode-map "\C-c\C-j" 'org-goto)
15614 (define-key org-mode-map "\C-c\C-t" 'org-todo)
15615 (define-key org-mode-map "\C-c\C-s" 'org-schedule)
15616 (define-key org-mode-map "\C-c\C-d" 'org-deadline)
15617 (define-key org-mode-map "\C-c;" 'org-toggle-comment)
15618 (define-key org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15619 (define-key org-mode-map "\C-c\C-w" 'org-check-deadlines)
15620 (define-key org-mode-map "\C-c/" 'org-occur) ; Minor-mode reserved
15621 (define-key org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
15622 (define-key org-mode-map "\C-c\C-m" 'org-insert-heading)
15623 (define-key org-mode-map "\M-\C-m" 'org-insert-heading)
15624 (define-key org-mode-map "\C-c\C-l" 'org-insert-link)
15625 (define-key org-mode-map "\C-c\C-o" 'org-open-at-point)
15626 (define-key org-mode-map "\C-c%" 'org-mark-ring-push)
15627 (define-key org-mode-map "\C-c&" 'org-mark-ring-goto)
15628 (define-key org-mode-map "\C-c\C-z" 'org-time-stamp) ; Alternative binding
15629 (define-key org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15630 (define-key org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15631 (define-key org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15632 (define-key org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15633 (define-key org-mode-map "\C-c>" 'org-goto-calendar)
15634 (define-key org-mode-map "\C-c<" 'org-date-from-calendar)
15635 (define-key org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15636 (define-key org-mode-map "\C-c[" 'org-agenda-file-to-front)
15637 (define-key org-mode-map "\C-c]" 'org-remove-file)
15638 (define-key org-mode-map "\C-c-" 'org-table-insert-hline)
15639 (define-key org-mode-map "\C-c^" 'org-table-sort-lines)
15640 (define-key org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15641 (define-key org-mode-map "\C-c#" 'org-update-checkbox-count)
15642 (define-key org-mode-map "\C-m" 'org-return)
15643 (define-key org-mode-map "\C-c?" 'org-table-current-column)
15644 (define-key org-mode-map "\C-c " 'org-table-blank-field)
15645 (define-key org-mode-map "\C-c+" 'org-table-sum)
15646 (define-key org-mode-map "\C-c=" 'org-table-eval-formula)
15647 (define-key org-mode-map "\C-c'" 'org-table-edit-formulas)
15648 (define-key org-mode-map "\C-c`" 'org-table-edit-field)
15649 (define-key org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15650 (define-key org-mode-map "\C-c*" 'org-table-recalculate)
15651 (define-key org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15652 (define-key org-mode-map "\C-c~" 'org-table-create-with-table.el)
15653 (define-key org-mode-map "\C-c\C-q" 'org-table-wrap-region)
15654 (define-key org-mode-map "\C-c\C-e" 'org-export)
15655 (define-key org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15657 (define-key org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
15658 (define-key org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15659 (define-key org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15660 (define-key org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15662 (define-key org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15663 (define-key org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15664 (define-key org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15665 (define-key org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15666 (define-key org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15667 (define-key org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15668 (define-key org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15669 (define-key org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15671 (when (featurep 'xemacs)
15672 (define-key org-mode-map 'button3 'popup-mode-menu))
15674 (defsubst org-table-p () (org-at-table-p))
15676 (defun org-self-insert-command (N)
15677 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15678 If the cursor is in a table looking at whitespace, the whitespace is
15679 overwritten, and the table is not marked as requiring realignment."
15680 (interactive "p")
15681 (if (and (org-table-p)
15682 (progn
15683 ;; check if we blank the field, and if that triggers align
15684 (and org-table-auto-blank-field
15685 (member last-command
15686 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
15687 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15688 ;; got extra space, this field does not determine column width
15689 (let (org-table-may-need-update) (org-table-blank-field))
15690 ;; no extra space, this field may determine column width
15691 (org-table-blank-field)))
15693 (eq N 1)
15694 (looking-at "[^|\n]* |"))
15695 (let (org-table-may-need-update)
15696 (goto-char (1- (match-end 0)))
15697 (delete-backward-char 1)
15698 (goto-char (match-beginning 0))
15699 (self-insert-command N))
15700 (setq org-table-may-need-update t)
15701 (self-insert-command N)))
15703 (defun org-delete-backward-char (N)
15704 "Like `delete-backward-char', insert whitespace at field end in tables.
15705 When deleting backwards, in tables this function will insert whitespace in
15706 front of the next \"|\" separator, to keep the table aligned. The table will
15707 still be marked for re-alignment if the field did fill the entire column,
15708 because, in this case the deletion might narrow the column."
15709 (interactive "p")
15710 (if (and (org-table-p)
15711 (eq N 1)
15712 (string-match "|" (buffer-substring (point-at-bol) (point)))
15713 (looking-at ".*?|"))
15714 (let ((pos (point))
15715 (noalign (looking-at "[^|\n\r]* |"))
15716 (c org-table-may-need-update))
15717 (backward-delete-char N)
15718 (skip-chars-forward "^|")
15719 (insert " ")
15720 (goto-char (1- pos))
15721 ;; noalign: if there were two spaces at the end, this field
15722 ;; does not determine the width of the column.
15723 (if noalign (setq org-table-may-need-update c)))
15724 (backward-delete-char N)))
15726 (defun org-delete-char (N)
15727 "Like `delete-char', but insert whitespace at field end in tables.
15728 When deleting characters, in tables this function will insert whitespace in
15729 front of the next \"|\" separator, to keep the table aligned. The table will
15730 still be marked for re-alignment if the field did fill the entire column,
15731 because, in this case the deletion might narrow the column."
15732 (interactive "p")
15733 (if (and (org-table-p)
15734 (not (bolp))
15735 (not (= (char-after) ?|))
15736 (eq N 1))
15737 (if (looking-at ".*?|")
15738 (let ((pos (point))
15739 (noalign (looking-at "[^|\n\r]* |"))
15740 (c org-table-may-need-update))
15741 (replace-match (concat
15742 (substring (match-string 0) 1 -1)
15743 " |"))
15744 (goto-char pos)
15745 ;; noalign: if there were two spaces at the end, this field
15746 ;; does not determine the width of the column.
15747 (if noalign (setq org-table-may-need-update c)))
15748 (delete-char N))
15749 (delete-char N)))
15751 ;; How to do this: Measure non-white length of current string
15752 ;; If equal to column width, we should realign.
15754 (defun org-remap (map &rest commands)
15755 "In MAP, remap the functions given in COMMANDS.
15756 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15757 (let (new old)
15758 (while commands
15759 (setq old (pop commands) new (pop commands))
15760 (if (fboundp 'command-remapping)
15761 (define-key map (vector 'remap old) new)
15762 (substitute-key-definition old new map global-map)))))
15764 (when (eq org-enable-table-editor 'optimized)
15765 ;; If the user wants maximum table support, we need to hijack
15766 ;; some standard editing functions
15767 (org-remap org-mode-map
15768 'self-insert-command 'org-self-insert-command
15769 'delete-char 'org-delete-char
15770 'delete-backward-char 'org-delete-backward-char)
15771 (define-key org-mode-map "|" 'org-force-self-insert))
15773 (defun org-shiftcursor-error ()
15774 "Throw an error because Shift-Cursor command was applied in wrong context."
15775 (error "This command is active in special context like tables, headlines or timestamps"))
15777 (defun org-shifttab (&optional arg)
15778 "Global visibility cycling or move to previous table field.
15779 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15780 on context.
15781 See the individual commands for more information."
15782 (interactive "P")
15783 (cond
15784 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15785 (t (call-interactively 'org-global-cycle))))
15787 (defun org-shiftmetaleft ()
15788 "Promote subtree or delete table column.
15789 Calls `org-promote-subtree' or `org-table-delete-column', depending on context.
15790 See the individual commands for more information."
15791 (interactive)
15792 (cond
15793 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15794 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15795 ((org-at-item-p) (call-interactively 'org-outdent-item))
15796 (t (org-shiftcursor-error))))
15798 (defun org-shiftmetaright ()
15799 "Demote subtree or insert table column.
15800 Calls `org-demote-subtree' or `org-table-insert-column', depending on context.
15801 See the individual commands for more information."
15802 (interactive)
15803 (cond
15804 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15805 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15806 ((org-at-item-p) (call-interactively 'org-indent-item))
15807 (t (org-shiftcursor-error))))
15809 (defun org-shiftmetaup (&optional arg)
15810 "Move subtree up or kill table row.
15811 Calls `org-move-subtree-up' or `org-table-kill-row' or
15812 `org-move-item-up' depending on context. See the individual commands
15813 for more information."
15814 (interactive "P")
15815 (cond
15816 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15817 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15818 ((org-at-item-p) (call-interactively 'org-move-item-up))
15819 (t (org-shiftcursor-error))))
15820 (defun org-shiftmetadown (&optional arg)
15821 "Move subtree down or insert table row.
15822 Calls `org-move-subtree-down' or `org-table-insert-row' or
15823 `org-move-item-down', depending on context. See the individual
15824 commands for more information."
15825 (interactive "P")
15826 (cond
15827 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15828 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15829 ((org-at-item-p) (call-interactively 'org-move-item-down))
15830 (t (org-shiftcursor-error))))
15832 (defun org-metaleft (&optional arg)
15833 "Promote heading or move table column to left.
15834 Calls `org-do-promote' or `org-table-move-column', depending on context.
15835 With no specific context, calls the Emacs default `backward-word'.
15836 See the individual commands for more information."
15837 (interactive "P")
15838 (cond
15839 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15840 ((or (org-on-heading-p) (org-region-active-p))
15841 (call-interactively 'org-do-promote))
15842 (t (call-interactively 'backward-word))))
15844 (defun org-metaright (&optional arg)
15845 "Demote subtree or move table column to right.
15846 Calls `org-do-demote' or `org-table-move-column', depending on context.
15847 With no specific context, calls the Emacs default `forward-word'.
15848 See the individual commands for more information."
15849 (interactive "P")
15850 (cond
15851 ((org-at-table-p) (call-interactively 'org-table-move-column))
15852 ((or (org-on-heading-p) (org-region-active-p))
15853 (call-interactively 'org-do-demote))
15854 (t (call-interactively 'forward-word))))
15856 (defun org-metaup (&optional arg)
15857 "Move subtree up or move table row up.
15858 Calls `org-move-subtree-up' or `org-table-move-row' or
15859 `org-move-item-up', depending on context. See the individual commands
15860 for more information."
15861 (interactive "P")
15862 (cond
15863 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
15864 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15865 ((org-at-item-p) (call-interactively 'org-move-item-up))
15866 (t (org-shiftcursor-error))))
15868 (defun org-metadown (&optional arg)
15869 "Move subtree down or move table row down.
15870 Calls `org-move-subtree-down' or `org-table-move-row' or
15871 `org-move-item-down', depending on context. See the individual
15872 commands for more information."
15873 (interactive "P")
15874 (cond
15875 ((org-at-table-p) (call-interactively 'org-table-move-row))
15876 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15877 ((org-at-item-p) (call-interactively 'org-move-item-down))
15878 (t (org-shiftcursor-error))))
15880 (defun org-shiftup (&optional arg)
15881 "Increase item in timestamp or increase priority of current headline.
15882 Calls `org-timestamp-up' or `org-priority-up', depending on context.
15883 See the individual commands for more information."
15884 (interactive "P")
15885 (cond
15886 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up))
15887 ((org-on-heading-p) (call-interactively 'org-priority-up))
15888 ((org-at-item-p) (call-interactively 'org-previous-item))
15889 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
15891 (defun org-shiftdown (&optional arg)
15892 "Decrease item in timestamp or decrease priority of current headline.
15893 Calls `org-timestamp-down' or `org-priority-down', depending on context.
15894 See the individual commands for more information."
15895 (interactive "P")
15896 (cond
15897 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down))
15898 ((org-on-heading-p) (call-interactively 'org-priority-down))
15899 (t (call-interactively 'org-next-item))))
15901 (defun org-shiftright ()
15902 "Next TODO keyword or timestamp one day later, depending on context."
15903 (interactive)
15904 (cond
15905 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
15906 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
15907 (t (org-shiftcursor-error))))
15909 (defun org-shiftleft ()
15910 "Previous TODO keyword or timestamp one day earlier, depending on context."
15911 (interactive)
15912 (cond
15913 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
15914 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
15915 (t (org-shiftcursor-error))))
15917 (defun org-copy-special ()
15918 "Copy region in table or copy current subtree.
15919 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15920 See the individual commands for more information."
15921 (interactive)
15922 (call-interactively
15923 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15925 (defun org-cut-special ()
15926 "Cut region in table or cut current subtree.
15927 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15928 See the individual commands for more information."
15929 (interactive)
15930 (call-interactively
15931 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15933 (defun org-paste-special (arg)
15934 "Paste rectangular region into table, or past subtree relative to level.
15935 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15936 See the individual commands for more information."
15937 (interactive "P")
15938 (if (org-at-table-p)
15939 (org-table-paste-rectangle)
15940 (org-paste-subtree arg)))
15942 (defun org-ctrl-c-ctrl-c (&optional arg)
15943 "Set tags in headline, or update according to changed information at point.
15945 This command does many different things, depending on context:
15947 - If the cursor is in a headline, prompt for tags and insert them
15948 into the current line, aligned to `org-tags-column'. When called
15949 with prefix arg, realign all tags in the current buffer.
15951 - If the cursor is in one of the special #+KEYWORD lines, this
15952 triggers scanning the buffer for these lines and updating the
15953 information.
15955 - If the cursor is inside a table, realign the table. This command
15956 works even if the automatic table editor has been turned off.
15958 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15959 the entire table.
15961 - If the cursor is inside a table created by the table.el package,
15962 activate that table.
15964 - If the current buffer is a remember buffer, close note and file it.
15965 with a prefix argument, file it without further interaction to the default
15966 location.
15968 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15969 links in this buffer.
15971 - If the cursor is on a numbered item in a plain list, renumber the
15972 ordered list."
15973 (interactive "P")
15974 (let ((org-enable-table-editor t))
15975 (cond
15976 ((or org-clock-overlays org-occur-highlights
15977 org-latex-fragment-image-overlays)
15978 (org-remove-clock-overlays)
15979 (org-remove-occur-highlights)
15980 (org-remove-latex-fragment-image-overlays)
15981 (message "Temporary highlights/overlays removed from current buffer"))
15982 ((and (local-variable-p 'org-finish-function (current-buffer))
15983 (fboundp org-finish-function))
15984 (funcall org-finish-function))
15985 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15986 ((org-on-heading-p) (call-interactively 'org-set-tags))
15987 ((org-at-table.el-p)
15988 (require 'table)
15989 (beginning-of-line 1)
15990 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15991 (call-interactively 'table-recognize-table))
15992 ((org-at-table-p)
15993 (org-table-maybe-eval-formula)
15994 (if arg
15995 (call-interactively 'org-table-recalculate)
15996 (org-table-maybe-recalculate-line))
15997 (call-interactively 'org-table-align))
15998 ((org-at-item-checkbox-p)
15999 (call-interactively 'org-toggle-checkbox))
16000 ((org-at-item-p)
16001 (call-interactively 'org-renumber-ordered-list))
16002 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
16003 (cond
16004 ((equal (match-string 1) "TBLFM")
16005 ;; Recalculate the table before this line
16006 (save-excursion
16007 (beginning-of-line 1)
16008 (skip-chars-backward " \r\n\t")
16009 (if (org-at-table-p)
16010 (org-call-with-arg 'org-table-recalculate t))))
16012 (call-interactively 'org-mode-restart))))
16013 (t (error "C-c C-c can do nothing useful at this location.")))))
16015 (defun org-mode-restart ()
16016 "Restart Org-mode, to scan again for special lines.
16017 Also updates the keyword regular expressions."
16018 (interactive)
16019 (let ((org-inhibit-startup t)) (org-mode))
16020 (message "Org-mode restarted to refresh keyword and special line setup"))
16022 (defun org-return ()
16023 "Goto next table row or insert a newline.
16024 Calls `org-table-next-row' or `newline', depending on context.
16025 See the individual commands for more information."
16026 (interactive)
16027 (cond
16028 ((org-at-table-p)
16029 (org-table-justify-field-maybe)
16030 (call-interactively 'org-table-next-row))
16031 (t (newline))))
16033 (defun org-meta-return (&optional arg)
16034 "Insert a new heading or wrap a region in a table.
16035 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16036 See the individual commands for more information."
16037 (interactive "P")
16038 (cond
16039 ((org-at-table-p)
16040 (call-interactively 'org-table-wrap-region))
16041 (t (call-interactively 'org-insert-heading))))
16043 ;;; Menu entries
16045 ;; Define the Org-mode menus
16046 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16047 '("Tbl"
16048 ["Align" org-ctrl-c-ctrl-c (org-at-table-p)]
16049 ["Next Field" org-cycle (org-at-table-p)]
16050 ["Previous Field" org-shifttab (org-at-table-p)]
16051 ["Next Row" org-return (org-at-table-p)]
16052 "--"
16053 ["Blank Field" org-table-blank-field (org-at-table-p)]
16054 ["Edit Field" org-table-edit-field (org-at-table-p)]
16055 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16056 "--"
16057 ("Column"
16058 ["Move Column Left" org-metaleft (org-at-table-p)]
16059 ["Move Column Right" org-metaright (org-at-table-p)]
16060 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16061 ["Insert Column" org-shiftmetaright (org-at-table-p)]
16062 "--"
16063 ["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])
16064 ("Row"
16065 ["Move Row Up" org-metaup (org-at-table-p)]
16066 ["Move Row Down" org-metadown (org-at-table-p)]
16067 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16068 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16069 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16070 "--"
16071 ["Insert Hline" org-table-insert-hline (org-at-table-p)])
16072 ("Rectangle"
16073 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16074 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16075 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16076 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16077 "--"
16078 ("Calculate"
16079 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16080 ["Set Named Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16081 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
16082 "--"
16083 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16084 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16085 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16086 "--"
16087 ["Sum Column/Rectangle" org-table-sum
16088 (or (org-at-table-p) (org-region-active-p))]
16089 ["Which Column?" org-table-current-column (org-at-table-p)])
16090 ["Debug Formulas"
16091 (setq org-table-formula-debug (not org-table-formula-debug))
16092 :style toggle :selected org-table-formula-debug]
16093 "--"
16094 ["Create" org-table-create (and (not (org-at-table-p))
16095 org-enable-table-editor)]
16096 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16097 ["Import from File" org-table-import (not (org-at-table-p))]
16098 ["Export to File" org-table-export (org-at-table-p)]
16099 "--"
16100 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16102 (easy-menu-define org-org-menu org-mode-map "Org menu"
16103 '("Org"
16104 ["Cycle Visibility" org-cycle (or (bobp) (outline-on-heading-p))]
16105 ["Cycle Global Visibility" org-shifttab (not (org-at-table-p))]
16106 ["Sparse Tree" org-occur t]
16107 ["Show All" show-all t]
16108 "--"
16109 ["New Heading" org-insert-heading t]
16110 ("Navigate Headings"
16111 ["Up" outline-up-heading t]
16112 ["Next" outline-next-visible-heading t]
16113 ["Previous" outline-previous-visible-heading t]
16114 ["Next Same Level" outline-forward-same-level t]
16115 ["Previous Same Level" outline-backward-same-level t]
16116 "--"
16117 ["Jump" org-goto t])
16118 ("Edit Structure"
16119 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16120 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16121 "--"
16122 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16123 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16124 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16125 "--"
16126 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16127 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16128 ["Demote Heading" org-metaright (not (org-at-table-p))]
16129 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16130 "--"
16131 ["Convert to odd levels" org-convert-to-odd-levels t]
16132 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16133 ("Archive"
16134 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16135 ["Check and Tag Children" (org-toggle-archive-tag (4))
16136 :active t :keys "C-u C-c C-x C-a"]
16137 ["Sparse trees open ARCHIVE trees"
16138 (setq org-sparse-tree-open-archived-trees
16139 (not org-sparse-tree-open-archived-trees))
16140 :style toggle :selected org-sparse-tree-open-archived-trees]
16141 ["Cycling opens ARCHIVE trees"
16142 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
16143 :style toggle :selected org-cycle-open-archived-trees]
16144 ["Agenda includes ARCHIVE trees"
16145 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
16146 :style toggle :selected (not org-agenda-skip-archived-trees)]
16147 "--"
16148 ["Move Subtree to Archive" org-archive-subtree t]
16149 ["Check and Move Children" (org-archive-subtree '(4))
16150 :active t :keys "C-u C-c $"])
16151 "--"
16152 ("TODO Lists"
16153 ["TODO/DONE/-" org-todo t]
16154 ("Select keyword"
16155 ["Next keyword" org-shiftright (org-on-heading-p)]
16156 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16157 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))])
16158 ["Show TODO Tree" org-show-todo-tree t]
16159 ["Global TODO list" org-todo-list t]
16160 "--"
16161 ["Set Priority" org-priority t]
16162 ["Priority Up" org-shiftup t]
16163 ["Priority Down" org-shiftdown t]
16164 "--"
16165 ["Insert Checkbox" org-insert-todo-heading (org-in-item-p) t]
16166 ["Toggle Checkbox" org-ctrl-c-ctrl-c (org-at-item-checkbox-p)]
16167 ["Insert [n/m] cookie" (progn (insert "[/]") (org-update-checkbox-count))
16168 (or (org-on-heading-p) (org-at-item-p))]
16169 ["Insert [%] cookie" (progn (insert "[%]") (org-update-checkbox-count))
16170 (or (org-on-heading-p) (org-at-item-p))]
16171 ["Update Statistics" org-update-checkbox-count t])
16172 ("Dates and Scheduling"
16173 ["Timestamp" org-time-stamp t]
16174 ["Timestamp (inactive)" org-time-stamp-inactive t]
16175 ("Change Date"
16176 ["1 Day Later" org-timestamp-up-day t]
16177 ["1 Day Earlier" org-timestamp-down-day t]
16178 ["1 ... Later" org-shiftup t]
16179 ["1 ... Earlier" org-shiftdown t])
16180 ["Compute Time Range" org-evaluate-time-range t]
16181 ["Schedule Item" org-schedule t]
16182 ["Deadline" org-deadline t]
16183 "--"
16184 ["Goto Calendar" org-goto-calendar t]
16185 ["Date from Calendar" org-date-from-calendar t])
16186 ("Logging work"
16187 ["Clock in" org-clock-in t]
16188 ["Clock out" org-clock-out t]
16189 ["Clock cancel" org-clock-cancel t]
16190 ["Display times" org-clock-display t]
16191 ["Create clock table" org-clock-report t]
16192 "--"
16193 ["Record DONE time"
16194 (progn (setq org-log-done (not org-log-done))
16195 (message "Switching to %s will %s record a timestamp"
16196 org-done-string
16197 (if org-log-done "automatically" "not")))
16198 :style toggle :selected org-log-done])
16199 "--"
16200 ["Agenda Command..." org-agenda t]
16201 ("File List for Agenda")
16202 ("Special views current file"
16203 ["TODO Tree" org-show-todo-tree t]
16204 ["Check Deadlines" org-check-deadlines t]
16205 ["Timeline" org-timeline t]
16206 ["Tags Tree" org-tags-sparse-tree t])
16207 "--"
16208 ("Hyperlinks"
16209 ["Store Link (Global)" org-store-link t]
16210 ["Insert Link" org-insert-link t]
16211 ["Follow Link" org-open-at-point t]
16212 "--"
16213 ["Descriptive Links"
16214 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16215 :style radio :selected (member '(org-link) buffer-invisibility-spec)]
16216 ["Literal Links"
16217 (progn
16218 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16219 :style radio :selected (not (member '(org-link) buffer-invisibility-spec))]
16220 "--"
16221 ["Upgrade all <link> to [[link][desc]]" org-upgrade-old-links
16222 (save-excursion (goto-char (point-min))
16223 (re-search-forward "<[a-z]+:" nil t))])
16224 "--"
16225 ["Export/Publish..." org-export t]
16226 ("LaTeX"
16227 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16228 :selected org-cdlatex-mode]
16229 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16230 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16231 ["Modify math symbol" org-cdlatex-math-modify
16232 (org-inside-LaTeX-fragment-p)]
16233 ["Export LaTeX fragments as images"
16234 (setq org-export-with-LaTeX-fragments (not org-export-with-LaTeX-fragments))
16235 :style toggle :selected org-export-with-LaTeX-fragments])
16236 "--"
16237 ("Documentation"
16238 ["Show Version" org-version t]
16239 ["Info Documentation" org-info t])
16240 ("Customize"
16241 ["Browse Org Group" org-customize t]
16242 "--"
16243 ["Expand This Menu" org-create-customize-menu
16244 (fboundp 'customize-menu-create)])
16245 "--"
16246 ["Refresh setup" org-mode-restart t]
16249 (defun org-info (&optional node)
16250 "Read documentation for Org-mode in the info system.
16251 With optional NODE, go directly to that node."
16252 (interactive)
16253 (require 'info)
16254 (Info-goto-node (format "(org)%s" (or node ""))))
16256 (defun org-install-agenda-files-menu ()
16257 (let ((bl (buffer-list)))
16258 (save-excursion
16259 (while bl
16260 (set-buffer (pop bl))
16261 (if (org-mode-p) (setq bl nil)))
16262 (when (org-mode-p)
16263 (easy-menu-change
16264 '("Org") "File List for Agenda"
16265 (append
16266 (list
16267 ["Edit File List" (org-edit-agenda-file-list) t]
16268 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16269 ["Remove Current File from List" org-remove-file t]
16270 ["Cycle through agenda files" org-cycle-agenda-files t]
16271 "--")
16272 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16274 ;;; Documentation
16276 (defun org-customize ()
16277 "Call the customize function with org as argument."
16278 (interactive)
16279 (customize-browse 'org))
16281 (defun org-create-customize-menu ()
16282 "Create a full customization menu for Org-mode, insert it into the menu."
16283 (interactive)
16284 (if (fboundp 'customize-menu-create)
16285 (progn
16286 (easy-menu-change
16287 '("Org") "Customize"
16288 `(["Browse Org group" org-customize t]
16289 "--"
16290 ,(customize-menu-create 'org)
16291 ["Set" Custom-set t]
16292 ["Save" Custom-save t]
16293 ["Reset to Current" Custom-reset-current t]
16294 ["Reset to Saved" Custom-reset-saved t]
16295 ["Reset to Standard Settings" Custom-reset-standard t]))
16296 (message "\"Org\"-menu now contains full customization menu"))
16297 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16299 ;;; Miscellaneous stuff
16301 (defun org-context ()
16302 "Return a list of contexts of the current cursor position.
16303 If several contexts apply, all are returned.
16304 Each context entry is a list with a symbol naming the context, and
16305 two positions indicating start and end of the context. Possible
16306 contexts are:
16308 :headline anywhere in a headline
16309 :headline-stars on the leading stars in a headline
16310 :todo-keyword on a TODO keyword (including DONE) in a headline
16311 :tags on the TAGS in a headline
16312 :priority on the priority cookie in a headline
16313 :item on the first line of a plain list item
16314 :item-bullet on the bullet/number of a plain list item
16315 :checkbox on the checkbox in a plain list item
16316 :table in an org-mode table
16317 :table-special on a special filed in a table
16318 :table-table in a table.el table
16319 :link on a hyperline
16320 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16321 :target on a <<target>>
16322 :radio-target on a <<<radio-target>>>
16323 :latex-fragment on a LaTeX fragment
16324 :latex-preview on a LaTeX fragment with overlayed preview image
16326 This function expects the position to be visible because it uses font-lock
16327 faces as a help to recognize the following contexts: :table-special, :link,
16328 and :keyword."
16329 (let* ((f (get-text-property (point) 'face))
16330 (faces (if (listp f) f (list f)))
16331 (p (point)) clist o)
16332 ;; First the large context
16333 (cond
16334 ((org-on-heading-p)
16335 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16336 (when (progn
16337 (beginning-of-line 1)
16338 (looking-at org-todo-line-tags-regexp))
16339 (push (org-point-in-group p 1 :headline-stars) clist)
16340 (push (org-point-in-group p 2 :todo-keyword) clist)
16341 (push (org-point-in-group p 4 :tags) clist))
16342 (goto-char p)
16343 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
16344 (if (looking-at "\\[#[A-Z]\\]")
16345 (push (org-point-in-group p 0 :priority) clist)))
16347 ((org-at-item-p)
16348 (push (org-point-in-group p 2 :item-bullet) clist)
16349 (push (list :item (point-at-bol)
16350 (save-excursion (org-end-of-item) (point)))
16351 clist)
16352 (and (org-at-item-checkbox-p)
16353 (push (org-point-in-group p 0 :checkbox) clist)))
16355 ((org-at-table-p)
16356 (push (list :table (org-table-begin) (org-table-end)) clist)
16357 (if (memq 'org-formula faces)
16358 (push (list :table-special
16359 (previous-single-property-change p 'face)
16360 (next-single-property-change p 'face)) clist)))
16361 ((org-at-table-p 'any)
16362 (push (list :table-table) clist)))
16363 (goto-char p)
16365 ;; Now the small context
16366 (cond
16367 ((org-at-timestamp-p)
16368 (push (org-point-in-group p 0 :timestamp) clist))
16369 ((memq 'org-link faces)
16370 (push (list :link
16371 (previous-single-property-change p 'face)
16372 (next-single-property-change p 'face)) clist))
16373 ((memq 'org-special-keyword faces)
16374 (push (list :keyword
16375 (previous-single-property-change p 'face)
16376 (next-single-property-change p 'face)) clist))
16377 ((org-on-target-p)
16378 (push (org-point-in-group p 0 :target) clist)
16379 (goto-char (1- (match-beginning 0)))
16380 (if (looking-at org-radio-target-regexp)
16381 (push (org-point-in-group p 0 :radio-target) clist))
16382 (goto-char p))
16383 ((setq o (car (delq nil
16384 (mapcar
16385 (lambda (x)
16386 (if (memq x org-latex-fragment-image-overlays) x))
16387 (org-overlays-at (point))))))
16388 (push (list :latex-fragment
16389 (org-overlay-start o) (org-overlay-end o)) clist)
16390 (push (list :latex-preview
16391 (org-overlay-start o) (org-overlay-end o)) clist))
16392 ((org-inside-LaTeX-fragment-p)
16393 ;; FIXME: positions wring.
16394 (push (list :latex-fragment (point) (point)) clist)))
16396 (setq clist (nreverse (delq nil clist)))
16397 clist))
16399 (defun org-point-in-group (point group &optional context)
16400 "Check if POINT is in match-group GROUP.
16401 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16402 match. If the match group does ot exist or point is not inside it,
16403 return nil."
16404 (and (match-beginning group)
16405 (>= point (match-beginning group))
16406 (<= point (match-end group))
16407 (if context
16408 (list context (match-beginning group) (match-end group))
16409 t)))
16411 (defun org-move-line-down (arg)
16412 "Move the current line down. With prefix argument, move it past ARG lines."
16413 (interactive "p")
16414 (let ((col (current-column))
16415 beg end pos)
16416 (beginning-of-line 1) (setq beg (point))
16417 (beginning-of-line 2) (setq end (point))
16418 (beginning-of-line (+ 1 arg))
16419 (setq pos (move-marker (make-marker) (point)))
16420 (insert (delete-and-extract-region beg end))
16421 (goto-char pos)
16422 (move-to-column col)))
16424 (defun org-move-line-up (arg)
16425 "Move the current line up. With prefix argument, move it past ARG lines."
16426 (interactive "p")
16427 (let ((col (current-column))
16428 beg end pos)
16429 (beginning-of-line 1) (setq beg (point))
16430 (beginning-of-line 2) (setq end (point))
16431 (beginning-of-line (- arg))
16432 (setq pos (move-marker (make-marker) (point)))
16433 (insert (delete-and-extract-region beg end))
16434 (goto-char pos)
16435 (move-to-column col)))
16437 ;; Paragraph filling stuff.
16438 ;; We want this to be just right, so use the full arsenal.
16440 (defun org-set-autofill-regexps ()
16441 (interactive)
16442 ;; In the paragraph separator we include headlines, because filling
16443 ;; text in a line directly attached to a headline would otherwise
16444 ;; fill the headline as well.
16445 (org-set-local 'comment-start-skip "^#+[ \t]*")
16446 (org-set-local 'paragraph-separate "\f\\|\\*\\|[ ]*$\\|[ \t]*[:|]")
16447 ;; The paragraph starter includes hand-formatted lists.
16448 (org-set-local 'paragraph-start
16449 "\f\\|[ ]*$\\|\\([*\f]+\\)\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
16450 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16451 ;; But only if the user has not turned off tables or fixed-width regions
16452 (org-set-local
16453 'auto-fill-inhibit-regexp
16454 (concat "\\*\\|#"
16455 "\\|[ \t]*" org-keyword-time-regexp
16456 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16457 (concat
16458 "\\|[ \t]*["
16459 (if org-enable-table-editor "|" "")
16460 (if org-enable-fixed-width-editor ":" "")
16461 "]"))))
16462 ;; We use our own fill-paragraph function, to make sure that tables
16463 ;; and fixed-width regions are not wrapped. That function will pass
16464 ;; through to `fill-paragraph' when appropriate.
16465 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16466 ; Adaptive filling: To get full control, first make sure that
16467 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16468 (org-set-local 'adaptive-fill-regexp "\000")
16469 (org-set-local 'adaptive-fill-function
16470 'org-adaptive-fill-function))
16472 (defun org-fill-paragraph (&optional justify)
16473 "Re-align a table, pass through to fill-paragraph if no table."
16474 (let ((table-p (org-at-table-p))
16475 (table.el-p (org-at-table.el-p)))
16476 (cond ((equal (char-after (point-at-bol)) ?*) t) ; skip headlines
16477 (table.el-p t) ; skip table.el tables
16478 (table-p (org-table-align) t) ; align org-mode tables
16479 (t nil)))) ; call paragraph-fill
16481 ;; For reference, this is the default value of adaptive-fill-regexp
16482 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16484 (defun org-adaptive-fill-function ()
16485 "Return a fill prefix for org-mode files.
16486 In particular, this makes sure hanging paragraphs for hand-formatted lists
16487 work correctly."
16488 (if (looking-at " *\\([-*+] \\|[0-9]+[.)] \\)?")
16489 (make-string (- (match-end 0) (match-beginning 0)) ?\ )))
16491 ;; Functions needed for Emacs/XEmacs region compatibility
16493 (defun org-add-hook (hook function &optional append local)
16494 "Add-hook, compatible with both Emacsen."
16495 (if (and local (featurep 'xemacs))
16496 (add-local-hook hook function append)
16497 (add-hook hook function append local)))
16499 (defun org-region-active-p ()
16500 "Is `transient-mark-mode' on and the region active?
16501 Works on both Emacs and XEmacs."
16502 (if org-ignore-region
16504 (if (featurep 'xemacs)
16505 (and zmacs-regions (region-active-p))
16506 (and transient-mark-mode mark-active))))
16508 (defun org-add-to-invisibility-spec (arg)
16509 "Add elements to `buffer-invisibility-spec'.
16510 See documentation for `buffer-invisibility-spec' for the kind of elements
16511 that can be added."
16512 (cond
16513 ((fboundp 'add-to-invisibility-spec)
16514 (add-to-invisibility-spec arg))
16515 ((or (null buffer-invisibility-spec) (eq buffer-invisibility-spec t))
16516 (setq buffer-invisibility-spec (list arg)))
16518 (setq buffer-invisibility-spec
16519 (cons arg buffer-invisibility-spec)))))
16521 (defun org-remove-from-invisibility-spec (arg)
16522 "Remove elements from `buffer-invisibility-spec'."
16523 (if (fboundp 'remove-from-invisibility-spec)
16524 (remove-from-invisibility-spec arg)
16525 (if (consp buffer-invisibility-spec)
16526 (setq buffer-invisibility-spec
16527 (delete arg buffer-invisibility-spec)))))
16529 (defun org-in-invisibility-spec-p (arg)
16530 "Is ARG a member of `buffer-invisibility-spec'?"
16531 (if (consp buffer-invisibility-spec)
16532 (member arg buffer-invisibility-spec)
16533 nil))
16535 (defun org-image-file-name-regexp ()
16536 "Return regexp matching the file names of images."
16537 (if (fboundp 'image-file-name-regexp)
16538 (image-file-name-regexp)
16539 (let ((image-file-name-extensions
16540 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16541 "xbm" "xpm" "pbm" "pgm" "ppm")))
16542 (concat "\\."
16543 (regexp-opt (nconc (mapcar 'upcase
16544 image-file-name-extensions)
16545 image-file-name-extensions)
16547 "\\'"))))
16549 ;; Functions extending outline functionality
16551 ;; C-a should go to the beginning of a *visible* line, also in the
16552 ;; new outline.el. I guess this should be patched into Emacs?
16553 (defun org-beginning-of-line ()
16554 "Go to the beginning of the current line. If that is invisible, continue
16555 to a visible line beginning. This makes the function of C-a more intuitive."
16556 (interactive)
16557 (beginning-of-line 1)
16558 (if (bobp)
16560 (backward-char 1)
16561 (if (org-invisible-p)
16562 (while (and (not (bobp)) (org-invisible-p))
16563 (backward-char 1)
16564 (beginning-of-line 1))
16565 (forward-char 1))))
16567 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16569 (defun org-invisible-p ()
16570 "Check if point is at a character currently not visible."
16571 ;; Early versions of noutline don't have `outline-invisible-p'.
16572 (if (fboundp 'outline-invisible-p)
16573 (outline-invisible-p)
16574 (get-char-property (point) 'invisible)))
16576 (defun org-invisible-p2 ()
16577 "Check if point is at a character currently not visible."
16578 (save-excursion
16579 (if (and (eolp) (not (bobp))) (backward-char 1))
16580 ;; Early versions of noutline don't have `outline-invisible-p'.
16581 (if (fboundp 'outline-invisible-p)
16582 (outline-invisible-p)
16583 (get-char-property (point) 'invisible))))
16585 (defalias 'org-back-to-heading 'outline-back-to-heading)
16586 (defalias 'org-on-heading-p 'outline-on-heading-p)
16588 (defun org-on-target-p ()
16589 (let ((pos (point)))
16590 (save-excursion
16591 (skip-chars-forward "<")
16592 (and (re-search-backward "<<" nil t)
16593 (or (looking-at org-radio-target-regexp)
16594 (looking-at org-target-regexp))
16595 (<= (match-beginning 0) pos)
16596 (>= (1+ (match-end 0)) pos)))))
16598 (defun org-up-heading-all (arg)
16599 "Move to the heading line of which the present line is a subheading.
16600 This function considers both visible and invisible heading lines.
16601 With argument, move up ARG levels."
16602 (if (fboundp 'outline-up-heading-all)
16603 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16604 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16606 (defun org-show-hidden-entry ()
16607 "Show an entry where even the heading is hidden."
16608 (save-excursion
16609 (org-show-entry)))
16611 (defun org-flag-heading (flag &optional entry)
16612 "Flag the current heading. FLAG non-nil means make invisible.
16613 When ENTRY is non-nil, show the entire entry."
16614 (save-excursion
16615 (org-back-to-heading t)
16616 ;; Check if we should show the entire entry
16617 (if entry
16618 (progn
16619 (org-show-entry)
16620 (save-excursion
16621 (and (outline-next-heading)
16622 (org-flag-heading nil))))
16623 (outline-flag-region (max 1 (1- (point)))
16624 (save-excursion (outline-end-of-heading) (point))
16625 flag))))
16627 (defun org-end-of-subtree (&optional invisible-OK)
16628 ;; This is an exact copy of the original function, but it uses
16629 ;; `org-back-to-heading', to make it work also in invisible
16630 ;; trees. And is uses an invisible-OK argument.
16631 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16632 (org-back-to-heading invisible-OK)
16633 (let ((first t)
16634 (level (funcall outline-level)))
16635 (while (and (not (eobp))
16636 (or first (> (funcall outline-level) level)))
16637 (setq first nil)
16638 (outline-next-heading))
16639 (if (memq (preceding-char) '(?\n ?\^M))
16640 (progn
16641 ;; Go to end of line before heading
16642 (forward-char -1)
16643 (if (memq (preceding-char) '(?\n ?\^M))
16644 ;; leave blank line before heading
16645 (forward-char -1)))))
16646 (point))
16648 (defun org-show-subtree ()
16649 "Show everything after this heading at deeper levels."
16650 (outline-flag-region
16651 (point)
16652 (save-excursion
16653 (outline-end-of-subtree) (outline-next-heading) (point))
16654 nil))
16656 (defun org-show-entry ()
16657 "Show the body directly following this heading.
16658 Show the heading too, if it is currently invisible."
16659 (interactive)
16660 (save-excursion
16661 (org-back-to-heading t)
16662 (outline-flag-region
16663 (max 1 (1- (point)))
16664 (save-excursion
16665 (re-search-forward (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
16666 (or (match-beginning 1) (point-max)))
16667 nil)))
16669 (defun org-make-options-regexp (kwds)
16670 "Make a regular expression for keyword lines."
16671 (concat
16673 "#?[ \t]*\\+\\("
16674 (mapconcat 'regexp-quote kwds "\\|")
16675 "\\):[ \t]*"
16676 "\\(.+\\)"))
16678 ;; Make `bookmark-jump' show the jump location if it was hidden.
16679 (eval-after-load "bookmark"
16680 '(if (boundp 'bookmark-after-jump-hook)
16681 ;; We can use the hook
16682 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16683 ;; Hook not available, use advice
16684 (defadvice bookmark-jump (after org-make-visible activate)
16685 "Make the position visible."
16686 (org-bookmark-jump-unhide))))
16688 (defun org-bookmark-jump-unhide ()
16689 "Unhide the current position, to show the bookmark location."
16690 (and (org-mode-p)
16691 (or (org-invisible-p)
16692 (save-excursion (goto-char (max (point-min) (1- (point))))
16693 (org-invisible-p)))
16694 (org-show-hierarchy-above)))
16696 ;;; Experimental code
16699 ;(add-hook 'org-load-hook
16700 ; (lambda ()
16701 ; (defun outline-show-heading ()
16702 ; "Show the current heading and move to its end."
16703 ; (outline-flag-region
16704 ; (- (point)
16705 ; (cond
16706 ; ((bobp) 0)
16707 ; ((equal (buffer-substring
16708 ; (max (point-min) (- (point) 3)) (point))
16709 ; "\n\n\n")
16710 ; 2)
16711 ; (t 1)))
16712 ; (progn (outline-end-of-heading) (point))
16713 ; nil))))
16715 ;;; Finish up
16717 (provide 'org)
16719 (run-hooks 'org-load-hook)
16721 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16722 ;;; org.el ends here